diff --git a/.github/workflows/build-distributions.yml b/.github/workflows/build-distributions.yml index 3a5c993e5c..713b54bcb0 100644 --- a/.github/workflows/build-distributions.yml +++ b/.github/workflows/build-distributions.yml @@ -145,9 +145,8 @@ jobs: name: Build wheel (${{ matrix.platform.name }}) needs: source runs-on: ${{ matrix.platform.runner }} - # Cold dist builds take up to about 2x the 17-31 minute release-profile jobs on Windows and macOS, - # and a cold macOS arm64 dist build has taken an hour. - timeout-minutes: 150 + # Release-profile wheel jobs take about 20-40 minutes; the limit leaves room for a slow runner. + timeout-minutes: 90 strategy: fail-fast: false matrix: @@ -202,11 +201,15 @@ jobs: uses: PyO3/maturin-action@v1 if: inputs.prebuilt-run-id == '' continue-on-error: true + # The extension embeds the UI as sqb does, so the sqb build below reuses the crates this + # build compiles instead of compiling sqlbuild-orchestration and sqlbuild-cli again. + env: + SQLBUILD_UI_REQUIRED: "1" with: command: build # One platform records a cargo build timing report for build time work. args: >- - --profile ${{ inputs.cargo-profile }} --out dist --features extension-module + --profile ${{ inputs.cargo-profile }} --out dist --features extension-module,sqlbuild-cli/ui ${{ matrix.platform.name == 'linux-x86_64' && '--timings' || '' }} target: ${{ matrix.platform.target }} manylinux: auto @@ -215,11 +218,13 @@ jobs: uses: PyO3/maturin-action@v1 if: inputs.prebuilt-run-id == '' && steps.extension.outcome == 'failure' continue-on-error: ${{ runner.os != 'Linux' }} + env: + SQLBUILD_UI_REQUIRED: "1" with: command: build # One platform records a cargo build timing report for build time work. args: >- - --profile ${{ inputs.cargo-profile }} --out dist --features extension-module + --profile ${{ inputs.cargo-profile }} --out dist --features extension-module,sqlbuild-cli/ui ${{ matrix.platform.name == 'linux-x86_64' && '--timings' || '' }} target: ${{ matrix.platform.target }} manylinux: auto @@ -229,8 +234,9 @@ jobs: && steps.extension.outcome == 'failure' && steps.extension-retry.outcome == 'failure' shell: bash env: + SQLBUILD_UI_REQUIRED: "1" MATURIN_ARGS: >- - --profile ${{ inputs.cargo-profile }} --out dist --features extension-module + --profile ${{ inputs.cargo-profile }} --out dist --features extension-module,sqlbuild-cli/ui TARGET: ${{ matrix.platform.target }} run: scripts/maturin_from_pypi.sh build ${MATURIN_ARGS} - id: cli @@ -368,9 +374,9 @@ jobs: cd "${RUNNER_TEMP}" "${smoke}/python" -c \ "import sqlbuild._native as native; assert native.semantic_help_catalogue()" - mkdir -p "${project}/models" + mkdir -p "${project}/sql/models" printf 'name = "scope_smoke"\nadapter = "duckdb"\n' > "${project}/sqlbuild_project.toml" - printf 'MODEL();\nSELECT 1 AS id\n' > "${project}/models/orders.sql" + printf 'MODEL();\nSELECT 1 AS id\n' > "${project}/sql/models/orders.sql" "${smoke}/sqb" --project-dir "${project}" scope model:orders --json "${smoke}/sqlbuild" --project-dir "${project}" scope model:orders # The packaged sqb server must serve the embedded UI, not only the API. diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 3133ae9e3d..bf90d08583 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -506,7 +506,7 @@ jobs: - name: Fetch the base for the new-duplicate check run: git fetch --no-tags --depth=1 origin "$BASE_REF" env: - BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || 'main:refs/remotes/origin/main' }} + BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || '+main:refs/remotes/origin/main' }} - name: Run static checks run: make check-ci env: diff --git a/Cargo.lock b/Cargo.lock index 19d056e54c..276c807115 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1410,9 +1410,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "fensu-facts" -version = "0.31.1" +version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ca6517dd7fb6fd5ec99d7c25be8ca860e4d753afb081cc0ab6a065aac40d0a8" +checksum = "3e9d30452db5ffec654a1dd1683178e14e0789338b57b0ea0a798595b576814e" dependencies = [ "dunce", "get-size2", @@ -1428,9 +1428,9 @@ dependencies = [ [[package]] name = "fensu-native" -version = "0.31.1" +version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbba81e35d514d8c889ef10287202e6c7920bdf43094ceb925616fded7cd5b92" +checksum = "b36fc5e154c5967d8126eca79ad1a64f75fe1ca9b38dca903678b55b5988ef4a" dependencies = [ "fensu-facts", "globset", @@ -2088,6 +2088,22 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "ignore" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "484be5657551d7868d67587df967fb4fcbe9d266a761cc855aaa148fda0b3cc7" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -4328,6 +4344,7 @@ dependencies = [ "sqlquack-syntax-postgres", "sqlquack-syntax-sqlite", "sqlquack-syntax-sqlserver", + "sqlquack-tokenize", "stacker", ] @@ -4442,6 +4459,7 @@ dependencies = [ name = "sqlbuild-discovery" version = "0.0.0" dependencies = [ + "ignore", "junction", "rayon", "serde", @@ -4814,6 +4832,7 @@ dependencies = [ "sqlclean", "sqlquack-parse", "sqlquack-syntax", + "sqlquack-tokenize", "stacker", "stats_alloc", "tempfile", @@ -4856,26 +4875,50 @@ dependencies = [ [[package]] name = "sqlclean" -version = "0.11.1" -source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=b0728bb990b7d8ff196cb00cc20545f2fa4df555#b0728bb990b7d8ff196cb00cc20545f2fa4df555" +version = "0.12.0" +source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=8550e6a45c95a4a9e8470a570ae786d6f0deee8e#8550e6a45c95a4a9e8470a570ae786d6f0deee8e" dependencies = [ "rayon", "rustc-hash", "serde", "serde_json", "sha2 0.10.9", + "sqlclean-lint", "sqlquack-fingerprint", "sqlquack-format", - "sqlquack-lint", "sqlquack-parse", "sqlquack-syntax", "sqlquack-syntax-sqlserver", + "sqlquack-tokenize", +] + +[[package]] +name = "sqlclean-lint" +version = "0.12.0" +source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=8550e6a45c95a4a9e8470a570ae786d6f0deee8e#8550e6a45c95a4a9e8470a570ae786d6f0deee8e" +dependencies = [ + "rayon", + "serde", + "serde_json", + "sqlclean-rules", + "sqlquack-parse", + "sqlquack-semantics", + "sqlquack-syntax", + "sqlquack-tokenize", +] + +[[package]] +name = "sqlclean-rules" +version = "0.12.0" +source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=8550e6a45c95a4a9e8470a570ae786d6f0deee8e#8550e6a45c95a4a9e8470a570ae786d6f0deee8e" +dependencies = [ + "sqlquack-syntax", ] [[package]] name = "sqlquack-derive" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "proc-macro2", "quote", @@ -4884,8 +4927,8 @@ dependencies = [ [[package]] name = "sqlquack-diagnostics" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "serde", "serde_json", @@ -4894,41 +4937,30 @@ dependencies = [ [[package]] name = "sqlquack-fingerprint" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "sha2 0.10.9", "sqlquack-parse", "sqlquack-syntax", + "sqlquack-tokenize", ] [[package]] name = "sqlquack-format" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" -dependencies = [ - "serde_json", - "sqlquack-parse", - "sqlquack-syntax", -] - -[[package]] -name = "sqlquack-lint" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ - "rayon", - "rustc-hash", - "serde", "serde_json", "sqlquack-parse", "sqlquack-syntax", + "sqlquack-tokenize", ] [[package]] name = "sqlquack-parse" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "sqlquack-syntax", "sqlquack-syntax-bigquery", @@ -4940,8 +4972,8 @@ dependencies = [ [[package]] name = "sqlquack-semantics" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "regex", "rustc-hash", @@ -4956,8 +4988,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "serde", "serde_json", @@ -4969,8 +5001,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-bigquery" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "sqlquack-syntax", "stacker", @@ -4978,8 +5010,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-clickhouse" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "sqlquack-syntax", "stacker", @@ -4987,8 +5019,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-databricks" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "sqlquack-syntax", "stacker", @@ -4996,8 +5028,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-duckdb" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "sqlquack-syntax", "stacker", @@ -5005,8 +5037,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-postgres" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "sqlquack-syntax", "stacker", @@ -5014,12 +5046,13 @@ dependencies = [ [[package]] name = "sqlquack-syntax-snowflake" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "serde", "serde_json", "sqlquack-syntax", + "sqlquack-tokenize", "stacker", "thiserror 1.0.69", "unicode-segmentation", @@ -5027,8 +5060,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-sqlite" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "sqlquack-syntax", "stacker", @@ -5036,13 +5069,23 @@ dependencies = [ [[package]] name = "sqlquack-syntax-sqlserver" -version = "0.22.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" dependencies = [ "sqlquack-syntax", + "sqlquack-tokenize", "stacker", ] +[[package]] +name = "sqlquack-tokenize" +version = "0.23.0" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +dependencies = [ + "sqlquack-syntax", + "thiserror 1.0.69", +] + [[package]] name = "sqlx-core" version = "0.8.6" diff --git a/Cargo.toml b/Cargo.toml index 627d06d190..121faef3b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,12 +95,14 @@ tower = { version = "0.5", default-features = false, features = ["util"] } fensu-policy = "=0.22.0" # Fensu's Python facts and core rules without their Python bindings: the default `python` # feature adds PyO3, rusqlite, flate2 and sha2. -fensu-facts = { version = "=0.31.1", default-features = false } -fensu-native = { version = "=0.31.1", default-features = false } +fensu-facts = { version = "=0.31.2", default-features = false } +fensu-native = { version = "=0.31.2", default-features = false } futures-util = { version = "0.3", default-features = false, features = ["std"] } # `sqb` names compute log captures with random ids, as `uuid.uuid4().hex`. getrandom = "0.4" globset = "0.4" +# Gitignore matching for the project layout check. +ignore = "0.4" # Windows only: tells NTFS junctions, which Python walks as directories, from symbolic links. junction = { version = "2.1.0", default-features = false } keyring = { version = "3.6.3", default-features = false } @@ -211,22 +213,24 @@ sqlbuild-scopes = { path = "crates/sqlbuild-scopes" } sqlbuild-sqltext = { path = "crates/sqlbuild-sqltext" } sqlbuild-state = { path = "crates/sqlbuild-state" } # SQL lint Rules, quality Rules and the formatter. -sqlclean = { git = "https://github.com/sqlstack-io/sqlclean.git", rev = "b0728bb990b7d8ff196cb00cc20545f2fa4df555" } +sqlclean = { git = "https://github.com/sqlstack-io/sqlclean.git", rev = "8550e6a45c95a4a9e8470a570ae786d6f0deee8e" } # SQL change fingerprints over SQLQuack's tokenizers. -sqlquack-fingerprint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } +sqlquack-fingerprint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } # Scopes, name resolution, types and lineage for the native analysis route. -sqlquack-semantics = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed", features = ["bigquery", "clickhouse", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } +sqlquack-semantics = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174", features = ["bigquery", "clickhouse", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } # SQLQuack's Snowflake-family parser and tokenizer, reached as SQLQuack exposes them. -sqlquack-parse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } +sqlquack-parse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } # SQLQuack's syntax tree and lossless tokens. -sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } -sqlquack-syntax-bigquery = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } -sqlquack-syntax-clickhouse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } -sqlquack-syntax-databricks = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } -sqlquack-syntax-duckdb = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } -sqlquack-syntax-postgres = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } -sqlquack-syntax-sqlite = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } -sqlquack-syntax-sqlserver = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } +sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +# SQLQuack's tokenizer: lossless tokens and tokenize failures. +sqlquack-tokenize = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +sqlquack-syntax-bigquery = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +sqlquack-syntax-clickhouse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +sqlquack-syntax-databricks = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +sqlquack-syntax-duckdb = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +sqlquack-syntax-postgres = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +sqlquack-syntax-sqlite = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +sqlquack-syntax-sqlserver = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } stacker = "0.1" # Counts heap allocations in growth tests, which measure work instead of time. stats_alloc = "0.1" @@ -256,11 +260,10 @@ debug = false [profile.release] strip = "symbols" -# Released wheels: one codegen unit per crate keeps one copy of generic code that parallel units -# each instantiate, so the native binaries are about an eighth smaller and build in about 2x time. +# Released wheels: Cargo's default 16 codegen units per crate. One unit made the binaries about an +# eighth of the size but doubled build time, and macOS wheel builds took 60-90 minutes. [profile.dist] inherits = "release" -codegen-units = 1 # Local iteration: release-level optimisation with incremental builds, so rebuilding after a # focused change does not recompile the whole binding crate. CI uses `release`. diff --git a/README.md b/README.md index 50e695227e..cadd81cfd2 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ from sqlbuild.rules import Finding, Model, RuleContext, rule remediation="Reference a staging model with __ref() instead.", ) def marts_use_staging(*, model: Model, ctx: RuleContext) -> list[Finding]: - layer = ctx.project.tree.relative_parts(path=model.path, under="models")[0] + layer = ctx.project.tree.relative_parts(path=model.path, under="sql/models")[0] sql = ctx.sql.for_model(model).authored.source if layer != "marts" or "__source(" not in sql: return [] diff --git a/benchmarks/dbt-compare/edit_models.py b/benchmarks/dbt-compare/edit_models.py index d77b50a0de..0c437884a5 100644 --- a/benchmarks/dbt-compare/edit_models.py +++ b/benchmarks/dbt-compare/edit_models.py @@ -28,9 +28,11 @@ def main() -> None: step = args.models // args.count for k in range(args.count): index = k * step + step // 2 + models = args.project / "sql" / "models" + if not models.is_dir(): + models = args.project / "models" path = ( - args.project - / "models" + models / f"sales{index // 1000:03d}" / "intermediate" / "clean" diff --git a/benchmarks/dbt-compare/write_dbt_dense.py b/benchmarks/dbt-compare/write_dbt_dense.py index 64b937ff5d..711dce29f4 100644 --- a/benchmarks/dbt-compare/write_dbt_dense.py +++ b/benchmarks/dbt-compare/write_dbt_dense.py @@ -66,7 +66,7 @@ def write_norules(project: Path) -> Path: shutil.copytree(project, target) toml = target / "sqlbuild_project.toml" text = toml.read_text() - new = text.replace('select = ["SQBR", "SQLCLEAN", "XSQBR"]', "select = []") + new = re.sub(r"^select = \[.*\]$", "select = []", text, count=1, flags=re.MULTILINE) assert new != text toml.write_text(new) return target @@ -163,7 +163,7 @@ def write_dbt(sqb: Path, out: Path, n: int) -> Path: # Seeds (dbt / "seeds").mkdir() seed_yml = ["seeds:"] - for csv in sorted((sqb / "seeds").glob("*.csv")): + for csv in sorted((sqb / "sql" / "seeds").glob("*.csv")): shutil.copy(csv, dbt / "seeds" / csv.name) seed_yml += [ f" - name: {csv.stem}", @@ -178,7 +178,7 @@ def write_dbt(sqb: Path, out: Path, n: int) -> Path: # Functions (dbt UDF resources) (dbt / "functions").mkdir() fn_yml = ["functions:"] - for fn in sorted((sqb / "functions" / "sql").glob("*.sql")): + for fn in sorted((sqb / "sql" / "functions" / "sql").glob("*.sql")): body = fn.read_text().split(");\n", 1)[1].strip() (dbt / "functions" / fn.name).write_text(body + "\n") fn_yml += [ @@ -201,7 +201,7 @@ def write_dbt(sqb: Path, out: Path, n: int) -> Path: base_re = re.compile( r'def (base_offset_\d{3})\(expression: str\) -> str:\n return f"\(\{expression\} \+ 1\)"' ) - for macro in sorted(sqb.glob("models/*/intermediate/clean/_sqlbuild/macros/python/*/*.py")): + for macro in sorted(sqb.glob("sql/models/*/intermediate/clean/_sqlbuild/macros/python/*/*.py")): text = macro.read_text() name, ret = macro_def_re.search(text).groups() offset = offset_re.search(text)[1] @@ -221,7 +221,7 @@ def write_dbt(sqb: Path, out: Path, n: int) -> Path: parts.append( f"{{% macro {name}(expression) -%}}({{{{ expression }}}} + {offset}){{%- endmacro %}}" ) - domain = macro.relative_to(sqb / "models").parts[0] + domain = macro.relative_to(sqb / "sql" / "models").parts[0] target = dbt / "macros" / domain / macro.parent.name / (macro.stem + ".sql") target.parent.mkdir(parents=True, exist_ok=True) target.write_text("\n".join(parts) + "\n") @@ -231,7 +231,7 @@ def write_dbt(sqb: Path, out: Path, n: int) -> Path: domain = f"sales{index // 1000:03d}" batch = f"batch{index // 5:05d}" rel = Path(domain) / "intermediate" / "clean" / batch - src = sqb / "models" / rel / f"{name}.sql" + src = sqb / "sql" / "models" / rel / f"{name}.sql" columns, body = model_header_and_body(src.read_text()) out_dir = dbt / "models" / rel out_dir.mkdir(parents=True, exist_ok=True) @@ -282,7 +282,7 @@ def write_dbt(sqb: Path, out: Path, n: int) -> Path: def model_relations(sqb: Path) -> list[tuple[str, str, list[tuple[str, str, bool, str, bool]]]]: """Name, materialization and columns of every model, read from the SQLBuild headers.""" relations = [] - for path in sorted((sqb / "models").rglob("*.sql")): + for path in sorted((sqb / "sql" / "models").rglob("*.sql")): text = path.read_text() materialized = MATERIALIZED_RE.search(text.split("\n", 1)[0]) assert materialized, path @@ -351,7 +351,8 @@ def seed_error(out: Path, kind: str) -> None: name = dense_model_name(ERROR_MODEL_INDEX) upstream = dense_model_name(ERROR_MODEL_INDEX - 1) for tool in ("sqlbuild", "sqlbuild-norules", "dbt", "dbt-remote"): - for path in (out / tool / "models").rglob(f"{name}.sql"): + models = out / tool / ("models" if tool.startswith("dbt") else "sql/models") + for path in models.rglob(f"{name}.sql"): text = path.read_text() if kind == "column": new = text.replace( diff --git a/benchmarks/duckshop-10k/checksum.txt b/benchmarks/duckshop-10k/checksum.txt index 968cf304d0..12393fd21a 100644 --- a/benchmarks/duckshop-10k/checksum.txt +++ b/benchmarks/duckshop-10k/checksum.txt @@ -1 +1 @@ -generator 4 files 11674 sha256 d0012261f902e87a546a04bd8c6552c8a050f9cec6753b5acccc53584bce9d37 +generator 4 files 11674 sha256 c3a3d8f62a23c4ae770c70ceb5437d849bb32211edb12b6017af25a76fb8d7e2 diff --git a/benchmarks/duckshop-10k/duckshop10k/chains.py b/benchmarks/duckshop-10k/duckshop10k/chains.py index fc7257b679..2e9a2ab326 100644 --- a/benchmarks/duckshop-10k/duckshop10k/chains.py +++ b/benchmarks/duckshop-10k/duckshop10k/chains.py @@ -40,7 +40,7 @@ def customer_chain(project: Project, result: Intermediate) -> None: identity = result.combined.get("customer_identity") if orders is None or identity is None: return - folder = "models/intermediate/customers" + folder = "sql/models/intermediate/customers" value = _model( project, "int_customer_value", @@ -160,7 +160,7 @@ def customer_chain(project: Project, result: Intermediate) -> None: dim = marts.publish( project, "dim_customers", - "models/marts/core", + "sql/models/marts/core", segments, "global_customer_key", "One row per global customer with their value scores and segment", @@ -168,7 +168,7 @@ def customer_chain(project: Project, result: Intermediate) -> None: segment_mix = marts.share_by( project, "rpt_marketing__segment_mix", - "models/marts/marketing", + "sql/models/marts/marketing", dim, "segment", "Global customers", @@ -176,7 +176,7 @@ def customer_chain(project: Project, result: Intermediate) -> None: vip_mix = marts.share_by( project, "rpt_marketing__vip_mix", - "models/marts/marketing", + "sql/models/marts/marketing", dim, "is_vip", "Global customers", @@ -191,7 +191,7 @@ def finance_chain(project: Project, result: Intermediate) -> None: budgets = result.combined.get("ledgers__budgets") if entries is None or budgets is None: return - folder = "models/intermediate/ledgers" + folder = "sql/models/intermediate/ledgers" usd = to_usd( project, "int_gl_entries_usd", @@ -297,7 +297,7 @@ def finance_chain(project: Project, result: Intermediate) -> None: fact = marts.publish( project, "fct_gl_budget_variance", - "models/marts/core", + "sql/models/marts/core", variance, "variance_key", "One row per legal entity, cost centre and month with actual and budgeted spend", @@ -305,7 +305,7 @@ def finance_chain(project: Project, result: Intermediate) -> None: by_entity = marts.share_by( project, "rpt_finance__variance_by_entity", - "models/marts/finance", + "sql/models/marts/finance", fact, "legal_entity_code", "Budget variance", @@ -313,7 +313,7 @@ def finance_chain(project: Project, result: Intermediate) -> None: quarterly = marts.period_rollup( project, "rpt_finance__variance_quarterly", - "models/marts/finance", + "sql/models/marts/finance", fact, "quarter", "Budget variance", @@ -321,7 +321,7 @@ def finance_chain(project: Project, result: Intermediate) -> None: monthly_report = marts.period_rollup( project, "rpt_finance__variance_monthly", - "models/marts/finance", + "sql/models/marts/finance", fact, "month", "Budget variance", @@ -354,7 +354,7 @@ def scorecards(project: Project, result: Intermediate) -> None: marts.wide_daily( project, f"rpt_{shop}__weekly_scorecard", - f"models/marts/storefronts/{shop}", + f"sql/models/marts/storefronts/{shop}", sources, f"One row per week with the sales, payments and refunds of {shop} side by side", ) @@ -374,13 +374,13 @@ def scorecards(project: Project, result: Intermediate) -> None: marts.wide_daily( project, f"rpt_{team}_{region.code}__scorecard", - f"models/marts/{team}/{region.code}", + f"sql/models/marts/{team}/{region.code}", weekly, f"One row per week with every weekly {team} headline for {region.name} " "side by side", ) ) - folder = "models/marts/executive" + folder = "sql/models/marts/executive" for team in ("finance", "marketing"): cards = [card for card in team_cards if card.name.startswith(f"rpt_{team}_")] if len(cards) >= 2: diff --git a/benchmarks/duckshop-10k/duckshop10k/core.py b/benchmarks/duckshop-10k/duckshop10k/core.py index 56275eac87..9bf1491b4d 100644 --- a/benchmarks/duckshop-10k/duckshop10k/core.py +++ b/benchmarks/duckshop-10k/duckshop10k/core.py @@ -115,6 +115,8 @@ def declaration_uses(text: str) -> set[tuple[str, str]]: return uses +SQL_ROOT = "sql" + _KIND_OF_ROLE = { "macros/sql": "macro", "macros/python": "macro", @@ -185,7 +187,7 @@ def render(self) -> dict[str, str]: def _consumers(self, files: dict[str, str]) -> dict[tuple[str, str], set[str]]: direct: dict[tuple[str, str], set[str]] = {} for path, text in files.items(): - if not path.endswith(".sql") or not path.startswith(("models/", "tests/")): + if not path.endswith(".sql") or not path.startswith(("sql/models/", "tests/")): continue folder = str(PurePosixPath(path).parent) uses = declaration_uses(text) @@ -196,9 +198,9 @@ def _consumers(self, files: dict[str, str]) -> dict[tuple[str, str], set[str]]: continue direct.setdefault(use, set()).add(folder) for path, text in files.items(): - if path.startswith(("sources/", "seeds/")): + if path.startswith(("sql/sources/", "sql/seeds/")): for use in declaration_uses(text): - direct.setdefault(use, set()).add(path.split("/")[0]) + direct.setdefault(use, set()).add("/".join(path.split("/")[:2])) # A declaration used inside another declaration is used wherever that one is. uses_of: dict[tuple[str, str], set[tuple[str, str]]] = { key: declaration_uses(declaration.content) & set(self.declarations) @@ -222,18 +224,20 @@ def resolve(key: tuple[str, str], stack: tuple[tuple[str, str], ...]) -> set[str def _placement(folders: set[str], role: str) -> str: - roots = {folder.split("/")[0] for folder in folders} + """The global `sql/`, or the `_sqlbuild/` role of the deepest folder all users share.""" + # Below sql/, each resource kind's folder (sql/models, sql/sources) is its own root. + parts = [PurePosixPath(folder.removeprefix(f"{SQL_ROOT}/")).parts for folder in folders] + roots = {folder_parts[0] for folder_parts in parts} if len(roots) > 1: - return role - parts = [PurePosixPath(folder).parts for folder in folders] + return f"{SQL_ROOT}/{role}" common: list[str] = [] for level in zip(*parts, strict=False): if len(set(level)) != 1: break common.append(level[0]) if len(common) < 2: - return role - owner = "/".join(common) + return f"{SQL_ROOT}/{role}" + owner = "/".join(common) if common[0] == "tests" else "/".join((SQL_ROOT, *common)) private = all(folder == owner for folder in folders) return f"{owner}/_sqlbuild/{'_' if private else ''}{role}" diff --git a/benchmarks/duckshop-10k/duckshop10k/extras.py b/benchmarks/duckshop-10k/duckshop10k/extras.py index d769f8f98e..f5cfa25069 100644 --- a/benchmarks/duckshop-10k/duckshop10k/extras.py +++ b/benchmarks/duckshop-10k/duckshop10k/extras.py @@ -163,15 +163,15 @@ def fx_source() -> str: def build_extras(project: Project, result: Intermediate) -> None: - project.write("functions/sql/udf__sku_family.sql", SKU_FAMILY) - project.write("functions/python/luhn_valid.py", LUHN_VALID) - project.write("python/audits/fact_quality.py", FACT_QUALITY) - project.write("sources/finance_reference.yml", fx_source()) + project.write("sql/functions/sql/udf__sku_family.sql", SKU_FAMILY) + project.write("sql/functions/python/luhn_valid.py", LUHN_VALID) + project.write("python/nodes/audits/fact_quality.py", FACT_QUALITY) + project.write("sql/sources/finance_reference.yml", fx_source()) charges = result.combined.get("payments__charges_enriched") if charges is not None: _card_checks(project, charges) if "fct_orders" in project.models: - project.write("functions/sql/table_fn__customer_orders.sql", CUSTOMER_ORDERS) + project.write("sql/functions/sql/table_fn__customer_orders.sql", CUSTOMER_ORDERS) _order_lookup(project) tickets = result.combined.get("support__tickets_enriched") if tickets is not None: @@ -202,7 +202,7 @@ def _card_checks(project: Project, charges: Model) -> None: project.add( Model( name="int_payments__card_bin_checks", - folder="models/intermediate/payments", + folder="sql/models/intermediate/payments", layer="intermediate", description="One row per gateway charge with checks on the card number" " prefix it reported", @@ -226,7 +226,7 @@ def _order_lookup(project: Project) -> None: project.add( Model( name="rpt_customer_order_lookup", - folder="models/marts/support", + folder="sql/models/marts/support", layer="marts", description=( "Every order of the customer named by the lookup_customer_id variable, for " @@ -278,7 +278,7 @@ def _open_ticket_age(project: Project, tickets: Model) -> None: project.add( Model( name="rpt_support__open_ticket_age", - folder="models/marts/support", + folder="sql/models/marts/support", layer="marts", description=( "Tickets with no satisfaction response yet and their age in hours at query time. " @@ -320,7 +320,7 @@ def _overdue_purchase_orders(project: Project, orders: Model) -> None: project.add( Model( name="rpt_operations__overdue_purchase_orders", - folder="models/marts/operations", + folder="sql/models/marts/operations", layer="marts", description=( "Purchase orders past their expected arrival with no invoice yet, aged at query " @@ -364,7 +364,7 @@ def _dim_date(project: Project) -> None: project.add( Model( name="dim_date", - folder="models/marts/core", + folder="sql/models/marts/core", layer="marts", description="One row per calendar day of the reporting history, from GENERATOR", config=["contract enforced"], diff --git a/benchmarks/duckshop-10k/duckshop10k/layers.py b/benchmarks/duckshop-10k/duckshop10k/layers.py index 4513d958cd..5133d3f264 100644 --- a/benchmarks/duckshop-10k/duckshop10k/layers.py +++ b/benchmarks/duckshop-10k/duckshop10k/layers.py @@ -329,7 +329,7 @@ def build_intermediate( continue area = AREA[system] for instance in values: - folder = f"models/intermediate/{area}/{instance.code}" + folder = f"sql/models/intermediate/{area}/{instance.code}" result.per_instance[instance.code] = _instance_models( project, instance, tables[instance.code], folder ) @@ -350,7 +350,7 @@ def build_intermediate( model = union( project, f"int_{area}_{region.code}__{entity}", - f"models/intermediate/{area}/regions", + f"sql/models/intermediate/{area}/regions", members, f"{entity.replace('_', ' ').capitalize()} from every {region.name} " "storefront", @@ -369,7 +369,7 @@ def build_intermediate( result.combined[f"{area}__{entity}"] = union( project, f"int_{area}__{entity}", - f"models/intermediate/{area}", + f"sql/models/intermediate/{area}", members, f"{entity.replace('_', ' ').capitalize()} from every {area.removesuffix('s')} " "instance", @@ -382,7 +382,7 @@ def build_intermediate( def _storefront_globals(project: Project, result: Intermediate) -> None: - folder = "models/intermediate/storefronts" + folder = "sql/models/intermediate/storefronts" orders = result.combined["storefronts__orders_enriched"] result.combined["orders_usd"] = to_usd( project, @@ -397,7 +397,7 @@ def _storefront_globals(project: Project, result: Intermediate) -> None: result.combined["customer_identity"] = domain.customer_identity( project, "int_customer_identity", - "models/intermediate/customers", + "sql/models/intermediate/customers", result.combined["storefronts__customer_profile"], ) catalogue = result.per_instance.get("pim") @@ -508,7 +508,7 @@ def _line_demand(project: Project, line: str, lines: Model) -> Model: return project.add( Model( name=f"int_{line}__sku_demand", - folder=f"models/intermediate/product_lines/{line}", + folder=f"sql/models/intermediate/product_lines/{line}", layer="intermediate", description=( f"Units and sales of every {line.title()} product-line SKU per storefront, ranked " @@ -533,7 +533,7 @@ def _clickstream( model = domain.sessions( project, f"int_{collector.code}__sessions", - f"models/intermediate/clickstream/{collector.code}", + f"sql/models/intermediate/clickstream/{collector.code}", project.ref(stream), ) result.per_instance.setdefault(collector.code, {})["sessions"] = model @@ -542,7 +542,7 @@ def _clickstream( result.combined["clickstream__sessions"] = union( project, "int_clickstream__sessions", - "models/intermediate/clickstream", + "sql/models/intermediate/clickstream", session_models, "Sessions from every web and app collector", "session_id", diff --git a/benchmarks/duckshop-10k/duckshop10k/mart_layer.py b/benchmarks/duckshop-10k/duckshop10k/mart_layer.py index 5c9272f273..e1d7c6d40f 100644 --- a/benchmarks/duckshop-10k/duckshop10k/mart_layer.py +++ b/benchmarks/duckshop-10k/duckshop10k/mart_layer.py @@ -231,7 +231,7 @@ def build_marts( for system, values in systems.items(): for instance in values: models = result.per_instance.get(instance.code, {}) - folder = f"models/marts/{AREA[system]}/{instance.code}" + folder = f"sql/models/marts/{AREA[system]}/{instance.code}" for spec in INSTANCE_MARTS.get(system, ()): source = models.get(spec[2]) if source is not None: @@ -248,7 +248,7 @@ def build_marts( models = result.regional.get(region.code) if not models: continue - folder = f"models/marts/{team}/{region.code}" + folder = f"sql/models/marts/{team}/{region.code}" for spec in specs: source = models.get(spec[2]) if source is not None: @@ -267,7 +267,7 @@ def build_marts( _apply( project, f"rpt_{team}__{spec[0]}", - f"models/marts/{team}", + f"sql/models/marts/{team}", spec, source, f"{spec[2].split('__')[-1].replace('_', ' ').capitalize()} company-wide", @@ -287,7 +287,7 @@ def _product_lines(project: Project, result: Intermediate) -> None: source = result.combined.get(f"{line}__daily_demand") if source is None: continue - folder = f"models/marts/merchandising/product_lines/{line}" + folder = f"sql/models/marts/merchandising/product_lines/{line}" subject = f"{line.title()} product-line demand" marts.top_n(project, f"rpt_{line}__top_skus", folder, source, "sku", 50, subject) marts.share_by( @@ -296,7 +296,7 @@ def _product_lines(project: Project, result: Intermediate) -> None: def _published(project: Project, result: Intermediate) -> dict[str, Model]: - folder = "models/marts/core" + folder = "sql/models/marts/core" combined = result.combined plan = ( ("fct_orders", "orders_usd", "order_id", "One row per storefront order with USD amounts"), @@ -408,7 +408,7 @@ def _published(project: Project, result: Intermediate) -> dict[str, Model]: def _executive(project: Project) -> None: - folder = "models/marts/executive" + folder = "sql/models/marts/executive" daily_sources = [ (region.code, project.models[f"int_storefronts_{region.code}__orders_enriched_daily"]) for region in REGIONS @@ -521,7 +521,7 @@ def _snapshot( project.add( Model( name=name, - folder="models/snapshots", + folder="sql/models/snapshots", layer="snapshots", description=description, config=config, diff --git a/benchmarks/duckshop-10k/duckshop10k/project.py b/benchmarks/duckshop-10k/duckshop10k/project.py index 4475b2f5f1..9d57f20d4a 100644 --- a/benchmarks/duckshop-10k/duckshop10k/project.py +++ b/benchmarks/duckshop-10k/duckshop10k/project.py @@ -77,7 +77,7 @@ def build(profile_name: str = "full") -> dict[str, str]: staging = Staging(tables={}, events={}) for system, values in systems.items(): for instance in values: - folder = f"models/staging/{_STAGING_FOLDER[system]}/{instance.code}" + folder = f"sql/models/staging/{_STAGING_FOLDER[system]}/{instance.code}" if system == "collector": staging.events[instance.code] = stage_collector(project, instance, folder) else: @@ -93,16 +93,16 @@ def build(profile_name: str = "full") -> dict[str, str]: build_workload(project) build_rules(project) _static_files(project) - project.write("seeds/source_instances.csv", instances_seed(systems)) + project.write("sql/seeds/source_instances.csv", instances_seed(systems)) return project.render() def _static_files(project: Project) -> None: project.write("sqlbuild_project.toml", project_toml()) project.write(".gitignore", "sqlbuild_local.toml\ntarget/\nlogs/\n.sqlbuild/\n") - project.write("seeds/currencies.csv", currencies_seed()) + project.write("sql/seeds/currencies.csv", currencies_seed()) project.write( - "seeds/seeds.yml", + "sql/seeds/seeds.yml", "seeds:\n" " - name: currencies\n" " description: ISO currencies with the number of decimal places in their minor unit\n" diff --git a/benchmarks/duckshop-10k/duckshop10k/rules_gen.py b/benchmarks/duckshop-10k/duckshop10k/rules_gen.py index 9010a21c86..5b94b9c6ed 100644 --- a/benchmarks/duckshop-10k/duckshop10k/rules_gen.py +++ b/benchmarks/duckshop-10k/duckshop10k/rules_gen.py @@ -16,7 +16,7 @@ def _is_change_log(ctx: RuleContext, source: str) -> bool: """Whether a source declares an _op column, read from its instance's own sources file.""" - path = f"sources/{source.split('__', 1)[0]}.yml" + path = f"sql/sources/{source.split('__', 1)[0]}.yml" if not ctx.project.tree.glob(path): return False text = ctx.project.tree.read_text(path) @@ -39,7 +39,7 @@ def _is_change_log(ctx: RuleContext, source: str) -> bool: ), ) def staging_uses_change_log_macro(*, model: Model, ctx: RuleContext) -> list[Finding]: - parts = ctx.project.tree.relative_parts(path=model.path, under="models") + parts = ctx.project.tree.relative_parts(path=model.path, under="sql/models") if not parts or parts[0] != "staging": return [] sql = ctx.sql.for_model(model).authored.source @@ -58,7 +58,7 @@ def staging_uses_change_log_macro(*, model: Model, ctx: RuleContext) -> list[Fin from sqlbuild.rules.testing import RuleCase, evaluate_rule _SOURCES = RuleFile( - path="sources/shop_xx.yml", + path="sql/sources/shop_xx.yml", source="""sources: - name: shop_xx__orders description: Orders change log @@ -93,7 +93,7 @@ def test_given_change_log_read_without_dedupe_macro_when_evaluating_then_reports test_case=RuleCase( description="staging model reads a change log directly", source=_RAW_CHANGE_LOG_READ, - path="models/staging/storefronts/shop_xx/base_shop_xx__orders.sql", + path="sql/models/staging/storefronts/shop_xx/base_shop_xx__orders.sql", files=(_SOURCES,), expected_finding_count=1, ), @@ -111,7 +111,7 @@ def test_given_append_only_source_when_evaluating_then_passes() -> None: source=_RAW_CHANGE_LOG_READ.replace("shop_xx__orders", "shop_xx__page_views").replace( "order_id", "event_id" ), - path="models/staging/storefronts/shop_xx/base_shop_xx__page_views.sql", + path="sql/models/staging/storefronts/shop_xx/base_shop_xx__page_views.sql", files=(_SOURCES,), expected_finding_count=0, ), @@ -126,7 +126,7 @@ def test_given_change_log_read_outside_staging_when_evaluating_then_passes() -> test_case=RuleCase( description="snapshots and other layers may read the full change log", source=_RAW_CHANGE_LOG_READ, - path="models/snapshots/snap_orders.sql", + path="sql/models/snapshots/snap_orders.sql", files=(_SOURCES,), expected_finding_count=0, ), diff --git a/benchmarks/duckshop-10k/duckshop10k/staging.py b/benchmarks/duckshop-10k/duckshop10k/staging.py index 6c1b751c07..2cb7dd537a 100644 --- a/benchmarks/duckshop-10k/duckshop10k/staging.py +++ b/benchmarks/duckshop-10k/duckshop10k/staging.py @@ -525,7 +525,7 @@ def stage_instance(project: Project, instance: Instance, folder: str) -> list[St ) staged.append(StagedTable(instance, archetype, stg.name, children, history)) project.write( - f"sources/{instance.code}.yml", + f"sql/sources/{instance.code}.yml", f"# Raw tables from {instance.label}.\nsources:\n" + "\n".join(yaml_entries) + "\n", ) return staged @@ -553,7 +553,7 @@ def stage_instance(project: Project, instance: Instance, folder: str) -> list[St def stage_collector(project: Project, instance: Instance, folder: str) -> tuple[str, list[str]]: source = f"{instance.code}__events" project.write( - f"sources/{instance.code}.yml", + f"sql/sources/{instance.code}.yml", "\n".join( [ f"# Raw events from the {instance.label} collector.", diff --git a/benchmarks/duckshop-10k/duckshop10k/stats.py b/benchmarks/duckshop-10k/duckshop10k/stats.py index 76d0c62cf0..4b3c2633d9 100644 --- a/benchmarks/duckshop-10k/duckshop10k/stats.py +++ b/benchmarks/duckshop-10k/duckshop10k/stats.py @@ -35,9 +35,9 @@ def layer_percent(self, layer: str) -> float: def _models(files: dict[str, str]) -> dict[str, tuple[str, str]]: return { - path.rsplit("/", 1)[1].removesuffix(".sql"): (path.split("/")[1], text) + path.rsplit("/", 1)[1].removesuffix(".sql"): (path.split("/")[2], text) for path, text in files.items() - if path.startswith("models/") and "/_sqlbuild/" not in path and path.endswith(".sql") + if path.startswith("sql/models/") and "/_sqlbuild/" not in path and path.endswith(".sql") } diff --git a/benchmarks/duckshop-10k/duckshop10k/tests_gen.py b/benchmarks/duckshop-10k/duckshop10k/tests_gen.py index 3054acc197..cef1785263 100644 --- a/benchmarks/duckshop-10k/duckshop10k/tests_gen.py +++ b/benchmarks/duckshop-10k/duckshop10k/tests_gen.py @@ -38,7 +38,7 @@ def _expected(names: list[str], rows: list[list[str]]) -> str: def _test_path(model: Model, behaviour: str) -> str: - folder = model.folder.removeprefix("models/") + folder = model.folder.removeprefix("sql/models/") return f"tests/unit/{folder}/test_{model.name}__{behaviour}.sql" diff --git a/benchmarks/duckshop-10k/duckshop10k/workload.py b/benchmarks/duckshop-10k/duckshop10k/workload.py index f39e47bd14..7358522c3f 100644 --- a/benchmarks/duckshop-10k/duckshop10k/workload.py +++ b/benchmarks/duckshop-10k/duckshop10k/workload.py @@ -22,9 +22,9 @@ #: Export assets per Python module, so discovery walks many modules. EXPORTS_PER_MODULE = 6 _TIMESTAMP = "TIMESTAMP_NTZ" -_INCREMENT_FOLDER = "models/intermediate/increments" -_EXPORT_PACKAGE = "python/exports" -_SHARED_MODULE = "python/shared/export_feed.py" +_INCREMENT_FOLDER = "sql/models/intermediate/increments" +_EXPORT_PACKAGE = "python/nodes/exports" +_SHARED_MODULE = "python/nodes/shared/export_feed.py" SHARED_EXPORT_HELPERS = '''"""What every export asset records about the relation it sent.""" @@ -149,5 +149,5 @@ def _export_module(folder: str, models: list[Model]) -> str: f'"""Exports of the {folder} marts to partner feeds."""\n\n' "from sqlbuild.assets import AssetContext, asset\n" "from sqlbuild.refs import model\n\n" - "from python.shared.export_feed import feed_metadata\n\n\n" + "\n\n".join(assets) + "from python.nodes.shared.export_feed import feed_metadata\n\n\n" + "\n\n".join(assets) ) diff --git a/benchmarks/duckshop-10k/tests/test_generator.py b/benchmarks/duckshop-10k/tests/test_generator.py index 6d616b795f..353b24ba1b 100644 --- a/benchmarks/duckshop-10k/tests/test_generator.py +++ b/benchmarks/duckshop-10k/tests/test_generator.py @@ -27,7 +27,7 @@ def models(files: dict[str, str]) -> dict[str, str]: return { path: text for path, text in files.items() - if path.startswith("models/") and "/_sqlbuild/" not in path and path.endswith(".sql") + if path.startswith("sql/models/") and "/_sqlbuild/" not in path and path.endswith(".sql") } @@ -100,14 +100,14 @@ def test_given_full_profile_when_scanning_then_uses_each_construct( def test_given_full_profile_when_scanning_then_writes_a_few_hundred_python_assets() -> None: files = full() - modules = [path for path in files if path.startswith("python/exports/")] + modules = [path for path in files if path.startswith("python/nodes/exports/")] assets = sum( files[path].count("\n@asset(") + files[path].startswith("@asset(") for path in modules ) assert 350 <= assets <= 500 assert len(modules) >= 40 - assert all("from python.shared.export_feed import" in files[path] for path in modules) + assert all("from python.nodes.shared.export_feed import" in files[path] for path in modules) def test_given_known_divergence_constructs_when_scanning_then_models_are_tagged() -> None: @@ -124,17 +124,24 @@ def test_given_generated_files_when_scanning_then_uses_only_synthetic_identifier def test_given_declarations_when_placing_then_follow_their_users() -> None: - assert _placement({"models/staging/a/x", "models/staging/b/y"}, "macros/sql") == ( - "models/staging/_sqlbuild/macros/sql" + assert _placement({"sql/models/staging/a/x", "sql/models/staging/b/y"}, "macros/sql") == ( + "sql/models/staging/_sqlbuild/macros/sql" + ) + assert ( + _placement({"sql/models/staging/a"}, "constants") + == "sql/models/staging/a/_sqlbuild/_constants" + ) + assert _placement({"sql/models/staging/a", "tests/unit/b"}, "macros/sql") == "sql/macros/sql" + assert _placement({"sql/models/staging/a", "sql/sources"}, "enums") == "sql/enums" + assert _placement({"sql/models/a", "sql/models/b"}, "enums") == "sql/enums" + assert _placement({"tests/unit/a", "tests/unit/b"}, "macros/sql") == ( + "tests/unit/_sqlbuild/macros/sql" ) - assert _placement({"models/staging/a"}, "constants") == "models/staging/a/_sqlbuild/_constants" - assert _placement({"models/staging/a", "tests/unit/b"}, "macros/sql") == "macros/sql" - assert _placement({"models/a", "models/b"}, "enums") == "enums" def test_given_full_profile_when_placing_then_every_used_declaration_is_written_once() -> None: files = full() - declared = [path for path in files if "/_sqlbuild/" in path or path.startswith("macros/")] + declared = [path for path in files if "/_sqlbuild/" in path or path.startswith("sql/macros/")] names = [Path(path).name for path in declared] assert len(names) == len(set(names)) diff --git a/benchmarks/duckshop/README.md b/benchmarks/duckshop/README.md index 0bd47022ec..def3facc79 100644 --- a/benchmarks/duckshop/README.md +++ b/benchmarks/duckshop/README.md @@ -18,7 +18,7 @@ Everything in it is synthetic: order references use a `DS-O-` prefix, email addr ```text benchmarks/duckshop/ -├── project/ the SQLBuild project (Snowflake adapter), with its data loaders in python/loaders/ +├── project/ the SQLBuild project (Snowflake adapter), with its data loaders in python/nodes/loaders/ ├── scripts/ tooling that is not part of the project: the construct census, cleanup SQL, the │ core-only copy and edge-case expectation capture ├── tests/ offline checks for the synthetic data loaders @@ -53,7 +53,7 @@ The core project, without the [edge-case area](#edge-cases): ## Tests and scenarios -`tests/unit/` mirrors `models/` and holds 266 core unit tests: +`tests/unit/` mirrors `sql/models/` and holds 266 core unit tests: - 260 model tests, including cursor-window tests on incremental models, a table-function mock, a macro mock, a fixture built by a test-only Python macro, an empty fixture for a contracted @@ -111,18 +111,18 @@ The edge-case area holds small, hand-picked cases for SQL whose results are easy wrong when translating Snowflake SQL or replaying it on another engine. It lives beside the core project and does not change it: -- models in `models/staging/edge_cases/`, `models/intermediate/edge_cases/` and - `models/marts/edge_cases/`, each tagged `edge_case`. The `XSQBRDUCK002` Rule fails a model in an +- models in `sql/models/staging/edge_cases/`, `sql/models/intermediate/edge_cases/` and + `sql/models/marts/edge_cases/`, each tagged `edge_case`. The `XSQBRDUCK002` Rule fails a model in an `edge_cases` folder without the tag, or a model with the tag outside one; - unit tests in the matching `tests/unit//edge_cases/` folders and scenarios in `tests/scenarios/edge_cases/`; -- raw `edge__*` sources in `sources/edge_cases.yml`, loaded by `python/loaders/edge_cases.py` from +- raw `edge__*` sources in `sql/sources/edge_cases.yml`, loaded by `python/nodes/loaders/edge_cases.py` from fixed rows that `data_scale` does not change, so core data and core expectations stay the same; -- Python functions in `functions/python/edge_*.py`, tagged `edge_case`, and their tests in +- Python functions in `sql/functions/python/edge_*.py`, tagged `edge_case`, and their tests in `tests/unit/functions/python/test_edge_*.sql`; -- a SQL table function, `functions/sql/edge_basket_lines_for.sql`, and a JavaScript function, +- a SQL table function, `sql/functions/sql/edge_basket_lines_for.sql`, and a JavaScript function, `edge_running_peaks`, that a pre-hook of `int_edge_basket_running_peaks` creates - (`models/intermediate/edge_cases/_sqlbuild/_hooks/sql/`) and SQLBuild does not declare. + (`sql/models/intermediate/edge_cases/_sqlbuild/_hooks/sql/`) and SQLBuild does not declare. It has 168 models (13 staging, 141 intermediate, 14 marts), 5 Python functions, a SQL table function, a hook-created JavaScript function, 193 unit tests and 4 scenarios, in nine groups: diff --git a/benchmarks/duckshop/RUNBOOK.md b/benchmarks/duckshop/RUNBOOK.md index 4ab8094084..bace68d248 100644 --- a/benchmarks/duckshop/RUNBOOK.md +++ b/benchmarks/duckshop/RUNBOOK.md @@ -178,7 +178,7 @@ sqb scenario test --target edge --select edge_cases ``` The build loads the `edge__*` sources from fixed rows that `data_scale` does not change, creates -the area's Python functions (`functions/python/edge_*.py`, tagged `edge_case`), then builds the edge +the area's Python functions (`sql/functions/python/edge_*.py`, tagged `edge_case`), then builds the edge models and runs their tests and audits. `fct_edge_delivery_events` is disabled and reports `skip: disabled` (see [Pending acceptance cases](#pending-acceptance-cases)). diff --git a/benchmarks/duckshop/edge_cases/changed_builds/models/customer_orders.sql b/benchmarks/duckshop/edge_cases/changed_builds/sql/models/customer_orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds/models/customer_orders.sql rename to benchmarks/duckshop/edge_cases/changed_builds/sql/models/customer_orders.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds/models/stg_customers.sql b/benchmarks/duckshop/edge_cases/changed_builds/sql/models/stg_customers.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds/models/stg_customers.sql rename to benchmarks/duckshop/edge_cases/changed_builds/sql/models/stg_customers.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds/models/stg_orders.sql b/benchmarks/duckshop/edge_cases/changed_builds/sql/models/stg_orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds/models/stg_orders.sql rename to benchmarks/duckshop/edge_cases/changed_builds/sql/models/stg_orders.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds/sources/raw.yml b/benchmarks/duckshop/edge_cases/changed_builds/sql/sources/raw.yml similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds/sources/raw.yml rename to benchmarks/duckshop/edge_cases/changed_builds/sql/sources/raw.yml diff --git a/benchmarks/duckshop/edge_cases/changed_builds_clone/models/dim_customers.sql b/benchmarks/duckshop/edge_cases/changed_builds_clone/sql/models/dim_customers.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_clone/models/dim_customers.sql rename to benchmarks/duckshop/edge_cases/changed_builds_clone/sql/models/dim_customers.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_clone/models/fact_orders.sql b/benchmarks/duckshop/edge_cases/changed_builds_clone/sql/models/fact_orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_clone/models/fact_orders.sql rename to benchmarks/duckshop/edge_cases/changed_builds_clone/sql/models/fact_orders.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_clone/models/orders_report.sql b/benchmarks/duckshop/edge_cases/changed_builds_clone/sql/models/orders_report.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_clone/models/orders_report.sql rename to benchmarks/duckshop/edge_cases/changed_builds_clone/sql/models/orders_report.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_reach/models/fct_revenue.sql b/benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/fct_revenue.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_reach/models/fct_revenue.sql rename to benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/fct_revenue.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_reach/models/int_orders.sql b/benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/int_orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_reach/models/int_orders.sql rename to benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/int_orders.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_reach/models/orders_export.sql b/benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/orders_export.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_reach/models/orders_export.sql rename to benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/orders_export.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_reach/models/rpt_pnl.sql b/benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/rpt_pnl.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_reach/models/rpt_pnl.sql rename to benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/rpt_pnl.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_reach/models/summary.sql b/benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/summary.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_reach/models/summary.sql rename to benchmarks/duckshop/edge_cases/changed_builds_reach/sql/models/summary.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_two_up/models/customer_sales.sql b/benchmarks/duckshop/edge_cases/changed_builds_two_up/sql/models/customer_sales.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_two_up/models/customer_sales.sql rename to benchmarks/duckshop/edge_cases/changed_builds_two_up/sql/models/customer_sales.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_udf/functions/sql/table_fn__customer_order_keys.sql b/benchmarks/duckshop/edge_cases/changed_builds_udf/sql/functions/sql/table_fn__customer_order_keys.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_udf/functions/sql/table_fn__customer_order_keys.sql rename to benchmarks/duckshop/edge_cases/changed_builds_udf/sql/functions/sql/table_fn__customer_order_keys.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_udf/functions/sql/table_fn__raw_customers_from.sql b/benchmarks/duckshop/edge_cases/changed_builds_udf/sql/functions/sql/table_fn__raw_customers_from.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_udf/functions/sql/table_fn__raw_customers_from.sql rename to benchmarks/duckshop/edge_cases/changed_builds_udf/sql/functions/sql/table_fn__raw_customers_from.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_udf/functions/sql/udf__order_key.sql b/benchmarks/duckshop/edge_cases/changed_builds_udf/sql/functions/sql/udf__order_key.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_udf/functions/sql/udf__order_key.sql rename to benchmarks/duckshop/edge_cases/changed_builds_udf/sql/functions/sql/udf__order_key.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_udf/functions/sql/udf__raw_customer_count.sql b/benchmarks/duckshop/edge_cases/changed_builds_udf/sql/functions/sql/udf__raw_customer_count.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_udf/functions/sql/udf__raw_customer_count.sql rename to benchmarks/duckshop/edge_cases/changed_builds_udf/sql/functions/sql/udf__raw_customer_count.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_udf/models/customer_count_via_udf.sql b/benchmarks/duckshop/edge_cases/changed_builds_udf/sql/models/customer_count_via_udf.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_udf/models/customer_count_via_udf.sql rename to benchmarks/duckshop/edge_cases/changed_builds_udf/sql/models/customer_count_via_udf.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_udf/models/customers_via_table_fn.sql b/benchmarks/duckshop/edge_cases/changed_builds_udf/sql/models/customers_via_table_fn.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_udf/models/customers_via_table_fn.sql rename to benchmarks/duckshop/edge_cases/changed_builds_udf/sql/models/customers_via_table_fn.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_udf/models/first_customer_order_keys.sql b/benchmarks/duckshop/edge_cases/changed_builds_udf/sql/models/first_customer_order_keys.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_udf/models/first_customer_order_keys.sql rename to benchmarks/duckshop/edge_cases/changed_builds_udf/sql/models/first_customer_order_keys.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_udf/models/stg_orders.sql b/benchmarks/duckshop/edge_cases/changed_builds_udf/sql/models/stg_orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_udf/models/stg_orders.sql rename to benchmarks/duckshop/edge_cases/changed_builds_udf/sql/models/stg_orders.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_unqualified/models/customers.sql b/benchmarks/duckshop/edge_cases/changed_builds_unqualified/sql/models/customers.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_unqualified/models/customers.sql rename to benchmarks/duckshop/edge_cases/changed_builds_unqualified/sql/models/customers.sql diff --git a/benchmarks/duckshop/edge_cases/changed_builds_unqualified/models/unqualified_customer_reader.sql b/benchmarks/duckshop/edge_cases/changed_builds_unqualified/sql/models/unqualified_customer_reader.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/changed_builds_unqualified/models/unqualified_customer_reader.sql rename to benchmarks/duckshop/edge_cases/changed_builds_unqualified/sql/models/unqualified_customer_reader.sql diff --git a/benchmarks/duckshop/edge_cases/deferred_reads/models/order_report.sql b/benchmarks/duckshop/edge_cases/deferred_reads/sql/models/order_report.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/deferred_reads/models/order_report.sql rename to benchmarks/duckshop/edge_cases/deferred_reads/sql/models/order_report.sql diff --git a/benchmarks/duckshop/edge_cases/deferred_reads/models/orders.sql b/benchmarks/duckshop/edge_cases/deferred_reads/sql/models/orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/deferred_reads/models/orders.sql rename to benchmarks/duckshop/edge_cases/deferred_reads/sql/models/orders.sql diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/loaders/partner.py b/benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/nodes/loaders/partner/loader.py similarity index 82% rename from benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/loaders/partner.py rename to benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/nodes/loaders/partner/loader.py index ec9332e1bb..1c0e0ace6a 100644 --- a/benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/loaders/partner.py +++ b/benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/nodes/loaders/partner/loader.py @@ -1,4 +1,4 @@ -from python.tasks.scoring import score_orders +from python.nodes.tasks.scoring.asset import score_orders from sqlbuild.loaders import loader diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/tasks/scoring.py b/benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/nodes/tasks/scoring/asset.py similarity index 100% rename from benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/tasks/scoring.py rename to benchmarks/duckshop/edge_cases/loaders/round_trip/project/python/nodes/tasks/scoring/asset.py diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/project/models/orders.sql b/benchmarks/duckshop/edge_cases/loaders/round_trip/project/sql/models/orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/loaders/round_trip/project/models/orders.sql rename to benchmarks/duckshop/edge_cases/loaders/round_trip/project/sql/models/orders.sql diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/project/models/scored_orders.sql b/benchmarks/duckshop/edge_cases/loaders/round_trip/project/sql/models/scored_orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/loaders/round_trip/project/models/scored_orders.sql rename to benchmarks/duckshop/edge_cases/loaders/round_trip/project/sql/models/scored_orders.sql diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/project/sources/partner.yml b/benchmarks/duckshop/edge_cases/loaders/round_trip/project/sql/sources/partner.yml similarity index 100% rename from benchmarks/duckshop/edge_cases/loaders/round_trip/project/sources/partner.yml rename to benchmarks/duckshop/edge_cases/loaders/round_trip/project/sql/sources/partner.yml diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/refusals/terminal_loader_reader.py b/benchmarks/duckshop/edge_cases/loaders/round_trip/refusals/terminal_loader_reader.py index 4a7c1bdc47..1111ed02c4 100644 --- a/benchmarks/duckshop/edge_cases/loaders/round_trip/refusals/terminal_loader_reader.py +++ b/benchmarks/duckshop/edge_cases/loaders/round_trip/refusals/terminal_loader_reader.py @@ -1,4 +1,4 @@ -from python.loaders.partner import partner_scores +from python.nodes.loaders.partner.loader import partner_scores from sqlbuild.assets import asset diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/ingress_gate/partner.py b/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/ingress_gate/partner.py index a3cf9f5bc7..b90f7740de 100644 --- a/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/ingress_gate/partner.py +++ b/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/ingress_gate/partner.py @@ -1,5 +1,5 @@ -from python.tasks.rates import fetch_rates -from python.tasks.scoring import score_orders +from python.nodes.tasks.rates.asset import fetch_rates +from python.nodes.tasks.scoring.asset import score_orders from sqlbuild.loaders import loader diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/ingress_gate/rates_loader.py b/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/ingress_gate/rates_loader.py index 4cc3351265..295c6a4704 100644 --- a/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/ingress_gate/rates_loader.py +++ b/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/ingress_gate/rates_loader.py @@ -1,4 +1,4 @@ -from python.tasks.rates import fetch_rates +from python.nodes.tasks.rates.asset import fetch_rates from sqlbuild.loaders import loader diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/transitive_gate/packaging.py b/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/transitive_gate/packaging.py index 7c3fecb226..412817e916 100644 --- a/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/transitive_gate/packaging.py +++ b/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/transitive_gate/packaging.py @@ -1,4 +1,4 @@ -from python.tasks.scoring import score_orders +from python.nodes.tasks.scoring.asset import score_orders from sqlbuild.assets import asset diff --git a/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/transitive_gate/partner.py b/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/transitive_gate/partner.py index 6054a3ee61..501542eb31 100644 --- a/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/transitive_gate/partner.py +++ b/benchmarks/duckshop/edge_cases/loaders/round_trip/variants/transitive_gate/partner.py @@ -1,4 +1,4 @@ -from python.tasks.packaging import package_scores +from python.nodes.tasks.packaging.asset import package_scores from sqlbuild.loaders import loader diff --git a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/jobs/orders_folder_job.toml b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/jobs/orders_folder_job.toml index 934ac24aae..9d818a8deb 100644 --- a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/jobs/orders_folder_job.toml +++ b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/jobs/orders_folder_job.toml @@ -1,4 +1,4 @@ # A folder, an expansion, a glob, an intersection's name, a job name and a repeated name: one named node. name = "orders_folder_job" description = "Selects the orders pipeline without listing it." -select = "models/orders +order_totals stg_* order_totals,tag:orders orders_listed_job order_totals" +select = "sql/models/orders +order_totals stg_* order_totals,tag:orders orders_listed_job order_totals" diff --git a/benchmarks/duckshop/edge_cases/named_selectors/models/orders/int_orders.sql b/benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/int_orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/named_selectors/models/orders/int_orders.sql rename to benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/int_orders.sql diff --git a/benchmarks/duckshop/edge_cases/named_selectors/models/orders/order_totals.sql b/benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/order_totals.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/named_selectors/models/orders/order_totals.sql rename to benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/order_totals.sql diff --git a/benchmarks/duckshop/edge_cases/named_selectors/models/orders/stg_orders.sql b/benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/stg_orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/named_selectors/models/orders/stg_orders.sql rename to benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/stg_orders.sql diff --git a/benchmarks/duckshop/edge_cases/named_selectors/models/orders/stg_payments.sql b/benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/stg_payments.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/named_selectors/models/orders/stg_payments.sql rename to benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/stg_payments.sql diff --git a/benchmarks/duckshop/edge_cases/orchestration/python_pipeline_carrier_sync.py b/benchmarks/duckshop/edge_cases/orchestration/python_pipeline_carrier_sync.py index 66b18447ad..7a5063c8c4 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/python_pipeline_carrier_sync.py +++ b/benchmarks/duckshop/edge_cases/orchestration/python_pipeline_carrier_sync.py @@ -1,6 +1,6 @@ """A task whose Python upstream another job builds, so a job group must order the two jobs.""" -from python.orders.partner_export.node import partner_orders_file +from python.nodes.orders.partner_export.node import partner_orders_file from sqlbuild.assets import asset diff --git a/benchmarks/duckshop/edge_cases/orchestration/semantic_identity.json b/benchmarks/duckshop/edge_cases/orchestration/semantic_identity.json index 5b1c5e0140..f6e49f745d 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/semantic_identity.json +++ b/benchmarks/duckshop/edge_cases/orchestration/semantic_identity.json @@ -1,54 +1,54 @@ { "files": { - "hooks/python/notifications.py": "from sqlbuild.hooks import hook\n\n@hook\ndef notify(ctx, channel):\n \"\"\"Notify support.\"\"\"\n return 'orders'\n", - "models/orders.sql": "MODEL (description 'Orders.', materialized 'table', pre_hooks [python('notify', channel: 'support')], columns (order_id (type INTEGER), amount (type BIGINT)));\nSELECT order_id, __udf(\"edge_next_quantity\")(amount) AS amount FROM __ref(\"stg_orders\")\n" + "sql/hooks/python/notifications.py": "from sqlbuild.hooks import hook\n\n@hook\ndef notify(ctx, channel):\n \"\"\"Notify support.\"\"\"\n return 'orders'\n", + "sql/models/orders.sql": "MODEL (description 'Orders.', materialized 'table', pre_hooks [python('notify', channel: 'support')], columns (order_id (type INTEGER), amount (type BIGINT)));\nSELECT order_id, __udf(\"edge_next_quantity\")(amount) AS amount FROM __ref(\"stg_orders\")\n" }, "cases": [ { "description": "layout does not change semantic identity", - "path": "models/orders.sql", + "path": "sql/models/orders.sql", "before": "SELECT order_id,", "after": "-- Order presentation\nSELECT\n order_id,", "expected_changed": [] }, { "description": "config changes with identical query", - "path": "models/orders.sql", + "path": "sql/models/orders.sql", "before": "materialized 'table'", "after": "materialized 'view'", "expected_changed": ["model:orders"] }, { "description": "hook code changes with identical query and config", - "path": "hooks/python/notifications.py", + "path": "sql/hooks/python/notifications.py", "before": "return 'orders'", "after": "return 'products'", "expected_changed": ["model:orders"] }, { "description": "referenced function changes consumer local identity", - "path": "functions/sql/edge_cases/edge_next_quantity.sql", + "path": "sql/functions/sql/edge_cases/edge_next_quantity.sql", "before": "quantity + 1", "after": "quantity + 3", "expected_changed": ["udf:edge_next_quantity", "model:orders"] }, { "description": "upstream query changes only its local identity", - "path": "models/stg_orders.sql", + "path": "sql/models/stg_orders.sql", "before": "CAST(5 AS INTEGER)", "after": "CAST(9 AS INTEGER)", "expected_changed": ["model:stg_orders"] }, { "description": "seed data changes its planner content identity", - "path": "seeds/edge_cases/edge_quantity_steps.csv", + "path": "sql/seeds/edge_cases/edge_quantity_steps.csv", "before": "\n7\n", "after": "\n11\n", "expected_changed": ["seed:edge_quantity_steps"] }, { "description": "CSV layout is not seed semantic data", - "path": "seeds/edge_cases/edge_quantity_steps.csv", + "path": "sql/seeds/edge_cases/edge_quantity_steps.csv", "before": "\n7\n", "after": "\n\"7\"\n", "expected_changed": [] diff --git a/benchmarks/duckshop/edge_cases/orchestration/shared_inline_audits.json b/benchmarks/duckshop/edge_cases/orchestration/shared_inline_audits.json index 410c38e177..af3c00db29 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/shared_inline_audits.json +++ b/benchmarks/duckshop/edge_cases/orchestration/shared_inline_audits.json @@ -2,8 +2,8 @@ "description": "Two models attach the same inline audit to a column of the same name, and the same explicitly named audit. Each attachment is its own snapshot node.", "files": { "sqlbuild_project.toml": "name = \"orders\"\nadapter = \"duckdb\"\n[connections.local]\ndatabase = \"warehouse.duckdb\"\n[targets.development]\nschema = \"main\"\n", - "models/orders.sql": "MODEL (\n materialized table,\n description \"Synthetic rows.\",\n columns (id (audits [not_null, unique, accepted_values (name \"id_known\", values [1, 2])])),\n);\n\nSELECT 1 AS id\n", - "models/customers.sql": "MODEL (\n materialized table,\n description \"Synthetic rows.\",\n columns (id (audits [not_null, accepted_values (name \"id_known\", values [1, 2])])),\n);\n\nSELECT 2 AS id\n" + "sql/models/orders.sql": "MODEL (\n materialized table,\n description \"Synthetic rows.\",\n columns (id (audits [not_null, unique, accepted_values (name \"id_known\", values [1, 2])])),\n);\n\nSELECT 1 AS id\n", + "sql/models/customers.sql": "MODEL (\n materialized table,\n description \"Synthetic rows.\",\n columns (id (audits [not_null, accepted_values (name \"id_known\", values [1, 2])])),\n);\n\nSELECT 2 AS id\n" }, "expected_audits": [ "audit:id_known:model:customers:id", diff --git a/benchmarks/duckshop/edge_cases/performance_rules/expected_findings.json b/benchmarks/duckshop/edge_cases/performance_rules/expected_findings.json index 1370a39d58..d9b00ea96f 100644 --- a/benchmarks/duckshop/edge_cases/performance_rules/expected_findings.json +++ b/benchmarks/duckshop/edge_cases/performance_rules/expected_findings.json @@ -1,7 +1,7 @@ { "findings": [ - ["SQBRPERFORMANCE101", "models/line_options.sql", 7, 3], - ["SQBRPERFORMANCE102", "models/order_lines_enriched.sql", 12, 3] + ["SQBRPERFORMANCE101", "sql/models/line_options.sql", 7, 3], + ["SQBRPERFORMANCE102", "sql/models/order_lines_enriched.sql", 12, 3] ], "skipped_note": "SQBRPERFORMANCE102 skipped 1 model without column lineage or inferred types" } diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/line_options.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/line_options.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/line_options.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/line_options.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/line_options_trimmed.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/line_options_trimmed.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/line_options_trimmed.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/line_options_trimmed.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/order_exports.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_exports.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/order_exports.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_exports.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/order_headers.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_headers.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/order_headers.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_headers.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/order_headers_dated.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_headers_dated.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/order_headers_dated.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_headers_dated.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/order_lines.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_lines.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/order_lines.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_lines.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/order_lines_customer.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_lines_customer.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/order_lines_customer.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_lines_customer.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/order_lines_enriched.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_lines_enriched.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/order_lines_enriched.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_lines_enriched.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/order_payload_dated.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_payload_dated.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/order_payload_dated.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_payload_dated.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/order_skus.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_skus.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/order_skus.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/order_skus.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/orders.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/orders.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/orders.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/orders.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/shop__mart__order_lines.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/shop__mart__order_lines.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/shop__mart__order_lines.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/shop__mart__order_lines.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/models/shop__mart_v__order_lines.sql b/benchmarks/duckshop/edge_cases/performance_rules/sql/models/shop__mart_v__order_lines.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/performance_rules/models/shop__mart_v__order_lines.sql rename to benchmarks/duckshop/edge_cases/performance_rules/sql/models/shop__mart_v__order_lines.sql diff --git a/benchmarks/duckshop/edge_cases/performance_rules/sqlbuild_project.toml b/benchmarks/duckshop/edge_cases/performance_rules/sqlbuild_project.toml index b5993670d5..c0c7e95cc5 100644 --- a/benchmarks/duckshop/edge_cases/performance_rules/sqlbuild_project.toml +++ b/benchmarks/duckshop/edge_cases/performance_rules/sqlbuild_project.toml @@ -1,3 +1,4 @@ +extra_paths = ["expected_findings.json"] name = "orders" adapter = "snowflake" diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_export/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_export/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_export/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_export/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_export/node.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_export/asset.py similarity index 82% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_export/node.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_export/asset.py index bf18e586e2..3aeb0a32ae 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_export/node.py +++ b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_export/asset.py @@ -1,6 +1,7 @@ """Export shipped orders to the carrier.""" -from python.fulfillment.shipment_export.main import main +from python.nodes.fulfillment.shipment_export.main import main + from sqlbuild.assets import AssetContext, asset from sqlbuild.executor.python_nodes.models import PythonNodeResult diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_export/main.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_export/main.py similarity index 88% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_export/main.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_export/main.py index 7664c575fa..4c1a87ff10 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_export/main.py +++ b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_export/main.py @@ -1,6 +1,7 @@ """Write each shipped order as one carrier line.""" -from python.utils.currency import amounts +from python.nodes.utils.currency import amounts + from sqlbuild.assets import AssetContext from sqlbuild.executor.python_nodes.models import PythonNodeResult diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_quality/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_quality/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_quality/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_quality/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_quality/factories.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_quality/factories.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/python/fulfillment/shipment_quality/factories.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/fulfillment/shipment_quality/factories.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/utils/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/utils/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/python/utils/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/utils/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/python/utils/currency/amounts.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/utils/currency/amounts.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/python/utils/currency/amounts.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/nodes/utils/currency/amounts.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/providers/carrier_api/constants.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/providers/carrier_api/constants.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/providers/carrier_api/constants.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/providers/carrier_api/constants.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/providers/carrier_api/provider.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/providers/carrier_api/provider.py similarity index 84% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/providers/carrier_api/provider.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/python/providers/carrier_api/provider.py index 86672d2b3e..82916c836c 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/conforming/providers/carrier_api/provider.py +++ b/benchmarks/duckshop/edge_cases/python_rules/conforming/python/providers/carrier_api/provider.py @@ -1,6 +1,6 @@ """Carrier pickup client.""" -from providers.carrier_api.constants import MINIMUM_CHARGE_CENTS +from python.providers.carrier_api.constants import MINIMUM_CHARGE_CENTS from sqlbuild.providers import Provider diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/audits/generic/expression_is_true.sql b/benchmarks/duckshop/edge_cases/python_rules/conforming/sql/audits/generic/expression_is_true.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/audits/generic/expression_is_true.sql rename to benchmarks/duckshop/edge_cases/python_rules/conforming/sql/audits/generic/expression_is_true.sql diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/hooks/python/notify.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/sql/hooks/python/notify.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/hooks/python/notify.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/sql/hooks/python/notify.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/models/shipments.sql b/benchmarks/duckshop/edge_cases/python_rules/conforming/sql/models/shipments.sql similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/models/shipments.sql rename to benchmarks/duckshop/edge_cases/python_rules/conforming/sql/models/shipments.sql diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/utils/currency/_test_types.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/nodes/utils/currency/_test_types.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/utils/currency/_test_types.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/nodes/utils/currency/_test_types.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/utils/currency/test_amounts.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/nodes/utils/currency/test_amounts.py similarity index 83% rename from benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/utils/currency/test_amounts.py rename to benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/nodes/utils/currency/test_amounts.py index ce9ebf710e..935d4a86b4 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/utils/currency/test_amounts.py +++ b/benchmarks/duckshop/edge_cases/python_rules/conforming/tests/python/nodes/utils/currency/test_amounts.py @@ -1,8 +1,8 @@ """Tests for carrier money formatting.""" import pytest -from python.utils.currency import amounts -from tests.python.utils.currency._test_types import CentsTextTestCase +from python.nodes.utils.currency import amounts +from tests.python.nodes.utils.currency._test_types import CentsTextTestCase @pytest.mark.parametrize( diff --git a/benchmarks/duckshop/edge_cases/python_rules/expected_findings.json b/benchmarks/duckshop/edge_cases/python_rules/expected_findings.json index dc6170c9ed..efc4811ccc 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/expected_findings.json +++ b/benchmarks/duckshop/edge_cases/python_rules/expected_findings.json @@ -1,7 +1,6 @@ { "select": ["SQBRPYTHON", "SQBRPYTHON306"], "findings": [ - ["SQBRPYTHON101", "hooks/python/alert.py", 4, 11], ["SQBRPYTHON301", "orchestration/sensors/inventory/_helpers/feed_window.py", 3, 1], ["SQBRPYTHON017", "orchestration/sensors/inventory/_helpers/feed_window.py", 3, 43], ["SQBRPYTHON017", "orchestration/sensors/inventory/_lib/age.py", 1, 1], @@ -9,42 +8,43 @@ ["SQBRPYTHON019", "orchestration/sensors/stock_feed.py", 3, 8], ["SQBRPYTHON018", "orchestration/sensors/stock_feed.py", 7, 1], ["SQBRPYTHON020", "orchestration/sensors/stock_feed.py", 14, 5], - ["SQBRPYTHON015", "providers/carrier_api/provider.py", 3, 8], - ["SQBRPYTHON014", "providers/carrier_api/provider.py", 8, 5], - ["SQBRPYTHON013", "providers/stock_feed.py", 1, 1], - ["SQBRPYTHON613", "python/inventory/__init__.py", 1, 1], - ["SQBRPYTHON002", "python/inventory/common/__init__.py", 1, 1], - ["SQBRPYTHON306", "python/inventory/common/stock.py", 4, 1], - ["SQBRPYTHON305", "python/inventory/main/publish.py", 1, 1], - ["SQBRPYTHON306", "python/inventory/main/publish.py", 4, 1], - ["SQBRPYTHON614", "python/inventory/replenishment.py", 1, 1], - ["SQBRPYTHON012", "python/inventory/replenishment.py", 7, 5], - ["SQBRPYTHON306", "python/inventory/restock/_helpers/thresholds.py", 6, 1], - ["SQBRPYTHON306", "python/inventory/restock/_helpers/thresholds.py", 9, 1], - ["SQBRPYTHON306", "python/inventory/restock/constants.py", 5, 1], - ["SQBRPYTHON022", "python/inventory/restock/constants.py", 5, 38], - ["SQBRPYTHON617", "python/inventory/restock/main.py", 1, 1], - ["SQBRPYTHON306", "python/inventory/restock/main.py", 4, 1], - ["SQBRPYTHON306", "python/inventory/restock/main.py", 9, 1], - ["SQBRPYTHON003", "python/inventory/stock_count/node.py", 1, 1], - ["SQBRPYTHON008", "python/inventory/stock_count/node.py", 3, 62], - ["SQBRPYTHON004", "python/inventory/stock_count/node.py", 7, 1], - ["SQBRPYTHON605", "python/inventory/stock_count/node.py", 7, 1], - ["SQBRPYTHON005", "python/inventory/stock_count/node.py", 11, 5], - ["SQBRPYTHON007", "python/inventory/stock_count/node.py", 11, 5], - ["SQBRPYTHON011", "python/inventory/stock_count/node.py", 11, 5], - ["SQBRPYTHON001", "python/report.py", 1, 1], - ["SQBRPYTHON614", "python/report.py", 1, 1], - ["SQBRPYTHON021", "tests/python/inventory/test_restock_window.py", 1, 1], - ["SQBRPYTHON710", "tests/python/inventory/test_restock_window.py", 1, 1], - ["SQBRPYTHON722", "tests/python/inventory/test_restock_window.py", 6, 35], - ["SQBRPYTHON712", "tests/python/inventory/test_restock_window.py", 7, 1], - ["SQBRPYTHON714", "tests/python/inventory/test_restock_window.py", 7, 1], - ["SQBRPYTHON715", "tests/python/inventory/test_restock_window.py", 7, 1], - ["SQBRPYTHON716", "tests/python/inventory/test_restock_window.py", 7, 1], - ["SQBRPYTHON718", "tests/python/inventory/test_restock_window.py", 7, 1], - ["SQBRPYTHON719", "tests/python/inventory/test_restock_window.py", 7, 1], - ["SQBRPYTHON724", "tests/python/inventory/test_restock_window.py", 7, 1], - ["SQBRPYTHON704", "tests/python/inventory/test_restock_window.py", 9, 5] + ["SQBRPYTHON613", "python/nodes/inventory/__init__.py", 1, 1], + ["SQBRPYTHON614", "python/nodes/inventory/asset.py", 1, 1], + ["SQBRPYTHON012", "python/nodes/inventory/asset.py", 7, 5], + ["SQBRPYTHON002", "python/nodes/inventory/common/__init__.py", 1, 1], + ["SQBRPYTHON306", "python/nodes/inventory/common/stock.py", 4, 1], + ["SQBRPYTHON305", "python/nodes/inventory/main/publish.py", 1, 1], + ["SQBRPYTHON306", "python/nodes/inventory/main/publish.py", 4, 1], + ["SQBRPYTHON306", "python/nodes/inventory/restock/_helpers/thresholds.py", 6, 1], + ["SQBRPYTHON306", "python/nodes/inventory/restock/_helpers/thresholds.py", 9, 1], + ["SQBRPYTHON306", "python/nodes/inventory/restock/constants.py", 5, 1], + ["SQBRPYTHON022", "python/nodes/inventory/restock/constants.py", 5, 38], + ["SQBRPYTHON617", "python/nodes/inventory/restock/main.py", 1, 1], + ["SQBRPYTHON306", "python/nodes/inventory/restock/main.py", 4, 1], + ["SQBRPYTHON306", "python/nodes/inventory/restock/main.py", 9, 1], + ["SQBRPYTHON003", "python/nodes/inventory/stock_count/asset.py", 1, 1], + ["SQBRPYTHON008", "python/nodes/inventory/stock_count/asset.py", 3, 62], + ["SQBRPYTHON004", "python/nodes/inventory/stock_count/asset.py", 7, 1], + ["SQBRPYTHON605", "python/nodes/inventory/stock_count/asset.py", 7, 1], + ["SQBRPYTHON005", "python/nodes/inventory/stock_count/asset.py", 11, 5], + ["SQBRPYTHON007", "python/nodes/inventory/stock_count/asset.py", 11, 5], + ["SQBRPYTHON011", "python/nodes/inventory/stock_count/asset.py", 11, 5], + ["SQBRPYTHON001", "python/nodes/report.py", 1, 1], + ["SQBRPYTHON614", "python/nodes/report.py", 1, 1], + ["SQBRPYTHON015", "python/providers/carrier_api/provider.py", 3, 8], + ["SQBRPYTHON014", "python/providers/carrier_api/provider.py", 8, 5], + ["SQBRPYTHON013", "python/providers/stock_feed.py", 1, 1], + ["SQBRPYTHON101", "sql/hooks/python/alert.py", 4, 11], + ["SQBRPYTHON021", "tests/python/nodes/inventory/test_restock_window.py", 1, 1], + ["SQBRPYTHON710", "tests/python/nodes/inventory/test_restock_window.py", 1, 1], + ["SQBRPYTHON722", "tests/python/nodes/inventory/test_restock_window.py", 6, 35], + ["SQBRPYTHON712", "tests/python/nodes/inventory/test_restock_window.py", 7, 1], + ["SQBRPYTHON714", "tests/python/nodes/inventory/test_restock_window.py", 7, 1], + ["SQBRPYTHON715", "tests/python/nodes/inventory/test_restock_window.py", 7, 1], + ["SQBRPYTHON716", "tests/python/nodes/inventory/test_restock_window.py", 7, 1], + ["SQBRPYTHON718", "tests/python/nodes/inventory/test_restock_window.py", 7, 1], + ["SQBRPYTHON719", "tests/python/nodes/inventory/test_restock_window.py", 7, 1], + ["SQBRPYTHON724", "tests/python/nodes/inventory/test_restock_window.py", 7, 1], + ["SQBRPYTHON704", "tests/python/nodes/inventory/test_restock_window.py", 9, 5] ] } diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/orchestration/sensors/stock_feed.py b/benchmarks/duckshop/edge_cases/python_rules/violations/orchestration/sensors/stock_feed.py index 7a4ce09da2..01b2924ee8 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/violations/orchestration/sensors/stock_feed.py +++ b/benchmarks/duckshop/edge_cases/python_rules/violations/orchestration/sensors/stock_feed.py @@ -1,6 +1,6 @@ """A sensor outside a domain folder that documents itself twice and reads a node module.""" -import python.report +import python.nodes.report from sqlbuild.orchestration import SensorContext, SkipReason, sensor diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/providers/stock_feed.py b/benchmarks/duckshop/edge_cases/python_rules/violations/providers/stock_feed.py deleted file mode 100644 index f12b5b36cc..0000000000 --- a/benchmarks/duckshop/edge_cases/python_rules/violations/providers/stock_feed.py +++ /dev/null @@ -1 +0,0 @@ -"""A provider module directly under providers/.""" diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/replenishment.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/asset.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/replenishment.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/asset.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/common/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/common/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/common/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/common/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/common/stock.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/common/stock.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/common/stock.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/common/stock.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/main/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/main/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/main/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/main/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/main/publish.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/main/publish.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/main/publish.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/main/publish.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/_helpers/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/_helpers/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/_helpers/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/_helpers/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/_helpers/thresholds.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/_helpers/thresholds.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/_helpers/thresholds.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/_helpers/thresholds.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/constants.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/constants.py similarity index 63% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/constants.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/constants.py index 67efb1a4b0..49f2ca3560 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/constants.py +++ b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/constants.py @@ -1,5 +1,5 @@ """Restock thresholds per warehouse.""" -from python.inventory.restock._helpers import thresholds +from python.nodes.inventory.restock._helpers import thresholds RESTOCK_THRESHOLDS: dict[str, int] = thresholds.load_thresholds() diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/main.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/main.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/restock/main.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/restock/main.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/stock_count/__init__.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/stock_count/__init__.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/stock_count/__init__.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/stock_count/__init__.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/stock_count/node.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/stock_count/asset.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/python/inventory/stock_count/node.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/inventory/stock_count/asset.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/report.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/report.py new file mode 100644 index 0000000000..fbc7d99eed --- /dev/null +++ b/benchmarks/duckshop/edge_cases/python_rules/violations/python/nodes/report.py @@ -0,0 +1 @@ +"""A module directly under python/nodes/.""" diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/providers/carrier_api/provider.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/providers/carrier_api/provider.py similarity index 92% rename from benchmarks/duckshop/edge_cases/python_rules/violations/providers/carrier_api/provider.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/python/providers/carrier_api/provider.py index 4a3dedd1d0..f32058fd38 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/violations/providers/carrier_api/provider.py +++ b/benchmarks/duckshop/edge_cases/python_rules/violations/python/providers/carrier_api/provider.py @@ -1,6 +1,6 @@ """Carrier pickup client.""" -import python.report +import python.nodes.report from sqlbuild.providers import Provider diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/providers/stock_feed.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/providers/stock_feed.py new file mode 100644 index 0000000000..bfea9bf2b0 --- /dev/null +++ b/benchmarks/duckshop/edge_cases/python_rules/violations/python/providers/stock_feed.py @@ -0,0 +1 @@ +"""A provider module directly under python/providers/.""" diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/python/report.py b/benchmarks/duckshop/edge_cases/python_rules/violations/python/report.py deleted file mode 100644 index 103fc50e75..0000000000 --- a/benchmarks/duckshop/edge_cases/python_rules/violations/python/report.py +++ /dev/null @@ -1 +0,0 @@ -"""A module directly under python/.""" diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/hooks/python/alert.py b/benchmarks/duckshop/edge_cases/python_rules/violations/sql/hooks/python/alert.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/hooks/python/alert.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/sql/hooks/python/alert.py diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/tests/python/inventory/test_restock_window.py b/benchmarks/duckshop/edge_cases/python_rules/violations/tests/python/nodes/inventory/test_restock_window.py similarity index 100% rename from benchmarks/duckshop/edge_cases/python_rules/violations/tests/python/inventory/test_restock_window.py rename to benchmarks/duckshop/edge_cases/python_rules/violations/tests/python/nodes/inventory/test_restock_window.py diff --git a/benchmarks/duckshop/project/python/loaders/catalogue.py b/benchmarks/duckshop/project/python/loaders/catalogue.py deleted file mode 100644 index 2bf8265a3e..0000000000 --- a/benchmarks/duckshop/project/python/loaders/catalogue.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Loaders for the synthetic catalogue source tables, generated in python.loaders._catalogue.""" - -from python.loaders._registry import load - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -@loader -def catalogue__brands(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__brands") - - -@loader -def catalogue__categories(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__categories") - - -@loader -def catalogue__products(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__products") - - -@loader -def catalogue__product_variants(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__product_variants") - - -@loader -def catalogue__price_lists(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__price_lists") - - -@loader -def catalogue__product_media(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__product_media") - - -@loader -def catalogue__bundles(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__bundles") - - -@loader -def catalogue__bundle_components(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__bundle_components") - - -@loader -def catalogue__suppliers(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__suppliers") - - -@loader -def catalogue__supplier_costs(ctx: LoaderContext) -> object: - return load(ctx, "catalogue__supplier_costs") diff --git a/benchmarks/duckshop/project/python/loaders/clickstream.py b/benchmarks/duckshop/project/python/loaders/clickstream.py deleted file mode 100644 index f7e201c7de..0000000000 --- a/benchmarks/duckshop/project/python/loaders/clickstream.py +++ /dev/null @@ -1,31 +0,0 @@ -"""Loaders for the synthetic clickstream source tables, generated in python.loaders._clickstream.""" - -from python.loaders._registry import load - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -@loader -def clickstream__web_events(ctx: LoaderContext) -> object: - return load(ctx, "clickstream__web_events") - - -@loader -def clickstream__app_events(ctx: LoaderContext) -> object: - return load(ctx, "clickstream__app_events") - - -@loader -def clickstream__search_queries(ctx: LoaderContext) -> object: - return load(ctx, "clickstream__search_queries") - - -@loader -def clickstream__email_events(ctx: LoaderContext) -> object: - return load(ctx, "clickstream__email_events") - - -@loader -def clickstream__experiment_assignments(ctx: LoaderContext) -> object: - return load(ctx, "clickstream__experiment_assignments") diff --git a/benchmarks/duckshop/project/python/loaders/edge_cases.py b/benchmarks/duckshop/project/python/loaders/edge_cases.py deleted file mode 100644 index 9cbbf862b9..0000000000 --- a/benchmarks/duckshop/project/python/loaders/edge_cases.py +++ /dev/null @@ -1,92 +0,0 @@ -"""Loaders for the edge-case area's raw tables, with the fixed rows in python.loaders._edge_cases. - -These rows are hand-picked edge values, not generated volume: `data_scale` does not change them, -and they never touch the core tables, so core outputs and expectations stay the same. -""" - -from python.loaders._edge_cases import DELIVERY_BATCH_VAR, TABLES, delivery_updates -from python.loaders._writer import statements - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -def _load(ctx: LoaderContext, source_name: str) -> object: - rows = TABLES[source_name] - for sql in statements(ctx.destination, source_name, rows): - ctx.execute_sql(sql) - return ctx.result(metadata={"rows": len(rows)}) - - -@loader -def edge__partner_payloads(ctx: LoaderContext) -> object: - return _load(ctx, "edge__partner_payloads") - - -@loader -def edge__gateway_callbacks(ctx: LoaderContext) -> object: - return _load(ctx, "edge__gateway_callbacks") - - -@loader -def edge__price_windows(ctx: LoaderContext) -> object: - return _load(ctx, "edge__price_windows") - - -@loader -def edge__customer_profiles(ctx: LoaderContext) -> object: - return _load(ctx, "edge__customer_profiles") - - -@loader -def edge__ledger_entries(ctx: LoaderContext) -> object: - return _load(ctx, "edge__ledger_entries") - - -@loader -def edge__ticket_notes(ctx: LoaderContext) -> object: - return _load(ctx, "edge__ticket_notes") - - -@loader -def edge__partner_listings(ctx: LoaderContext) -> object: - return _load(ctx, "edge__partner_listings") - - -@loader -def edge__basket_lines(ctx: LoaderContext) -> object: - return _load(ctx, "edge__basket_lines") - - -@loader -def edge__date_texts(ctx: LoaderContext) -> object: - return _load(ctx, "edge__date_texts") - - -@loader -def edge__amount_checks(ctx: LoaderContext) -> object: - return _load(ctx, "edge__amount_checks") - - -@loader -def edge__variant_values(ctx: LoaderContext) -> object: - return _load(ctx, "edge__variant_values") - - -@loader -def edge__category_links(ctx: LoaderContext) -> object: - return _load(ctx, "edge__category_links") - - -@loader -def edge__supplier_notes(ctx: LoaderContext) -> object: - return _load(ctx, "edge__supplier_notes") - - -@loader -def edge__delivery_updates(ctx: LoaderContext) -> object: - batch = int(ctx.vars.get(DELIVERY_BATCH_VAR, 2)) # type: ignore[call-overload] - rows = delivery_updates(batch) - for sql in statements(ctx.destination, "edge__delivery_updates", rows): - ctx.execute_sql(sql) - return ctx.result(metadata={"rows": len(rows), "batch": batch}) diff --git a/benchmarks/duckshop/project/python/loaders/finance.py b/benchmarks/duckshop/project/python/loaders/finance.py deleted file mode 100644 index 35a1ffc738..0000000000 --- a/benchmarks/duckshop/project/python/loaders/finance.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Loaders for the synthetic finance source tables, generated in python.loaders._finance.""" - -from python.loaders._registry import load - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -@loader -def finance__invoices(ctx: LoaderContext) -> object: - return load(ctx, "finance__invoices") - - -@loader -def finance__ledger_entries(ctx: LoaderContext) -> object: - return load(ctx, "finance__ledger_entries") - - -@loader -def finance__payouts(ctx: LoaderContext) -> object: - return load(ctx, "finance__payouts") - - -@loader -def finance__tax_rates(ctx: LoaderContext) -> object: - return load(ctx, "finance__tax_rates") - - -@loader -def finance__chargebacks(ctx: LoaderContext) -> object: - return load(ctx, "finance__chargebacks") - - -@loader -def finance__settlement_reports(ctx: LoaderContext) -> object: - return load(ctx, "finance__settlement_reports") diff --git a/benchmarks/duckshop/project/python/loaders/fulfilment.py b/benchmarks/duckshop/project/python/loaders/fulfilment.py deleted file mode 100644 index fb28e6cc24..0000000000 --- a/benchmarks/duckshop/project/python/loaders/fulfilment.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Loaders for the synthetic fulfilment source tables, generated in python.loaders._fulfilment.""" - -from python.loaders._registry import load - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -@loader -def fulfilment__shipments(ctx: LoaderContext) -> object: - return load(ctx, "fulfilment__shipments") - - -@loader -def fulfilment__shipment_packages(ctx: LoaderContext) -> object: - return load(ctx, "fulfilment__shipment_packages") - - -@loader -def fulfilment__carrier_webhooks(ctx: LoaderContext) -> object: - return load(ctx, "fulfilment__carrier_webhooks") - - -@loader -def fulfilment__returns(ctx: LoaderContext) -> object: - return load(ctx, "fulfilment__returns") - - -@loader -def fulfilment__return_inspections(ctx: LoaderContext) -> object: - return load(ctx, "fulfilment__return_inspections") - - -@loader -def fulfilment__carrier_rate_cards(ctx: LoaderContext) -> object: - return load(ctx, "fulfilment__carrier_rate_cards") - - -@loader -def fulfilment__delivery_slots(ctx: LoaderContext) -> object: - return load(ctx, "fulfilment__delivery_slots") - - -@loader -def fulfilment__pick_tasks(ctx: LoaderContext) -> object: - return load(ctx, "fulfilment__pick_tasks") - - -@loader -def fulfilment__delivery_exceptions(ctx: LoaderContext) -> object: - return load(ctx, "fulfilment__delivery_exceptions") diff --git a/benchmarks/duckshop/project/python/loaders/growth.py b/benchmarks/duckshop/project/python/loaders/growth.py deleted file mode 100644 index 94af00577d..0000000000 --- a/benchmarks/duckshop/project/python/loaders/growth.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Loaders for the synthetic growth source tables, generated in python.loaders._growth.""" - -from python.loaders._registry import load - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -@loader -def growth__campaigns(ctx: LoaderContext) -> object: - return load(ctx, "growth__campaigns") - - -@loader -def growth__campaign_spend(ctx: LoaderContext) -> object: - return load(ctx, "growth__campaign_spend") - - -@loader -def growth__affiliate_conversions(ctx: LoaderContext) -> object: - return load(ctx, "growth__affiliate_conversions") - - -@loader -def growth__referral_invites(ctx: LoaderContext) -> object: - return load(ctx, "growth__referral_invites") - - -@loader -def growth__newsletter_subscriptions(ctx: LoaderContext) -> object: - return load(ctx, "growth__newsletter_subscriptions") - - -@loader -def growth__survey_responses(ctx: LoaderContext) -> object: - return load(ctx, "growth__survey_responses") - - -@loader -def growth__influencer_posts(ctx: LoaderContext) -> object: - return load(ctx, "growth__influencer_posts") diff --git a/benchmarks/duckshop/project/python/loaders/inventory.py b/benchmarks/duckshop/project/python/loaders/inventory.py deleted file mode 100644 index 064aa2b7aa..0000000000 --- a/benchmarks/duckshop/project/python/loaders/inventory.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Loaders for the synthetic inventory source tables, generated in python.loaders._inventory.""" - -from python.loaders._registry import load - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -@loader -def inventory__warehouses(ctx: LoaderContext) -> object: - return load(ctx, "inventory__warehouses") - - -@loader -def inventory__stock_movements(ctx: LoaderContext) -> object: - return load(ctx, "inventory__stock_movements") - - -@loader -def inventory__stock_counts(ctx: LoaderContext) -> object: - return load(ctx, "inventory__stock_counts") - - -@loader -def inventory__purchase_orders(ctx: LoaderContext) -> object: - return load(ctx, "inventory__purchase_orders") - - -@loader -def inventory__po_receipts(ctx: LoaderContext) -> object: - return load(ctx, "inventory__po_receipts") - - -@loader -def inventory__stock_transfers(ctx: LoaderContext) -> object: - return load(ctx, "inventory__stock_transfers") - - -@loader -def inventory__stock_reservations(ctx: LoaderContext) -> object: - return load(ctx, "inventory__stock_reservations") - - -@loader -def inventory__bin_locations(ctx: LoaderContext) -> object: - return load(ctx, "inventory__bin_locations") diff --git a/benchmarks/duckshop/project/python/loaders/partners.py b/benchmarks/duckshop/project/python/loaders/partners.py deleted file mode 100644 index 0ec8dfc147..0000000000 --- a/benchmarks/duckshop/project/python/loaders/partners.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Loaders for the synthetic partners source tables, generated in python.loaders._partners.""" - -from python.loaders._registry import load - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -@loader -def partners__partner_orders(ctx: LoaderContext) -> object: - return load(ctx, "partners__partner_orders") - - -@loader -def partners__partner_listings(ctx: LoaderContext) -> object: - return load(ctx, "partners__partner_listings") - - -@loader -def partners__partner_settlements(ctx: LoaderContext) -> object: - return load(ctx, "partners__partner_settlements") diff --git a/benchmarks/duckshop/project/python/loaders/storefront.py b/benchmarks/duckshop/project/python/loaders/storefront.py deleted file mode 100644 index 4ca5a0e4aa..0000000000 --- a/benchmarks/duckshop/project/python/loaders/storefront.py +++ /dev/null @@ -1,106 +0,0 @@ -"""Loaders for the synthetic storefront source tables, generated in python.loaders._storefront.""" - -from python.loaders._registry import load - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -@loader -def storefront__customers(ctx: LoaderContext) -> object: - return load(ctx, "storefront__customers") - - -@loader -def storefront__customer_addresses(ctx: LoaderContext) -> object: - return load(ctx, "storefront__customer_addresses") - - -@loader -def storefront__customer_consents(ctx: LoaderContext) -> object: - return load(ctx, "storefront__customer_consents") - - -@loader -def storefront__loyalty_accounts(ctx: LoaderContext) -> object: - return load(ctx, "storefront__loyalty_accounts") - - -@loader -def storefront__loyalty_ledger(ctx: LoaderContext) -> object: - return load(ctx, "storefront__loyalty_ledger") - - -@loader -def storefront__wishlists(ctx: LoaderContext) -> object: - return load(ctx, "storefront__wishlists") - - -@loader -def storefront__gift_cards(ctx: LoaderContext) -> object: - return load(ctx, "storefront__gift_cards") - - -@loader -def storefront__gift_card_transactions(ctx: LoaderContext) -> object: - return load(ctx, "storefront__gift_card_transactions") - - -@loader -def storefront__orders(ctx: LoaderContext) -> object: - return load(ctx, "storefront__orders") - - -@loader -def storefront__order_lines(ctx: LoaderContext) -> object: - return load(ctx, "storefront__order_lines") - - -@loader -def storefront__order_status_events(ctx: LoaderContext) -> object: - return load(ctx, "storefront__order_status_events") - - -@loader -def storefront__payments(ctx: LoaderContext) -> object: - return load(ctx, "storefront__payments") - - -@loader -def storefront__refunds(ctx: LoaderContext) -> object: - return load(ctx, "storefront__refunds") - - -@loader -def storefront__promotions(ctx: LoaderContext) -> object: - return load(ctx, "storefront__promotions") - - -@loader -def storefront__promotion_redemptions(ctx: LoaderContext) -> object: - return load(ctx, "storefront__promotion_redemptions") - - -@loader -def storefront__carts(ctx: LoaderContext) -> object: - return load(ctx, "storefront__carts") - - -@loader -def storefront__reviews(ctx: LoaderContext) -> object: - return load(ctx, "storefront__reviews") - - -@loader -def storefront__subscriptions(ctx: LoaderContext) -> object: - return load(ctx, "storefront__subscriptions") - - -@loader -def storefront__subscription_events(ctx: LoaderContext) -> object: - return load(ctx, "storefront__subscription_events") - - -@loader -def storefront__store_credit_ledger(ctx: LoaderContext) -> object: - return load(ctx, "storefront__store_credit_ledger") diff --git a/benchmarks/duckshop/project/python/loaders/support.py b/benchmarks/duckshop/project/python/loaders/support.py deleted file mode 100644 index e139df27b9..0000000000 --- a/benchmarks/duckshop/project/python/loaders/support.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Loaders for the synthetic support source tables, generated in python.loaders._support.""" - -from python.loaders._registry import load - -from sqlbuild.executor.load.models import LoaderContext -from sqlbuild.loaders import loader - - -@loader -def support__tickets(ctx: LoaderContext) -> object: - return load(ctx, "support__tickets") - - -@loader -def support__ticket_comments(ctx: LoaderContext) -> object: - return load(ctx, "support__ticket_comments") - - -@loader -def support__csat_responses(ctx: LoaderContext) -> object: - return load(ctx, "support__csat_responses") - - -@loader -def support__agents(ctx: LoaderContext) -> object: - return load(ctx, "support__agents") - - -@loader -def support__agent_shifts(ctx: LoaderContext) -> object: - return load(ctx, "support__agent_shifts") - - -@loader -def support__chat_transcripts(ctx: LoaderContext) -> object: - return load(ctx, "support__chat_transcripts") - - -@loader -def support__call_records(ctx: LoaderContext) -> object: - return load(ctx, "support__call_records") - - -@loader -def support__sla_policies(ctx: LoaderContext) -> object: - return load(ctx, "support__sla_policies") diff --git a/benchmarks/duckshop/project/python/audits/fact_quality.py b/benchmarks/duckshop/project/python/nodes/audits/fact_quality.py similarity index 100% rename from benchmarks/duckshop/project/python/audits/fact_quality.py rename to benchmarks/duckshop/project/python/nodes/audits/fact_quality.py diff --git a/benchmarks/duckshop/project/python/loaders/_catalogue.py b/benchmarks/duckshop/project/python/nodes/loaders/_catalogue.py similarity index 99% rename from benchmarks/duckshop/project/python/loaders/_catalogue.py rename to benchmarks/duckshop/project/python/nodes/loaders/_catalogue.py index 82762c8b7d..fd4da8a02a 100644 --- a/benchmarks/duckshop/project/python/loaders/_catalogue.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_catalogue.py @@ -4,8 +4,8 @@ from datetime import date, datetime, timedelta -from python.loaders._core import ChangeLog, at, chance, emit, in_zone, rng -from python.loaders._world import CURRENCY_EXPONENT, World, local_price +from python.nodes.loaders._core import ChangeLog, at, chance, emit, in_zone, rng +from python.nodes.loaders._world import CURRENCY_EXPONENT, World, local_price Rows = list[dict[str, object]] diff --git a/benchmarks/duckshop/project/python/loaders/_clickstream.py b/benchmarks/duckshop/project/python/nodes/loaders/_clickstream.py similarity index 99% rename from benchmarks/duckshop/project/python/loaders/_clickstream.py rename to benchmarks/duckshop/project/python/nodes/loaders/_clickstream.py index f2c168861d..d4391b860c 100644 --- a/benchmarks/duckshop/project/python/loaders/_clickstream.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_clickstream.py @@ -6,8 +6,8 @@ from datetime import datetime, timedelta from functools import lru_cache -from python.loaders._core import EventLog, at, chance, in_zone, naive_utc, rng -from python.loaders._world import ( +from python.nodes.loaders._core import EventLog, at, chance, in_zone, naive_utc, rng +from python.nodes.loaders._world import ( CAMPAIGNS, STOREFRONTS, World, diff --git a/benchmarks/duckshop/project/python/loaders/_core.py b/benchmarks/duckshop/project/python/nodes/loaders/_core.py similarity index 100% rename from benchmarks/duckshop/project/python/loaders/_core.py rename to benchmarks/duckshop/project/python/nodes/loaders/_core.py diff --git a/benchmarks/duckshop/project/python/loaders/_edge_cases.py b/benchmarks/duckshop/project/python/nodes/loaders/_edge_cases.py similarity index 100% rename from benchmarks/duckshop/project/python/loaders/_edge_cases.py rename to benchmarks/duckshop/project/python/nodes/loaders/_edge_cases.py diff --git a/benchmarks/duckshop/project/python/loaders/_finance.py b/benchmarks/duckshop/project/python/nodes/loaders/_finance.py similarity index 98% rename from benchmarks/duckshop/project/python/loaders/_finance.py rename to benchmarks/duckshop/project/python/nodes/loaders/_finance.py index 4b00ed84dc..5d6dfc6f11 100644 --- a/benchmarks/duckshop/project/python/loaders/_finance.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_finance.py @@ -6,9 +6,14 @@ from collections import defaultdict from datetime import date, datetime, timedelta -from python.loaders._core import ChangeLog, EventLog, at, chance, emit, in_zone, rng -from python.loaders._storefront import gateway_reference, payments_plan, provider_for, refunds_plan -from python.loaders._world import STOREFRONTS, World +from python.nodes.loaders._core import ChangeLog, EventLog, at, chance, emit, in_zone, rng +from python.nodes.loaders._storefront import ( + gateway_reference, + payments_plan, + provider_for, + refunds_plan, +) +from python.nodes.loaders._world import STOREFRONTS, World Rows = list[dict[str, object]] TAX_RATES = [ diff --git a/benchmarks/duckshop/project/python/loaders/_fulfilment.py b/benchmarks/duckshop/project/python/nodes/loaders/_fulfilment.py similarity index 99% rename from benchmarks/duckshop/project/python/loaders/_fulfilment.py rename to benchmarks/duckshop/project/python/nodes/loaders/_fulfilment.py index aee9d729e8..1668298340 100644 --- a/benchmarks/duckshop/project/python/loaders/_fulfilment.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_fulfilment.py @@ -7,7 +7,7 @@ from datetime import date, datetime, timedelta from functools import lru_cache -from python.loaders._core import ( +from python.nodes.loaders._core import ( ChangeLog, EventLog, at, @@ -18,7 +18,7 @@ rng, weighted, ) -from python.loaders._world import ( +from python.nodes.loaders._world import ( CARRIERS, STOREFRONTS, WAREHOUSE_FOR_REGION, diff --git a/benchmarks/duckshop/project/python/loaders/_growth.py b/benchmarks/duckshop/project/python/nodes/loaders/_growth.py similarity index 98% rename from benchmarks/duckshop/project/python/loaders/_growth.py rename to benchmarks/duckshop/project/python/nodes/loaders/_growth.py index 2a4dab63ea..811d7cce2a 100644 --- a/benchmarks/duckshop/project/python/loaders/_growth.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_growth.py @@ -4,8 +4,8 @@ from datetime import date, timedelta -from python.loaders._core import ChangeLog, at, chance, emit, in_zone, random_instant, rng -from python.loaders._world import CAMPAIGNS, STOREFRONTS, World +from python.nodes.loaders._core import ChangeLog, at, chance, emit, in_zone, random_instant, rng +from python.nodes.loaders._world import CAMPAIGNS, STOREFRONTS, World Rows = list[dict[str, object]] SPEND_CURRENCY = { diff --git a/benchmarks/duckshop/project/python/loaders/_inventory.py b/benchmarks/duckshop/project/python/nodes/loaders/_inventory.py similarity index 98% rename from benchmarks/duckshop/project/python/loaders/_inventory.py rename to benchmarks/duckshop/project/python/nodes/loaders/_inventory.py index a83723dbff..fb245531c7 100644 --- a/benchmarks/duckshop/project/python/loaders/_inventory.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_inventory.py @@ -6,8 +6,8 @@ from datetime import date, datetime, time, timedelta from functools import lru_cache -from python.loaders._catalogue import SUPPLIER_CURRENCY, SUPPLIER_FOR_FAMILY -from python.loaders._core import ( +from python.nodes.loaders._catalogue import SUPPLIER_CURRENCY, SUPPLIER_FOR_FAMILY +from python.nodes.loaders._core import ( ChangeLog, EventLog, at, @@ -18,8 +18,8 @@ messy_sku, rng, ) -from python.loaders._fulfilment import WAREHOUSE, return_plan, shipment_plan -from python.loaders._world import ( +from python.nodes.loaders._fulfilment import WAREHOUSE, return_plan, shipment_plan +from python.nodes.loaders._world import ( CURRENCY_EXPONENT, STOREFRONTS, WAREHOUSE_FOR_REGION, diff --git a/benchmarks/duckshop/project/python/loaders/_partners.py b/benchmarks/duckshop/project/python/nodes/loaders/_partners.py similarity index 97% rename from benchmarks/duckshop/project/python/loaders/_partners.py rename to benchmarks/duckshop/project/python/nodes/loaders/_partners.py index 2f3ddbad5f..e6ded9cf33 100644 --- a/benchmarks/duckshop/project/python/loaders/_partners.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_partners.py @@ -5,8 +5,17 @@ import hashlib from datetime import date, timedelta -from python.loaders._core import ChangeLog, EventLog, at, chance, emit, in_zone, random_instant, rng -from python.loaders._world import CURRENCY_EXPONENT, PER_USD, World +from python.nodes.loaders._core import ( + ChangeLog, + EventLog, + at, + chance, + emit, + in_zone, + random_instant, + rng, +) +from python.nodes.loaders._world import CURRENCY_EXPONENT, PER_USD, World Rows = list[dict[str, object]] # Partner code, payload version, currency. diff --git a/benchmarks/duckshop/project/python/loaders/_registry.py b/benchmarks/duckshop/project/python/nodes/loaders/_registry.py similarity index 91% rename from benchmarks/duckshop/project/python/loaders/_registry.py rename to benchmarks/duckshop/project/python/nodes/loaders/_registry.py index 92f8f61e7a..b2d4b906df 100644 --- a/benchmarks/duckshop/project/python/loaders/_registry.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_registry.py @@ -5,7 +5,7 @@ from collections.abc import Callable from typing import Any -from python.loaders import ( +from python.nodes.loaders import ( _catalogue, _clickstream, _finance, @@ -16,8 +16,8 @@ _storefront, _support, ) -from python.loaders._world import World, build_world -from python.loaders._writer import statements +from python.nodes.loaders._world import World, build_world +from python.nodes.loaders._writer import statements SCALE_VAR = "data_scale" """Project variable that multiplies generated volume; 1 is the small default.""" diff --git a/benchmarks/duckshop/project/python/loaders/_storefront.py b/benchmarks/duckshop/project/python/nodes/loaders/_storefront.py similarity index 99% rename from benchmarks/duckshop/project/python/loaders/_storefront.py rename to benchmarks/duckshop/project/python/nodes/loaders/_storefront.py index 4f866271f6..7106fca5da 100644 --- a/benchmarks/duckshop/project/python/loaders/_storefront.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_storefront.py @@ -6,7 +6,7 @@ from datetime import date, datetime, timedelta from functools import lru_cache -from python.loaders._core import ( +from python.nodes.loaders._core import ( ChangeLog, at, chance, @@ -16,7 +16,7 @@ rng, weighted, ) -from python.loaders._world import ( +from python.nodes.loaders._world import ( CITIES, GEO, STOREFRONTS, @@ -171,7 +171,7 @@ def customer_consents(world: World) -> Rows: @lru_cache(maxsize=4) def _loyalty_members(scale: int) -> tuple[str, ...]: - from python.loaders._world import build_world + from python.nodes.loaders._world import build_world r = rng("loyalty_members") return tuple( @@ -346,7 +346,7 @@ class GiftTender: def gift_cards_and_tender(scale: int) -> tuple[tuple[GiftCard, ...], tuple[GiftTender, ...]]: """Gift cards and the orders part-paid with them; payments and refunds read this too.""" - from python.loaders._world import build_world + from python.nodes.loaders._world import build_world world = build_world(scale) r = rng("gift_cards") @@ -638,7 +638,7 @@ def order_status_events(world: World) -> Rows: def payments_plan(scale: int) -> tuple[tuple[str, str, str, int, datetime, str], ...]: """(payment_id, order_id, method, amount_minor, authorised_at, gateway status) per attempt.""" - from python.loaders._world import build_world + from python.nodes.loaders._world import build_world world = build_world(scale) r = rng("payments_plan") @@ -741,7 +741,7 @@ def payments(world: World) -> Rows: def refunds_plan(scale: int) -> tuple[tuple[str, str, str, int, datetime, str], ...]: """(refund_id, payment_id, order_id, amount_minor, refunded_at, reason) for refunded orders.""" - from python.loaders._world import build_world + from python.nodes.loaders._world import build_world world = build_world(scale) r = rng("refunds_plan") @@ -1023,7 +1023,7 @@ def reviews(world: World) -> Rows: def subscription_plan( scale: int, ) -> tuple[tuple[str, str, str, datetime, list[tuple[str, datetime]]], ...]: - from python.loaders._world import build_world + from python.nodes.loaders._world import build_world world = build_world(scale) r = rng("subscription_plan") diff --git a/benchmarks/duckshop/project/python/loaders/_support.py b/benchmarks/duckshop/project/python/nodes/loaders/_support.py similarity index 98% rename from benchmarks/duckshop/project/python/loaders/_support.py rename to benchmarks/duckshop/project/python/nodes/loaders/_support.py index ff84a409b0..e191a7e2f7 100644 --- a/benchmarks/duckshop/project/python/loaders/_support.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_support.py @@ -5,8 +5,17 @@ from datetime import date, datetime, timedelta from functools import lru_cache -from python.loaders._core import ChangeLog, at, chance, emit, in_zone, random_instant, rng, weighted -from python.loaders._world import World, build_world +from python.nodes.loaders._core import ( + ChangeLog, + at, + chance, + emit, + in_zone, + random_instant, + rng, + weighted, +) +from python.nodes.loaders._world import World, build_world Rows = list[dict[str, object]] AGENTS = [ diff --git a/benchmarks/duckshop/project/python/loaders/_world.py b/benchmarks/duckshop/project/python/nodes/loaders/_world.py similarity index 99% rename from benchmarks/duckshop/project/python/loaders/_world.py rename to benchmarks/duckshop/project/python/nodes/loaders/_world.py index 01c93e4a41..bdd5f3fd76 100644 --- a/benchmarks/duckshop/project/python/loaders/_world.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_world.py @@ -10,7 +10,7 @@ from datetime import date, datetime, timedelta from functools import lru_cache -from python.loaders._core import ( +from python.nodes.loaders._core import ( CLICKSTREAM_START, ORDERS_START, VALUATION_DATE, diff --git a/benchmarks/duckshop/project/python/loaders/_writer.py b/benchmarks/duckshop/project/python/nodes/loaders/_writer.py similarity index 98% rename from benchmarks/duckshop/project/python/loaders/_writer.py rename to benchmarks/duckshop/project/python/nodes/loaders/_writer.py index a6eb0692fb..b1b8872f65 100644 --- a/benchmarks/duckshop/project/python/loaders/_writer.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_writer.py @@ -17,7 +17,7 @@ import yaml -SOURCES_DIR = Path(__file__).resolve().parents[2] / "sources" +SOURCES_DIR = Path(__file__).resolve().parents[2] / "sql" / "sources" BATCH_SIZE = 500 JSON_TYPES = {"VARIANT": "", "OBJECT": "::OBJECT", "ARRAY": "::ARRAY"} diff --git a/benchmarks/duckshop/project/python/nodes/loaders/catalogue/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/catalogue/loaders.py new file mode 100644 index 0000000000..1b947c0179 --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/catalogue/loaders.py @@ -0,0 +1,63 @@ +"""Loaders for the synthetic catalogue source tables, generated in python.loaders._catalogue.""" + +from python.nodes.loaders._registry import load + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def catalogue_loaders() -> list[object]: + @loader + def catalogue__brands(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__brands") + + @loader + def catalogue__categories(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__categories") + + @loader + def catalogue__products(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__products") + + @loader + def catalogue__product_variants(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__product_variants") + + @loader + def catalogue__price_lists(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__price_lists") + + @loader + def catalogue__product_media(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__product_media") + + @loader + def catalogue__bundles(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__bundles") + + @loader + def catalogue__bundle_components(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__bundle_components") + + @loader + def catalogue__suppliers(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__suppliers") + + @loader + def catalogue__supplier_costs(ctx: LoaderContext) -> object: + return load(ctx, "catalogue__supplier_costs") + + return [ + catalogue__brands, + catalogue__categories, + catalogue__products, + catalogue__product_variants, + catalogue__price_lists, + catalogue__product_media, + catalogue__bundles, + catalogue__bundle_components, + catalogue__suppliers, + catalogue__supplier_costs, + ] diff --git a/benchmarks/duckshop/project/python/nodes/loaders/clickstream/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/clickstream/loaders.py new file mode 100644 index 0000000000..90ff7a3688 --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/clickstream/loaders.py @@ -0,0 +1,38 @@ +"""Loaders for the synthetic clickstream source tables, generated in python.loaders._clickstream.""" + +from python.nodes.loaders._registry import load + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def clickstream_loaders() -> list[object]: + @loader + def clickstream__web_events(ctx: LoaderContext) -> object: + return load(ctx, "clickstream__web_events") + + @loader + def clickstream__app_events(ctx: LoaderContext) -> object: + return load(ctx, "clickstream__app_events") + + @loader + def clickstream__search_queries(ctx: LoaderContext) -> object: + return load(ctx, "clickstream__search_queries") + + @loader + def clickstream__email_events(ctx: LoaderContext) -> object: + return load(ctx, "clickstream__email_events") + + @loader + def clickstream__experiment_assignments(ctx: LoaderContext) -> object: + return load(ctx, "clickstream__experiment_assignments") + + return [ + clickstream__web_events, + clickstream__app_events, + clickstream__search_queries, + clickstream__email_events, + clickstream__experiment_assignments, + ] diff --git a/benchmarks/duckshop/project/python/nodes/loaders/edge_cases/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/edge_cases/loaders.py new file mode 100644 index 0000000000..f450d1fe51 --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/edge_cases/loaders.py @@ -0,0 +1,99 @@ +"""Loaders for the edge-case area's raw tables, with the fixed rows in python.loaders._edge_cases. + +These rows are hand-picked edge values, not generated volume: `data_scale` does not change them, +and they never touch the core tables, so core outputs and expectations stay the same. +""" + +from python.nodes.loaders._edge_cases import DELIVERY_BATCH_VAR, TABLES, delivery_updates +from python.nodes.loaders._writer import statements + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +def _load(ctx: LoaderContext, source_name: str) -> object: + rows = TABLES[source_name] + for sql in statements(ctx.destination, source_name, rows): + ctx.execute_sql(sql) + return ctx.result(metadata={"rows": len(rows)}) + + +@factory +def edge_cases_loaders() -> list[object]: + @loader + def edge__partner_payloads(ctx: LoaderContext) -> object: + return _load(ctx, "edge__partner_payloads") + + @loader + def edge__gateway_callbacks(ctx: LoaderContext) -> object: + return _load(ctx, "edge__gateway_callbacks") + + @loader + def edge__price_windows(ctx: LoaderContext) -> object: + return _load(ctx, "edge__price_windows") + + @loader + def edge__customer_profiles(ctx: LoaderContext) -> object: + return _load(ctx, "edge__customer_profiles") + + @loader + def edge__ledger_entries(ctx: LoaderContext) -> object: + return _load(ctx, "edge__ledger_entries") + + @loader + def edge__ticket_notes(ctx: LoaderContext) -> object: + return _load(ctx, "edge__ticket_notes") + + @loader + def edge__partner_listings(ctx: LoaderContext) -> object: + return _load(ctx, "edge__partner_listings") + + @loader + def edge__basket_lines(ctx: LoaderContext) -> object: + return _load(ctx, "edge__basket_lines") + + @loader + def edge__date_texts(ctx: LoaderContext) -> object: + return _load(ctx, "edge__date_texts") + + @loader + def edge__amount_checks(ctx: LoaderContext) -> object: + return _load(ctx, "edge__amount_checks") + + @loader + def edge__variant_values(ctx: LoaderContext) -> object: + return _load(ctx, "edge__variant_values") + + @loader + def edge__category_links(ctx: LoaderContext) -> object: + return _load(ctx, "edge__category_links") + + @loader + def edge__supplier_notes(ctx: LoaderContext) -> object: + return _load(ctx, "edge__supplier_notes") + + @loader + def edge__delivery_updates(ctx: LoaderContext) -> object: + batch = int(ctx.vars.get(DELIVERY_BATCH_VAR, 2)) # type: ignore[call-overload] + rows = delivery_updates(batch) + for sql in statements(ctx.destination, "edge__delivery_updates", rows): + ctx.execute_sql(sql) + return ctx.result(metadata={"rows": len(rows), "batch": batch}) + + return [ + edge__partner_payloads, + edge__gateway_callbacks, + edge__price_windows, + edge__customer_profiles, + edge__ledger_entries, + edge__ticket_notes, + edge__partner_listings, + edge__basket_lines, + edge__date_texts, + edge__amount_checks, + edge__variant_values, + edge__category_links, + edge__supplier_notes, + edge__delivery_updates, + ] diff --git a/benchmarks/duckshop/project/python/nodes/loaders/finance/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/finance/loaders.py new file mode 100644 index 0000000000..5efe2b629e --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/finance/loaders.py @@ -0,0 +1,43 @@ +"""Loaders for the synthetic finance source tables, generated in python.loaders._finance.""" + +from python.nodes.loaders._registry import load + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def finance_loaders() -> list[object]: + @loader + def finance__invoices(ctx: LoaderContext) -> object: + return load(ctx, "finance__invoices") + + @loader + def finance__ledger_entries(ctx: LoaderContext) -> object: + return load(ctx, "finance__ledger_entries") + + @loader + def finance__payouts(ctx: LoaderContext) -> object: + return load(ctx, "finance__payouts") + + @loader + def finance__tax_rates(ctx: LoaderContext) -> object: + return load(ctx, "finance__tax_rates") + + @loader + def finance__chargebacks(ctx: LoaderContext) -> object: + return load(ctx, "finance__chargebacks") + + @loader + def finance__settlement_reports(ctx: LoaderContext) -> object: + return load(ctx, "finance__settlement_reports") + + return [ + finance__invoices, + finance__ledger_entries, + finance__payouts, + finance__tax_rates, + finance__chargebacks, + finance__settlement_reports, + ] diff --git a/benchmarks/duckshop/project/python/nodes/loaders/fulfilment/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/fulfilment/loaders.py new file mode 100644 index 0000000000..c3a940f065 --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/fulfilment/loaders.py @@ -0,0 +1,58 @@ +"""Loaders for the synthetic fulfilment source tables, generated in python.loaders._fulfilment.""" + +from python.nodes.loaders._registry import load + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def fulfilment_loaders() -> list[object]: + @loader + def fulfilment__shipments(ctx: LoaderContext) -> object: + return load(ctx, "fulfilment__shipments") + + @loader + def fulfilment__shipment_packages(ctx: LoaderContext) -> object: + return load(ctx, "fulfilment__shipment_packages") + + @loader + def fulfilment__carrier_webhooks(ctx: LoaderContext) -> object: + return load(ctx, "fulfilment__carrier_webhooks") + + @loader + def fulfilment__returns(ctx: LoaderContext) -> object: + return load(ctx, "fulfilment__returns") + + @loader + def fulfilment__return_inspections(ctx: LoaderContext) -> object: + return load(ctx, "fulfilment__return_inspections") + + @loader + def fulfilment__carrier_rate_cards(ctx: LoaderContext) -> object: + return load(ctx, "fulfilment__carrier_rate_cards") + + @loader + def fulfilment__delivery_slots(ctx: LoaderContext) -> object: + return load(ctx, "fulfilment__delivery_slots") + + @loader + def fulfilment__pick_tasks(ctx: LoaderContext) -> object: + return load(ctx, "fulfilment__pick_tasks") + + @loader + def fulfilment__delivery_exceptions(ctx: LoaderContext) -> object: + return load(ctx, "fulfilment__delivery_exceptions") + + return [ + fulfilment__shipments, + fulfilment__shipment_packages, + fulfilment__carrier_webhooks, + fulfilment__returns, + fulfilment__return_inspections, + fulfilment__carrier_rate_cards, + fulfilment__delivery_slots, + fulfilment__pick_tasks, + fulfilment__delivery_exceptions, + ] diff --git a/benchmarks/duckshop/project/python/nodes/loaders/growth/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/growth/loaders.py new file mode 100644 index 0000000000..89d7a0cbc2 --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/growth/loaders.py @@ -0,0 +1,48 @@ +"""Loaders for the synthetic growth source tables, generated in python.loaders._growth.""" + +from python.nodes.loaders._registry import load + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def growth_loaders() -> list[object]: + @loader + def growth__campaigns(ctx: LoaderContext) -> object: + return load(ctx, "growth__campaigns") + + @loader + def growth__campaign_spend(ctx: LoaderContext) -> object: + return load(ctx, "growth__campaign_spend") + + @loader + def growth__affiliate_conversions(ctx: LoaderContext) -> object: + return load(ctx, "growth__affiliate_conversions") + + @loader + def growth__referral_invites(ctx: LoaderContext) -> object: + return load(ctx, "growth__referral_invites") + + @loader + def growth__newsletter_subscriptions(ctx: LoaderContext) -> object: + return load(ctx, "growth__newsletter_subscriptions") + + @loader + def growth__survey_responses(ctx: LoaderContext) -> object: + return load(ctx, "growth__survey_responses") + + @loader + def growth__influencer_posts(ctx: LoaderContext) -> object: + return load(ctx, "growth__influencer_posts") + + return [ + growth__campaigns, + growth__campaign_spend, + growth__affiliate_conversions, + growth__referral_invites, + growth__newsletter_subscriptions, + growth__survey_responses, + growth__influencer_posts, + ] diff --git a/benchmarks/duckshop/project/python/nodes/loaders/inventory/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/inventory/loaders.py new file mode 100644 index 0000000000..c05e36123c --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/inventory/loaders.py @@ -0,0 +1,53 @@ +"""Loaders for the synthetic inventory source tables, generated in python.loaders._inventory.""" + +from python.nodes.loaders._registry import load + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def inventory_loaders() -> list[object]: + @loader + def inventory__warehouses(ctx: LoaderContext) -> object: + return load(ctx, "inventory__warehouses") + + @loader + def inventory__stock_movements(ctx: LoaderContext) -> object: + return load(ctx, "inventory__stock_movements") + + @loader + def inventory__stock_counts(ctx: LoaderContext) -> object: + return load(ctx, "inventory__stock_counts") + + @loader + def inventory__purchase_orders(ctx: LoaderContext) -> object: + return load(ctx, "inventory__purchase_orders") + + @loader + def inventory__po_receipts(ctx: LoaderContext) -> object: + return load(ctx, "inventory__po_receipts") + + @loader + def inventory__stock_transfers(ctx: LoaderContext) -> object: + return load(ctx, "inventory__stock_transfers") + + @loader + def inventory__stock_reservations(ctx: LoaderContext) -> object: + return load(ctx, "inventory__stock_reservations") + + @loader + def inventory__bin_locations(ctx: LoaderContext) -> object: + return load(ctx, "inventory__bin_locations") + + return [ + inventory__warehouses, + inventory__stock_movements, + inventory__stock_counts, + inventory__purchase_orders, + inventory__po_receipts, + inventory__stock_transfers, + inventory__stock_reservations, + inventory__bin_locations, + ] diff --git a/benchmarks/duckshop/project/python/nodes/loaders/partners/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/partners/loaders.py new file mode 100644 index 0000000000..f8c7f167fe --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/partners/loaders.py @@ -0,0 +1,24 @@ +"""Loaders for the synthetic partners source tables, generated in python.loaders._partners.""" + +from python.nodes.loaders._registry import load + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def partners_loaders() -> list[object]: + @loader + def partners__partner_orders(ctx: LoaderContext) -> object: + return load(ctx, "partners__partner_orders") + + @loader + def partners__partner_listings(ctx: LoaderContext) -> object: + return load(ctx, "partners__partner_listings") + + @loader + def partners__partner_settlements(ctx: LoaderContext) -> object: + return load(ctx, "partners__partner_settlements") + + return [partners__partner_orders, partners__partner_listings, partners__partner_settlements] diff --git a/benchmarks/duckshop/project/python/nodes/loaders/storefront/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/storefront/loaders.py new file mode 100644 index 0000000000..9f885b3e86 --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/storefront/loaders.py @@ -0,0 +1,113 @@ +"""Loaders for the synthetic storefront source tables, generated in python.loaders._storefront.""" + +from python.nodes.loaders._registry import load + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def storefront_loaders() -> list[object]: + @loader + def storefront__customers(ctx: LoaderContext) -> object: + return load(ctx, "storefront__customers") + + @loader + def storefront__customer_addresses(ctx: LoaderContext) -> object: + return load(ctx, "storefront__customer_addresses") + + @loader + def storefront__customer_consents(ctx: LoaderContext) -> object: + return load(ctx, "storefront__customer_consents") + + @loader + def storefront__loyalty_accounts(ctx: LoaderContext) -> object: + return load(ctx, "storefront__loyalty_accounts") + + @loader + def storefront__loyalty_ledger(ctx: LoaderContext) -> object: + return load(ctx, "storefront__loyalty_ledger") + + @loader + def storefront__wishlists(ctx: LoaderContext) -> object: + return load(ctx, "storefront__wishlists") + + @loader + def storefront__gift_cards(ctx: LoaderContext) -> object: + return load(ctx, "storefront__gift_cards") + + @loader + def storefront__gift_card_transactions(ctx: LoaderContext) -> object: + return load(ctx, "storefront__gift_card_transactions") + + @loader + def storefront__orders(ctx: LoaderContext) -> object: + return load(ctx, "storefront__orders") + + @loader + def storefront__order_lines(ctx: LoaderContext) -> object: + return load(ctx, "storefront__order_lines") + + @loader + def storefront__order_status_events(ctx: LoaderContext) -> object: + return load(ctx, "storefront__order_status_events") + + @loader + def storefront__payments(ctx: LoaderContext) -> object: + return load(ctx, "storefront__payments") + + @loader + def storefront__refunds(ctx: LoaderContext) -> object: + return load(ctx, "storefront__refunds") + + @loader + def storefront__promotions(ctx: LoaderContext) -> object: + return load(ctx, "storefront__promotions") + + @loader + def storefront__promotion_redemptions(ctx: LoaderContext) -> object: + return load(ctx, "storefront__promotion_redemptions") + + @loader + def storefront__carts(ctx: LoaderContext) -> object: + return load(ctx, "storefront__carts") + + @loader + def storefront__reviews(ctx: LoaderContext) -> object: + return load(ctx, "storefront__reviews") + + @loader + def storefront__subscriptions(ctx: LoaderContext) -> object: + return load(ctx, "storefront__subscriptions") + + @loader + def storefront__subscription_events(ctx: LoaderContext) -> object: + return load(ctx, "storefront__subscription_events") + + @loader + def storefront__store_credit_ledger(ctx: LoaderContext) -> object: + return load(ctx, "storefront__store_credit_ledger") + + return [ + storefront__customers, + storefront__customer_addresses, + storefront__customer_consents, + storefront__loyalty_accounts, + storefront__loyalty_ledger, + storefront__wishlists, + storefront__gift_cards, + storefront__gift_card_transactions, + storefront__orders, + storefront__order_lines, + storefront__order_status_events, + storefront__payments, + storefront__refunds, + storefront__promotions, + storefront__promotion_redemptions, + storefront__carts, + storefront__reviews, + storefront__subscriptions, + storefront__subscription_events, + storefront__store_credit_ledger, + ] diff --git a/benchmarks/duckshop/project/python/nodes/loaders/support/loaders.py b/benchmarks/duckshop/project/python/nodes/loaders/support/loaders.py new file mode 100644 index 0000000000..aae2d9b0d3 --- /dev/null +++ b/benchmarks/duckshop/project/python/nodes/loaders/support/loaders.py @@ -0,0 +1,53 @@ +"""Loaders for the synthetic support source tables, generated in python.loaders._support.""" + +from python.nodes.loaders._registry import load + +from sqlbuild.executor.load.models import LoaderContext +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def support_loaders() -> list[object]: + @loader + def support__tickets(ctx: LoaderContext) -> object: + return load(ctx, "support__tickets") + + @loader + def support__ticket_comments(ctx: LoaderContext) -> object: + return load(ctx, "support__ticket_comments") + + @loader + def support__csat_responses(ctx: LoaderContext) -> object: + return load(ctx, "support__csat_responses") + + @loader + def support__agents(ctx: LoaderContext) -> object: + return load(ctx, "support__agents") + + @loader + def support__agent_shifts(ctx: LoaderContext) -> object: + return load(ctx, "support__agent_shifts") + + @loader + def support__chat_transcripts(ctx: LoaderContext) -> object: + return load(ctx, "support__chat_transcripts") + + @loader + def support__call_records(ctx: LoaderContext) -> object: + return load(ctx, "support__call_records") + + @loader + def support__sla_policies(ctx: LoaderContext) -> object: + return load(ctx, "support__sla_policies") + + return [ + support__tickets, + support__ticket_comments, + support__csat_responses, + support__agents, + support__agent_shifts, + support__chat_transcripts, + support__call_records, + support__sla_policies, + ] diff --git a/benchmarks/duckshop/project/rules/edge_area_tags.py b/benchmarks/duckshop/project/rules/edge_area_tags.py index 7ba35badac..9aff4c5eb6 100644 --- a/benchmarks/duckshop/project/rules/edge_area_tags.py +++ b/benchmarks/duckshop/project/rules/edge_area_tags.py @@ -54,13 +54,13 @@ def _header_tags(sql: str) -> tuple[set[str], int]: code="XSQBRDUCK002", message="Models in an edge_cases folder, and only those, must declare the edge_case tag", remediation=( - "Add `tags [edge_case]` to the header of every model under models//edge_cases/, " + "Add `tags [edge_case]` to the header of every model under sql/models//edge_cases/, " "and move a model that declares the tag into that folder, so benchmark and core runs can " "exclude the edge-case area with --exclude tag:edge_case." ), ) def edge_area_is_tagged(*, model: Model, ctx: RuleContext) -> list[Finding]: - parts = ctx.project.tree.relative_parts(path=model.path, under="models") + parts = ctx.project.tree.relative_parts(path=model.path, under="sql/models") in_area = EDGE_FOLDER in parts tags, line = _header_tags(ctx.sql.for_model(model).authored.source) if in_area == (EDGE_TAG in tags): diff --git a/benchmarks/duckshop/project/rules/staging_dedupe.py b/benchmarks/duckshop/project/rules/staging_dedupe.py index 1a41f278c2..d1926f136b 100644 --- a/benchmarks/duckshop/project/rules/staging_dedupe.py +++ b/benchmarks/duckshop/project/rules/staging_dedupe.py @@ -11,7 +11,7 @@ def _change_log_sources(ctx: RuleContext) -> set[str]: names: set[str] = set() - for path in ctx.project.tree.glob("sources/*.yml"): + for path in ctx.project.tree.glob("sql/sources/*.yml"): text = ctx.project.tree.read_text(path.value) for match in _SOURCE_BLOCK.finditer(text): if _CHANGE_LOG_MARKER.search(match.group(2)): @@ -29,7 +29,7 @@ def _change_log_sources(ctx: RuleContext) -> set[str]: ), ) def staging_uses_cdc_latest(*, model: Model, ctx: RuleContext) -> list[Finding]: - parts = ctx.project.tree.relative_parts(path=model.path, under="models") + parts = ctx.project.tree.relative_parts(path=model.path, under="sql/models") if not parts or parts[0] != "staging": return [] sql = ctx.sql.for_model(model).authored.source diff --git a/benchmarks/duckshop/project/audits/generic/unique_per_delivery.sql b/benchmarks/duckshop/project/sql/audits/generic/unique_per_delivery.sql similarity index 100% rename from benchmarks/duckshop/project/audits/generic/unique_per_delivery.sql rename to benchmarks/duckshop/project/sql/audits/generic/unique_per_delivery.sql diff --git a/benchmarks/duckshop/project/constants/history_start_date.sql b/benchmarks/duckshop/project/sql/constants/history_start_date.sql similarity index 100% rename from benchmarks/duckshop/project/constants/history_start_date.sql rename to benchmarks/duckshop/project/sql/constants/history_start_date.sql diff --git a/benchmarks/duckshop/project/enums/fulfilment_method.sql b/benchmarks/duckshop/project/sql/enums/fulfilment_method.sql similarity index 100% rename from benchmarks/duckshop/project/enums/fulfilment_method.sql rename to benchmarks/duckshop/project/sql/enums/fulfilment_method.sql diff --git a/benchmarks/duckshop/project/enums/order_status.sql b/benchmarks/duckshop/project/sql/enums/order_status.sql similarity index 100% rename from benchmarks/duckshop/project/enums/order_status.sql rename to benchmarks/duckshop/project/sql/enums/order_status.sql diff --git a/benchmarks/duckshop/project/enums/return_reason.sql b/benchmarks/duckshop/project/sql/enums/return_reason.sql similarity index 100% rename from benchmarks/duckshop/project/enums/return_reason.sql rename to benchmarks/duckshop/project/sql/enums/return_reason.sql diff --git a/benchmarks/duckshop/project/enums/sales_channel.sql b/benchmarks/duckshop/project/sql/enums/sales_channel.sql similarity index 100% rename from benchmarks/duckshop/project/enums/sales_channel.sql rename to benchmarks/duckshop/project/sql/enums/sales_channel.sql diff --git a/benchmarks/duckshop/project/enums/ticket_priority.sql b/benchmarks/duckshop/project/sql/enums/ticket_priority.sql similarity index 100% rename from benchmarks/duckshop/project/enums/ticket_priority.sql rename to benchmarks/duckshop/project/sql/enums/ticket_priority.sql diff --git a/benchmarks/duckshop/project/functions/python/edge_float_value.py b/benchmarks/duckshop/project/sql/functions/python/edge_float_value.py similarity index 100% rename from benchmarks/duckshop/project/functions/python/edge_float_value.py rename to benchmarks/duckshop/project/sql/functions/python/edge_float_value.py diff --git a/benchmarks/duckshop/project/functions/python/edge_next_ticket.py b/benchmarks/duckshop/project/sql/functions/python/edge_next_ticket.py similarity index 100% rename from benchmarks/duckshop/project/functions/python/edge_next_ticket.py rename to benchmarks/duckshop/project/sql/functions/python/edge_next_ticket.py diff --git a/benchmarks/duckshop/project/functions/python/edge_payload_value.py b/benchmarks/duckshop/project/sql/functions/python/edge_payload_value.py similarity index 100% rename from benchmarks/duckshop/project/functions/python/edge_payload_value.py rename to benchmarks/duckshop/project/sql/functions/python/edge_payload_value.py diff --git a/benchmarks/duckshop/project/functions/python/edge_tag_label.py b/benchmarks/duckshop/project/sql/functions/python/edge_tag_label.py similarity index 100% rename from benchmarks/duckshop/project/functions/python/edge_tag_label.py rename to benchmarks/duckshop/project/sql/functions/python/edge_tag_label.py diff --git a/benchmarks/duckshop/project/functions/python/edge_ticket_token.py b/benchmarks/duckshop/project/sql/functions/python/edge_ticket_token.py similarity index 100% rename from benchmarks/duckshop/project/functions/python/edge_ticket_token.py rename to benchmarks/duckshop/project/sql/functions/python/edge_ticket_token.py diff --git a/benchmarks/duckshop/project/functions/python/luhn_valid.py b/benchmarks/duckshop/project/sql/functions/python/luhn_valid.py similarity index 100% rename from benchmarks/duckshop/project/functions/python/luhn_valid.py rename to benchmarks/duckshop/project/sql/functions/python/luhn_valid.py diff --git a/benchmarks/duckshop/project/functions/sql/edge_basket_lines_for.sql b/benchmarks/duckshop/project/sql/functions/sql/edge_basket_lines_for.sql similarity index 100% rename from benchmarks/duckshop/project/functions/sql/edge_basket_lines_for.sql rename to benchmarks/duckshop/project/sql/functions/sql/edge_basket_lines_for.sql diff --git a/benchmarks/duckshop/project/functions/sql/edge_cases/edge_next_quantity.sql b/benchmarks/duckshop/project/sql/functions/sql/edge_cases/edge_next_quantity.sql similarity index 100% rename from benchmarks/duckshop/project/functions/sql/edge_cases/edge_next_quantity.sql rename to benchmarks/duckshop/project/sql/functions/sql/edge_cases/edge_next_quantity.sql diff --git a/benchmarks/duckshop/project/functions/sql/table_fn__customer_orders.sql b/benchmarks/duckshop/project/sql/functions/sql/table_fn__customer_orders.sql similarity index 100% rename from benchmarks/duckshop/project/functions/sql/table_fn__customer_orders.sql rename to benchmarks/duckshop/project/sql/functions/sql/table_fn__customer_orders.sql diff --git a/benchmarks/duckshop/project/functions/sql/udf__sku_family.sql b/benchmarks/duckshop/project/sql/functions/sql/udf__sku_family.sql similarity index 100% rename from benchmarks/duckshop/project/functions/sql/udf__sku_family.sql rename to benchmarks/duckshop/project/sql/functions/sql/udf__sku_family.sql diff --git a/benchmarks/duckshop/project/macros/python/rounding.py b/benchmarks/duckshop/project/sql/macros/python/rounding.py similarity index 100% rename from benchmarks/duckshop/project/macros/python/rounding.py rename to benchmarks/duckshop/project/sql/macros/python/rounding.py diff --git a/benchmarks/duckshop/project/macros/sql/money_columns.sql b/benchmarks/duckshop/project/sql/macros/sql/money_columns.sql similarity index 100% rename from benchmarks/duckshop/project/macros/sql/money_columns.sql rename to benchmarks/duckshop/project/sql/macros/sql/money_columns.sql diff --git a/benchmarks/duckshop/project/macros/sql/money_from_minor.sql b/benchmarks/duckshop/project/sql/macros/sql/money_from_minor.sql similarity index 100% rename from benchmarks/duckshop/project/macros/sql/money_from_minor.sql rename to benchmarks/duckshop/project/sql/macros/sql/money_from_minor.sql diff --git a/benchmarks/duckshop/project/macros/sql/safe_divide.sql b/benchmarks/duckshop/project/sql/macros/sql/safe_divide.sql similarity index 100% rename from benchmarks/duckshop/project/macros/sql/safe_divide.sql rename to benchmarks/duckshop/project/sql/macros/sql/safe_divide.sql diff --git a/benchmarks/duckshop/project/models/intermediate/_sqlbuild/audits/generic/match_rate.sql b/benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/audits/generic/match_rate.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/_sqlbuild/audits/generic/match_rate.sql rename to benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/audits/generic/match_rate.sql diff --git a/benchmarks/duckshop/project/models/intermediate/_sqlbuild/constants/supported_regions.sql b/benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/constants/supported_regions.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/_sqlbuild/constants/supported_regions.sql rename to benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/constants/supported_regions.sql diff --git a/benchmarks/duckshop/project/models/intermediate/_sqlbuild/macros/sql/date_spine.sql b/benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/macros/sql/date_spine.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/_sqlbuild/macros/sql/date_spine.sql rename to benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/macros/sql/date_spine.sql diff --git a/benchmarks/duckshop/project/models/intermediate/_sqlbuild/macros/sql/in_regions.sql b/benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/macros/sql/in_regions.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/_sqlbuild/macros/sql/in_regions.sql rename to benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/macros/sql/in_regions.sql diff --git a/benchmarks/duckshop/project/models/intermediate/_sqlbuild/macros/sql/local_business_date.sql b/benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/macros/sql/local_business_date.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/_sqlbuild/macros/sql/local_business_date.sql rename to benchmarks/duckshop/project/sql/models/intermediate/_sqlbuild/macros/sql/local_business_date.sql diff --git a/benchmarks/duckshop/project/models/intermediate/catalogue/int_bundle_pricing.sql b/benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_bundle_pricing.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/catalogue/int_bundle_pricing.sql rename to benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_bundle_pricing.sql diff --git a/benchmarks/duckshop/project/models/intermediate/catalogue/int_category_paths.sql b/benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_category_paths.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/catalogue/int_category_paths.sql rename to benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_category_paths.sql diff --git a/benchmarks/duckshop/project/models/intermediate/catalogue/int_price_history.sql b/benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_price_history.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/catalogue/int_price_history.sql rename to benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_price_history.sql diff --git a/benchmarks/duckshop/project/models/intermediate/catalogue/int_product_catalogue.sql b/benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_product_catalogue.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/catalogue/int_product_catalogue.sql rename to benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_product_catalogue.sql diff --git a/benchmarks/duckshop/project/models/intermediate/catalogue/int_product_margin.sql b/benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_product_margin.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/catalogue/int_product_margin.sql rename to benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_product_margin.sql diff --git a/benchmarks/duckshop/project/models/intermediate/catalogue/int_product_specs_flat.sql b/benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_product_specs_flat.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/catalogue/int_product_specs_flat.sql rename to benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_product_specs_flat.sql diff --git a/benchmarks/duckshop/project/models/intermediate/catalogue/int_supplier_cost_current.sql b/benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_supplier_cost_current.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/catalogue/int_supplier_cost_current.sql rename to benchmarks/duckshop/project/sql/models/intermediate/catalogue/int_supplier_cost_current.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/_sqlbuild/_constants/session_gap_minutes.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/_sqlbuild/_constants/session_gap_minutes.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/_sqlbuild/_constants/session_gap_minutes.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/_sqlbuild/_constants/session_gap_minutes.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/int_app_sessions.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_app_sessions.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/int_app_sessions.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_app_sessions.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/int_cart_funnel.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_cart_funnel.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/int_cart_funnel.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_cart_funnel.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/int_cross_device_identity.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_cross_device_identity.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/int_cross_device_identity.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_cross_device_identity.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/int_email_engagement.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_email_engagement.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/int_email_engagement.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_email_engagement.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/int_experiment_exposures.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_experiment_exposures.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/int_experiment_exposures.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_experiment_exposures.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/int_product_view_affinity.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_product_view_affinity.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/int_product_view_affinity.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_product_view_affinity.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/int_search_conversion.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_search_conversion.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/int_search_conversion.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_search_conversion.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/int_session_attribution.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_session_attribution.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/int_session_attribution.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_session_attribution.sql diff --git a/benchmarks/duckshop/project/models/intermediate/clickstream/int_web_sessions.sql b/benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_web_sessions.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/clickstream/int_web_sessions.sql rename to benchmarks/duckshop/project/sql/models/intermediate/clickstream/int_web_sessions.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/_sqlbuild/_constants/vip_ltv_threshold.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/_sqlbuild/_constants/vip_ltv_threshold.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/_sqlbuild/_constants/vip_ltv_threshold.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/_sqlbuild/_constants/vip_ltv_threshold.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/_sqlbuild/_macros/sql/is_status.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/_sqlbuild/_macros/sql/is_status.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/_sqlbuild/_macros/sql/is_status.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/_sqlbuild/_macros/sql/is_status.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_customer_address_current.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_address_current.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_customer_address_current.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_address_current.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_customer_consent_state.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_consent_state.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_customer_consent_state.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_consent_state.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_customer_identity.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_identity.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_customer_identity.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_identity.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_customer_order_sequence.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_order_sequence.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_customer_order_sequence.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_order_sequence.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_customer_rfm.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_rfm.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_customer_rfm.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_rfm.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_gift_card_balances.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_gift_card_balances.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_gift_card_balances.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_gift_card_balances.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_loyalty_balances.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_loyalty_balances.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_loyalty_balances.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_loyalty_balances.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_loyalty_tier_changes.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_loyalty_tier_changes.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_loyalty_tier_changes.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_loyalty_tier_changes.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_store_credit_balances.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_store_credit_balances.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_store_credit_balances.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_store_credit_balances.sql diff --git a/benchmarks/duckshop/project/models/intermediate/customers/int_wishlist_demand.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_wishlist_demand.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/customers/int_wishlist_demand.sql rename to benchmarks/duckshop/project/sql/models/intermediate/customers/int_wishlist_demand.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/_sqlbuild/_hooks/sql/create_edge_running_peaks.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/_sqlbuild/_hooks/sql/create_edge_running_peaks.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/_sqlbuild/_hooks/sql/create_edge_running_peaks.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/_sqlbuild/_hooks/sql/create_edge_running_peaks.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/_sqlbuild/audits/singular/edge_delivery_status_matches_rebuild.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/_sqlbuild/audits/singular/edge_delivery_status_matches_rebuild.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/_sqlbuild/audits/singular/edge_delivery_status_matches_rebuild.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/_sqlbuild/audits/singular/edge_delivery_status_matches_rebuild.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_amount_bit_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_bit_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_amount_bit_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_bit_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_amount_edges.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_edges.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_amount_edges.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_edges.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_amount_percent_texts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_percent_texts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_amount_percent_texts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_percent_texts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_amount_statistics.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_statistics.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_amount_statistics.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_statistics.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_analysis_patterns.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_analysis_patterns.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_analysis_patterns.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_analysis_patterns.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_array_edits.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_array_edits.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_array_edits.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_array_edits.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_distinct_tags.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_distinct_tags.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_distinct_tags.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_distinct_tags.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_grouped_sku_filters.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_grouped_sku_filters.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_grouped_sku_filters.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_grouped_sku_filters.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_line_laterals.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_line_laterals.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_line_laterals.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_line_laterals.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_line_lookups.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_line_lookups.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_line_lookups.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_line_lookups.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_line_neighbours.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_line_neighbours.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_line_neighbours.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_line_neighbours.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_line_sku_parts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_line_sku_parts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_line_sku_parts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_line_sku_parts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_running_peaks.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_running_peaks.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_running_peaks.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_running_peaks.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_sku_part_filters.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_sku_part_filters.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_sku_part_filters.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_sku_part_filters.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_tag_list_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_tag_list_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_tag_list_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_tag_list_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_tag_pairs.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_tag_pairs.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_tag_pairs.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_tag_pairs.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_tag_sets.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_tag_sets.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_tag_sets.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_tag_sets.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_top_tags.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_top_tags.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_top_tags.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_top_tags.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_xml_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_xml_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_basket_xml_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_basket_xml_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_clock_times.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_clock_times.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_clock_times.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_clock_times.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_date_lists.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_date_lists.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_date_lists.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_date_lists.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_day_documents.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_day_documents.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_day_documents.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_day_documents.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_day_starts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_day_starts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_day_starts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_day_starts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_epoch_parts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_epoch_parts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_epoch_parts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_epoch_parts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_epoch_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_epoch_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_epoch_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_epoch_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_last_day.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_last_day.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_last_day.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_last_day.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_latest_dates.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_latest_dates.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_latest_dates.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_latest_dates.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_london_times.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_london_times.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_london_times.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_london_times.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_recent_offsets.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_recent_offsets.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_recent_offsets.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_recent_offsets.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_row_numbers.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_row_numbers.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_row_numbers.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_row_numbers.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_safe_dates.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_safe_dates.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_safe_dates.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_safe_dates.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_start_fallbacks.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_start_fallbacks.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_start_fallbacks.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_start_fallbacks.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_text_dates.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_text_dates.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_text_dates.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_text_dates.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_times.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_times.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_times.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_times.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_wall_time_lists.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_wall_time_lists.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_wall_time_lists.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_wall_time_lists.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_zone_words.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_zone_words.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_zone_words.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_zone_words.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_zoned_dates.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_zoned_dates.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_callback_zoned_dates.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_callback_zoned_dates.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_category_walk.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_category_walk.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_category_walk.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_category_walk.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_amount_spreads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_amount_spreads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_amount_spreads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_amount_spreads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_any_amounts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_any_amounts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_any_amounts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_any_amounts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_bracket_strips.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_bracket_strips.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_bracket_strips.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_bracket_strips.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_complete_pairs.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_complete_pairs.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_complete_pairs.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_complete_pairs.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_decoded_keys.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_decoded_keys.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_decoded_keys.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_decoded_keys.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_distinct_tuples.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_distinct_tuples.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_distinct_tuples.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_distinct_tuples.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_formatted_dates.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_formatted_dates.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_formatted_dates.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_formatted_dates.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_generated_rows.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_generated_rows.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_generated_rows.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_generated_rows.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_group_flags.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_group_flags.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_group_flags.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_group_flags.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_group_key_lists.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_group_key_lists.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_group_key_lists.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_group_key_lists.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_group_pivots.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_group_pivots.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_group_pivots.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_group_pivots.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_key_list_edits.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_key_list_edits.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_key_list_edits.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_key_list_edits.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_key_parts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_key_parts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_key_parts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_key_parts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_key_rewrites.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_key_rewrites.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_key_rewrites.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_key_rewrites.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_label_lookups.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_label_lookups.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_label_lookups.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_label_lookups.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_last_known_keys.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_last_known_keys.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_last_known_keys.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_last_known_keys.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_local_times.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_local_times.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_local_times.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_local_times.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_minute_times.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_minute_times.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_minute_times.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_minute_times.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_month_starts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_month_starts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_month_starts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_month_starts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_note_unions.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_note_unions.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_note_unions.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_note_unions.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_number_arrays.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_number_arrays.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_number_arrays.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_number_arrays.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_number_labels.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_number_labels.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_number_labels.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_number_labels.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_pair_filters.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_pair_filters.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_pair_filters.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_pair_filters.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_pattern_matches.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_pattern_matches.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_pattern_matches.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_pattern_matches.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_reduced_keys.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_reduced_keys.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_reduced_keys.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_reduced_keys.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_sparse_arrays.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_sparse_arrays.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_sparse_arrays.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_sparse_arrays.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_text_arrays.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_text_arrays.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_text_arrays.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_text_arrays.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_unnamed_labels.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_unnamed_labels.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_unnamed_labels.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_unnamed_labels.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_variant_branches.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_variant_branches.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_variant_branches.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_variant_branches.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_wide_sums.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_wide_sums.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_wide_sums.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_wide_sums.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_xml_checks.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_xml_checks.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_xml_checks.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_xml_checks.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_zoned_literals.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_zoned_literals.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_check_zoned_literals.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_check_zoned_literals.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_clock_arithmetic.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_clock_arithmetic.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_clock_arithmetic.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_clock_arithmetic.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_clock_text_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_clock_text_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_clock_text_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_clock_text_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_customer_eligibility.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_customer_eligibility.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_customer_eligibility.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_customer_eligibility.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_customer_matches.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_customer_matches.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_customer_matches.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_customer_matches.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_status.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_status.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_status.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_status.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_status_rebuilt.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_status_rebuilt.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_status_rebuilt.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_status_rebuilt.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_status_replaced.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_status_replaced.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_status_replaced.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_status_replaced.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_update_versions.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_update_versions.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_update_versions.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_update_versions.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_versions_replaced.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_versions_replaced.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_delivery_versions_replaced.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_delivery_versions_replaced.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_expression_spans.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_expression_spans.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_expression_spans.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_expression_spans.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_first_last_aliases.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_first_last_aliases.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_first_last_aliases.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_first_last_aliases.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_grouped_windows.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_grouped_windows.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_grouped_windows.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_grouped_windows.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_join_keys.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_join_keys.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_join_keys.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_join_keys.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_json_numbers.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_json_numbers.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_json_numbers.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_json_numbers.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_key_number_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_key_number_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_key_number_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_key_number_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_key_rank_offsets.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_key_rank_offsets.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_key_rank_offsets.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_key_rank_offsets.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_key_widths.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_key_widths.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_key_widths.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_key_widths.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ledger_paid_quantities.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ledger_paid_quantities.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ledger_paid_quantities.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ledger_paid_quantities.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ledger_quantity_steps.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ledger_quantity_steps.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ledger_quantity_steps.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ledger_quantity_steps.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_line_amounts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_line_amounts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_line_amounts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_line_amounts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_note_patterns.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_note_patterns.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_note_patterns.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_note_patterns.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_null_arithmetic.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_null_arithmetic.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_null_arithmetic.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_null_arithmetic.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_order_line_labels.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_order_line_labels.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_order_line_labels.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_order_line_labels.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_order_status.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_order_status.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_order_status.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_order_status.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_orders_all_channels.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_orders_all_channels.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_orders_all_channels.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_orders_all_channels.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_arrays.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_arrays.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_arrays.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_arrays.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_attributes.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_attributes.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_attributes.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_attributes.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_documents.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_documents.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_documents.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_documents.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_item_totals.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_item_totals.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_item_totals.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_item_totals.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_lines.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_lines.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_lines.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_lines.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_objects.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_objects.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_objects.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_objects.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_paths.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_paths.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_paths.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_paths.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_tags.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_tags.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_payload_tags.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_payload_tags.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_price_changes.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_price_changes.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_price_changes.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_price_changes.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_python_values.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_python_values.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_python_values.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_python_values.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_quantity_checks.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_quantity_checks.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_quantity_checks.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_quantity_checks.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_array_bounds.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_array_bounds.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_array_bounds.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_array_bounds.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_array_casts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_array_casts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_array_casts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_array_casts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_array_positions.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_array_positions.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_array_positions.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_array_positions.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_averages.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_averages.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_averages.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_averages.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_fixed_scales.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_fixed_scales.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_fixed_scales.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_fixed_scales.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_group_objects.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_group_objects.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_group_objects.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_group_objects.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_hashes.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_hashes.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_hashes.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_hashes.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_identity_objects.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_identity_objects.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_identity_objects.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_identity_objects.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_ignore_case_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_ignore_case_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_ignore_case_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_ignore_case_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_object_differences.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_object_differences.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_object_differences.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_object_differences.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_object_flags.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_object_flags.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_object_flags.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_object_flags.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_object_inserts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_object_inserts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_object_inserts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_object_inserts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_object_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_object_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_object_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_object_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_path_checks.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_path_checks.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_path_checks.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_path_checks.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_percent_texts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_percent_texts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_percent_texts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_percent_texts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_running_totals.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_running_totals.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_running_totals.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_running_totals.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_safe_casts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_safe_casts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_safe_casts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_safe_casts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_text_forms.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_text_forms.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_text_forms.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_text_forms.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_text_replaces.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_text_replaces.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_text_replaces.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_text_replaces.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_variant_unions.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_variant_unions.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ratio_variant_unions.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ratio_variant_unions.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_recursive_counts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_recursive_counts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_recursive_counts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_recursive_counts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_reference_qualified_spans.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_reference_qualified_spans.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_reference_qualified_spans.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_reference_qualified_spans.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_row_deciders.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_row_deciders.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_row_deciders.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_row_deciders.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_settlement_calendar.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_settlement_calendar.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_settlement_calendar.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_settlement_calendar.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_settlement_periods.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_settlement_periods.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_settlement_periods.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_settlement_periods.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_sku_text_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_sku_text_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_sku_text_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_sku_text_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_text_dates.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_text_dates.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_text_dates.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_text_dates.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_text_payload_skus.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_text_payload_skus.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_text_payload_skus.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_text_payload_skus.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ticket_tokens.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ticket_tokens.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_ticket_tokens.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_ticket_tokens.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_decimal_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_decimal_reads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_decimal_reads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_decimal_reads.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_element_counts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_element_counts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_element_counts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_element_counts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_expected_values.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_expected_values.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_expected_values.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_expected_values.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_extremes.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_extremes.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_extremes.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_extremes.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_matches.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_matches.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_matches.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_matches.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_xml_elements.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_xml_elements.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_variant_xml_elements.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_variant_xml_elements.sql diff --git a/benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_zoned_texts.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_zoned_texts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/edge_cases/int_edge_zoned_texts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_zoned_texts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/finance/_sqlbuild/_constants/reporting_timezone_by_region.sql b/benchmarks/duckshop/project/sql/models/intermediate/finance/_sqlbuild/_constants/reporting_timezone_by_region.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/finance/_sqlbuild/_constants/reporting_timezone_by_region.sql rename to benchmarks/duckshop/project/sql/models/intermediate/finance/_sqlbuild/_constants/reporting_timezone_by_region.sql diff --git a/benchmarks/duckshop/project/models/intermediate/finance/int_chargeback_exposure.sql b/benchmarks/duckshop/project/sql/models/intermediate/finance/int_chargeback_exposure.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/finance/int_chargeback_exposure.sql rename to benchmarks/duckshop/project/sql/models/intermediate/finance/int_chargeback_exposure.sql diff --git a/benchmarks/duckshop/project/models/intermediate/finance/int_invoices_reconciled.sql b/benchmarks/duckshop/project/sql/models/intermediate/finance/int_invoices_reconciled.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/finance/int_invoices_reconciled.sql rename to benchmarks/duckshop/project/sql/models/intermediate/finance/int_invoices_reconciled.sql diff --git a/benchmarks/duckshop/project/models/intermediate/finance/int_ledger_balances_daily.sql b/benchmarks/duckshop/project/sql/models/intermediate/finance/int_ledger_balances_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/finance/int_ledger_balances_daily.sql rename to benchmarks/duckshop/project/sql/models/intermediate/finance/int_ledger_balances_daily.sql diff --git a/benchmarks/duckshop/project/models/intermediate/finance/int_payout_reconciliation.sql b/benchmarks/duckshop/project/sql/models/intermediate/finance/int_payout_reconciliation.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/finance/int_payout_reconciliation.sql rename to benchmarks/duckshop/project/sql/models/intermediate/finance/int_payout_reconciliation.sql diff --git a/benchmarks/duckshop/project/models/intermediate/finance/int_revenue_recognition_daily.sql b/benchmarks/duckshop/project/sql/models/intermediate/finance/int_revenue_recognition_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/finance/int_revenue_recognition_daily.sql rename to benchmarks/duckshop/project/sql/models/intermediate/finance/int_revenue_recognition_daily.sql diff --git a/benchmarks/duckshop/project/models/intermediate/finance/int_settlement_lines.sql b/benchmarks/duckshop/project/sql/models/intermediate/finance/int_settlement_lines.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/finance/int_settlement_lines.sql rename to benchmarks/duckshop/project/sql/models/intermediate/finance/int_settlement_lines.sql diff --git a/benchmarks/duckshop/project/models/intermediate/finance/int_tax_applied.sql b/benchmarks/duckshop/project/sql/models/intermediate/finance/int_tax_applied.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/finance/int_tax_applied.sql rename to benchmarks/duckshop/project/sql/models/intermediate/finance/int_tax_applied.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/_sqlbuild/_constants/unknown_region_code.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/_sqlbuild/_constants/unknown_region_code.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/_sqlbuild/_constants/unknown_region_code.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/_sqlbuild/_constants/unknown_region_code.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/_sqlbuild/_macros/python/currency_exponents.py b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/_sqlbuild/_macros/python/currency_exponents.py similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/_sqlbuild/_macros/python/currency_exponents.py rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/_sqlbuild/_macros/python/currency_exponents.py diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/int_carrier_webhook_events.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_carrier_webhook_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/int_carrier_webhook_events.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_carrier_webhook_events.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/int_delivery_exceptions_classified.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_delivery_exceptions_classified.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/int_delivery_exceptions_classified.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_delivery_exceptions_classified.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/int_delivery_slot_utilisation.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_delivery_slot_utilisation.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/int_delivery_slot_utilisation.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_delivery_slot_utilisation.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/int_fulfilment_sla.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_fulfilment_sla.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/int_fulfilment_sla.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_fulfilment_sla.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/int_pick_performance.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_pick_performance.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/int_pick_performance.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_pick_performance.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/int_return_outcomes.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_return_outcomes.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/int_return_outcomes.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_return_outcomes.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/int_return_reasons.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_return_reasons.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/int_return_reasons.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_return_reasons.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/int_shipment_costs.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_shipment_costs.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/int_shipment_costs.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_shipment_costs.sql diff --git a/benchmarks/duckshop/project/models/intermediate/fulfilment/int_shipment_tracking_events.sql b/benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_shipment_tracking_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/fulfilment/int_shipment_tracking_events.sql rename to benchmarks/duckshop/project/sql/models/intermediate/fulfilment/int_shipment_tracking_events.sql diff --git a/benchmarks/duckshop/project/models/intermediate/growth/_sqlbuild/_macros/sql/any_to_text.sql b/benchmarks/duckshop/project/sql/models/intermediate/growth/_sqlbuild/_macros/sql/any_to_text.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/growth/_sqlbuild/_macros/sql/any_to_text.sql rename to benchmarks/duckshop/project/sql/models/intermediate/growth/_sqlbuild/_macros/sql/any_to_text.sql diff --git a/benchmarks/duckshop/project/models/intermediate/growth/int_affiliate_commissions_usd.sql b/benchmarks/duckshop/project/sql/models/intermediate/growth/int_affiliate_commissions_usd.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/growth/int_affiliate_commissions_usd.sql rename to benchmarks/duckshop/project/sql/models/intermediate/growth/int_affiliate_commissions_usd.sql diff --git a/benchmarks/duckshop/project/models/intermediate/growth/int_campaign_performance.sql b/benchmarks/duckshop/project/sql/models/intermediate/growth/int_campaign_performance.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/growth/int_campaign_performance.sql rename to benchmarks/duckshop/project/sql/models/intermediate/growth/int_campaign_performance.sql diff --git a/benchmarks/duckshop/project/models/intermediate/growth/int_campaign_spend_usd.sql b/benchmarks/duckshop/project/sql/models/intermediate/growth/int_campaign_spend_usd.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/growth/int_campaign_spend_usd.sql rename to benchmarks/duckshop/project/sql/models/intermediate/growth/int_campaign_spend_usd.sql diff --git a/benchmarks/duckshop/project/models/intermediate/growth/int_influencer_promo_orders.sql b/benchmarks/duckshop/project/sql/models/intermediate/growth/int_influencer_promo_orders.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/growth/int_influencer_promo_orders.sql rename to benchmarks/duckshop/project/sql/models/intermediate/growth/int_influencer_promo_orders.sql diff --git a/benchmarks/duckshop/project/models/intermediate/growth/int_newsletter_status.sql b/benchmarks/duckshop/project/sql/models/intermediate/growth/int_newsletter_status.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/growth/int_newsletter_status.sql rename to benchmarks/duckshop/project/sql/models/intermediate/growth/int_newsletter_status.sql diff --git a/benchmarks/duckshop/project/models/intermediate/growth/int_referral_conversions.sql b/benchmarks/duckshop/project/sql/models/intermediate/growth/int_referral_conversions.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/growth/int_referral_conversions.sql rename to benchmarks/duckshop/project/sql/models/intermediate/growth/int_referral_conversions.sql diff --git a/benchmarks/duckshop/project/models/intermediate/growth/int_survey_answers_flat.sql b/benchmarks/duckshop/project/sql/models/intermediate/growth/int_survey_answers_flat.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/growth/int_survey_answers_flat.sql rename to benchmarks/duckshop/project/sql/models/intermediate/growth/int_survey_answers_flat.sql diff --git a/benchmarks/duckshop/project/models/intermediate/inventory/int_inventory_ledger.sql b/benchmarks/duckshop/project/sql/models/intermediate/inventory/int_inventory_ledger.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/inventory/int_inventory_ledger.sql rename to benchmarks/duckshop/project/sql/models/intermediate/inventory/int_inventory_ledger.sql diff --git a/benchmarks/duckshop/project/models/intermediate/inventory/int_inventory_valuation_daily.sql b/benchmarks/duckshop/project/sql/models/intermediate/inventory/int_inventory_valuation_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/inventory/int_inventory_valuation_daily.sql rename to benchmarks/duckshop/project/sql/models/intermediate/inventory/int_inventory_valuation_daily.sql diff --git a/benchmarks/duckshop/project/models/intermediate/inventory/int_purchase_order_lines_received.sql b/benchmarks/duckshop/project/sql/models/intermediate/inventory/int_purchase_order_lines_received.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/inventory/int_purchase_order_lines_received.sql rename to benchmarks/duckshop/project/sql/models/intermediate/inventory/int_purchase_order_lines_received.sql diff --git a/benchmarks/duckshop/project/models/intermediate/inventory/int_reservations_open.sql b/benchmarks/duckshop/project/sql/models/intermediate/inventory/int_reservations_open.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/inventory/int_reservations_open.sql rename to benchmarks/duckshop/project/sql/models/intermediate/inventory/int_reservations_open.sql diff --git a/benchmarks/duckshop/project/models/intermediate/inventory/int_stock_count_variances.sql b/benchmarks/duckshop/project/sql/models/intermediate/inventory/int_stock_count_variances.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/inventory/int_stock_count_variances.sql rename to benchmarks/duckshop/project/sql/models/intermediate/inventory/int_stock_count_variances.sql diff --git a/benchmarks/duckshop/project/models/intermediate/inventory/int_stock_on_hand_daily.sql b/benchmarks/duckshop/project/sql/models/intermediate/inventory/int_stock_on_hand_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/inventory/int_stock_on_hand_daily.sql rename to benchmarks/duckshop/project/sql/models/intermediate/inventory/int_stock_on_hand_daily.sql diff --git a/benchmarks/duckshop/project/models/intermediate/inventory/int_stock_transfers_in_transit.sql b/benchmarks/duckshop/project/sql/models/intermediate/inventory/int_stock_transfers_in_transit.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/inventory/int_stock_transfers_in_transit.sql rename to benchmarks/duckshop/project/sql/models/intermediate/inventory/int_stock_transfers_in_transit.sql diff --git a/benchmarks/duckshop/project/models/intermediate/inventory/int_supplier_lead_times.sql b/benchmarks/duckshop/project/sql/models/intermediate/inventory/int_supplier_lead_times.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/inventory/int_supplier_lead_times.sql rename to benchmarks/duckshop/project/sql/models/intermediate/inventory/int_supplier_lead_times.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_cart_abandonment.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_cart_abandonment.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_cart_abandonment.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_cart_abandonment.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_order_lines_discounted.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_order_lines_discounted.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_order_lines_discounted.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_order_lines_discounted.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_order_lines_priced.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_order_lines_priced.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_order_lines_priced.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_order_lines_priced.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_order_payments_rollup.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_order_payments_rollup.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_order_payments_rollup.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_order_payments_rollup.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_order_status_timeline.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_order_status_timeline.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_order_status_timeline.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_order_status_timeline.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_orders_enriched.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_orders_enriched.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_orders_enriched.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_orders_enriched.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_orders_usd.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_orders_usd.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_orders_usd.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_orders_usd.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_payment_attempts.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_payment_attempts.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_payment_attempts.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_payment_attempts.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_promotion_performance.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_promotion_performance.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_promotion_performance.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_promotion_performance.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_refunds_usd.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_refunds_usd.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_refunds_usd.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_refunds_usd.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_reviews_moderated.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_reviews_moderated.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_reviews_moderated.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_reviews_moderated.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_subscription_mrr_daily.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_subscription_mrr_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_subscription_mrr_daily.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_subscription_mrr_daily.sql diff --git a/benchmarks/duckshop/project/models/intermediate/orders/int_subscription_periods.sql b/benchmarks/duckshop/project/sql/models/intermediate/orders/int_subscription_periods.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/orders/int_subscription_periods.sql rename to benchmarks/duckshop/project/sql/models/intermediate/orders/int_subscription_periods.sql diff --git a/benchmarks/duckshop/project/models/intermediate/partners/_sqlbuild/_constants/default_currency.sql b/benchmarks/duckshop/project/sql/models/intermediate/partners/_sqlbuild/_constants/default_currency.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/partners/_sqlbuild/_constants/default_currency.sql rename to benchmarks/duckshop/project/sql/models/intermediate/partners/_sqlbuild/_constants/default_currency.sql diff --git a/benchmarks/duckshop/project/models/intermediate/partners/_sqlbuild/_macros/python/relations.py b/benchmarks/duckshop/project/sql/models/intermediate/partners/_sqlbuild/_macros/python/relations.py similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/partners/_sqlbuild/_macros/python/relations.py rename to benchmarks/duckshop/project/sql/models/intermediate/partners/_sqlbuild/_macros/python/relations.py diff --git a/benchmarks/duckshop/project/models/intermediate/partners/int_partner_fees_usd.sql b/benchmarks/duckshop/project/sql/models/intermediate/partners/int_partner_fees_usd.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/partners/int_partner_fees_usd.sql rename to benchmarks/duckshop/project/sql/models/intermediate/partners/int_partner_fees_usd.sql diff --git a/benchmarks/duckshop/project/models/intermediate/partners/int_partner_listing_status.sql b/benchmarks/duckshop/project/sql/models/intermediate/partners/int_partner_listing_status.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/partners/int_partner_listing_status.sql rename to benchmarks/duckshop/project/sql/models/intermediate/partners/int_partner_listing_status.sql diff --git a/benchmarks/duckshop/project/models/intermediate/partners/int_partner_orders_unified.sql b/benchmarks/duckshop/project/sql/models/intermediate/partners/int_partner_orders_unified.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/partners/int_partner_orders_unified.sql rename to benchmarks/duckshop/project/sql/models/intermediate/partners/int_partner_orders_unified.sql diff --git a/benchmarks/duckshop/project/models/intermediate/support/int_agent_utilisation.sql b/benchmarks/duckshop/project/sql/models/intermediate/support/int_agent_utilisation.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/support/int_agent_utilisation.sql rename to benchmarks/duckshop/project/sql/models/intermediate/support/int_agent_utilisation.sql diff --git a/benchmarks/duckshop/project/models/intermediate/support/int_call_ivr_paths.sql b/benchmarks/duckshop/project/sql/models/intermediate/support/int_call_ivr_paths.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/support/int_call_ivr_paths.sql rename to benchmarks/duckshop/project/sql/models/intermediate/support/int_call_ivr_paths.sql diff --git a/benchmarks/duckshop/project/models/intermediate/support/int_chat_sentiment.sql b/benchmarks/duckshop/project/sql/models/intermediate/support/int_chat_sentiment.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/support/int_chat_sentiment.sql rename to benchmarks/duckshop/project/sql/models/intermediate/support/int_chat_sentiment.sql diff --git a/benchmarks/duckshop/project/models/intermediate/support/int_customer_support_history.sql b/benchmarks/duckshop/project/sql/models/intermediate/support/int_customer_support_history.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/support/int_customer_support_history.sql rename to benchmarks/duckshop/project/sql/models/intermediate/support/int_customer_support_history.sql diff --git a/benchmarks/duckshop/project/models/intermediate/support/int_ticket_business_hours.sql b/benchmarks/duckshop/project/sql/models/intermediate/support/int_ticket_business_hours.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/support/int_ticket_business_hours.sql rename to benchmarks/duckshop/project/sql/models/intermediate/support/int_ticket_business_hours.sql diff --git a/benchmarks/duckshop/project/models/intermediate/support/int_ticket_first_response.sql b/benchmarks/duckshop/project/sql/models/intermediate/support/int_ticket_first_response.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/support/int_ticket_first_response.sql rename to benchmarks/duckshop/project/sql/models/intermediate/support/int_ticket_first_response.sql diff --git a/benchmarks/duckshop/project/models/intermediate/support/int_ticket_sla_breaches.sql b/benchmarks/duckshop/project/sql/models/intermediate/support/int_ticket_sla_breaches.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/support/int_ticket_sla_breaches.sql rename to benchmarks/duckshop/project/sql/models/intermediate/support/int_ticket_sla_breaches.sql diff --git a/benchmarks/duckshop/project/models/intermediate/support/int_ticket_threads.sql b/benchmarks/duckshop/project/sql/models/intermediate/support/int_ticket_threads.sql similarity index 100% rename from benchmarks/duckshop/project/models/intermediate/support/int_ticket_threads.sql rename to benchmarks/duckshop/project/sql/models/intermediate/support/int_ticket_threads.sql diff --git a/benchmarks/duckshop/project/models/marts/_sqlbuild/audits/generic/has_rows.sql b/benchmarks/duckshop/project/sql/models/marts/_sqlbuild/audits/generic/has_rows.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/_sqlbuild/audits/generic/has_rows.sql rename to benchmarks/duckshop/project/sql/models/marts/_sqlbuild/audits/generic/has_rows.sql diff --git a/benchmarks/duckshop/project/models/marts/_sqlbuild/audits/generic/non_negative.sql b/benchmarks/duckshop/project/sql/models/marts/_sqlbuild/audits/generic/non_negative.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/_sqlbuild/audits/generic/non_negative.sql rename to benchmarks/duckshop/project/sql/models/marts/_sqlbuild/audits/generic/non_negative.sql diff --git a/benchmarks/duckshop/project/models/marts/catalogue/rpt_category_tree_sales.sql b/benchmarks/duckshop/project/sql/models/marts/catalogue/rpt_category_tree_sales.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/catalogue/rpt_category_tree_sales.sql rename to benchmarks/duckshop/project/sql/models/marts/catalogue/rpt_category_tree_sales.sql diff --git a/benchmarks/duckshop/project/models/marts/catalogue/rpt_margin_by_category.sql b/benchmarks/duckshop/project/sql/models/marts/catalogue/rpt_margin_by_category.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/catalogue/rpt_margin_by_category.sql rename to benchmarks/duckshop/project/sql/models/marts/catalogue/rpt_margin_by_category.sql diff --git a/benchmarks/duckshop/project/models/marts/catalogue/rpt_price_changes_weekly.sql b/benchmarks/duckshop/project/sql/models/marts/catalogue/rpt_price_changes_weekly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/catalogue/rpt_price_changes_weekly.sql rename to benchmarks/duckshop/project/sql/models/marts/catalogue/rpt_price_changes_weekly.sql diff --git a/benchmarks/duckshop/project/models/marts/catalogue/rpt_wishlist_conversion.sql b/benchmarks/duckshop/project/sql/models/marts/catalogue/rpt_wishlist_conversion.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/catalogue/rpt_wishlist_conversion.sql rename to benchmarks/duckshop/project/sql/models/marts/catalogue/rpt_wishlist_conversion.sql diff --git a/benchmarks/duckshop/project/models/marts/clickstream/fct_web_sessions.sql b/benchmarks/duckshop/project/sql/models/marts/clickstream/fct_web_sessions.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/clickstream/fct_web_sessions.sql rename to benchmarks/duckshop/project/sql/models/marts/clickstream/fct_web_sessions.sql diff --git a/benchmarks/duckshop/project/models/marts/clickstream/rpt_app_engagement_weekly.sql b/benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_app_engagement_weekly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/clickstream/rpt_app_engagement_weekly.sql rename to benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_app_engagement_weekly.sql diff --git a/benchmarks/duckshop/project/models/marts/clickstream/rpt_channel_attribution_daily.sql b/benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_channel_attribution_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/clickstream/rpt_channel_attribution_daily.sql rename to benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_channel_attribution_daily.sql diff --git a/benchmarks/duckshop/project/models/marts/clickstream/rpt_experiment_results.sql b/benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_experiment_results.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/clickstream/rpt_experiment_results.sql rename to benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_experiment_results.sql diff --git a/benchmarks/duckshop/project/models/marts/clickstream/rpt_product_affinity_top.sql b/benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_product_affinity_top.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/clickstream/rpt_product_affinity_top.sql rename to benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_product_affinity_top.sql diff --git a/benchmarks/duckshop/project/models/marts/clickstream/rpt_search_terms_top.sql b/benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_search_terms_top.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/clickstream/rpt_search_terms_top.sql rename to benchmarks/duckshop/project/sql/models/marts/clickstream/rpt_search_terms_top.sql diff --git a/benchmarks/duckshop/project/models/marts/core/_sqlbuild/_schemas/address.sql b/benchmarks/duckshop/project/sql/models/marts/core/_sqlbuild/_schemas/address.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/_sqlbuild/_schemas/address.sql rename to benchmarks/duckshop/project/sql/models/marts/core/_sqlbuild/_schemas/address.sql diff --git a/benchmarks/duckshop/project/models/marts/core/_sqlbuild/_schemas/audit_ts.sql b/benchmarks/duckshop/project/sql/models/marts/core/_sqlbuild/_schemas/audit_ts.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/_sqlbuild/_schemas/audit_ts.sql rename to benchmarks/duckshop/project/sql/models/marts/core/_sqlbuild/_schemas/audit_ts.sql diff --git a/benchmarks/duckshop/project/models/marts/core/dim_campaigns.sql b/benchmarks/duckshop/project/sql/models/marts/core/dim_campaigns.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/dim_campaigns.sql rename to benchmarks/duckshop/project/sql/models/marts/core/dim_campaigns.sql diff --git a/benchmarks/duckshop/project/models/marts/core/dim_carriers.sql b/benchmarks/duckshop/project/sql/models/marts/core/dim_carriers.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/dim_carriers.sql rename to benchmarks/duckshop/project/sql/models/marts/core/dim_carriers.sql diff --git a/benchmarks/duckshop/project/models/marts/core/dim_customers.sql b/benchmarks/duckshop/project/sql/models/marts/core/dim_customers.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/dim_customers.sql rename to benchmarks/duckshop/project/sql/models/marts/core/dim_customers.sql diff --git a/benchmarks/duckshop/project/models/marts/core/dim_date.sql b/benchmarks/duckshop/project/sql/models/marts/core/dim_date.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/dim_date.sql rename to benchmarks/duckshop/project/sql/models/marts/core/dim_date.sql diff --git a/benchmarks/duckshop/project/models/marts/core/dim_products.sql b/benchmarks/duckshop/project/sql/models/marts/core/dim_products.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/dim_products.sql rename to benchmarks/duckshop/project/sql/models/marts/core/dim_products.sql diff --git a/benchmarks/duckshop/project/models/marts/core/dim_promotions.sql b/benchmarks/duckshop/project/sql/models/marts/core/dim_promotions.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/dim_promotions.sql rename to benchmarks/duckshop/project/sql/models/marts/core/dim_promotions.sql diff --git a/benchmarks/duckshop/project/models/marts/core/dim_suppliers.sql b/benchmarks/duckshop/project/sql/models/marts/core/dim_suppliers.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/dim_suppliers.sql rename to benchmarks/duckshop/project/sql/models/marts/core/dim_suppliers.sql diff --git a/benchmarks/duckshop/project/models/marts/core/dim_warehouses.sql b/benchmarks/duckshop/project/sql/models/marts/core/dim_warehouses.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/core/dim_warehouses.sql rename to benchmarks/duckshop/project/sql/models/marts/core/dim_warehouses.sql diff --git a/benchmarks/duckshop/project/models/marts/customers/rpt_consent_coverage.sql b/benchmarks/duckshop/project/sql/models/marts/customers/rpt_consent_coverage.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/customers/rpt_consent_coverage.sql rename to benchmarks/duckshop/project/sql/models/marts/customers/rpt_consent_coverage.sql diff --git a/benchmarks/duckshop/project/models/marts/customers/rpt_customer_cohorts_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/customers/rpt_customer_cohorts_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/customers/rpt_customer_cohorts_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/customers/rpt_customer_cohorts_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/customers/rpt_customer_order_lookup.sql b/benchmarks/duckshop/project/sql/models/marts/customers/rpt_customer_order_lookup.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/customers/rpt_customer_order_lookup.sql rename to benchmarks/duckshop/project/sql/models/marts/customers/rpt_customer_order_lookup.sql diff --git a/benchmarks/duckshop/project/models/marts/customers/rpt_gift_card_liability.sql b/benchmarks/duckshop/project/sql/models/marts/customers/rpt_gift_card_liability.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/customers/rpt_gift_card_liability.sql rename to benchmarks/duckshop/project/sql/models/marts/customers/rpt_gift_card_liability.sql diff --git a/benchmarks/duckshop/project/models/marts/customers/rpt_loyalty_liability.sql b/benchmarks/duckshop/project/sql/models/marts/customers/rpt_loyalty_liability.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/customers/rpt_loyalty_liability.sql rename to benchmarks/duckshop/project/sql/models/marts/customers/rpt_loyalty_liability.sql diff --git a/benchmarks/duckshop/project/models/marts/customers/rpt_referral_program.sql b/benchmarks/duckshop/project/sql/models/marts/customers/rpt_referral_program.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/customers/rpt_referral_program.sql rename to benchmarks/duckshop/project/sql/models/marts/customers/rpt_referral_program.sql diff --git a/benchmarks/duckshop/project/models/marts/customers/rpt_rfm_segment_summary.sql b/benchmarks/duckshop/project/sql/models/marts/customers/rpt_rfm_segment_summary.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/customers/rpt_rfm_segment_summary.sql rename to benchmarks/duckshop/project/sql/models/marts/customers/rpt_rfm_segment_summary.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/dim_edge_partner_listings.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/dim_edge_partner_listings.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/dim_edge_partner_listings.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/dim_edge_partner_listings.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/fct_edge_delivery_events.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/fct_edge_delivery_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/fct_edge_delivery_events.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/fct_edge_delivery_events.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/fct_edge_payload_events.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/fct_edge_payload_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/fct_edge_payload_events.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/fct_edge_payload_events.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_case_array_model_keys.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_case_array_model_keys.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_case_array_model_keys.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_case_array_model_keys.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_case_model_keys.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_case_model_keys.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_case_model_keys.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_case_model_keys.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_channel_reasons.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_channel_reasons.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_channel_reasons.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_channel_reasons.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_daily_callbacks.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_daily_callbacks.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_daily_callbacks.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_daily_callbacks.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_header_contracts.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_header_contracts.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_header_contracts.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_header_contracts.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_partner_listing_export.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_partner_listing_export.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_partner_listing_export.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_partner_listing_export.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_partner_payload_fields.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_partner_payload_fields.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_partner_payload_fields.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_partner_payload_fields.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_payload_price_types.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_payload_price_types.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_payload_price_types.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_payload_price_types.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_planner_fan_in.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_planner_fan_in.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_planner_fan_in.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_planner_fan_in.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_scheduled_function.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_scheduled_function.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_scheduled_function.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_scheduled_function.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_stock_reconciliation.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_stock_reconciliation.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/rpt_edge_stock_reconciliation.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/rpt_edge_stock_reconciliation.sql diff --git a/benchmarks/duckshop/project/models/marts/edge_cases/snap_edge_partner_listing_export.sql b/benchmarks/duckshop/project/sql/models/marts/edge_cases/snap_edge_partner_listing_export.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/edge_cases/snap_edge_partner_listing_export.sql rename to benchmarks/duckshop/project/sql/models/marts/edge_cases/snap_edge_partner_listing_export.sql diff --git a/benchmarks/duckshop/project/models/marts/executive/rpt_executive_kpis_daily.sql b/benchmarks/duckshop/project/sql/models/marts/executive/rpt_executive_kpis_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/executive/rpt_executive_kpis_daily.sql rename to benchmarks/duckshop/project/sql/models/marts/executive/rpt_executive_kpis_daily.sql diff --git a/benchmarks/duckshop/project/models/marts/executive/rpt_region_scorecard_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/executive/rpt_region_scorecard_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/executive/rpt_region_scorecard_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/executive/rpt_region_scorecard_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/finance/fct_ledger_month_end.sql b/benchmarks/duckshop/project/sql/models/marts/finance/fct_ledger_month_end.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/finance/fct_ledger_month_end.sql rename to benchmarks/duckshop/project/sql/models/marts/finance/fct_ledger_month_end.sql diff --git a/benchmarks/duckshop/project/models/marts/finance/rpt_chargeback_exposure.sql b/benchmarks/duckshop/project/sql/models/marts/finance/rpt_chargeback_exposure.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/finance/rpt_chargeback_exposure.sql rename to benchmarks/duckshop/project/sql/models/marts/finance/rpt_chargeback_exposure.sql diff --git a/benchmarks/duckshop/project/models/marts/finance/rpt_invoice_sequence_gaps.sql b/benchmarks/duckshop/project/sql/models/marts/finance/rpt_invoice_sequence_gaps.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/finance/rpt_invoice_sequence_gaps.sql rename to benchmarks/duckshop/project/sql/models/marts/finance/rpt_invoice_sequence_gaps.sql diff --git a/benchmarks/duckshop/project/models/marts/finance/rpt_payout_reconciliation_status.sql b/benchmarks/duckshop/project/sql/models/marts/finance/rpt_payout_reconciliation_status.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/finance/rpt_payout_reconciliation_status.sql rename to benchmarks/duckshop/project/sql/models/marts/finance/rpt_payout_reconciliation_status.sql diff --git a/benchmarks/duckshop/project/models/marts/finance/rpt_revenue_recognition_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/finance/rpt_revenue_recognition_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/finance/rpt_revenue_recognition_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/finance/rpt_revenue_recognition_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/finance/rpt_tax_variance_by_country.sql b/benchmarks/duckshop/project/sql/models/marts/finance/rpt_tax_variance_by_country.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/finance/rpt_tax_variance_by_country.sql rename to benchmarks/duckshop/project/sql/models/marts/finance/rpt_tax_variance_by_country.sql diff --git a/benchmarks/duckshop/project/models/marts/fulfilment/fct_shipments.sql b/benchmarks/duckshop/project/sql/models/marts/fulfilment/fct_shipments.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/fulfilment/fct_shipments.sql rename to benchmarks/duckshop/project/sql/models/marts/fulfilment/fct_shipments.sql diff --git a/benchmarks/duckshop/project/models/marts/fulfilment/rpt_carrier_performance_weekly.sql b/benchmarks/duckshop/project/sql/models/marts/fulfilment/rpt_carrier_performance_weekly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/fulfilment/rpt_carrier_performance_weekly.sql rename to benchmarks/duckshop/project/sql/models/marts/fulfilment/rpt_carrier_performance_weekly.sql diff --git a/benchmarks/duckshop/project/models/marts/fulfilment/rpt_delivery_exceptions_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/fulfilment/rpt_delivery_exceptions_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/fulfilment/rpt_delivery_exceptions_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/fulfilment/rpt_delivery_exceptions_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/fulfilment/rpt_returns_by_reason.sql b/benchmarks/duckshop/project/sql/models/marts/fulfilment/rpt_returns_by_reason.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/fulfilment/rpt_returns_by_reason.sql rename to benchmarks/duckshop/project/sql/models/marts/fulfilment/rpt_returns_by_reason.sql diff --git a/benchmarks/duckshop/project/models/marts/fulfilment/rpt_warehouse_productivity_daily.sql b/benchmarks/duckshop/project/sql/models/marts/fulfilment/rpt_warehouse_productivity_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/fulfilment/rpt_warehouse_productivity_daily.sql rename to benchmarks/duckshop/project/sql/models/marts/fulfilment/rpt_warehouse_productivity_daily.sql diff --git a/benchmarks/duckshop/project/models/marts/growth/fct_campaign_spend.sql b/benchmarks/duckshop/project/sql/models/marts/growth/fct_campaign_spend.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/growth/fct_campaign_spend.sql rename to benchmarks/duckshop/project/sql/models/marts/growth/fct_campaign_spend.sql diff --git a/benchmarks/duckshop/project/models/marts/growth/rpt_affiliate_payouts_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/growth/rpt_affiliate_payouts_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/growth/rpt_affiliate_payouts_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/growth/rpt_affiliate_payouts_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/growth/rpt_campaign_roas_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/growth/rpt_campaign_roas_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/growth/rpt_campaign_roas_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/growth/rpt_campaign_roas_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/growth/rpt_influencer_leaderboard.sql b/benchmarks/duckshop/project/sql/models/marts/growth/rpt_influencer_leaderboard.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/growth/rpt_influencer_leaderboard.sql rename to benchmarks/duckshop/project/sql/models/marts/growth/rpt_influencer_leaderboard.sql diff --git a/benchmarks/duckshop/project/models/marts/growth/rpt_newsletter_growth_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/growth/rpt_newsletter_growth_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/growth/rpt_newsletter_growth_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/growth/rpt_newsletter_growth_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/growth/rpt_survey_nps_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/growth/rpt_survey_nps_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/growth/rpt_survey_nps_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/growth/rpt_survey_nps_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/inventory/fct_inventory_daily.sql b/benchmarks/duckshop/project/sql/models/marts/inventory/fct_inventory_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/inventory/fct_inventory_daily.sql rename to benchmarks/duckshop/project/sql/models/marts/inventory/fct_inventory_daily.sql diff --git a/benchmarks/duckshop/project/models/marts/inventory/rpt_inventory_valuation_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/inventory/rpt_inventory_valuation_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/inventory/rpt_inventory_valuation_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/inventory/rpt_inventory_valuation_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/inventory/rpt_stock_count_accuracy.sql b/benchmarks/duckshop/project/sql/models/marts/inventory/rpt_stock_count_accuracy.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/inventory/rpt_stock_count_accuracy.sql rename to benchmarks/duckshop/project/sql/models/marts/inventory/rpt_stock_count_accuracy.sql diff --git a/benchmarks/duckshop/project/models/marts/inventory/rpt_stock_outs_weekly.sql b/benchmarks/duckshop/project/sql/models/marts/inventory/rpt_stock_outs_weekly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/inventory/rpt_stock_outs_weekly.sql rename to benchmarks/duckshop/project/sql/models/marts/inventory/rpt_stock_outs_weekly.sql diff --git a/benchmarks/duckshop/project/models/marts/inventory/rpt_supplier_scorecard.sql b/benchmarks/duckshop/project/sql/models/marts/inventory/rpt_supplier_scorecard.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/inventory/rpt_supplier_scorecard.sql rename to benchmarks/duckshop/project/sql/models/marts/inventory/rpt_supplier_scorecard.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/_sqlbuild/_audits/generic/valid_currency.sql b/benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/_audits/generic/valid_currency.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/_sqlbuild/_audits/generic/valid_currency.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/_audits/generic/valid_currency.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/_sqlbuild/_hooks/sql/comment_on_relation.sql b/benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/_hooks/sql/comment_on_relation.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/_sqlbuild/_hooks/sql/comment_on_relation.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/_hooks/sql/comment_on_relation.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/_sqlbuild/_schemas/money.sql b/benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/_schemas/money.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/_sqlbuild/_schemas/money.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/_schemas/money.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/_sqlbuild/_schemas/money_with_fx.sql b/benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/_schemas/money_with_fx.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/_sqlbuild/_schemas/money_with_fx.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/_schemas/money_with_fx.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/_sqlbuild/audits/singular/orders_balance_to_payments.sql b/benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/audits/singular/orders_balance_to_payments.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/_sqlbuild/audits/singular/orders_balance_to_payments.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/_sqlbuild/audits/singular/orders_balance_to_payments.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/fct_order_lines.sql b/benchmarks/duckshop/project/sql/models/marts/orders/fct_order_lines.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/fct_order_lines.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/fct_order_lines.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/fct_orders.sql b/benchmarks/duckshop/project/sql/models/marts/orders/fct_orders.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/fct_orders.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/fct_orders.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/fct_payments.sql b/benchmarks/duckshop/project/sql/models/marts/orders/fct_payments.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/fct_payments.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/fct_payments.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/fct_refunds.sql b/benchmarks/duckshop/project/sql/models/marts/orders/fct_refunds.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/fct_refunds.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/fct_refunds.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/rpt_basket_mix_weekly.sql b/benchmarks/duckshop/project/sql/models/marts/orders/rpt_basket_mix_weekly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/rpt_basket_mix_weekly.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/rpt_basket_mix_weekly.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/rpt_cart_abandonment_daily.sql b/benchmarks/duckshop/project/sql/models/marts/orders/rpt_cart_abandonment_daily.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/rpt_cart_abandonment_daily.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/rpt_cart_abandonment_daily.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/rpt_daily_sales_by_region.sql b/benchmarks/duckshop/project/sql/models/marts/orders/rpt_daily_sales_by_region.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/rpt_daily_sales_by_region.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/rpt_daily_sales_by_region.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/rpt_payment_decline_rates.sql b/benchmarks/duckshop/project/sql/models/marts/orders/rpt_payment_decline_rates.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/rpt_payment_decline_rates.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/rpt_payment_decline_rates.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/rpt_review_scores_by_product.sql b/benchmarks/duckshop/project/sql/models/marts/orders/rpt_review_scores_by_product.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/rpt_review_scores_by_product.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/rpt_review_scores_by_product.sql diff --git a/benchmarks/duckshop/project/models/marts/orders/rpt_subscription_mrr_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/orders/rpt_subscription_mrr_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/orders/rpt_subscription_mrr_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/orders/rpt_subscription_mrr_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/partners/fct_partner_orders.sql b/benchmarks/duckshop/project/sql/models/marts/partners/fct_partner_orders.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/partners/fct_partner_orders.sql rename to benchmarks/duckshop/project/sql/models/marts/partners/fct_partner_orders.sql diff --git a/benchmarks/duckshop/project/models/marts/partners/rpt_partner_fees_variance.sql b/benchmarks/duckshop/project/sql/models/marts/partners/rpt_partner_fees_variance.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/partners/rpt_partner_fees_variance.sql rename to benchmarks/duckshop/project/sql/models/marts/partners/rpt_partner_fees_variance.sql diff --git a/benchmarks/duckshop/project/models/marts/partners/rpt_partner_listing_health.sql b/benchmarks/duckshop/project/sql/models/marts/partners/rpt_partner_listing_health.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/partners/rpt_partner_listing_health.sql rename to benchmarks/duckshop/project/sql/models/marts/partners/rpt_partner_listing_health.sql diff --git a/benchmarks/duckshop/project/models/marts/support/fct_support_tickets.sql b/benchmarks/duckshop/project/sql/models/marts/support/fct_support_tickets.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/support/fct_support_tickets.sql rename to benchmarks/duckshop/project/sql/models/marts/support/fct_support_tickets.sql diff --git a/benchmarks/duckshop/project/models/marts/support/rpt_agent_scorecard.sql b/benchmarks/duckshop/project/sql/models/marts/support/rpt_agent_scorecard.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/support/rpt_agent_scorecard.sql rename to benchmarks/duckshop/project/sql/models/marts/support/rpt_agent_scorecard.sql diff --git a/benchmarks/duckshop/project/models/marts/support/rpt_contact_reasons_monthly.sql b/benchmarks/duckshop/project/sql/models/marts/support/rpt_contact_reasons_monthly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/support/rpt_contact_reasons_monthly.sql rename to benchmarks/duckshop/project/sql/models/marts/support/rpt_contact_reasons_monthly.sql diff --git a/benchmarks/duckshop/project/models/marts/support/rpt_support_sla_weekly.sql b/benchmarks/duckshop/project/sql/models/marts/support/rpt_support_sla_weekly.sql similarity index 100% rename from benchmarks/duckshop/project/models/marts/support/rpt_support_sla_weekly.sql rename to benchmarks/duckshop/project/sql/models/marts/support/rpt_support_sla_weekly.sql diff --git a/benchmarks/duckshop/project/models/snapshots/snap_customers.sql b/benchmarks/duckshop/project/sql/models/snapshots/snap_customers.sql similarity index 100% rename from benchmarks/duckshop/project/models/snapshots/snap_customers.sql rename to benchmarks/duckshop/project/sql/models/snapshots/snap_customers.sql diff --git a/benchmarks/duckshop/project/models/snapshots/snap_loyalty_tiers.sql b/benchmarks/duckshop/project/sql/models/snapshots/snap_loyalty_tiers.sql similarity index 100% rename from benchmarks/duckshop/project/models/snapshots/snap_loyalty_tiers.sql rename to benchmarks/duckshop/project/sql/models/snapshots/snap_loyalty_tiers.sql diff --git a/benchmarks/duckshop/project/models/snapshots/snap_partner_listings.sql b/benchmarks/duckshop/project/sql/models/snapshots/snap_partner_listings.sql similarity index 100% rename from benchmarks/duckshop/project/models/snapshots/snap_partner_listings.sql rename to benchmarks/duckshop/project/sql/models/snapshots/snap_partner_listings.sql diff --git a/benchmarks/duckshop/project/models/snapshots/snap_price_list_history.sql b/benchmarks/duckshop/project/sql/models/snapshots/snap_price_list_history.sql similarity index 100% rename from benchmarks/duckshop/project/models/snapshots/snap_price_list_history.sql rename to benchmarks/duckshop/project/sql/models/snapshots/snap_price_list_history.sql diff --git a/benchmarks/duckshop/project/models/snapshots/snap_products.sql b/benchmarks/duckshop/project/sql/models/snapshots/snap_products.sql similarity index 100% rename from benchmarks/duckshop/project/models/snapshots/snap_products.sql rename to benchmarks/duckshop/project/sql/models/snapshots/snap_products.sql diff --git a/benchmarks/duckshop/project/models/snapshots/snap_warehouses.sql b/benchmarks/duckshop/project/sql/models/snapshots/snap_warehouses.sql similarity index 100% rename from benchmarks/duckshop/project/models/snapshots/snap_warehouses.sql rename to benchmarks/duckshop/project/sql/models/snapshots/snap_warehouses.sql diff --git a/benchmarks/duckshop/project/models/staging/_sqlbuild/constants/patterns.sql b/benchmarks/duckshop/project/sql/models/staging/_sqlbuild/constants/patterns.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/_sqlbuild/constants/patterns.sql rename to benchmarks/duckshop/project/sql/models/staging/_sqlbuild/constants/patterns.sql diff --git a/benchmarks/duckshop/project/models/staging/_sqlbuild/enums/cdc_op.sql b/benchmarks/duckshop/project/sql/models/staging/_sqlbuild/enums/cdc_op.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/_sqlbuild/enums/cdc_op.sql rename to benchmarks/duckshop/project/sql/models/staging/_sqlbuild/enums/cdc_op.sql diff --git a/benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/cdc_latest.sql b/benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/cdc_latest.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/cdc_latest.sql rename to benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/cdc_latest.sql diff --git a/benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/epoch_ms_to_utc.sql b/benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/epoch_ms_to_utc.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/epoch_ms_to_utc.sql rename to benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/epoch_ms_to_utc.sql diff --git a/benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/json_text.sql b/benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/json_text.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/json_text.sql rename to benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/json_text.sql diff --git a/benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/load_metadata.sql b/benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/load_metadata.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/load_metadata.sql rename to benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/load_metadata.sql diff --git a/benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/normalise_email.sql b/benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/normalise_email.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/normalise_email.sql rename to benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/normalise_email.sql diff --git a/benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/normalise_phone.sql b/benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/normalise_phone.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/normalise_phone.sql rename to benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/normalise_phone.sql diff --git a/benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/normalise_sku.sql b/benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/normalise_sku.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/_sqlbuild/macros/sql/normalise_sku.sql rename to benchmarks/duckshop/project/sql/models/staging/_sqlbuild/macros/sql/normalise_sku.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_brands.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_brands.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_brands.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_brands.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_bundle_components.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_bundle_components.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_bundle_components.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_bundle_components.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_bundles.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_bundles.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_bundles.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_bundles.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_categories.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_categories.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_categories.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_categories.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_price_lists.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_price_lists.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_price_lists.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_price_lists.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_product_media.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_product_media.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_product_media.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_product_media.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_product_variant_barcodes.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_product_variant_barcodes.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_product_variant_barcodes.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_product_variant_barcodes.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_product_variants.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_product_variants.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_product_variants.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_product_variants.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_products.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_products.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_products.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_products.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_supplier_costs.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_supplier_costs.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_supplier_costs.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_supplier_costs.sql diff --git a/benchmarks/duckshop/project/models/staging/catalogue/stg_suppliers.sql b/benchmarks/duckshop/project/sql/models/staging/catalogue/stg_suppliers.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/catalogue/stg_suppliers.sql rename to benchmarks/duckshop/project/sql/models/staging/catalogue/stg_suppliers.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_app_events.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_app_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_app_events.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_app_events.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_app_push_opens.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_app_push_opens.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_app_push_opens.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_app_push_opens.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_app_screen_views.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_app_screen_views.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_app_screen_views.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_app_screen_views.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_email_events.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_email_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_email_events.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_email_events.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_experiment_assignments.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_experiment_assignments.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_experiment_assignments.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_experiment_assignments.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_search_queries.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_search_queries.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_search_queries.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_search_queries.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_web_cart_events.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_cart_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_web_cart_events.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_cart_events.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_web_checkout_steps.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_checkout_steps.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_web_checkout_steps.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_checkout_steps.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_web_events.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_web_events.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_events.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_web_identifies.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_identifies.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_web_identifies.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_identifies.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_web_page_views.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_page_views.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_web_page_views.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_page_views.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_web_product_views.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_product_views.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_web_product_views.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_product_views.sql diff --git a/benchmarks/duckshop/project/models/staging/clickstream/stg_web_searches.sql b/benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_searches.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/clickstream/stg_web_searches.sql rename to benchmarks/duckshop/project/sql/models/staging/clickstream/stg_web_searches.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/_sqlbuild/_macros/sql/collapse_whitespace.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/_sqlbuild/_macros/sql/collapse_whitespace.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/_sqlbuild/_macros/sql/collapse_whitespace.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/_sqlbuild/_macros/sql/collapse_whitespace.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_amount_checks.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_amount_checks.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_amount_checks.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_amount_checks.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_basket_lines.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_basket_lines.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_basket_lines.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_basket_lines.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_category_links.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_category_links.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_category_links.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_category_links.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_customer_profiles.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_customer_profiles.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_customer_profiles.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_customer_profiles.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_date_texts.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_date_texts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_date_texts.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_date_texts.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_gateway_callbacks.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_gateway_callbacks.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_gateway_callbacks.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_gateway_callbacks.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_ledger_entries.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_ledger_entries.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_ledger_entries.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_ledger_entries.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_partner_listings.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_partner_listings.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_partner_listings.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_partner_listings.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_partner_payloads.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_partner_payloads.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_partner_payloads.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_partner_payloads.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_price_windows.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_price_windows.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_price_windows.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_price_windows.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_supplier_notes.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_supplier_notes.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_supplier_notes.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_supplier_notes.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_ticket_notes.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_ticket_notes.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_ticket_notes.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_ticket_notes.sql diff --git a/benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_variant_values.sql b/benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_variant_values.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/edge_cases/stg_edge_variant_values.sql rename to benchmarks/duckshop/project/sql/models/staging/edge_cases/stg_edge_variant_values.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/_sqlbuild/_audits/generic/unique_combination.sql b/benchmarks/duckshop/project/sql/models/staging/finance/_sqlbuild/_audits/generic/unique_combination.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/_sqlbuild/_audits/generic/unique_combination.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/_sqlbuild/_audits/generic/unique_combination.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/stg_chargebacks.sql b/benchmarks/duckshop/project/sql/models/staging/finance/stg_chargebacks.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/stg_chargebacks.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/stg_chargebacks.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/stg_fx_rates.sql b/benchmarks/duckshop/project/sql/models/staging/finance/stg_fx_rates.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/stg_fx_rates.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/stg_fx_rates.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/stg_invoice_tax_lines.sql b/benchmarks/duckshop/project/sql/models/staging/finance/stg_invoice_tax_lines.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/stg_invoice_tax_lines.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/stg_invoice_tax_lines.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/stg_invoices.sql b/benchmarks/duckshop/project/sql/models/staging/finance/stg_invoices.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/stg_invoices.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/stg_invoices.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/stg_ledger_entries.sql b/benchmarks/duckshop/project/sql/models/staging/finance/stg_ledger_entries.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/stg_ledger_entries.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/stg_ledger_entries.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/stg_payout_lines.sql b/benchmarks/duckshop/project/sql/models/staging/finance/stg_payout_lines.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/stg_payout_lines.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/stg_payout_lines.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/stg_payouts.sql b/benchmarks/duckshop/project/sql/models/staging/finance/stg_payouts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/stg_payouts.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/stg_payouts.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/stg_settlement_reports.sql b/benchmarks/duckshop/project/sql/models/staging/finance/stg_settlement_reports.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/stg_settlement_reports.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/stg_settlement_reports.sql diff --git a/benchmarks/duckshop/project/models/staging/finance/stg_tax_rates.sql b/benchmarks/duckshop/project/sql/models/staging/finance/stg_tax_rates.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/finance/stg_tax_rates.sql rename to benchmarks/duckshop/project/sql/models/staging/finance/stg_tax_rates.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_carrier_rate_cards.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_carrier_rate_cards.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_carrier_rate_cards.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_carrier_rate_cards.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_carrier_webhook_errors.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_carrier_webhook_errors.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_carrier_webhook_errors.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_carrier_webhook_errors.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_carrier_webhooks.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_carrier_webhooks.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_carrier_webhooks.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_carrier_webhooks.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_delivery_exceptions.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_delivery_exceptions.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_delivery_exceptions.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_delivery_exceptions.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_delivery_slots.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_delivery_slots.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_delivery_slots.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_delivery_slots.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_pick_tasks.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_pick_tasks.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_pick_tasks.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_pick_tasks.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_return_inspections.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_return_inspections.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_return_inspections.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_return_inspections.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_returns.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_returns.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_returns.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_returns.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_shipment_packages.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_shipment_packages.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_shipment_packages.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_shipment_packages.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_shipment_tracking_events.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_shipment_tracking_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_shipment_tracking_events.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_shipment_tracking_events.sql diff --git a/benchmarks/duckshop/project/models/staging/fulfilment/stg_shipments.sql b/benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_shipments.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/fulfilment/stg_shipments.sql rename to benchmarks/duckshop/project/sql/models/staging/fulfilment/stg_shipments.sql diff --git a/benchmarks/duckshop/project/models/staging/growth/stg_affiliate_conversions.sql b/benchmarks/duckshop/project/sql/models/staging/growth/stg_affiliate_conversions.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/growth/stg_affiliate_conversions.sql rename to benchmarks/duckshop/project/sql/models/staging/growth/stg_affiliate_conversions.sql diff --git a/benchmarks/duckshop/project/models/staging/growth/stg_campaign_spend.sql b/benchmarks/duckshop/project/sql/models/staging/growth/stg_campaign_spend.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/growth/stg_campaign_spend.sql rename to benchmarks/duckshop/project/sql/models/staging/growth/stg_campaign_spend.sql diff --git a/benchmarks/duckshop/project/models/staging/growth/stg_campaigns.sql b/benchmarks/duckshop/project/sql/models/staging/growth/stg_campaigns.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/growth/stg_campaigns.sql rename to benchmarks/duckshop/project/sql/models/staging/growth/stg_campaigns.sql diff --git a/benchmarks/duckshop/project/models/staging/growth/stg_influencer_posts.sql b/benchmarks/duckshop/project/sql/models/staging/growth/stg_influencer_posts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/growth/stg_influencer_posts.sql rename to benchmarks/duckshop/project/sql/models/staging/growth/stg_influencer_posts.sql diff --git a/benchmarks/duckshop/project/models/staging/growth/stg_newsletter_subscriptions.sql b/benchmarks/duckshop/project/sql/models/staging/growth/stg_newsletter_subscriptions.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/growth/stg_newsletter_subscriptions.sql rename to benchmarks/duckshop/project/sql/models/staging/growth/stg_newsletter_subscriptions.sql diff --git a/benchmarks/duckshop/project/models/staging/growth/stg_referral_invites.sql b/benchmarks/duckshop/project/sql/models/staging/growth/stg_referral_invites.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/growth/stg_referral_invites.sql rename to benchmarks/duckshop/project/sql/models/staging/growth/stg_referral_invites.sql diff --git a/benchmarks/duckshop/project/models/staging/growth/stg_survey_responses.sql b/benchmarks/duckshop/project/sql/models/staging/growth/stg_survey_responses.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/growth/stg_survey_responses.sql rename to benchmarks/duckshop/project/sql/models/staging/growth/stg_survey_responses.sql diff --git a/benchmarks/duckshop/project/models/staging/inventory/stg_bin_locations.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_bin_locations.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/inventory/stg_bin_locations.sql rename to benchmarks/duckshop/project/sql/models/staging/inventory/stg_bin_locations.sql diff --git a/benchmarks/duckshop/project/models/staging/inventory/stg_po_receipts.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_po_receipts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/inventory/stg_po_receipts.sql rename to benchmarks/duckshop/project/sql/models/staging/inventory/stg_po_receipts.sql diff --git a/benchmarks/duckshop/project/models/staging/inventory/stg_purchase_order_lines.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_purchase_order_lines.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/inventory/stg_purchase_order_lines.sql rename to benchmarks/duckshop/project/sql/models/staging/inventory/stg_purchase_order_lines.sql diff --git a/benchmarks/duckshop/project/models/staging/inventory/stg_purchase_orders.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_purchase_orders.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/inventory/stg_purchase_orders.sql rename to benchmarks/duckshop/project/sql/models/staging/inventory/stg_purchase_orders.sql diff --git a/benchmarks/duckshop/project/models/staging/inventory/stg_stock_counts.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_counts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/inventory/stg_stock_counts.sql rename to benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_counts.sql diff --git a/benchmarks/duckshop/project/models/staging/inventory/stg_stock_movements.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_movements.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/inventory/stg_stock_movements.sql rename to benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_movements.sql diff --git a/benchmarks/duckshop/project/models/staging/inventory/stg_stock_reservations.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_reservations.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/inventory/stg_stock_reservations.sql rename to benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_reservations.sql diff --git a/benchmarks/duckshop/project/models/staging/inventory/stg_stock_transfers.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_transfers.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/inventory/stg_stock_transfers.sql rename to benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_transfers.sql diff --git a/benchmarks/duckshop/project/models/staging/inventory/stg_warehouses.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_warehouses.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/inventory/stg_warehouses.sql rename to benchmarks/duckshop/project/sql/models/staging/inventory/stg_warehouses.sql diff --git a/benchmarks/duckshop/project/models/staging/partners/stg_partner_listings.sql b/benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_listings.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/partners/stg_partner_listings.sql rename to benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_listings.sql diff --git a/benchmarks/duckshop/project/models/staging/partners/stg_partner_order_lines.sql b/benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_order_lines.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/partners/stg_partner_order_lines.sql rename to benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_order_lines.sql diff --git a/benchmarks/duckshop/project/models/staging/partners/stg_partner_orders.sql b/benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_orders.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/partners/stg_partner_orders.sql rename to benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_orders.sql diff --git a/benchmarks/duckshop/project/models/staging/partners/stg_partner_orders_v1.sql b/benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_orders_v1.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/partners/stg_partner_orders_v1.sql rename to benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_orders_v1.sql diff --git a/benchmarks/duckshop/project/models/staging/partners/stg_partner_orders_v2.sql b/benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_orders_v2.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/partners/stg_partner_orders_v2.sql rename to benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_orders_v2.sql diff --git a/benchmarks/duckshop/project/models/staging/partners/stg_partner_settlements.sql b/benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_settlements.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/partners/stg_partner_settlements.sql rename to benchmarks/duckshop/project/sql/models/staging/partners/stg_partner_settlements.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/_sqlbuild/_macros/python/variants.py b/benchmarks/duckshop/project/sql/models/staging/storefront/_sqlbuild/_macros/python/variants.py similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/_sqlbuild/_macros/python/variants.py rename to benchmarks/duckshop/project/sql/models/staging/storefront/_sqlbuild/_macros/python/variants.py diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_cart_items.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_cart_items.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_cart_items.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_cart_items.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_carts.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_carts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_carts.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_carts.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_customer_addresses.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_customer_addresses.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_customer_addresses.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_customer_addresses.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_customer_consents.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_customer_consents.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_customer_consents.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_customer_consents.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_customers.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_customers.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_customers.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_customers.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_gift_card_transactions.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_gift_card_transactions.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_gift_card_transactions.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_gift_card_transactions.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_gift_cards.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_gift_cards.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_gift_cards.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_gift_cards.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_loyalty_accounts.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_loyalty_accounts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_loyalty_accounts.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_loyalty_accounts.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_loyalty_ledger.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_loyalty_ledger.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_loyalty_ledger.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_loyalty_ledger.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_order_line_discounts.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_order_line_discounts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_order_line_discounts.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_order_line_discounts.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_order_lines.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_order_lines.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_order_lines.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_order_lines.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_order_status_events.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_order_status_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_order_status_events.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_order_status_events.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_orders.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_orders.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_orders.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_orders.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_payments.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_payments.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_payments.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_payments.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_promotion_redemptions.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_promotion_redemptions.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_promotion_redemptions.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_promotion_redemptions.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_promotions.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_promotions.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_promotions.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_promotions.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_refunds.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_refunds.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_refunds.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_refunds.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_reviews.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_reviews.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_reviews.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_reviews.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_store_credit_ledger.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_store_credit_ledger.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_store_credit_ledger.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_store_credit_ledger.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_subscription_events.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_subscription_events.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_subscription_events.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_subscription_events.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_subscriptions.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_subscriptions.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_subscriptions.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_subscriptions.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_wishlist_items.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_wishlist_items.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_wishlist_items.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_wishlist_items.sql diff --git a/benchmarks/duckshop/project/models/staging/storefront/stg_wishlists.sql b/benchmarks/duckshop/project/sql/models/staging/storefront/stg_wishlists.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/storefront/stg_wishlists.sql rename to benchmarks/duckshop/project/sql/models/staging/storefront/stg_wishlists.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_agent_shifts.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_agent_shifts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_agent_shifts.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_agent_shifts.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_agents.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_agents.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_agents.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_agents.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_call_records.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_call_records.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_call_records.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_call_records.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_chat_messages.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_chat_messages.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_chat_messages.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_chat_messages.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_chat_transcripts.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_chat_transcripts.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_chat_transcripts.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_chat_transcripts.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_csat_responses.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_csat_responses.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_csat_responses.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_csat_responses.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_sla_policies.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_sla_policies.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_sla_policies.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_sla_policies.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_ticket_comments.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_ticket_comments.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_ticket_comments.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_ticket_comments.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_ticket_tags.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_ticket_tags.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_ticket_tags.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_ticket_tags.sql diff --git a/benchmarks/duckshop/project/models/staging/support/stg_tickets.sql b/benchmarks/duckshop/project/sql/models/staging/support/stg_tickets.sql similarity index 100% rename from benchmarks/duckshop/project/models/staging/support/stg_tickets.sql rename to benchmarks/duckshop/project/sql/models/staging/support/stg_tickets.sql diff --git a/benchmarks/duckshop/project/seeds/carriers.csv b/benchmarks/duckshop/project/sql/seeds/carriers.csv similarity index 100% rename from benchmarks/duckshop/project/seeds/carriers.csv rename to benchmarks/duckshop/project/sql/seeds/carriers.csv diff --git a/benchmarks/duckshop/project/seeds/channel_mapping.csv b/benchmarks/duckshop/project/sql/seeds/channel_mapping.csv similarity index 100% rename from benchmarks/duckshop/project/seeds/channel_mapping.csv rename to benchmarks/duckshop/project/sql/seeds/channel_mapping.csv diff --git a/benchmarks/duckshop/project/seeds/countries.csv b/benchmarks/duckshop/project/sql/seeds/countries.csv similarity index 100% rename from benchmarks/duckshop/project/seeds/countries.csv rename to benchmarks/duckshop/project/sql/seeds/countries.csv diff --git a/benchmarks/duckshop/project/seeds/currencies.csv b/benchmarks/duckshop/project/sql/seeds/currencies.csv similarity index 100% rename from benchmarks/duckshop/project/seeds/currencies.csv rename to benchmarks/duckshop/project/sql/seeds/currencies.csv diff --git a/benchmarks/duckshop/project/seeds/edge_cases/edge_quantity_steps.csv b/benchmarks/duckshop/project/sql/seeds/edge_cases/edge_quantity_steps.csv similarity index 100% rename from benchmarks/duckshop/project/seeds/edge_cases/edge_quantity_steps.csv rename to benchmarks/duckshop/project/sql/seeds/edge_cases/edge_quantity_steps.csv diff --git a/benchmarks/duckshop/project/seeds/edge_cases/edge_quantity_steps.yml b/benchmarks/duckshop/project/sql/seeds/edge_cases/edge_quantity_steps.yml similarity index 100% rename from benchmarks/duckshop/project/seeds/edge_cases/edge_quantity_steps.yml rename to benchmarks/duckshop/project/sql/seeds/edge_cases/edge_quantity_steps.yml diff --git a/benchmarks/duckshop/project/seeds/holiday_calendar.csv b/benchmarks/duckshop/project/sql/seeds/holiday_calendar.csv similarity index 100% rename from benchmarks/duckshop/project/seeds/holiday_calendar.csv rename to benchmarks/duckshop/project/sql/seeds/holiday_calendar.csv diff --git a/benchmarks/duckshop/project/seeds/seeds.yml b/benchmarks/duckshop/project/sql/seeds/seeds.yml similarity index 100% rename from benchmarks/duckshop/project/seeds/seeds.yml rename to benchmarks/duckshop/project/sql/seeds/seeds.yml diff --git a/benchmarks/duckshop/project/sources/catalogue.yml b/benchmarks/duckshop/project/sql/sources/catalogue.yml similarity index 99% rename from benchmarks/duckshop/project/sources/catalogue.yml rename to benchmarks/duckshop/project/sql/sources/catalogue.yml index 8d67e209a2..7dbd1771be 100644 --- a/benchmarks/duckshop/project/sources/catalogue.yml +++ b/benchmarks/duckshop/project/sql/sources/catalogue.yml @@ -1,4 +1,4 @@ -# Raw catalogue tables, generated by the synthetic data loaders in python/loaders/catalogue.py. +# Raw catalogue tables, generated by the synthetic data loaders in python/nodes/loaders/catalogue.py. sources: - name: catalogue__products description: Product master change log (rubber ducks, decoys, duck-print textiles, pond and bath goods) diff --git a/benchmarks/duckshop/project/sources/clickstream.yml b/benchmarks/duckshop/project/sql/sources/clickstream.yml similarity index 98% rename from benchmarks/duckshop/project/sources/clickstream.yml rename to benchmarks/duckshop/project/sql/sources/clickstream.yml index eff6281f3b..38c3cc9c97 100644 --- a/benchmarks/duckshop/project/sources/clickstream.yml +++ b/benchmarks/duckshop/project/sql/sources/clickstream.yml @@ -1,4 +1,4 @@ -# Raw clickstream tables, generated by the synthetic data loaders in python/loaders/clickstream.py. +# Raw clickstream tables, generated by the synthetic data loaders in python/nodes/loaders/clickstream.py. sources: - name: clickstream__web_events description: Append-only web clickstream; event is the raw tracker payload diff --git a/benchmarks/duckshop/project/sources/edge_cases.yml b/benchmarks/duckshop/project/sql/sources/edge_cases.yml similarity index 99% rename from benchmarks/duckshop/project/sources/edge_cases.yml rename to benchmarks/duckshop/project/sql/sources/edge_cases.yml index ea73c90c66..d623df9229 100644 --- a/benchmarks/duckshop/project/sources/edge_cases.yml +++ b/benchmarks/duckshop/project/sql/sources/edge_cases.yml @@ -1,5 +1,5 @@ # Edge-case area: raw partner payload feed with hand-picked JSON edge values, written by the fixed -# loaders in python/loaders/edge_cases.py. Not scaled by data_scale. +# loaders in python/nodes/loaders/edge_cases.py. Not scaled by data_scale. sources: - name: edge__partner_payloads description: >- diff --git a/benchmarks/duckshop/project/sources/finance.yml b/benchmarks/duckshop/project/sql/sources/finance.yml similarity index 99% rename from benchmarks/duckshop/project/sources/finance.yml rename to benchmarks/duckshop/project/sql/sources/finance.yml index fe865daf87..cb8cd7d164 100644 --- a/benchmarks/duckshop/project/sources/finance.yml +++ b/benchmarks/duckshop/project/sql/sources/finance.yml @@ -1,4 +1,4 @@ -# Raw finance tables, generated by the synthetic data loaders in python/loaders/finance.py. +# Raw finance tables, generated by the synthetic data loaders in python/nodes/loaders/finance.py. sources: - name: finance__invoices description: Customer invoices change log diff --git a/benchmarks/duckshop/project/sources/finance_reference.yml b/benchmarks/duckshop/project/sql/sources/finance_reference.yml similarity index 100% rename from benchmarks/duckshop/project/sources/finance_reference.yml rename to benchmarks/duckshop/project/sql/sources/finance_reference.yml diff --git a/benchmarks/duckshop/project/sources/fulfilment.yml b/benchmarks/duckshop/project/sql/sources/fulfilment.yml similarity index 99% rename from benchmarks/duckshop/project/sources/fulfilment.yml rename to benchmarks/duckshop/project/sql/sources/fulfilment.yml index a4b55edcc1..34008c043a 100644 --- a/benchmarks/duckshop/project/sources/fulfilment.yml +++ b/benchmarks/duckshop/project/sql/sources/fulfilment.yml @@ -1,4 +1,4 @@ -# Raw fulfilment tables, generated by the synthetic data loaders in python/loaders/fulfilment.py. +# Raw fulfilment tables, generated by the synthetic data loaders in python/nodes/loaders/fulfilment.py. sources: - name: fulfilment__shipments description: Shipments change log diff --git a/benchmarks/duckshop/project/sources/growth.yml b/benchmarks/duckshop/project/sql/sources/growth.yml similarity index 99% rename from benchmarks/duckshop/project/sources/growth.yml rename to benchmarks/duckshop/project/sql/sources/growth.yml index 26605d5b73..16b1fd07c9 100644 --- a/benchmarks/duckshop/project/sources/growth.yml +++ b/benchmarks/duckshop/project/sql/sources/growth.yml @@ -1,4 +1,4 @@ -# Raw growth tables, generated by the synthetic data loaders in python/loaders/growth.py. +# Raw growth tables, generated by the synthetic data loaders in python/nodes/loaders/growth.py. sources: - name: growth__campaign_spend description: Daily advertising spend exports change log diff --git a/benchmarks/duckshop/project/sources/inventory.yml b/benchmarks/duckshop/project/sql/sources/inventory.yml similarity index 99% rename from benchmarks/duckshop/project/sources/inventory.yml rename to benchmarks/duckshop/project/sql/sources/inventory.yml index 4373086173..4c776f5be6 100644 --- a/benchmarks/duckshop/project/sources/inventory.yml +++ b/benchmarks/duckshop/project/sql/sources/inventory.yml @@ -1,4 +1,4 @@ -# Raw inventory tables, generated by the synthetic data loaders in python/loaders/inventory.py. +# Raw inventory tables, generated by the synthetic data loaders in python/nodes/loaders/inventory.py. sources: - name: inventory__warehouses description: Warehouses change log, such as The Pond and The Nest diff --git a/benchmarks/duckshop/project/sources/partners.yml b/benchmarks/duckshop/project/sql/sources/partners.yml similarity index 98% rename from benchmarks/duckshop/project/sources/partners.yml rename to benchmarks/duckshop/project/sql/sources/partners.yml index bec3020c0d..d4d4803831 100644 --- a/benchmarks/duckshop/project/sources/partners.yml +++ b/benchmarks/duckshop/project/sql/sources/partners.yml @@ -1,4 +1,4 @@ -# Raw partners tables, generated by the synthetic data loaders in python/loaders/partners.py. +# Raw partners tables, generated by the synthetic data loaders in python/nodes/loaders/partners.py. sources: - name: partners__partner_orders description: Append-only partner sales channel order messages in two payload versions diff --git a/benchmarks/duckshop/project/sources/storefront.yml b/benchmarks/duckshop/project/sql/sources/storefront.yml similarity index 99% rename from benchmarks/duckshop/project/sources/storefront.yml rename to benchmarks/duckshop/project/sql/sources/storefront.yml index 03abf20551..a7e1e93b0b 100644 --- a/benchmarks/duckshop/project/sources/storefront.yml +++ b/benchmarks/duckshop/project/sql/sources/storefront.yml @@ -1,4 +1,4 @@ -# Raw storefront tables, generated by the synthetic data loaders in python/loaders/storefront.py. +# Raw storefront tables, generated by the synthetic data loaders in python/nodes/loaders/storefront.py. sources: - name: storefront__customers description: Customer accounts change log diff --git a/benchmarks/duckshop/project/sources/support.yml b/benchmarks/duckshop/project/sql/sources/support.yml similarity index 99% rename from benchmarks/duckshop/project/sources/support.yml rename to benchmarks/duckshop/project/sql/sources/support.yml index 72b1c3fedc..5b7e4ed03d 100644 --- a/benchmarks/duckshop/project/sources/support.yml +++ b/benchmarks/duckshop/project/sql/sources/support.yml @@ -1,4 +1,4 @@ -# Raw support tables, generated by the synthetic data loaders in python/loaders/support.py. +# Raw support tables, generated by the synthetic data loaders in python/nodes/loaders/support.py. sources: - name: support__tickets description: Support tickets change log; created_at is session-time-zone dependent diff --git a/benchmarks/duckshop/project/sqlbuild_project.toml b/benchmarks/duckshop/project/sqlbuild_project.toml index 8304ad9919..079c893c6b 100644 --- a/benchmarks/duckshop/project/sqlbuild_project.toml +++ b/benchmarks/duckshop/project/sqlbuild_project.toml @@ -1,3 +1,4 @@ +extra_paths = ["sqlbuild_local.toml.example"] name = "duckshop" adapter = "snowflake" default_target = "dev" @@ -97,7 +98,7 @@ reporting_currency = "USD" valuation_date = "2026-03-31" # Customer shown by the order lookup report; override per run with --vars. lookup_customer_id = "C000001" -# Volume multiplier for the synthetic data loaders in python/loaders; 1 is the small default. +# Volume multiplier for the synthetic data loaders in python/nodes/loaders; 1 is the small default. data_scale = "1" # >>> edge-case area (scripts/core_project.py leaves this block out of the core copy) # Last load of the edge-case delivery change log to include; "1" replays the first load only (see @@ -119,7 +120,7 @@ ignore = ["SQLCLEAN021", "SQBRCONTRACT101"] [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/_sqlbuild/macros/sql/cdc_latest.sql" +path = "sql/models/staging/_sqlbuild/macros/sql/cdc_latest.sql" reason = """ The macro cannot see its callers' keys on its own. Every call site is still checked, against the unique, non-null _seq that each change-log source declares. @@ -127,7 +128,7 @@ unique, non-null _seq that each change-log source declares. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/marts/core/dim_date.sql" +path = "sql/models/marts/core/dim_date.sql" reason = """ SEQ4() is distinct for every row of one GENERATOR call, so ordering by it is unique. ROW_NUMBER() renumbers it because SEQ4() alone may leave gaps. @@ -135,7 +136,7 @@ renumbers it because SEQ4() alone may leave gaps. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/clickstream/stg_app_events.sql" +path = "sql/models/staging/clickstream/stg_app_events.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -145,7 +146,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/clickstream/stg_email_events.sql" +path = "sql/models/staging/clickstream/stg_email_events.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -155,7 +156,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/clickstream/stg_experiment_assignments.sql" +path = "sql/models/staging/clickstream/stg_experiment_assignments.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -165,7 +166,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/clickstream/stg_search_queries.sql" +path = "sql/models/staging/clickstream/stg_search_queries.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -175,7 +176,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/clickstream/stg_web_events.sql" +path = "sql/models/staging/clickstream/stg_web_events.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -185,7 +186,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/finance/stg_settlement_reports.sql" +path = "sql/models/staging/finance/stg_settlement_reports.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -195,7 +196,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/fulfilment/stg_carrier_webhook_errors.sql" +path = "sql/models/staging/fulfilment/stg_carrier_webhook_errors.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -205,7 +206,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/fulfilment/stg_carrier_webhooks.sql" +path = "sql/models/staging/fulfilment/stg_carrier_webhooks.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -215,7 +216,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/inventory/stg_stock_movements.sql" +path = "sql/models/staging/inventory/stg_stock_movements.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -225,7 +226,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN018" -path = "models/staging/partners/stg_partner_orders.sql" +path = "sql/models/staging/partners/stg_partner_orders.sql" reason = """ Append-only feeds redeliver rows, so the source id repeats across loads and only (id, _loaded_at) is unique, which the source's unique_per_delivery audit checks. Rules cannot use a two-column key @@ -235,7 +236,7 @@ whichever copy ranks first. [[rules.rule_exceptions]] rule = "SQLCLEAN034" -path = "models/staging/_sqlbuild/macros/sql/load_metadata.sql" +path = "sql/models/staging/_sqlbuild/macros/sql/load_metadata.sql" reason = """ A column-list macro body is a select list by construction. Its columns are inserted into the caller's own CTE, where the rule is checked again. @@ -243,7 +244,7 @@ caller's own CTE, where the rule is checked again. [[rules.rule_exceptions]] rule = "SQLCLEAN034" -path = "macros/sql/money_columns.sql" +path = "sql/macros/sql/money_columns.sql" reason = """ A column-list macro body is a select list by construction. Its columns are inserted into the caller's own CTE, where the rule is checked again. @@ -251,7 +252,7 @@ caller's own CTE, where the rule is checked again. [[rules.rule_exceptions]] rule = "SQLCLEAN028" -path = "models/intermediate/catalogue/int_category_paths.sql" +path = "sql/models/intermediate/catalogue/int_category_paths.sql" reason = """ LEVEL and the CONNECT_BY_ROOT operator are hierarchical-query pseudo-columns that cannot be qualified with a table alias. @@ -259,7 +260,7 @@ qualified with a table alias. [[rules.rule_exceptions]] rule = "SQBRTEST202" -path = "models/intermediate/catalogue/int_category_paths.sql" +path = "sql/models/intermediate/catalogue/int_category_paths.sql" reason = """ Unit-test fixture checking treats the LEVEL pseudo-column as a column the mocked categories relation must supply, so no test of this model can compile yet. The @@ -268,7 +269,7 @@ category_tree__rolls_sales_up_built_paths scenario builds the hierarchy from a s [[rules.rule_exceptions]] rule = "SQBRTEST202" -path = "models/intermediate/clickstream/int_cart_funnel.sql" +path = "sql/models/intermediate/clickstream/int_cart_funnel.sql" reason = """ Unit-test fixture checking treats the FILTER, TRANSFORM and REDUCE lambda parameters (i, acc, q) as columns the mocked relations must supply, so no test of this model can compile yet. The @@ -277,7 +278,7 @@ cart_funnel__assigns_furthest_stage_per_session scenario covers the funnel inste [[rules.rule_exceptions]] rule = "SQLCLEAN038" -path = "models/marts/executive/rpt_executive_kpis_daily.sql" +path = "sql/models/marts/executive/rpt_executive_kpis_daily.sql" relation = "metric_regions" reason = """ The KPI grid is every reporting day for every region and metric pair that has ever had a value, so @@ -287,7 +288,7 @@ days without activity report zero instead of disappearing. Both sides are small # >>> edge-case area (scripts/core_project.py leaves this block out of the core copy) [[rules.rule_ignores]] rules = ["SQLCLEAN027"] -paths = ["models/marts/edge_cases/rpt_edge_stock_reconciliation.sql"] +paths = ["sql/models/marts/edge_cases/rpt_edge_stock_reconciliation.sql"] reason = """ The edge case selects the key columns that FULL OUTER JOIN ... USING merges. They belong to neither side, so qualifying them with either alias would drop the keys of rows found only on the other side. @@ -295,7 +296,7 @@ side, so qualifying them with either alias would drop the keys of rows found onl [[rules.rule_ignores]] rules = ["SQLCLEAN003", "SQLCLEAN023", "SQLCLEAN027", "SQLCLEAN051"] -paths = ["models/intermediate/edge_cases/int_edge_join_keys.sql"] +paths = ["sql/models/intermediate/edge_cases/int_edge_join_keys.sql"] reason = """ The edge cases read the merged key of RIGHT JOIN ... USING and of a USING join followed by an outer join unqualified, because it belongs to neither side; the side aliases are then unused. An ASOF @@ -306,8 +307,8 @@ under test. [[rules.rule_ignores]] rules = ["SQLCLEAN018"] paths = [ - "models/intermediate/edge_cases/int_edge_grouped_windows.sql", - "models/intermediate/edge_cases/int_edge_null_arithmetic.sql", + "sql/models/intermediate/edge_cases/int_edge_grouped_windows.sql", + "sql/models/intermediate/edge_cases/int_edge_null_arithmetic.sql", ] reason = """ The ranking windows order by the group code of a grouped query and by the check id, both unique @@ -316,7 +317,7 @@ where they are ranked, which Rules cannot prove through a GROUP BY or a CTE. [[rules.rule_ignores]] rules = ["SQLCLEAN022"] -paths = ["models/intermediate/edge_cases/int_edge_analysis_patterns.sql"] +paths = ["sql/models/intermediate/edge_cases/int_edge_analysis_patterns.sql"] reason = """ The edge case leaves two calculated columns unaliased on purpose, and reads them by the names Snowflake gives them. @@ -324,21 +325,21 @@ Snowflake gives them. [[rules.rule_ignores]] rules = ["SQLCLEAN022"] -paths = ["models/intermediate/edge_cases/int_edge_check_unnamed_labels.sql"] +paths = ["sql/models/intermediate/edge_cases/int_edge_check_unnamed_labels.sql"] reason = """ The edge case leaves a literal unaliased on purpose, and reads it by the name Snowflake gives it. """ [[rules.rule_ignores]] rules = ["SQLCLEAN044"] -paths = ["models/intermediate/edge_cases/_sqlbuild/_hooks/sql/create_edge_running_peaks.sql"] +paths = ["sql/models/intermediate/edge_cases/_sqlbuild/_hooks/sql/create_edge_running_peaks.sql"] reason = """ The hook creates a JavaScript function, whose body Snowflake takes as one dollar-quoted string. """ [[rules.rule_ignores]] rules = ["SQLCLEAN039"] -paths = ["models/intermediate/edge_cases/int_edge_basket_line_sku_parts.sql"] +paths = ["sql/models/intermediate/edge_cases/int_edge_basket_line_sku_parts.sql"] reason = """ The edge case reads the line through a derived table nested in a comma-joined LATERAL on purpose: that shape is the case under test. @@ -347,8 +348,8 @@ that shape is the case under test. [[rules.rule_ignores]] rules = ["SQLCLEAN034"] paths = [ - "models/intermediate/edge_cases/int_edge_expression_spans.sql", - "models/intermediate/edge_cases/int_edge_reference_qualified_spans.sql", + "sql/models/intermediate/edge_cases/int_edge_expression_spans.sql", + "sql/models/intermediate/edge_cases/int_edge_reference_qualified_spans.sql", ] reason = """ These edge cases keep their macro calls, variable, literals and reference calls in the terminal @@ -358,7 +359,7 @@ the compiled SQL must differ from the authored text. [[rules.rule_ignores]] rules = ["SQLCLEAN040"] -paths = ["models/intermediate/edge_cases/int_edge_amount_bit_reads.sql"] +paths = ["sql/models/intermediate/edge_cases/int_edge_amount_bit_reads.sql"] reason = """ The edge case joins the group list with a comma after an explicit join on purpose, and Rules read the comma-joined relation as part of the preceding ON condition. @@ -366,7 +367,7 @@ the comma-joined relation as part of the preceding ON condition. [[rules.rule_ignores]] rules = ["SQLCLEAN033"] -paths = ["models/intermediate/edge_cases/int_edge_sku_text_reads.sql"] +paths = ["sql/models/intermediate/edge_cases/int_edge_sku_text_reads.sql"] reason = """ The edge case attaches a comment to a text literal on purpose, the shape that parsers keep as an annotated expression. @@ -374,7 +375,7 @@ annotated expression. [[rules.rule_ignores]] rules = ["SQLCLEAN027", "SQLCLEAN028"] -paths = ["models/intermediate/edge_cases/int_edge_category_walk.sql"] +paths = ["sql/models/intermediate/edge_cases/int_edge_category_walk.sql"] reason = """ LEVEL and CONNECT_BY_ROOT belong to the walk, not to a relation, so they cannot be qualified, and the edge case reads a column named level from another relation unqualified inside a scalar diff --git a/benchmarks/duckshop/project/tests/_scenario_snapshots/category_tree__rolls_sales_up_built_paths/scenario.json b/benchmarks/duckshop/project/tests/_scenario_snapshots/category_tree__rolls_sales_up_built_paths/scenario.json index 9a5c73cb10..39d6300e4c 100644 --- a/benchmarks/duckshop/project/tests/_scenario_snapshots/category_tree__rolls_sales_up_built_paths/scenario.json +++ b/benchmarks/duckshop/project/tests/_scenario_snapshots/category_tree__rolls_sales_up_built_paths/scenario.json @@ -346,7 +346,7 @@ "warehouse_type": "TIMESTAMP_NTZ(9)" } ], - "file": "sources/catalogue__categories.jsonl", + "file": "sql/sources/catalogue__categories.jsonl", "kind": "source", "logical_name": "catalogue__categories", "row_count": 5 diff --git a/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_delivery_status__cursor_model_over_far_apart_fixture_loads/scenario.json b/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_delivery_status__cursor_model_over_far_apart_fixture_loads/scenario.json index 2959c94a0c..f076ef403b 100644 --- a/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_delivery_status__cursor_model_over_far_apart_fixture_loads/scenario.json +++ b/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_delivery_status__cursor_model_over_far_apart_fixture_loads/scenario.json @@ -54,7 +54,7 @@ "warehouse_type": "TIMESTAMP_NTZ(9)" } ], - "file": "sources/edge__delivery_updates.jsonl", + "file": "sql/sources/edge__delivery_updates.jsonl", "kind": "source", "logical_name": "edge__delivery_updates", "row_count": 5 diff --git a/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_payload_lines__mixed_type_arrays_flatten_to_lines/scenario.json b/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_payload_lines__mixed_type_arrays_flatten_to_lines/scenario.json index e492c80709..d5d3d7a95e 100644 --- a/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_payload_lines__mixed_type_arrays_flatten_to_lines/scenario.json +++ b/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_payload_lines__mixed_type_arrays_flatten_to_lines/scenario.json @@ -44,7 +44,7 @@ "warehouse_type": "TIMESTAMP_NTZ(9)" } ], - "file": "sources/edge__partner_payloads.jsonl", + "file": "sql/sources/edge__partner_payloads.jsonl", "kind": "source", "logical_name": "edge__partner_payloads", "row_count": 2 diff --git a/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_variant_chain__typed_payload_survives_models/scenario.json b/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_variant_chain__typed_payload_survives_models/scenario.json index 11ca8d3ad3..5ab36a947b 100644 --- a/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_variant_chain__typed_payload_survives_models/scenario.json +++ b/benchmarks/duckshop/project/tests/_scenario_snapshots/edge_variant_chain__typed_payload_survives_models/scenario.json @@ -44,7 +44,7 @@ "warehouse_type": "TIMESTAMP_NTZ(9)" } ], - "file": "sources/edge__partner_payloads.jsonl", + "file": "sql/sources/edge__partner_payloads.jsonl", "kind": "source", "logical_name": "edge__partner_payloads", "row_count": 3 diff --git a/benchmarks/duckshop/project/tests/test_edge_area_tags.py b/benchmarks/duckshop/project/tests/test_edge_area_tags.py index 77eed8f3cf..6c4ae4bc98 100644 --- a/benchmarks/duckshop/project/tests/test_edge_area_tags.py +++ b/benchmarks/duckshop/project/tests/test_edge_area_tags.py @@ -15,7 +15,7 @@ def test_given_tagged_model_in_edge_folder_when_evaluating_then_passes() -> None test_case=RuleCase( description="edge model declares the edge_case tag", source=_TAGGED, - path="models/intermediate/edge_cases/int_edge_orders.sql", + path="sql/models/intermediate/edge_cases/int_edge_orders.sql", expected_finding_count=0, ), ) @@ -29,7 +29,7 @@ def test_given_untagged_model_in_edge_folder_when_evaluating_then_reports_it() - test_case=RuleCase( description="edge model without the edge_case tag", source=_OTHER_TAG, - path="models/staging/edge_cases/stg_edge_orders.sql", + path="sql/models/staging/edge_cases/stg_edge_orders.sql", expected_finding_count=1, ), ) @@ -44,7 +44,7 @@ def test_given_tagged_model_outside_edge_folder_when_evaluating_then_reports_it( test_case=RuleCase( description="core model declares the edge_case tag", source=_TAGGED, - path="models/marts/orders/fct_orders.sql", + path="sql/models/marts/orders/fct_orders.sql", expected_finding_count=1, ), ) @@ -58,7 +58,7 @@ def test_given_untagged_model_outside_edge_folder_when_evaluating_then_passes() test_case=RuleCase( description="core model without the tag", source=_UNTAGGED, - path="models/marts/orders/fct_orders.sql", + path="sql/models/marts/orders/fct_orders.sql", expected_finding_count=0, ), ) @@ -76,7 +76,7 @@ def test_given_tags_text_in_description_when_evaluating_then_reads_only_header_t " columns (\n order_id (type VARCHAR),\n ),\n" " tags [orders],\n);\nSELECT 1 AS order_id\n" ), - path="models/staging/edge_cases/stg_edge_orders.sql", + path="sql/models/staging/edge_cases/stg_edge_orders.sql", expected_finding_count=1, ), ) diff --git a/benchmarks/duckshop/project/tests/test_rule_quoted_aliases.py b/benchmarks/duckshop/project/tests/test_rule_quoted_aliases.py index 1303b6da7f..ae61cd05e0 100644 --- a/benchmarks/duckshop/project/tests/test_rule_quoted_aliases.py +++ b/benchmarks/duckshop/project/tests/test_rule_quoted_aliases.py @@ -12,7 +12,7 @@ + 'FROM __ref("dim_listings") AS l\n' ) _LISTINGS = RuleFile( - path="models/marts/catalogue/dim_listings.sql", + path="sql/models/marts/catalogue/dim_listings.sql", source=_HEADER + "SELECT 1 AS listing_id, 'new' AS note\n", ) @@ -23,7 +23,7 @@ def test_given_quoted_mixed_case_alias_outside_an_export_when_evaluating_then_re test_case=RuleCase( description="a mart names a column in a partner's case", source=_MIXED_CASE, - path="models/marts/catalogue/rpt_listings.sql", + path="sql/models/marts/catalogue/rpt_listings.sql", files=(_LISTINGS,), expected_finding_count=1, ), @@ -42,7 +42,7 @@ def test_given_quoted_mixed_case_alias_in_an_export_when_evaluating_then_passes( test_case=RuleCase( description="a partner export writes the partner's own names", source=_MIXED_CASE, - path="models/marts/edge_cases/rpt_edge_partner_listing_export.sql", + path="sql/models/marts/edge_cases/rpt_edge_partner_listing_export.sql", files=(_LISTINGS,), expected_finding_count=0, ), diff --git a/benchmarks/duckshop/project/tests/test_rule_staging_dedupe.py b/benchmarks/duckshop/project/tests/test_rule_staging_dedupe.py index d3e0dc63fb..b5f0f6d2bf 100644 --- a/benchmarks/duckshop/project/tests/test_rule_staging_dedupe.py +++ b/benchmarks/duckshop/project/tests/test_rule_staging_dedupe.py @@ -4,7 +4,7 @@ from sqlbuild.rules.testing import RuleCase, evaluate_rule _SOURCES = RuleFile( - path="sources/shop.yml", + path="sql/sources/shop.yml", source="""sources: - name: shop__orders description: Orders change log @@ -39,7 +39,7 @@ def test_given_change_log_read_without_cdc_latest_when_evaluating_then_reports_i test_case=RuleCase( description="staging model reads a change log directly", source=_RAW_CHANGE_LOG_READ, - path="models/staging/shop/stg_orders.sql", + path="sql/models/staging/shop/stg_orders.sql", files=(_SOURCES,), expected_finding_count=1, ), @@ -57,7 +57,7 @@ def test_given_staging_model_reading_append_only_source_when_evaluating_then_pas source=_RAW_CHANGE_LOG_READ.replace("shop__orders", "shop__page_views").replace( "order_id", "event_id" ), - path="models/staging/shop/stg_page_views.sql", + path="sql/models/staging/shop/stg_page_views.sql", files=(_SOURCES,), expected_finding_count=0, ), @@ -72,7 +72,7 @@ def test_given_change_log_read_outside_staging_when_evaluating_then_passes() -> test_case=RuleCase( description="snapshots and other layers may read the full change log", source=_RAW_CHANGE_LOG_READ, - path="models/snapshots/snap_orders.sql", + path="sql/models/snapshots/snap_orders.sql", files=(_SOURCES,), expected_finding_count=0, ), diff --git a/benchmarks/duckshop/scripts/census.py b/benchmarks/duckshop/scripts/census.py index fc431e6f78..5b2f3542cc 100644 --- a/benchmarks/duckshop/scripts/census.py +++ b/benchmarks/duckshop/scripts/census.py @@ -20,7 +20,7 @@ import sys PROJECT = pathlib.Path(__file__).resolve().parent.parent / "project" -COMPILED = PROJECT / "target" / "compiled" / "models" +COMPILED = PROJECT / "target" / "compiled" / "sql" / "models" EDGE_FOLDER = "edge_cases" AREAS = ("core", "edge", "all") diff --git a/benchmarks/duckshop/scripts/duckdb_project.py b/benchmarks/duckshop/scripts/duckdb_project.py index 0b9e17d92f..dae5a579e9 100644 --- a/benchmarks/duckshop/scripts/duckdb_project.py +++ b/benchmarks/duckshop/scripts/duckdb_project.py @@ -148,16 +148,16 @@ def write_models(snow: pathlib.Path, out: pathlib.Path, report: dict[str, Any]) path = out / model["relative_path"] body = translate(model["query_sql"], model["name"]) path.write_text(model_header(path.read_text()) + "\n" + body + "\n") - for path in (out / "functions" / "sql").glob("*.sql"): + for path in (out / "sql" / "functions" / "sql").glob("*.sql"): text = path.read_text() head = header(text, "FUNCTION") - compiled = snow / "target" / "compiled" / "functions" / path.name + compiled = snow / "target" / "compiled" / "sql" / "functions" / path.name body = compiled.read_text() if compiled.exists() else text[len(head) :] path.write_text(types(head) + "\n" + translate(body) + "\n") def write_sources(out: pathlib.Path) -> None: - for path in [*(out / "sources").glob("*.yml"), out / "seeds" / "seeds.yml"]: + for path in [*(out / "sql" / "sources").glob("*.yml"), out / "sql" / "seeds" / "seeds.yml"]: doc = yaml.safe_load(path.read_text()) for entry in doc.get("sources", doc.get("seeds", [])): for column in entry.get("columns", []): @@ -176,16 +176,16 @@ def write_sources(out: pathlib.Path) -> None: for path in out.rglob("*.py"): if "functions" not in path.parts: path.write_text(types(path.read_text())) - writer = out / "python" / "loaders" / "_writer.py" + writer = out / "python" / "nodes" / "loaders" / "_writer.py" text = writer.read_text() if WRITER_QUOTE[0] not in text: - raise SystemExit("python/loaders/_writer.py changed: update WRITER_QUOTE") + raise SystemExit("python/nodes/loaders/_writer.py changed: update WRITER_QUOTE") text = text.replace(*WRITER_QUOTE) text, count = re.subn( r"def insert_sql\(.*?\n\n\ndef statements", lambda _: WRITER_INSERT, text, flags=re.S ) if count != 1: - raise SystemExit("python/loaders/_writer.py changed: update WRITER_INSERT") + raise SystemExit("python/nodes/loaders/_writer.py changed: update WRITER_INSERT") writer.write_text(text) @@ -196,9 +196,9 @@ def write_declarations(out: pathlib.Path) -> None: for path in [p for p in out.rglob("*.sql") if "audits" in str(p.relative_to(out))]: path.write_text(audit_sql(path.read_text())) - for path in out.glob("models/**/_sqlbuild/_schemas/*.sql"): + for path in out.glob("sql/models/**/_sqlbuild/_schemas/*.sql"): path.write_text(types(path.read_text())) - models = [p for p in out.glob("models/**/*.sql") if "_sqlbuild" not in p.parts] + models = [p for p in out.glob("sql/models/**/*.sql") if "_sqlbuild" not in p.parts] enums = {path.stem: path for path in out.glob("**/enums/*.sql")} for name in [n for n, p in enums.items() if re.search(r"members \(\w+ \d", p.read_text())]: del enums[name] @@ -211,12 +211,14 @@ def write_declarations(out: pathlib.Path) -> None: owners.setdefault(name, set()).add(path.parent) keep: dict[pathlib.Path, str] = {} for name, folders in owners.items(): - folder = folders.pop() / "_sqlbuild" / "_enums" if len(folders) == 1 else out / "enums" + folder = ( + folders.pop() / "_sqlbuild" / "_enums" if len(folders) == 1 else out / "sql" / "enums" + ) keep[folder / f"{name}.sql"] = types(enums[name].read_text()) for gone in ("tests", "macros", "rules", "constants", "enums"): shutil.rmtree(out / gone, ignore_errors=True) for folder in ("_macros", "macros", "constants", "_constants", "enums", "_enums"): - for path in list(out.glob(f"models/**/_sqlbuild/{folder}")): + for path in list(out.glob(f"sql/models/**/_sqlbuild/{folder}")): shutil.rmtree(path) for path, text in keep.items(): path.parent.mkdir(parents=True, exist_ok=True) diff --git a/benchmarks/duckshop/scripts/duckdb_rewrites.py b/benchmarks/duckshop/scripts/duckdb_rewrites.py index 4715310c03..6447569fcf 100644 --- a/benchmarks/duckshop/scripts/duckdb_rewrites.py +++ b/benchmarks/duckshop/scripts/duckdb_rewrites.py @@ -589,8 +589,8 @@ def macro_folder(root: pathlib.Path, folders: list[pathlib.Path]) -> pathlib.Pat if len(folders) == 1: return folders[0] / "_sqlbuild" / "_macros" / "sql" common = pathlib.Path(os.path.commonpath(folders)) - if common in (root, root / "models"): - return root / "macros" / "sql" + if common in (root, root / "sql" / "models"): + return root / "sql" / "macros" / "sql" return common / "_sqlbuild" / "macros" / "sql" @@ -598,7 +598,7 @@ def write_shims(root: pathlib.Path) -> None: """Write each shim overload a model calls, in the folder that owns its callers.""" callers: dict[str, set[pathlib.Path]] = {} - for path in root.glob("models/**/*.sql"): + for path in root.glob("sql/models/**/*.sql"): for name in re.findall(r"@sql\.(\w+)\(", path.read_text()): callers.setdefault(name, set()).add(path.parent) for name, overloads in SHIMS.items(): diff --git a/benchmarks/duckshop/scripts/relations.py b/benchmarks/duckshop/scripts/relations.py index 4eb00fa945..38e7258116 100644 --- a/benchmarks/duckshop/scripts/relations.py +++ b/benchmarks/duckshop/scripts/relations.py @@ -39,10 +39,10 @@ def _function_arguments(relative_path: str) -> list[str]: def managed_sources() -> list[str]: - """Managed source names from sources/*.yml; each loader writes a table of the same name.""" + """Managed source names from sql/sources/*.yml; each loader writes a table of the same name.""" names: list[str] = [] - for path in sorted((PROJECT_DIR / "sources").glob("*.yml")): + for path in sorted((PROJECT_DIR / "sql" / "sources").glob("*.yml")): for block in re.split(r"\n - name: ", path.read_text())[1:]: if re.search(r"^ managed: true$", block, flags=re.MULTILINE): names.append(block.split("\n", 1)[0].strip()) @@ -58,7 +58,7 @@ def hook_functions() -> list[str]: """`name(type, ...)` of each function a SQL hook creates; SQLBuild does not declare them.""" found: list[str] = [] - for path in sorted(PROJECT_DIR.glob("models/**/_hooks/sql/*.sql")): + for path in sorted(PROJECT_DIR.glob("sql/models/**/_hooks/sql/*.sql")): for name, arguments in HOOK_FUNCTION.findall(path.read_text()): types = [ part.strip().split(None, 1)[1] for part in arguments.split(",") if part.strip() diff --git a/benchmarks/duckshop/tests/test_synthetic_data.py b/benchmarks/duckshop/tests/test_synthetic_data.py index b376ec2544..fe8f0bace4 100644 --- a/benchmarks/duckshop/tests/test_synthetic_data.py +++ b/benchmarks/duckshop/tests/test_synthetic_data.py @@ -22,18 +22,18 @@ PROJECT_DIR = Path(__file__).resolve().parents[1] / "project" sys.path.insert(0, str(PROJECT_DIR)) -from python.loaders import _edge_cases, _world # noqa: E402 -from python.loaders._registry import GENERATORS, generate, scale_from_vars # noqa: E402 +from python.nodes.loaders import _edge_cases, _world # noqa: E402 +from python.nodes.loaders._registry import GENERATORS, generate, scale_from_vars # noqa: E402 Rows = list[dict[str, object]] -EDGE_SOURCES_FILE = PROJECT_DIR / "sources" / "edge_cases.yml" +EDGE_SOURCES_FILE = PROJECT_DIR / "sql" / "sources" / "edge_cases.yml" def _sources(*, edge: bool) -> dict[str, dict[str, object]]: sources: dict[str, dict[str, object]] = {} - for path in sorted((PROJECT_DIR / "sources").glob("*.yml")): + for path in sorted((PROJECT_DIR / "sql" / "sources").glob("*.yml")): if (path == EDGE_SOURCES_FILE) != edge: continue for source in yaml.safe_load(path.read_text())["sources"]: @@ -103,7 +103,7 @@ def test_given_fresh_caches_when_generating_again_then_rows_are_identical(name: first = _digest(generate(name)) _world.build_world.cache_clear() for module in ("_storefront", "_fulfilment", "_inventory", "_clickstream", "_support"): - for value in vars(sys.modules[f"python.loaders.{module}"]).values(): + for value in vars(sys.modules[f"python.nodes.loaders.{module}"]).values(): if hasattr(value, "cache_clear"): value.cache_clear() assert _digest(generate(name)) == first @@ -409,7 +409,7 @@ def result(self, **kwargs: object) -> dict[str, object]: def test_given_loader_context_when_loading_then_table_is_replaced_with_typed_inserts( name: str, ) -> None: - from python.loaders._registry import load + from python.nodes.loaders._registry import load context = _FakeContext() result = load(context, name) @@ -426,7 +426,7 @@ def test_given_loader_context_when_loading_then_table_is_replaced_with_typed_ins def test_given_special_characters_when_rendering_literals_then_they_are_escaped() -> None: - from python.loaders._writer import literal + from python.nodes.loaders._writer import literal assert literal("it's") == "'it''s'" assert literal({"note": "a\nb"}) == '\'{"note": "a\\\\nb"}\'' @@ -436,7 +436,7 @@ def test_given_special_characters_when_rendering_literals_then_they_are_escaped( def test_given_edge_sources_when_listing_fixed_tables_then_each_has_rows_and_a_loader() -> None: - loaders = (PROJECT_DIR / "python" / "loaders" / "edge_cases.py").read_text() + loaders = (PROJECT_DIR / "python" / "nodes" / "loaders" / "edge_cases.py").read_text() assert EDGE_MANAGED assert sorted(_edge_cases.TABLES) == EDGE_MANAGED diff --git a/clients/typescript/src/schema.d.ts b/clients/typescript/src/schema.d.ts index fb4dc36314..b6dd0d98ce 100644 --- a/clients/typescript/src/schema.d.ts +++ b/clients/typescript/src/schema.d.ts @@ -569,6 +569,38 @@ export interface paths { patch?: never; trace?: never; }; + "/api/control/locations/{location_id}/targets/{target}/cost/selection": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readCostSelection"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/control/locations/{location_id}/targets/{target}/cost/series": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readCostSeries"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/control/locations/{location_id}/targets/{target}/discovered": { parameters: { query?: never; @@ -2201,6 +2233,34 @@ export interface components { /** @description Where signing out goes when a trusted proxy owns the sign-in; absent means no sign-out link. */ logout_url?: string | null; }; + /** @description One job's estimated query cost on one node: in the period, and in the period before it. */ + CostFactRecord: { + /** Format: int64 */ + bytes_scanned: number; + /** Format: double */ + credits: number; + /** @description The node's folder as `costFolder` names it; empty at the top of `sql/models`. */ + folder: string; + /** @description None for builds no server run started. */ + job?: string | null; + /** @description `:`, like catalog node keys. */ + node_key: string; + /** Format: double */ + previous_credits: number; + /** Format: double */ + previous_usd?: number | null; + /** Format: int64 */ + queries: number; + /** + * Format: int64 + * @description Builds in the period, counted once each. + */ + runs: number; + /** Format: double */ + seconds: number; + /** Format: double */ + usd?: number | null; + }; /** @description Estimated query cost of one group, such as a job, a warehouse size or a node. */ CostGroup: { /** Format: double */ @@ -2220,6 +2280,67 @@ export interface components { */ usd?: number | null; }; + /** @description The price the dollars of a cost read use, and where it came from. */ + CostPrice: { + /** @description `config` (`[cost] usd_per_credit`), `rate_sheet`, `list_price` (also when only some) or `mixed`. */ + source: string; + /** Format: double */ + usd_per_credit: number; + }; + /** @description A selection's estimated query cost over a period, job by node, with daily series. */ + CostSelectionRecord: { + /** Format: int64 */ + bytes_scanned: number; + /** Format: double */ + credits: number; + /** @description The period's days, `YYYY-MM-DD` in UTC, oldest first; every series follows them. */ + dates: string[]; + /** Format: int32 */ + days: number; + error?: null | components["schemas"]["SelectionProblem"]; + facts: components["schemas"]["CostFactRecord"][]; + folder_daily: components["schemas"]["CostSeriesRecord"][]; + /** + * Format: int64 + * @description Of those, builds whose cost is still pending or partial. + */ + incomplete_runs: number; + job_daily: components["schemas"]["CostSeriesRecord"][]; + /** Format: double */ + previous_credits: number; + /** Format: double */ + previous_usd?: number | null; + price?: null | components["schemas"]["CostPrice"]; + /** Format: int64 */ + queries: number; + /** + * Format: int64 + * @description Builds in the period that spent cost on a selected node. + */ + runs: number; + /** Format: double */ + seconds: number; + /** Format: date-time */ + since: string; + /** + * Format: uuid + * @description The publication the selection was evaluated against; None before the first one. + */ + snapshot_id?: string | null; + /** Format: double */ + usd?: number | null; + }; + /** @description Daily series for a batch of groups, in their order. */ + CostSeriesBatch: { + dates: string[]; + series: number[][]; + }; + /** @description Credits per day of the period, oldest first, for one group. */ + CostSeriesRecord: { + credits: number[]; + /** @description The job, or top-level folder; None for builds no server run started. */ + key?: string | null; + }; /** @description A target's estimated query cost over a window, from the latest observation of each run. */ CostSummaryRecord: { by_job: components["schemas"]["CostGroup"][]; @@ -2239,6 +2360,8 @@ export interface components { since: string; /** Format: double */ usd?: number | null; + /** @description `config`, `rate_sheet`, `list_price` (also when only some are) or `mixed`; None without dollars. */ + usd_per_credit_source?: string | null; }; /** @description One stretch of the cursor, as raw bound texts. */ CoverageBatch: { @@ -2281,6 +2404,18 @@ export interface components { /** @enum {string} */ status: "unavailable"; }; + /** @description The node one item of a discovered set became under one `for_each` asset. */ + DiscoveredNodeReadback: { + /** @description The item's arguments; one that is not a string reads as its JSON text. */ + args: { + [key: string]: string; + }; + asset: string; + /** @description The node key, `asset:[]`. */ + key: string; + /** @description The item's ID, or `*` for the placeholder of a set that never succeeded. */ + step: string; + }; /** @description The discovered sets of a target's current snapshot; empty when it saved none. */ DiscoveredReadback: { /** Format: int64 */ @@ -2293,6 +2428,8 @@ export interface components { }; /** @description One discovered set of the current snapshot, as a deploy reads it back. */ DiscoveredSetReadback: { + /** @description The `for_each` assets that read the set. */ + assets: string[]; /** Format: int64 */ check_every_seconds?: number | null; digest?: string | null; @@ -2304,9 +2441,13 @@ export interface components { /** Format: date-time */ last_good_at?: string | null; name: string; + /** @description The node each served item became under each of `assets`, or each asset's placeholder. */ + nodes: components["schemas"]["DiscoveredNodeReadback"][]; status: components["schemas"]["DiscoveredSetStatus"]; - /** @description The tags of the result the set serves: its newest, or its last good one after a failure. */ - tags: Record; + /** @description The tags of the result the set serves (its newest, or its last good one), each as text. */ + tags: { + [key: string]: string; + }; }; /** * @description How a set's newest attempt went. @@ -2893,6 +3034,8 @@ export interface components { status: string; /** Format: double */ usd?: number | null; + /** @description Where the build's price per credit came from: `config`, `rate_sheet` or `list_price`. */ + usd_per_credit_source?: string | null; }; /** @enum {string} */ NodeEventKind: "success" | "failed" | "recovered"; @@ -3141,6 +3284,11 @@ export interface components { dropped_bytes?: number; /** @description The node that printed the lines, keyed `:`; `None` for lines printed outside a node. */ node_key?: string | null; + /** + * Format: date-time + * @description When the worker read these lines from the command's output, to the millisecond. + */ + read_at: string; stream: components["schemas"]["OutputStream"]; text: string; }; @@ -4007,10 +4155,16 @@ export interface components { event_id: string; event_type: string; invocation_id: string; - /** @description A summary the scheduler writes for a group run's member events, such as a member retry; never error or SQL text. */ + /** @description A summary of what an event names, such as a member retry or the command a worker started; never error or SQL text. */ message?: string | null; occurred_at: string; outcome?: string | null; + /** @description For a phase of a worker's command, such as `compiled` or `planned`: what it counted, what it is about and its sub-steps. */ + phase?: string | null; + /** Format: int64 */ + phase_count?: number | null; + phase_detail?: string | null; + phase_name?: string | null; producer?: string | null; resource_attempt_id?: string | null; resource_id?: string | null; @@ -5113,6 +5267,10 @@ export interface components { statements_observed: number; status: string; target_name?: string | null; + /** @description The price per credit `estimated_usd` used; None on rows recorded before prices were. */ + usd_per_credit?: string | null; + /** @description `config`, `rate_sheet` or `list_price` (an estimate); None on rows recorded before prices were. */ + usd_per_credit_source?: string | null; warehouse_name: string; warehouse_size: string; warehouse_type?: string | null; @@ -6762,6 +6920,106 @@ export interface operations { }; }; }; + readCostSelection: { + parameters: { + query?: { + /** @description Builds that started in the last this many whole UTC days, today included; defaults to 7, capped at 90 */ + days?: number; + /** @description Space-separated selectors, as `sqb build -s` takes them; empty selects every node */ + select?: string; + /** @description Space-separated selectors, as `--exclude` takes them */ + exclude?: string; + }; + header?: never; + path: { + location_id: string; + target: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The selection's cost job by node, against the period before, with daily series by job and top-level folder */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CostSelectionRecord"]; + }; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; + readCostSeries: { + parameters: { + query: { + /** @description As `readCostSelection` */ + days?: number; + /** @description As `readCostSelection` */ + select?: string; + /** @description As `readCostSelection` */ + exclude?: string; + /** @description A JSON array of at most 200 `CostSeriesGroup`s */ + groups: string; + }; + header?: never; + path: { + location_id: string; + target: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Each group's credits per day, in the groups' order */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CostSeriesBatch"]; + }; + }; + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; readDiscovered: { parameters: { query?: never; diff --git a/crates/sqlbuild-analysis/Cargo.toml b/crates/sqlbuild-analysis/Cargo.toml index 374738924f..5fd86ce8d2 100644 --- a/crates/sqlbuild-analysis/Cargo.toml +++ b/crates/sqlbuild-analysis/Cargo.toml @@ -29,6 +29,7 @@ sqlquack-fingerprint.workspace = true sqlquack-parse.workspace = true sqlquack-semantics.workspace = true sqlquack-syntax.workspace = true +sqlquack-tokenize.workspace = true sqlquack-syntax-bigquery.workspace = true sqlquack-syntax-clickhouse.workspace = true sqlquack-syntax-databricks.workspace = true diff --git a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/snowflake_dialect.rs b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/snowflake_dialect.rs index adc88494de..24dffd94ff 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/snowflake_dialect.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/snowflake_dialect.rs @@ -5,7 +5,8 @@ use std::num::IntErrorKind; use sqlquack_parse::{StrictFailure, parse_strict}; use sqlquack_semantics::dialects::constants::{SNOWFLAKE, SNOWFLAKE_QUOTED_IGNORING_CASE}; use sqlquack_semantics::dialects::types::DialectProfile; -use sqlquack_syntax::{Dialect, Error, Expression, Parsed, TokenizeFailure}; +use sqlquack_syntax::{Dialect, Error, Expression, Parsed}; +use sqlquack_tokenize::TokenizeFailure; use crate::analysis_route::_helpers::dialects::engine_types::snowflake_engine_type; use crate::analysis_route::_helpers::dialects::type_spelling::respelt; diff --git a/crates/sqlbuild-analysis/src/analysis_route/tests/test_native_gap.rs b/crates/sqlbuild-analysis/src/analysis_route/tests/test_native_gap.rs index dfc4885da3..b354bfb34f 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/tests/test_native_gap.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/tests/test_native_gap.rs @@ -209,14 +209,14 @@ fn given_a_located_gap_when_skipping_analysis_then_p026_names_the_model_its_site }, site: GapSite { label: None, - path: "models/orders.sql", + path: "sql/models/orders.sql", position: GapPosition::File(TextPosition { line: 5, column: 18, }), }, expected_code: "P001", - expected_message: "SQL syntax error in model 'orders' (models/orders.sql): the \ + expected_message: "SQL syntax error in model 'orders' (sql/models/orders.sql): the \ postgres parser cannot read syntax error at line 5, column 18: \ syntax error at or near \"FROM\"", }, @@ -234,7 +234,7 @@ fn given_a_located_gap_when_skipping_analysis_then_p026_names_the_model_its_site }, site: GapSite { label: Some("post_hooks[0] sql(\"record_refresh\")"), - path: "hooks/sql/record_refresh.sql", + path: "sql/hooks/sql/record_refresh.sql", position: GapPosition::Statement(TextPosition { line: 1, column: 13, @@ -242,7 +242,7 @@ fn given_a_located_gap_when_skipping_analysis_then_p026_names_the_model_its_site }, expected_code: "P001", expected_message: "SQL syntax error in model 'customer_totals' post_hooks[0] \ - sql(\"record_refresh\") (hooks/sql/record_refresh.sql): the duckdb \ + sql(\"record_refresh\") (sql/hooks/sql/record_refresh.sql): the duckdb \ parser cannot read Syntax error at or near 'WHERE' at line 1, \ column 13 of its SQL", }, @@ -260,12 +260,12 @@ fn given_a_located_gap_when_skipping_analysis_then_p026_names_the_model_its_site }, site: GapSite { label: None, - path: "models/orders_pivot.sql", + path: "sql/models/orders_pivot.sql", position: GapPosition::Analysed, }, expected_code: "P026", expected_message: "SQL analysis skipped for model 'orders_pivot' \ - (models/orders_pivot.sql): the postgres parser cannot read PIVOT at \ + (sql/models/orders_pivot.sql): the postgres parser cannot read PIVOT at \ line 3, column 3 of the analysed SQL", }, ]; diff --git a/crates/sqlbuild-analysis/src/compiled_project/tests/test_declaration_errors.rs b/crates/sqlbuild-analysis/src/compiled_project/tests/test_declaration_errors.rs index fa83f0a5ab..d8e37ae60d 100644 --- a/crates/sqlbuild-analysis/src/compiled_project/tests/test_declaration_errors.rs +++ b/crates/sqlbuild-analysis/src/compiled_project/tests/test_declaration_errors.rs @@ -13,7 +13,7 @@ fn given_declaration_error_when_wording_then_attachment_message_is_returned() { name: "_status".to_owned(), visible: vec!["region".to_owned(), "channel".to_owned()], }, - expected_message: "Unknown enum '_status' in this model in 'models/orders.sql'. \ + expected_message: "Unknown enum '_status' in this model in 'sql/models/orders.sql'. \ Visible enums: channel, region", }, DeclarationErrorTestCase { @@ -23,7 +23,7 @@ fn given_declaration_error_when_wording_then_attachment_message_is_returned() { name: "cap".to_owned(), visible: Vec::new(), }, - expected_message: "Unknown constant 'cap' in 'models/orders.sql'. Visible constants: none", + expected_message: "Unknown constant 'cap' in 'sql/models/orders.sql'. Visible constants: none", }, DeclarationErrorTestCase { description: "inaccessible resource-owned constant", @@ -31,23 +31,23 @@ fn given_declaration_error_when_wording_then_attachment_message_is_returned() { kind: "constant".to_owned(), name: "cap".to_owned(), record: InaccessibleDeclaration { - path: "models/marts/_constants/limits.sql".to_owned(), + path: "sql/models/marts/_constants/limits.sql".to_owned(), line: 1, column: 11, scope: "directory".to_owned(), - owner: "models/marts".to_owned(), + owner: "sql/models/marts".to_owned(), owner_identity: Some(("model".to_owned(), "orders_daily".to_owned())), }, }, - expected_message: "Constant 'cap' is known but inaccessible in 'models/orders.sql'. \ - It is defined at models/marts/_constants/limits.sql:1:11 with \ - directory scope owned by 'models/marts' (model 'orders_daily'); \ - consumer path: 'models/orders.sql'", + expected_message: "Constant 'cap' is known but inaccessible in 'sql/models/orders.sql'. \ + It is defined at sql/models/marts/_constants/limits.sql:1:11 with \ + directory scope owned by 'sql/models/marts' (model 'orders_daily'); \ + consumer path: 'sql/models/orders.sql'", }, DeclarationErrorTestCase { description: "invalid enum reference stop", error: DeclarationError::ScanStop(2), - expected_message: "Invalid enum reference in 'models/orders.sql'", + expected_message: "Invalid enum reference in 'sql/models/orders.sql'", }, DeclarationErrorTestCase { description: "unclosed quote stop", @@ -58,7 +58,7 @@ fn given_declaration_error_when_wording_then_attachment_message_is_returned() { for test_case in test_cases { assert_eq!( - declaration_error_message(&test_case.error, "models/orders.sql"), + declaration_error_message(&test_case.error, "sql/models/orders.sql"), test_case.expected_message, "{}", test_case.description diff --git a/crates/sqlbuild-analysis/src/compiled_project/tests/test_locating.rs b/crates/sqlbuild-analysis/src/compiled_project/tests/test_locating.rs index 54f612c3b7..d300ffd3bc 100644 --- a/crates/sqlbuild-analysis/src/compiled_project/tests/test_locating.rs +++ b/crates/sqlbuild-analysis/src/compiled_project/tests/test_locating.rs @@ -13,42 +13,42 @@ fn given_reference_scan_fault_when_locating_then_python_message_is_returned() { sql: "SELECT *\nFROM __ref(\"orders\"", contents: "MODEL (description \"Orders\");\n\nSELECT *\nFROM __ref(\"orders\"", passes: Some(vec![Vec::new(), Vec::new()]), - expected_message: "models/orders.sql:4:6: SQL reference contains an unclosed parenthesis", + expected_message: "sql/models/orders.sql:4:6: SQL reference contains an unclosed parenthesis", }, LocatedScanErrorTestCase { description: "unclosed quote counted in code points", sql: "SELECT 'é', __ref(\"orders\") WHERE note = 'open", contents: "MODEL ();\nSELECT 'é', __ref(\"orders\") WHERE note = 'open", passes: Some(vec![Vec::new(), Vec::new()]), - expected_message: "models/orders.sql:2:42: SQL reference contains an unclosed quoted string", + expected_message: "sql/models/orders.sql:2:42: SQL reference contains an unclosed quoted string", }, LocatedScanErrorTestCase { description: "fault after neutral expansions maps through both passes", sql: "SELECT 'open', 1 + 2\nFROM __ref(\"orders\"", contents: "MODEL ();\nSELECT @enum(\"s\").OPEN, @m()\nFROM __ref(\"orders\"", passes: Some(vec![vec![span(7, 22, 7, 13)], vec![span(15, 19, 15, 20)]]), - expected_message: "models/orders.sql:3:6: SQL reference contains an unclosed parenthesis", + expected_message: "sql/models/orders.sql:3:6: SQL reference contains an unclosed parenthesis", }, LocatedScanErrorTestCase { description: "fault inside macro output is unlocated", sql: "SELECT * FROM __ref(\"orders\") /* expanded", contents: "MODEL ();\nSELECT * FROM __ref(\"orders\") @expand()", passes: Some(vec![Vec::new(), vec![span(30, 39, 30, 41)]]), - expected_message: "models/orders.sql: SQL reference contains an unclosed block comment", + expected_message: "sql/models/orders.sql: SQL reference contains an unclosed block comment", }, LocatedScanErrorTestCase { description: "authored fault shaped by an unclosed macro quote is unlocated", sql: "SELECT 'x || ' || note || 'open", contents: "MODEL ();\nSELECT @q() || ' || note || 'open", passes: Some(vec![Vec::new(), vec![span(7, 11, 7, 9)]]), - expected_message: "models/orders.sql: SQL reference contains an unclosed quoted string", + expected_message: "sql/models/orders.sql: SQL reference contains an unclosed quoted string", }, LocatedScanErrorTestCase { description: "without authored passes only the file is named", sql: "SELECT *\nFROM __ref(\"orders\"", contents: "MODEL ();\nSELECT *\nFROM __ref(\"orders\"", passes: None, - expected_message: "models/orders.sql: SQL reference contains an unclosed parenthesis", + expected_message: "sql/models/orders.sql: SQL reference contains an unclosed parenthesis", }, ]; @@ -64,7 +64,7 @@ fn given_reference_scan_fault_when_locating_then_python_message_is_returned() { .map_or(test_case.contents, |(_, query)| query.trim_start()) .to_owned(); let origin = ScanFaultOrigin { - relative_path: "models/orders.sql", + relative_path: "sql/models/orders.sql", contents: test_case.contents, query_sql: &query_sql, passes: test_case.passes, diff --git a/crates/sqlbuild-analysis/src/dag_artifact/constants.rs b/crates/sqlbuild-analysis/src/dag_artifact/constants.rs index ea0c4a97f4..41442aa2d3 100644 --- a/crates/sqlbuild-analysis/src/dag_artifact/constants.rs +++ b/crates/sqlbuild-analysis/src/dag_artifact/constants.rs @@ -34,6 +34,6 @@ pub(crate) const SELECTOR_KIND_CHECK: &str = "check"; pub(crate) const SELECTOR_KIND_TEST: &str = "test"; pub(crate) const SELECTOR_KIND_JOB: &str = "job"; pub(crate) const SELECTOR_KIND_SEPARATOR: &str = ":"; -pub(crate) const SELECTOR_MODELS_PREFIX: &str = "models/"; +pub(crate) const SELECTOR_MODELS_PREFIX: &str = "sql/models/"; /// The orchestrator kind every SQLBuild asset carries. pub(crate) const SQLBUILD_ASSET_KIND: &str = "sqlbuild"; diff --git a/crates/sqlbuild-analysis/src/dag_artifact/tests/helpers.rs b/crates/sqlbuild-analysis/src/dag_artifact/tests/helpers.rs index 73c51d7f8d..e960549005 100644 --- a/crates/sqlbuild-analysis/src/dag_artifact/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/dag_artifact/tests/helpers.rs @@ -30,7 +30,7 @@ pub(crate) fn source(name: &str, loader: Option<&str>, meta: DagValue) -> DagSou DagSourceInput { key: key("source", name), name: name.to_owned(), - path: "sources/raw.yml".to_owned(), + path: "sql/sources/raw.yml".to_owned(), entry: DagSourceEntryInput { name: name.to_owned(), database: None, @@ -52,7 +52,7 @@ pub(crate) fn loader( ) -> DagLoaderInput { DagLoaderInput { name: name.to_owned(), - path: "python/loaders.py".to_owned(), + path: "python/nodes/loaders.py".to_owned(), destination: destination.map(str::to_owned), columns: Vec::new(), dependency_names: dependencies.iter().map(|name| (*name).to_owned()).collect(), @@ -64,7 +64,7 @@ pub(crate) fn python_node(kind: &str, name: &str, sql_deps: Vec) -> D DagPythonNodeInput { kind: kind.to_owned(), name: name.to_owned(), - path: "python/nodes.py".to_owned(), + path: "python/nodes/nodes.py".to_owned(), description: None, tags: Vec::new(), group: None, diff --git a/crates/sqlbuild-analysis/src/dag_artifact/tests/test_build_dag_json.rs b/crates/sqlbuild-analysis/src/dag_artifact/tests/test_build_dag_json.rs index beda363adc..d17359d6b2 100644 --- a/crates/sqlbuild-analysis/src/dag_artifact/tests/test_build_dag_json.rs +++ b/crates/sqlbuild-analysis/src/dag_artifact/tests/test_build_dag_json.rs @@ -31,7 +31,7 @@ const LOADED_JSON: &str = "{ \"name\": \"orders\", \"qualified_name\": \"raw.orders\" }, - \"path\": \"sources/raw.yml\", + \"path\": \"sql/sources/raw.yml\", \"meta\": { \"team\": \"ops\" }, @@ -54,7 +54,7 @@ const LOADED_JSON: &str = "{ \"name\": \"__loader__load_customers\", \"qualified_name\": \"main.__loader__load_customers\" }, - \"path\": \"python/loaders.py\", + \"path\": \"python/nodes/loaders.py\", \"meta\": { \"sqlbuild_loader_node\": true }, @@ -68,7 +68,7 @@ const LOADED_JSON: &str = "{ \"check\", \"orders_check\" ], - \"path\": \"python/nodes.py\" + \"path\": \"python/nodes/nodes.py\" } ], \"edges\": [ @@ -89,7 +89,7 @@ const LOADED_JSON: &str = "{ \"checked_asset_ids\": [ \"source:orders\" ], - \"path\": \"python/nodes.py\", + \"path\": \"python/nodes/nodes.py\", \"severity\": \"error\" } ] diff --git a/crates/sqlbuild-analysis/src/definition_changes/tests/test_definition_changes.rs b/crates/sqlbuild-analysis/src/definition_changes/tests/test_definition_changes.rs index ac2497638f..c82fef37d4 100644 --- a/crates/sqlbuild-analysis/src/definition_changes/tests/test_definition_changes.rs +++ b/crates/sqlbuild-analysis/src/definition_changes/tests/test_definition_changes.rs @@ -428,7 +428,7 @@ fn given_changes_and_selection_when_writing_json_then_lists_nodes_and_reasons() #[test] fn given_a_sql_macro_when_fingerprinting_definition_then_ignores_layout_comments_and_description() { - let path: &str = "macros/sql/net.sql"; + let path: &str = "sql/macros/sql/net.sql"; let original: String = sql_macro_definition_digest( "net", path, diff --git a/crates/sqlbuild-analysis/src/diff_selection/constants.rs b/crates/sqlbuild-analysis/src/diff_selection/constants.rs index ad63030eee..9e3ab43998 100644 --- a/crates/sqlbuild-analysis/src/diff_selection/constants.rs +++ b/crates/sqlbuild-analysis/src/diff_selection/constants.rs @@ -3,8 +3,8 @@ pub(crate) const TAG_PREFIX: &str = "tag:"; pub(crate) const PATH_PREFIX: &str = "path:"; pub(crate) const PATH_SEPARATORS: [char; 2] = ['/', '\\']; -pub(crate) const MODEL_PATH_ROOT: &str = "models"; -pub(crate) const MODEL_PATH_PREFIX: &str = "models/"; +pub(crate) const MODEL_PATH_ROOT: &str = "sql/models"; +pub(crate) const MODEL_PATH_PREFIX: &str = "sql/models/"; pub(crate) const GRAPH_OPERATOR: char = '+'; pub(crate) const INTERSECTION_SEPARATOR: char = ','; pub(crate) const EMPTY_SELECTOR_CODE: &str = "S001"; diff --git a/crates/sqlbuild-analysis/src/diff_selection/tests/test_resolve_diff_selection.rs b/crates/sqlbuild-analysis/src/diff_selection/tests/test_resolve_diff_selection.rs index d3485cfb06..29d46f7115 100644 --- a/crates/sqlbuild-analysis/src/diff_selection/tests/test_resolve_diff_selection.rs +++ b/crates/sqlbuild-analysis/src/diff_selection/tests/test_resolve_diff_selection.rs @@ -19,7 +19,7 @@ fn given_selectors_when_resolving_diff_selection_then_matches_python_semantics() }, DiffSelectionTestCase { description: "a comma intersects tag and path", - select: &["tag:finance,path:models\\marts\\"], + select: &["tag:finance,path:sql\\models\\marts\\"], exclude: &[], expected_selection: Ok(&[2, 3]), }, @@ -49,7 +49,7 @@ fn given_selectors_when_resolving_diff_selection_then_matches_python_semantics() }, DiffSelectionTestCase { description: "an unknown path", - select: &["path:models/intermediate"], + select: &["path:sql/models/intermediate"], exclude: &[], expected_selection: Err("S009"), }, diff --git a/crates/sqlbuild-analysis/src/explicit_references/tests/helpers.rs b/crates/sqlbuild-analysis/src/explicit_references/tests/helpers.rs index 7ee8a76c62..bebe5db534 100644 --- a/crates/sqlbuild-analysis/src/explicit_references/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/explicit_references/tests/helpers.rs @@ -13,7 +13,7 @@ pub(crate) fn relation(name: &str, schema: Option<&str>, database: Option<&str>) fn model(name: &str, migrate_from: Option<&str>) -> ModelReferences { ModelReferences { name: name.to_owned(), - path: format!("models/{name}.sql"), + path: format!("sql/models/{name}.sql"), destination: relation(name, Some("main"), Some("memory")), python_hooks: Vec::new(), sql_hooks: Vec::new(), diff --git a/crates/sqlbuild-analysis/src/graph/constants.rs b/crates/sqlbuild-analysis/src/graph/constants.rs index d1a004f835..9bfdc3311b 100644 --- a/crates/sqlbuild-analysis/src/graph/constants.rs +++ b/crates/sqlbuild-analysis/src/graph/constants.rs @@ -12,8 +12,8 @@ pub(crate) const KIND_SEPARATOR: char = ':'; pub(crate) const FOLDER_SEPARATOR: char = '/'; pub(crate) const INTERSECTION_SEPARATOR: char = ','; pub(crate) const PATTERN_CHARACTERS: [char; 3] = ['*', '?', '[']; -pub(crate) const MODEL_ROOT: &str = "models"; -pub(crate) const MODEL_ROOT_PREFIX: &str = "models/"; +pub(crate) const MODEL_ROOT: &str = "sql/models"; +pub(crate) const MODEL_ROOT_PREFIX: &str = "sql/models/"; pub(crate) const SQL_FILE_SUFFIX: &str = ".sql"; pub(crate) const TAG_KIND: &str = "tag"; pub(crate) const PATH_KIND: &str = "path"; @@ -44,7 +44,7 @@ pub(crate) const PATH_ROOT_CODE: &str = "S012"; pub(crate) const UNIT_TEST_CODE: &str = "S013"; pub const PLANNER_DEFAULT_CODE: &str = "S000"; pub(crate) const PATH_ROOT_ERROR: &str = - "path selectors require an explicit root: use 'models/' or 'python/'"; + "path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'"; pub(crate) const UNIT_TEST_ONLY_TEST_AND_BUILD: &str = "only `sqb test` and `sqb build` accept unit-test selectors"; /// `difflib.SequenceMatcher` treats an element as popular only in sequences this long. diff --git a/crates/sqlbuild-analysis/src/graph/tests/helpers.rs b/crates/sqlbuild-analysis/src/graph/tests/helpers.rs index 9b9d9e0f2a..e38a899592 100644 --- a/crates/sqlbuild-analysis/src/graph/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/graph/tests/helpers.rs @@ -33,7 +33,7 @@ const ORDERS_PROJECT: &[ResourceSpec] = &[ "order_items", &[("model", "orders"), ("seed", "countries")], &["daily", "finance"], - Some("models/mart/items"), + Some("sql/models/mart/items"), ), ("model", "customers", &[], &[], Some("staging/crm")), ( diff --git a/crates/sqlbuild-analysis/src/graph/tests/test_graph.rs b/crates/sqlbuild-analysis/src/graph/tests/test_graph.rs index d0c68e6470..d4b6d673ee 100644 --- a/crates/sqlbuild-analysis/src/graph/tests/test_graph.rs +++ b/crates/sqlbuild-analysis/src/graph/tests/test_graph.rs @@ -55,8 +55,8 @@ fn given_selectors_when_resolving_then_keys_match_python() { expected_keys: &[("model", "orders"), ("udf", "tax")], }, SelectorTestCase { - description: "models/mart", - select: &["models/mart"], + description: "sql/models/mart", + select: &["sql/models/mart"], exclude: &[], expected_keys: &[ ("model", "order_items"), @@ -65,8 +65,8 @@ fn given_selectors_when_resolving_then_keys_match_python() { ], }, SelectorTestCase { - description: "path:models/staging", - select: &["path:models/staging"], + description: "path:sql/models/staging", + select: &["path:sql/models/staging"], exclude: &[], expected_keys: &[("model", "customers")], }, @@ -112,8 +112,8 @@ fn given_selectors_when_resolving_then_keys_match_python() { ], }, SelectorTestCase { - description: "tag:daily,models/mart/items", - select: &["tag:daily,models/mart/items"], + description: "tag:daily,sql/models/mart/items", + select: &["tag:daily,sql/models/mart/items"], exclude: &[], expected_keys: &[("model", "order_items"), ("udf", "tax")], }, @@ -251,7 +251,7 @@ fn given_invalid_selectors_when_resolving_then_errors_match_python() { exclude: &[], expected_error: ( "S012", - "path selectors require an explicit root: use 'models/' or 'python/'", + "path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'", None, ), }, diff --git a/crates/sqlbuild-analysis/src/graph/tests/test_job_selectors.rs b/crates/sqlbuild-analysis/src/graph/tests/test_job_selectors.rs index d196f7ee4f..d9a7f94632 100644 --- a/crates/sqlbuild-analysis/src/graph/tests/test_job_selectors.rs +++ b/crates/sqlbuild-analysis/src/graph/tests/test_job_selectors.rs @@ -196,7 +196,12 @@ fn given_selectors_when_scanning_then_only_job_references_need_jobs() { }, NeedsJobsTestCase { description: "patterns, paths and folders", - selectors: &["night*", "orders~nightly", "path:models/mart", "tag:daily"], + selectors: &[ + "night*", + "orders~nightly", + "path:sql/models/mart", + "tag:daily", + ], also_known: &[], expected_needs_jobs: false, }, diff --git a/crates/sqlbuild-analysis/src/graph/tests/test_named_selector_atoms.rs b/crates/sqlbuild-analysis/src/graph/tests/test_named_selector_atoms.rs index 82343c112e..e0902ea84f 100644 --- a/crates/sqlbuild-analysis/src/graph/tests/test_named_selector_atoms.rs +++ b/crates/sqlbuild-analysis/src/graph/tests/test_named_selector_atoms.rs @@ -36,7 +36,7 @@ fn given_a_selection_when_listing_named_atoms_then_only_single_node_names_count( }, NamedAtomsTestCase { description: "folder paths do not count", - selection: "models/orders python/orders path:models/finance", + selection: "sql/models/orders python/nodes/orders path:sql/models/finance", expected_atoms: &[], }, NamedAtomsTestCase { diff --git a/crates/sqlbuild-analysis/src/graph/tests/test_selector_scenarios.rs b/crates/sqlbuild-analysis/src/graph/tests/test_selector_scenarios.rs index 330b330bd3..2eb0e6c403 100644 --- a/crates/sqlbuild-analysis/src/graph/tests/test_selector_scenarios.rs +++ b/crates/sqlbuild-analysis/src/graph/tests/test_selector_scenarios.rs @@ -48,8 +48,8 @@ fn given_raw_selector_when_parsing_then_returns_kind_value_and_expansion() { }, ParseSelectorTestCase { description: "path typed selector", - raw: "path:models/staging", - expected_selector: kind("path", "models/staging", false, false), + raw: "path:sql/models/staging", + expected_selector: kind("path", "sql/models/staging", false, false), }, ParseSelectorTestCase { description: "typed selector with upstream expansion", @@ -421,14 +421,14 @@ fn given_selectors_when_resolving_then_selects_expected_names() { SelectedNamesTestCase { description: "folder including nested folders", project: FOLDER_PROJECT, - select: &["path:models/staging"], + select: &["path:sql/models/staging"], exclude: &[], expected_names: &["stg_customers", "stg_deep", "stg_orders"], }, SelectedNamesTestCase { description: "models root", project: FOLDER_PROJECT, - select: &["path:models"], + select: &["path:sql/models"], exclude: &[], expected_names: &[ "fact_orders", @@ -441,28 +441,28 @@ fn given_selectors_when_resolving_then_selects_expected_names() { SelectedNamesTestCase { description: "trailing slash with explicit root", project: FOLDER_PROJECT, - select: &["models/staging/"], + select: &["sql/models/staging/"], exclude: &[], expected_names: &["stg_customers", "stg_deep", "stg_orders"], }, SelectedNamesTestCase { description: "leading slash with explicit root", project: FOLDER_PROJECT, - select: &["/models/staging"], + select: &["/sql/models/staging"], exclude: &[], expected_names: &["stg_customers", "stg_deep", "stg_orders"], }, SelectedNamesTestCase { description: "folder with one model", project: FOLDER_PROJECT, - select: &["path:models/marts"], + select: &["path:sql/models/marts"], exclude: &[], expected_names: &["fact_orders"], }, SelectedNamesTestCase { description: "folder with downstream expansion", project: FOLDER_PROJECT, - select: &["path:models/staging+"], + select: &["path:sql/models/staging+"], exclude: &[], expected_names: &[ "fact_orders", @@ -475,7 +475,7 @@ fn given_selectors_when_resolving_then_selects_expected_names() { SelectedNamesTestCase { description: "folder with upstream expansion", project: FOLDER_PROJECT, - select: &["+path:models/marts"], + select: &["+path:sql/models/marts"], exclude: &[], expected_names: &[ "fact_orders", @@ -489,7 +489,7 @@ fn given_selectors_when_resolving_then_selects_expected_names() { SelectedNamesTestCase { description: "folder intersected with a name", project: FOLDER_PROJECT, - select: &["path:models/staging,stg_orders"], + select: &["path:sql/models/staging,stg_orders"], exclude: &[], expected_names: &["stg_orders"], }, @@ -497,20 +497,20 @@ fn given_selectors_when_resolving_then_selects_expected_names() { description: "folder excluded from selection", project: FOLDER_PROJECT, select: &["+fact_orders"], - exclude: &["path:models/staging"], + exclude: &["path:sql/models/staging"], expected_names: &["fact_orders", "int_enriched", "raw_customers", "raw_orders"], }, SelectedNamesTestCase { description: "trailing slash selects a one-model folder", project: FOLDER_PROJECT, - select: &["models/intermediate/"], + select: &["sql/models/intermediate/"], exclude: &[], expected_names: &["int_enriched"], }, SelectedNamesTestCase { description: "nested folder without its parent", project: FOLDER_PROJECT, - select: &["path:models/staging/raw"], + select: &["path:sql/models/staging/raw"], exclude: &[], expected_names: &["stg_deep"], }, @@ -567,7 +567,7 @@ fn given_unresolvable_selectors_when_resolving_then_fails_with_message() { select: &["path:nonexistent"], expected_error: ( "S012", - "path selectors require an explicit root: use 'models/' or 'python/'", + "path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'", None, ), }, @@ -577,17 +577,17 @@ fn given_unresolvable_selectors_when_resolving_then_fails_with_message() { select: &["nonexistent/"], expected_error: ( "S012", - "path selectors require an explicit root: use 'models/' or 'python/'", + "path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'", None, ), }, ProjectSelectorErrorTestCase { description: "folder with no models", project: FOLDER_PROJECT, - select: &["path:models/nonexistent"], + select: &["path:sql/models/nonexistent"], expected_error: ( "S009", - "no models found under path 'models/nonexistent'.", + "no models found under path 'sql/models/nonexistent'.", None, ), }, diff --git a/crates/sqlbuild-analysis/src/job_settings/tests/test_build_job_settings.rs b/crates/sqlbuild-analysis/src/job_settings/tests/test_build_job_settings.rs index e34ce90a5d..21b88facca 100644 --- a/crates/sqlbuild-analysis/src/job_settings/tests/test_build_job_settings.rs +++ b/crates/sqlbuild-analysis/src/job_settings/tests/test_build_job_settings.rs @@ -57,7 +57,7 @@ fn given_named_jobs_when_merging_build_settings_then_they_must_agree() { }, BuildJobSettingsTestCase { description: "tags, paths and node names name no job", - select: &["tag:daily models/marts orders"], + select: &["tag:daily sql/models/marts orders"], expected_named: vec![], expected_settings: Ok(BTreeMap::new()), }, diff --git a/crates/sqlbuild-analysis/src/lineage_command/tests/helpers.rs b/crates/sqlbuild-analysis/src/lineage_command/tests/helpers.rs index b37c7758dc..5bc864d9a2 100644 --- a/crates/sqlbuild-analysis/src/lineage_command/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/lineage_command/tests/helpers.rs @@ -17,8 +17,8 @@ pub(super) fn orders_index() -> LineageIndex { let fact: LineageKey = key("model", "fact_orders"); let seed: LineageKey = key("seed", "waffle_types"); let nodes: HashMap = [ - (stg.clone(), Some("models/stg_orders.sql")), - (fact.clone(), Some("models/fact_orders.sql")), + (stg.clone(), Some("sql/models/stg_orders.sql")), + (fact.clone(), Some("sql/models/fact_orders.sql")), (raw.clone(), None), (seed.clone(), None), ] diff --git a/crates/sqlbuild-analysis/src/lineage_command/tests/test_lineage_command.rs b/crates/sqlbuild-analysis/src/lineage_command/tests/test_lineage_command.rs index c1173a53a4..6040d44def 100644 --- a/crates/sqlbuild-analysis/src/lineage_command/tests/test_lineage_command.rs +++ b/crates/sqlbuild-analysis/src/lineage_command/tests/test_lineage_command.rs @@ -18,8 +18,8 @@ fn given_targets_when_selecting_lineage_then_stdout_matches() { direction: "upstream", depth: None, expected_stdout: Ok( - "\nLineage model fact_orders models/fact_orders.sql upstream\n\ - \u{251c}\u{2500}\u{2500} model stg_orders models/stg_orders.sql\n\ + "\nLineage model fact_orders sql/models/fact_orders.sql upstream\n\ + \u{251c}\u{2500}\u{2500} model stg_orders sql/models/stg_orders.sql\n\ \u{2502} \u{2514}\u{2500}\u{2500} source raw_orders\n\ \u{2514}\u{2500}\u{2500} seed waffle_types\n\n", ), @@ -43,9 +43,9 @@ fn given_targets_when_selecting_lineage_then_stdout_matches() { expected_stdout: Ok( "{\n \"nodes\": [\n {\n \"id\": \"model:fact_orders\",\n \ \"name\": \"fact_orders\",\n \"resource_type\": \"model\",\n \ - \"relative_path\": \"models/fact_orders.sql\"\n },\n {\n \ + \"relative_path\": \"sql/models/fact_orders.sql\"\n },\n {\n \ \"id\": \"model:stg_orders\",\n \"name\": \"stg_orders\",\n \ - \"resource_type\": \"model\",\n \"relative_path\": \"models/stg_orders.sql\"\n \ + \"resource_type\": \"model\",\n \"relative_path\": \"sql/models/stg_orders.sql\"\n \ }\n ],\n \"edges\": [\n {\n \"from\": \"model:stg_orders\",\n \ \"to\": \"model:fact_orders\"\n }\n ],\n \"focus\": [\n \ \"model:stg_orders\"\n ],\n \"direction\": \"downstream\"\n}\n", diff --git a/crates/sqlbuild-analysis/src/manifest/_helpers/node_fields.rs b/crates/sqlbuild-analysis/src/manifest/_helpers/node_fields.rs index 8c9aed05f2..db15781807 100644 --- a/crates/sqlbuild-analysis/src/manifest/_helpers/node_fields.rs +++ b/crates/sqlbuild-analysis/src/manifest/_helpers/node_fields.rs @@ -11,11 +11,15 @@ use crate::manifest::models::{ }; use crate::python_values::models::PythonValue; -/// `[project, *relative_path.parent.parts, relative_path.stem]`. +/// `[project, *relative_path.parent.parts, relative_path.stem]`, with the parts read below `sql/`. pub(crate) fn fqn(project_name: &str, path: &ManifestPathInput) -> PythonValue { + let parents: &[String] = match path.parent_parts.split_first() { + Some((first, rest)) if first == sqlbuild_core::constants::SQL_DIRECTORY => rest, + _ => &path.parent_parts, + }; texts( std::iter::once(project_name) - .chain(path.parent_parts.iter().map(String::as_str)) + .chain(parents.iter().map(String::as_str)) .chain(std::iter::once(path.stem.as_str())), ) } diff --git a/crates/sqlbuild-analysis/src/manifest/tests/helpers.rs b/crates/sqlbuild-analysis/src/manifest/tests/helpers.rs index 8523893f3a..cb8ffc80e3 100644 --- a/crates/sqlbuild-analysis/src/manifest/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/manifest/tests/helpers.rs @@ -42,8 +42,8 @@ pub(crate) fn model(meta: Option, config: ManifestConfigInput) -> M ManifestModelInput { name: "orders".to_owned(), path: ManifestPathInput { - text: "models/orders.sql".to_owned(), - parent_parts: vec!["models".to_owned()], + text: "sql/models/orders.sql".to_owned(), + parent_parts: vec!["sql".to_owned(), "models".to_owned()], stem: "orders".to_owned(), }, destination: ManifestRelationInput::default(), diff --git a/crates/sqlbuild-analysis/src/node_set_dependencies/_helpers/sets.rs b/crates/sqlbuild-analysis/src/node_set_dependencies/_helpers/sets.rs index bac31025b7..c87060ed1f 100644 --- a/crates/sqlbuild-analysis/src/node_set_dependencies/_helpers/sets.rs +++ b/crates/sqlbuild-analysis/src/node_set_dependencies/_helpers/sets.rs @@ -3,14 +3,14 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use crate::graph::errors::SelectorError; -use crate::graph::models::JobSelection; +use crate::graph::models::{JobSelection, ProjectGraph}; use crate::node_set_dependencies::_helpers::combined::Combined; use crate::node_set_dependencies::_helpers::labels::{ excluding, listed, node_label, node_name, set_label, }; use crate::node_set_dependencies::constants::{ - DEPENDABLE_PYTHON_KINDS, DEPENDABLE_SQL_KINDS, JOB_SET, LOADER_KIND, LOCATION_SEPARATOR, - NODE_SET_CODE, TAG_SET, + DEPENDABLE_PYTHON_KINDS, DEPENDABLE_SQL_KINDS, JOB_SET, LOCATION_SEPARATOR, NODE_SET_CODE, + TAG_SET, }; use crate::node_set_dependencies::models::{ DependantNode, GraphNode, NodeSetDependency, ResolvedNode, @@ -35,6 +35,12 @@ pub(crate) fn python_kinds(python: &PythonSelectionGraph) -> HashMap bool { + graph.tags.iter().any(|(name, _)| name == tag) + || python.tags.iter().any(|(name, _)| name == tag) +} + /// The dependable nodes `dependency` names, less its `exclude`. pub(crate) fn members( (sql, python): (SqlSelectionGraph<'_>, &PythonSelectionGraph), @@ -43,12 +49,6 @@ pub(crate) fn members( ) -> Result, SelectorError> { let owner: String = format!("{} '{}'", dependant.kind, dependant.name); let set: String = set_label(dependency); - if dependant.kind == LOADER_KIND { - return Err(failure( - format!("{owner} depends on {set}; loaders cannot depend on a job or a tag"), - Some("name the loaders or assets it depends on one by one".to_owned()), - )); - } if dependency.name.contains(LOCATION_SEPARATOR) { return Err(failure( format!("{owner} depends on {set}, a job of another code location"), @@ -64,13 +64,7 @@ pub(crate) fn members( ), )); } - let tagged: bool = sql - .graph - .tags - .iter() - .any(|(tag, _)| *tag == dependency.name) - || python.tags.iter().any(|(tag, _)| *tag == dependency.name); - if dependency.kind == TAG_SET && !tagged { + if dependency.kind == TAG_SET && !tag_carried(sql.graph, python, &dependency.name) { return Err(failure( format!("{owner} depends on {set}, which no node carries"), None, diff --git a/crates/sqlbuild-analysis/src/node_set_dependencies/constants.rs b/crates/sqlbuild-analysis/src/node_set_dependencies/constants.rs index f0465ff2dd..a8f7cafcd9 100644 --- a/crates/sqlbuild-analysis/src/node_set_dependencies/constants.rs +++ b/crates/sqlbuild-analysis/src/node_set_dependencies/constants.rs @@ -10,8 +10,6 @@ pub(crate) const NODE_SET_CODE: &str = "S000"; pub(crate) const DEPENDABLE_SQL_KINDS: [&str; 3] = ["model", "seed", "source"]; /// Python node kinds a Python node may depend on. pub(crate) const DEPENDABLE_PYTHON_KINDS: [&str; 2] = ["loader", "asset"]; -/// The Python node kind that may depend on Python nodes only. -pub(crate) const LOADER_KIND: &str = "loader"; /// The SQL resource type a loader fills. pub(crate) const SOURCE_KIND: &str = "source"; /// What separates a code location from a job name in a cross-location dependency. diff --git a/crates/sqlbuild-analysis/src/node_set_dependencies/main/mod.rs b/crates/sqlbuild-analysis/src/node_set_dependencies/main/mod.rs index aa5575f475..d2d857f3c6 100644 --- a/crates/sqlbuild-analysis/src/node_set_dependencies/main/mod.rs +++ b/crates/sqlbuild-analysis/src/node_set_dependencies/main/mod.rs @@ -1,3 +1,4 @@ pub mod resolve_node_set_dependencies; pub mod set_dependency_metadata; +pub mod unknown_tags; pub mod wait_changes; diff --git a/crates/sqlbuild-analysis/src/node_set_dependencies/main/unknown_tags.rs b/crates/sqlbuild-analysis/src/node_set_dependencies/main/unknown_tags.rs new file mode 100644 index 0000000000..e3ec508372 --- /dev/null +++ b/crates/sqlbuild-analysis/src/node_set_dependencies/main/unknown_tags.rs @@ -0,0 +1,24 @@ +//! `unknown_tags`: each dependant's `tag(...)` dependencies that no node carries. + +use crate::graph::models::ProjectGraph; +use crate::node_set_dependencies::_helpers::sets::tag_carried; +use crate::node_set_dependencies::constants::TAG_SET; +use crate::node_set_dependencies::models::DependantNode; +use crate::python_selection::models::PythonSelectionGraph; + +/// Each `(dependant, tag)` where the dependant depends on a tag no SQL resource or Python node carries. +pub fn unknown_tags( + graph: &ProjectGraph, + python: &PythonSelectionGraph, + dependants: &[DependantNode], +) -> Vec<(String, String)> { + let mut unknown: Vec<(String, String)> = Vec::new(); + for dependant in dependants { + for dependency in &dependant.sets { + if dependency.kind == TAG_SET && !tag_carried(graph, python, &dependency.name) { + unknown.push((dependant.name.clone(), dependency.name.clone())); + } + } + } + unknown +} diff --git a/crates/sqlbuild-analysis/src/node_set_dependencies/tests/helpers.rs b/crates/sqlbuild-analysis/src/node_set_dependencies/tests/helpers.rs index c2d4eb1e27..720f44ed69 100644 --- a/crates/sqlbuild-analysis/src/node_set_dependencies/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/node_set_dependencies/tests/helpers.rs @@ -99,7 +99,7 @@ fn python_graph() -> PythonSelectionGraph { .map(|(name, _, tags, upstream, _)| InventoryNode { name: (*name).to_owned(), tags: owned(tags), - relative_path: format!("python/{name}.py"), + relative_path: format!("python/nodes/{name}.py"), upstream: owned(upstream), }) .collect(); diff --git a/crates/sqlbuild-analysis/src/node_set_dependencies/tests/test_resolve_node_set_dependencies.rs b/crates/sqlbuild-analysis/src/node_set_dependencies/tests/test_resolve_node_set_dependencies.rs index 5a3f102d1e..137bf3a2a5 100644 --- a/crates/sqlbuild-analysis/src/node_set_dependencies/tests/test_resolve_node_set_dependencies.rs +++ b/crates/sqlbuild-analysis/src/node_set_dependencies/tests/test_resolve_node_set_dependencies.rs @@ -118,15 +118,6 @@ fn given_unresolvable_dependencies_when_resolving_then_compile_fails_naming_the_ sets: &[("job", "billing:nightly", None)], expected_fragments: &["a job of another code location"], }, - FailureTestCase { - description: "a loader's set", - dependant: ("sync_events", "loader"), - groups: &[], - sets: &[("job", "single", None)], - expected_fragments: &[ - "loader 'sync_events' depends on job 'single'; loaders cannot depend on a job or a tag", - ], - }, FailureTestCase { description: "a job node reading the dependant's output closes a cycle", dependant: ("report", "asset"), diff --git a/crates/sqlbuild-analysis/src/planner_selection/tests/helpers.rs b/crates/sqlbuild-analysis/src/planner_selection/tests/helpers.rs index c63689fbe6..8c0e8d798c 100644 --- a/crates/sqlbuild-analysis/src/planner_selection/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/planner_selection/tests/helpers.rs @@ -50,9 +50,9 @@ pub(super) fn models() -> Vec { folder: folder.to_owned(), }; vec![ - model("orders", &["daily"], "models/staging"), - model("customers", &[], "models/staging/sub"), - model("report", &["daily"], "models/marts"), + model("orders", &["daily"], "sql/models/staging"), + model("customers", &[], "sql/models/staging/sub"), + model("report", &["daily"], "sql/models/marts"), ] } diff --git a/crates/sqlbuild-analysis/src/planner_selection/tests/test_planner_selection.rs b/crates/sqlbuild-analysis/src/planner_selection/tests/test_planner_selection.rs index 67acc8357c..9fef37658a 100644 --- a/crates/sqlbuild-analysis/src/planner_selection/tests/test_planner_selection.rs +++ b/crates/sqlbuild-analysis/src/planner_selection/tests/test_planner_selection.rs @@ -170,12 +170,12 @@ fn given_model_selector_term_when_resolving_then_returns_model_names() { }, ModelSelectorTestCase { description: "windows path is translated and matches nested folders", - term: "path:models\\staging", - expected_names: names(&["orders", "customers"], Some("path:models/staging")), + term: "path:sql\\models\\staging", + expected_names: names(&["orders", "customers"], Some("path:sql/models/staging")), }, ModelSelectorTestCase { description: "path selects the folder's models", - term: "path:models/marts", + term: "path:sql/models/marts", expected_names: names(&["report"], None), }, ModelSelectorTestCase { @@ -253,12 +253,12 @@ fn given_order_selectors_when_splitting_unit_tests_then_tests_and_resources_sepa }, UnitTestSplitTestCase { description: "selectors without unit tests pass through unchanged", - select: texts(&["orders", "customers,tag:daily", "models/marts"]), + select: texts(&["orders", "customers,tag:daily", "sql/models/marts"]), exclude: texts(&["raw_orders"]), accepts_unit_tests: true, expected_split: Ok(full_split( ( - &["orders", "customers,tag:daily", "models/marts"], + &["orders", "customers,tag:daily", "sql/models/marts"], &["raw_orders"], ), (&[], &[]), diff --git a/crates/sqlbuild-analysis/src/planner_warehouse/tests/helpers.rs b/crates/sqlbuild-analysis/src/planner_warehouse/tests/helpers.rs index 3687bf4c31..7edd69150a 100644 --- a/crates/sqlbuild-analysis/src/planner_warehouse/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/planner_warehouse/tests/helpers.rs @@ -21,6 +21,6 @@ pub(super) fn missing(name: &str, read_by: &[&str], role: Option<&str>) -> Missi read_by: read_by.iter().map(|reader| (*reader).to_owned()).collect(), unreadable: role.is_some(), role: role.map(str::to_owned), - location: format!("sources/{name}.yml:2"), + location: format!("sql/sources/{name}.yml:2"), } } diff --git a/crates/sqlbuild-analysis/src/planner_warehouse/tests/test_messages.rs b/crates/sqlbuild-analysis/src/planner_warehouse/tests/test_messages.rs index c119e89243..d769bbef79 100644 --- a/crates/sqlbuild-analysis/src/planner_warehouse/tests/test_messages.rs +++ b/crates/sqlbuild-analysis/src/planner_warehouse/tests/test_messages.rs @@ -17,7 +17,7 @@ fn given_missing_source_tables_when_reporting_then_lists_readers_and_remedies() description: "one missing table", missing: vec![missing("orders", &["fact_orders"], None)], expected_message: "cannot build selected scope: 1 source table read by selected resources does not exist in the warehouse:\n - source 'orders' (raw.orders), read by fact_orders", - expected_help: "create or load the table, correct its database, schema, or table in the source declaration, or stop reading it from the selected models; declared 'orders' at sources/orders.yml:2", + expected_help: "create or load the table, correct its database, schema, or table in the source declaration, or stop reading it from the selected models; declared 'orders' at sql/sources/orders.yml:2", }, MissingSourceTestCase { description: "unreadable table names the role", @@ -26,7 +26,7 @@ fn given_missing_source_tables_when_reporting_then_lists_readers_and_remedies() missing("customers", &["c"], Some("ANALYST")), ], expected_message: "cannot build selected scope: 2 source tables read by selected resources do not exist in the warehouse or are not readable by the current role:\n - source 'orders' (raw.orders), read by a, b\n - source 'customers' (raw.customers), read by c; the warehouse reports it does not exist or is not readable by role ANALYST", - expected_help: "create or load the table, grant SELECT on it to the role in use (ANALYST), correct its database, schema, or table in the source declaration, or stop reading it from the selected models; declared 'orders' at sources/orders.yml:2, 'customers' at sources/customers.yml:2", + expected_help: "create or load the table, grant SELECT on it to the role in use (ANALYST), correct its database, schema, or table in the source declaration, or stop reading it from the selected models; declared 'orders' at sql/sources/orders.yml:2, 'customers' at sql/sources/customers.yml:2", }, ]; for test_case in test_cases { diff --git a/crates/sqlbuild-analysis/src/python_selection/_helpers/nodes.rs b/crates/sqlbuild-analysis/src/python_selection/_helpers/nodes.rs index 8f29b2369c..131db8460d 100644 --- a/crates/sqlbuild-analysis/src/python_selection/_helpers/nodes.rs +++ b/crates/sqlbuild-analysis/src/python_selection/_helpers/nodes.rs @@ -50,9 +50,17 @@ pub(crate) fn selector_folder(value: &str) -> String { value.replace('\\', "/").trim_matches('/').to_owned() } -/// The first segment of a selector folder. +/// The path root a selector folder starts with: `sql/models`, `python/nodes`, or its first segment. pub(crate) fn folder_root(folder: &str) -> &str { - folder.split('/').next().unwrap_or_default() + [SQL_MODEL_PATH_ROOT, PYTHON_NODE_PATH_ROOT] + .into_iter() + .find(|root| { + folder == *root + || folder + .strip_prefix(root) + .is_some_and(|rest| rest.starts_with('/')) + }) + .unwrap_or_else(|| folder.split('/').next().unwrap_or_default()) } fn keyed(rows: &[(String, Vec)]) -> HashMap<&str, &[String]> { diff --git a/crates/sqlbuild-analysis/src/python_selection/constants.rs b/crates/sqlbuild-analysis/src/python_selection/constants.rs index 18b286a695..7d4db32976 100644 --- a/crates/sqlbuild-analysis/src/python_selection/constants.rs +++ b/crates/sqlbuild-analysis/src/python_selection/constants.rs @@ -19,7 +19,7 @@ pub(crate) const SQL_MODEL_DEPENDENCY_TYPES: [&str; 6] = pub(crate) const EXPANSION_MARKER: char = '+'; pub(crate) const INTERSECTION_SEPARATOR: char = ','; pub(crate) const PATTERN_CHARACTERS: [char; 3] = ['*', '?', '[']; -pub(crate) const SQL_MODEL_PATH_ROOT: &str = "models"; +pub(crate) const SQL_MODEL_PATH_ROOT: &str = sqlbuild_core::constants::MODELS_PATH; pub(crate) const CURRENT_DIRECTORY: &str = "."; pub(crate) const ROOT_DIRECTORY: &str = "/"; pub(crate) const PLANNER_DEFAULT_CODE: &str = "S000"; @@ -31,7 +31,7 @@ pub(crate) const PATH_BETWEEN_CODE: &str = "S011"; pub(crate) const PATH_ROOT_CODE: &str = "S012"; pub(crate) const UNIT_TEST_CODE: &str = "S013"; pub(crate) const PATH_ROOT_ERROR: &str = - "path selectors require an explicit root: use 'models/' or 'python/'"; + "path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'"; pub(crate) const UNIT_TEST_ONLY_TEST_AND_BUILD: &str = "only `sqb test` and `sqb build` accept unit-test selectors"; /// Codes `sqb check` ignores for an exclude token that matches no Python node. diff --git a/crates/sqlbuild-analysis/src/python_selection/tests/helpers.rs b/crates/sqlbuild-analysis/src/python_selection/tests/helpers.rs index 6ace228bd1..b73b6ffc45 100644 --- a/crates/sqlbuild-analysis/src/python_selection/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/python_selection/tests/helpers.rs @@ -31,7 +31,7 @@ const ORDERS_NODES: &[NodeSpec] = &[ ( "load_events", "loader", - "python/loaders/events.py", + "python/nodes/loaders/events.py", &[], &["prepare_orders"], &[], @@ -39,7 +39,7 @@ const ORDERS_NODES: &[NodeSpec] = &[ ( "prepare_orders", "asset", - "python/tasks/orders.py", + "python/nodes/tasks/orders.py", &["orders", "daily"], &[], &[], @@ -47,7 +47,7 @@ const ORDERS_NODES: &[NodeSpec] = &[ ( "export_orders", "asset", - "python/assets/orders.py", + "python/nodes/assets/orders.py", &["exports", "daily"], &["prepare_orders"], &[("model", "orders")], @@ -55,7 +55,7 @@ const ORDERS_NODES: &[NodeSpec] = &[ ( "check_orders_export", "check", - "python/checks/orders.py", + "python/nodes/checks/orders.py", &["exports"], &["export_orders"], &[], @@ -63,7 +63,7 @@ const ORDERS_NODES: &[NodeSpec] = &[ ( "raw_orders", "loader", - "python/loaders/orders.py", + "python/nodes/loaders/orders.py", &[], &[], &[], @@ -71,7 +71,7 @@ const ORDERS_NODES: &[NodeSpec] = &[ ( "check_raw_customers", "check", - "python/checks/customers.py", + "python/nodes/checks/customers.py", &["customer_checks"], &[], &[("source", "raw_customers")], @@ -92,11 +92,18 @@ fn failure(error: SelectorError) -> OwnedFailure { /// The orders nodes plus `step`, a `for_each` asset with items `a` and `b`, and `step_total`. const DISCOVERED_NODES: &[NodeSpec] = &[ - ("step[a]", "asset", "python/plan/node.py", &[], &[], &[]), + ( + "step[a]", + "asset", + "python/nodes/plan/node.py", + &[], + &[], + &[], + ), ( "step[b]", "asset", - "python/plan/node.py", + "python/nodes/plan/node.py", &[], &["step[a]"], &[], @@ -104,7 +111,7 @@ const DISCOVERED_NODES: &[NodeSpec] = &[ ( "step_total", "asset", - "python/plan/total.py", + "python/nodes/plan/total.py", &[], &["step[b]"], &[], @@ -318,7 +325,7 @@ fn round_trip_python_graph(nodes: &[RoundTripNodeSpec]) -> PythonSelectionGraph .map(|(name, _, upstream, _)| InventoryNode { name: (*name).to_owned(), tags: Vec::new(), - relative_path: "python/nodes.py".to_owned(), + relative_path: "python/nodes/nodes.py".to_owned(), upstream: owned(upstream), }) .collect(); diff --git a/crates/sqlbuild-analysis/src/python_selection/tests/test_python_selection.rs b/crates/sqlbuild-analysis/src/python_selection/tests/test_python_selection.rs index 97109c375e..ec26c889b8 100644 --- a/crates/sqlbuild-analysis/src/python_selection/tests/test_python_selection.rs +++ b/crates/sqlbuild-analysis/src/python_selection/tests/test_python_selection.rs @@ -23,7 +23,7 @@ fn given_python_node_selectors_when_resolving_then_names_match_python() { }, NodeSelectorTestCase { description: "explicit Python path", - select: &["path:python/tasks"], + select: &["path:python/nodes/tasks"], exclude: &[], expected_names: Ok(&["prepare_orders"]), }, @@ -54,7 +54,7 @@ fn given_python_node_selectors_when_resolving_then_names_match_python() { exclude: &[], expected_names: Err(( "S012", - "path selectors require an explicit root: use 'models/' or 'python/'", + "path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'", )), }, NodeSelectorTestCase { @@ -261,8 +261,8 @@ fn given_relative_paths_when_indexing_then_folders_match_python_parent() { let test_cases = [ InventoryTestCase { description: "nested file", - relative_path: "python/tasks/orders.py", - expected_folder: "python/tasks", + relative_path: "python/nodes/tasks/orders.py", + expected_folder: "python/nodes/tasks", }, InventoryTestCase { description: "top-level file", @@ -293,7 +293,7 @@ fn given_check_exclude_tokens_when_resolving_then_unmatched_tokens_are_skipped() NodeSelectorTestCase { description: "unknown name, tag and path are skipped", select: &[], - exclude: &["missing tag:missing path:python/none", "tag:exports"], + exclude: &["missing tag:missing path:python/nodes/none", "tag:exports"], expected_names: Ok(&["check_orders_export", "export_orders"]), }, NodeSelectorTestCase { @@ -302,7 +302,7 @@ fn given_check_exclude_tokens_when_resolving_then_unmatched_tokens_are_skipped() exclude: &["path:other"], expected_names: Err(( "S012", - "path selectors require an explicit root: use 'models/' or 'python/'", + "path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'", )), }, ]; diff --git a/crates/sqlbuild-analysis/src/resource_diagnostics/tests/test_resource_diagnostics.rs b/crates/sqlbuild-analysis/src/resource_diagnostics/tests/test_resource_diagnostics.rs index cca1589364..5f821af9d2 100644 --- a/crates/sqlbuild-analysis/src/resource_diagnostics/tests/test_resource_diagnostics.rs +++ b/crates/sqlbuild-analysis/src/resource_diagnostics/tests/test_resource_diagnostics.rs @@ -92,10 +92,10 @@ fn given_resources_when_building_description_help_then_snippets_match_python() { name: "orders", statement: "MODEL", entry: "description \"What one row of orders represents\"", - path: "models/orders.sql", + path: "sql/models/orders.sql", description_only: false, }, - expected_help: "to describe model 'orders', add this to the MODEL header in models/orders.sql:\n MODEL (\n description \"What one row of orders represents\",\n ...\n );", + expected_help: "to describe model 'orders', add this to the MODEL header in sql/models/orders.sql:\n MODEL (\n description \"What one row of orders represents\",\n ...\n );", }, HelpTestCase { description: "a one-line HOOK header snippet", @@ -104,10 +104,10 @@ fn given_resources_when_building_description_help_then_snippets_match_python() { name: "grant", statement: "HOOK", entry: "description \"What grant does\"", - path: "hooks/grant.sql", + path: "sql/hooks/grant.sql", description_only: true, }, - expected_help: "to describe hook 'grant', add this to the HOOK header in hooks/grant.sql:\n HOOK (description \"What grant does\");", + expected_help: "to describe hook 'grant', add this to the HOOK header in sql/hooks/grant.sql:\n HOOK (description \"What grant does\");", }, ]; for test_case in test_cases { @@ -124,8 +124,8 @@ fn given_resources_when_building_description_help_then_snippets_match_python() { fn given_yaml_entries_when_building_description_help_then_snippets_match_python() { let test_cases = [YamlHelpTestCase { description: "a seed entry snippet", - entry: ("seed", "customers", "seeds/schema.yml"), - expected_help: "to describe seed 'customers', add `description` to its entry in seeds/schema.yml:\n - name: customers\n description: What one row of customers represents", + entry: ("seed", "customers", "sql/seeds/schema.yml"), + expected_help: "to describe seed 'customers', add `description` to its entry in sql/seeds/schema.yml:\n - name: customers\n description: What one row of customers represents", }]; for test_case in test_cases { let (kind, name, path) = test_case.entry; diff --git a/crates/sqlbuild-analysis/src/semantic_checks/tests/helpers.rs b/crates/sqlbuild-analysis/src/semantic_checks/tests/helpers.rs index 9e695d0328..9f323dd4f4 100644 --- a/crates/sqlbuild-analysis/src/semantic_checks/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/semantic_checks/tests/helpers.rs @@ -718,7 +718,7 @@ pub(crate) fn missing_column_request(audit: AuditSqlInput) -> ResourceSqlRequest sql_tests: Vec::new(), models: vec![HookModelInput { name: "orders".to_owned(), - path: "models/orders.sql".to_owned(), + path: "sql/models/orders.sql".to_owned(), authored_sql: Arc::from( "MODEL (description \"Orders not_null\", columns (order_id (audits [unique]), \ shipped_at (audits [not_null, unique])));\nSELECT 1 AS order_id\n", diff --git a/crates/sqlbuild-analysis/src/semantic_checks/tests/test_resource_sql.rs b/crates/sqlbuild-analysis/src/semantic_checks/tests/test_resource_sql.rs index f91795ba59..b54ec4eff5 100644 --- a/crates/sqlbuild-analysis/src/semantic_checks/tests/test_resource_sql.rs +++ b/crates/sqlbuild-analysis/src/semantic_checks/tests/test_resource_sql.rs @@ -102,7 +102,7 @@ fn given_built_in_audit_on_missing_column_when_checking_then_reports_once_at_its attached_target: Some(("model".to_owned(), "orders".to_owned())), attached_column: Some(test_case.column.to_owned()), built_in: test_case.built_in, - path: format!("audits/generic/{}.sql", test_case.definition), + path: format!("sql/audits/generic/{}.sql", test_case.definition), contents: Arc::from(""), bodies: Vec::new(), opts_out: false, @@ -114,7 +114,7 @@ fn given_built_in_audit_on_missing_column_when_checking_then_reports_once_at_its let diagnostic = missing_column_diagnostic(missing).expect(test_case.description); assert_eq!(diagnostic.code, "B002", "{}", test_case.description); assert_eq!( - diagnostic.path, "models/orders.sql", + diagnostic.path, "sql/models/orders.sql", "{}", test_case.description ); diff --git a/crates/sqlbuild-analysis/src/sql_macros/tests/helpers.rs b/crates/sqlbuild-analysis/src/sql_macros/tests/helpers.rs index 5ccf28eae7..844b76d9d9 100644 --- a/crates/sqlbuild-analysis/src/sql_macros/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/sql_macros/tests/helpers.rs @@ -24,7 +24,7 @@ impl FakeHost { let definitions = macros .iter() .map(|(name, source)| { - let path: String = format!("macros/sql/{name}.sql"); + let path: String = format!("sql/macros/sql/{name}.sql"); let definition = parse_sql_macro(name, &path, source).expect("valid macro"); ((*name).to_owned(), Arc::new(definition)) }) diff --git a/crates/sqlbuild-analysis/src/sql_macros/tests/test_definitions.rs b/crates/sqlbuild-analysis/src/sql_macros/tests/test_definitions.rs index 1ece5d76c8..45e75e919a 100644 --- a/crates/sqlbuild-analysis/src/sql_macros/tests/test_definitions.rs +++ b/crates/sqlbuild-analysis/src/sql_macros/tests/test_definitions.rs @@ -75,7 +75,7 @@ fn given_valid_macro_files_when_parsing_then_each_parameter_and_the_body_are_rea ]; for test_case in test_cases { - let definition = parse_sql_macro("m", "macros/sql/m.sql", test_case.source) + let definition = parse_sql_macro("m", "sql/macros/sql/m.sql", test_case.source) .expect(test_case.description); let labels: Vec = definition @@ -350,7 +350,7 @@ fn given_invalid_macro_files_when_parsing_then_each_is_rejected() { description: "missing header", source: "SELECT 1", expected_code: "P015", - expected_message: "SQL macro file macros/sql/m.sql must start with a MACRO (...) header", + expected_message: "SQL macro file sql/macros/sql/m.sql must start with a MACRO (...) header", }, DefinitionErrorTestCase { description: "unknown header key", @@ -361,7 +361,7 @@ fn given_invalid_macro_files_when_parsing_then_each_is_rejected() { ]; for test_case in test_cases { - let error = parse_sql_macro("m", "macros/sql/m.sql", test_case.source) + let error = parse_sql_macro("m", "sql/macros/sql/m.sql", test_case.source) .expect_err(test_case.description); assert_eq!( @@ -414,7 +414,7 @@ fn given_macro_descriptions_when_parsing_then_the_folded_text_is_stored() { ]; for test_case in test_cases { - let definition = parse_sql_macro("m", "macros/sql/m.sql", test_case.source) + let definition = parse_sql_macro("m", "sql/macros/sql/m.sql", test_case.source) .expect(test_case.description); assert_eq!( @@ -474,7 +474,7 @@ fn given_misquoted_macro_descriptions_when_parsing_then_the_quote_is_located() { ]; for test_case in test_cases { - let error = parse_sql_macro("m", "macros/sql/m.sql", test_case.source) + let error = parse_sql_macro("m", "sql/macros/sql/m.sql", test_case.source) .expect_err(test_case.description); let location = error .locations diff --git a/crates/sqlbuild-analysis/src/target_paths/constants.rs b/crates/sqlbuild-analysis/src/target_paths/constants.rs index 99f4861abc..6ff6781b3a 100644 --- a/crates/sqlbuild-analysis/src/target_paths/constants.rs +++ b/crates/sqlbuild-analysis/src/target_paths/constants.rs @@ -7,5 +7,5 @@ pub(crate) const MAX_CHAIN_COMPONENT_BYTES: usize = 200; pub(crate) const CHAIN_DIGEST_LENGTH: usize = 12; /// Bytes kept from the first and last model names of a shortened chain directory. pub(crate) const CHAIN_EDGE_NAME_BYTES: usize = 80; -pub(crate) const MODELS_DIR: &str = "models"; -pub(crate) const FUNCTIONS_DIR: &str = "functions"; +pub(crate) const MODELS_DIR: &str = sqlbuild_core::constants::MODELS_PATH; +pub(crate) const FUNCTIONS_DIR: &str = sqlbuild_core::constants::FUNCTIONS_PATH; diff --git a/crates/sqlbuild-analysis/src/target_paths/main/function_run_path.rs b/crates/sqlbuild-analysis/src/target_paths/main/function_run_path.rs index 6b46b65f1b..318f44a477 100644 --- a/crates/sqlbuild-analysis/src/target_paths/main/function_run_path.rs +++ b/crates/sqlbuild-analysis/src/target_paths/main/function_run_path.rs @@ -3,14 +3,14 @@ use crate::target_paths::_helpers::path_text::with_suffix; use crate::target_paths::constants::{FUNCTIONS_DIR, SQL_FILE_SUFFIX}; -/// The function's path under `functions//`, with a `.sql` suffix. +/// The function's path under `sql/functions//`, with a `.sql` suffix. #[must_use] pub fn function_run_path(relative_path: &str, language: &str) -> String { - let mut parts = relative_path.split('/'); - let path: String = if parts.next() == Some(FUNCTIONS_DIR) && parts.next() == Some(language) { + let root: String = format!("{FUNCTIONS_DIR}/{language}/"); + let path: String = if relative_path.starts_with(&root) { relative_path.to_owned() } else { - format!("{FUNCTIONS_DIR}/{language}/{relative_path}") + format!("{root}{relative_path}") }; with_suffix(&path, SQL_FILE_SUFFIX) } diff --git a/crates/sqlbuild-analysis/src/target_paths/main/model_run_path.rs b/crates/sqlbuild-analysis/src/target_paths/main/model_run_path.rs index 1b65f25dd1..c21f251622 100644 --- a/crates/sqlbuild-analysis/src/target_paths/main/model_run_path.rs +++ b/crates/sqlbuild-analysis/src/target_paths/main/model_run_path.rs @@ -2,10 +2,13 @@ use crate::target_paths::constants::MODELS_DIR; -/// The model's relative path, under `models/` unless it already starts there. +/// The model's relative path, under `sql/models/` unless it already starts there. #[must_use] pub fn model_run_path(relative_path: &str) -> String { - if relative_path.split('/').next() == Some(MODELS_DIR) { + if relative_path + .strip_prefix(MODELS_DIR) + .is_some_and(|rest| rest.starts_with('/')) + { return relative_path.to_owned(); } format!("{MODELS_DIR}/{relative_path}") diff --git a/crates/sqlbuild-analysis/src/target_paths/tests/test_target_paths.rs b/crates/sqlbuild-analysis/src/target_paths/tests/test_target_paths.rs index 2d8f49a8c8..b7ccedf293 100644 --- a/crates/sqlbuild-analysis/src/target_paths/tests/test_target_paths.rs +++ b/crates/sqlbuild-analysis/src/target_paths/tests/test_target_paths.rs @@ -68,24 +68,24 @@ fn given_relative_path_when_building_run_paths_then_matches_python() { let test_cases = [ RunPathTestCase { description: "paths already under their directory are kept", - relative_path: "models/a/b.sql", + relative_path: "sql/models/a/b.sql", language: "sql", - expected_model_path: "models/a/b.sql", - expected_function_path: "functions/sql/models/a/b.sql", + expected_model_path: "sql/models/a/b.sql", + expected_function_path: "sql/functions/sql/sql/models/a/b.sql", }, RunPathTestCase { description: "other paths are nested and functions get a sql suffix", relative_path: "udfs/f.py", language: "python", - expected_model_path: "models/udfs/f.py", - expected_function_path: "functions/python/udfs/f.sql", + expected_model_path: "sql/models/udfs/f.py", + expected_function_path: "sql/functions/python/udfs/f.sql", }, RunPathTestCase { description: "a function under its language directory is kept", - relative_path: "functions/sql/f.sql", + relative_path: "sql/functions/sql/f.sql", language: "sql", - expected_model_path: "models/functions/sql/f.sql", - expected_function_path: "functions/sql/f.sql", + expected_model_path: "sql/models/sql/functions/sql/f.sql", + expected_function_path: "sql/functions/sql/f.sql", }, ]; diff --git a/crates/sqlbuild-attachments/src/audits/tests/helpers.rs b/crates/sqlbuild-attachments/src/audits/tests/helpers.rs index 6c10347805..9c1facc8c6 100644 --- a/crates/sqlbuild-attachments/src/audits/tests/helpers.rs +++ b/crates/sqlbuild-attachments/src/audits/tests/helpers.rs @@ -38,7 +38,7 @@ pub(super) fn attachment( run_scope: Option<&str>, ) -> AuditAttachment { AuditAttachment { - owner_label: "models/schema.yml".to_owned(), + owner_label: "sql/models/schema.yml".to_owned(), definition_name: "accepted_values".to_owned(), definition_path: None, sql_body: "SELECT * FROM t WHERE @column NOT IN (@'values')".to_owned(), diff --git a/crates/sqlbuild-attachments/src/audits/tests/test_render_attached_audit.rs b/crates/sqlbuild-attachments/src/audits/tests/test_render_attached_audit.rs index 8fc33cf95a..c5de79568f 100644 --- a/crates/sqlbuild-attachments/src/audits/tests/test_render_attached_audit.rs +++ b/crates/sqlbuild-attachments/src/audits/tests/test_render_attached_audit.rs @@ -37,7 +37,7 @@ fn given_attached_audits_when_rendering_then_python_rendering_is_returned() { None, ), expected_rendering: failed( - "models/schema.yml audit 'accepted_values' must not override \ + "sql/models/schema.yml audit 'accepted_values' must not override \ implicit column from attached context", ), }, @@ -76,14 +76,14 @@ fn given_attached_audits_when_rendering_then_python_rendering_is_returned() { None, ), expected_rendering: failed( - "models/schema.yml audit 'accepted_values' must not override \ + "sql/models/schema.yml audit 'accepted_values' must not override \ implicit column from attached context", ), }, AttachedAuditTestCase { description: "an argument the audit SQL never reads names itself for removal", attachment: AuditAttachment { - definition_path: Some("audits/generic/accepted_values.sql".to_owned()), + definition_path: Some("sql/audits/generic/accepted_values.sql".to_owned()), ..attachment( vec![ values.clone(), @@ -97,8 +97,8 @@ fn given_attached_audits_when_rendering_then_python_rendering_is_returned() { ) }, expected_rendering: failed( - "models/schema.yml audit 'accepted_values' passes argument 'where_condition', \ - which the audit's SQL in audits/generic/accepted_values.sql never uses; remove \ + "sql/models/schema.yml audit 'accepted_values' passes argument 'where_condition', \ + which the audit's SQL in sql/audits/generic/accepted_values.sql never uses; remove \ 'where_condition' from the attachment", ), }, @@ -117,7 +117,7 @@ fn given_attached_audits_when_rendering_then_python_rendering_is_returned() { ) }, expected_rendering: failed( - "models/schema.yml audit 'relationships' argument 'to' is customers, not a \ + "sql/models/schema.yml audit 'relationships' argument 'to' is customers, not a \ relation reference; write to __ref(\"customers\") (or __source or __seed) so \ the audit reads the built relation and runs after it", ), @@ -148,14 +148,14 @@ fn given_attached_audits_when_rendering_then_python_rendering_is_returned() { description: "a missing argument is Python's error before the policies", attachment: attachment(Vec::new(), Some("fatal"), None), expected_rendering: failed( - "models/schema.yml is missing argument 'values' for generic audit \ + "sql/models/schema.yml is missing argument 'values' for generic audit \ 'accepted_values'", ), }, AttachedAuditTestCase { description: "a seed audit reading @model is told to read @relation", attachment: AuditAttachment { - owner_label: "seeds/waffle_types.yml".to_owned(), + owner_label: "sql/seeds/waffle_types.yml".to_owned(), sql_body: "SELECT * FROM __ref(\"@model\") WHERE NOT (price_cents >= 0)".to_owned(), implicit_arguments: vec![ ("seed".to_owned(), "waffle_types".to_owned()), @@ -164,7 +164,7 @@ fn given_attached_audits_when_rendering_then_python_rendering_is_returned() { ..attachment(Vec::new(), None, None) }, expected_rendering: failed( - "seeds/waffle_types.yml is missing argument 'model' for generic audit \ + "sql/seeds/waffle_types.yml is missing argument 'model' for generic audit \ 'accepted_values'; a seed audit receives 'seed' and 'relation', not 'model', \ so read the attached relation with @relation", ), @@ -180,7 +180,7 @@ fn given_attached_audits_when_rendering_then_python_rendering_is_returned() { None, ), expected_rendering: failed( - "models/schema.yml generic audit 'accepted_values' argument \ + "sql/models/schema.yml generic audit 'accepted_values' argument \ 'values' uses an unsupported value", ), }, @@ -189,7 +189,7 @@ fn given_attached_audits_when_rendering_then_python_rendering_is_returned() { attachment: attachment(vec![values.clone()], Some("fatal"), Some("delta")), expected_rendering: rendered( "SELECT * FROM t WHERE status NOT IN (1)", - Err("models/schema.yml audit \ + Err("sql/models/schema.yml audit \ 'accepted_values': unknown severity 'fatal'; valid values: warn, error"), ), }, diff --git a/crates/sqlbuild-attachments/src/functions/tests/test_frame_argument_error.rs b/crates/sqlbuild-attachments/src/functions/tests/test_frame_argument_error.rs index 5ecda76ac3..ee55da2889 100644 --- a/crates/sqlbuild-attachments/src/functions/tests/test_frame_argument_error.rs +++ b/crates/sqlbuild-attachments/src/functions/tests/test_frame_argument_error.rs @@ -1,7 +1,7 @@ use crate::functions::main::frame_argument_error::frame_argument_error; use crate::functions::tests::test_types::FrameArgumentTestCase; -const DECIMAL_ERROR: &str = "Python function functions/python/smooth.py argument 'amount' is \ +const DECIMAL_ERROR: &str = "Python function sql/functions/python/smooth.py argument 'amount' is \ NUMBER(10, 2), which Snowflake passes to a polars frame as Python Decimal objects, a slow \ object column; declare it as FLOAT, or as INTEGER when it has no fraction"; @@ -20,7 +20,7 @@ fn given_table_function_arguments_when_checking_the_frame_then_fractional_number dataframe: Some("polars"), argument_type: "decimal(12,4)", expected_error: Some( - "Python function functions/python/smooth.py argument 'amount' is \ + "Python function sql/functions/python/smooth.py argument 'amount' is \ decimal(12,4), which Snowflake passes to a polars frame as Python Decimal \ objects, a slow object column; declare it as FLOAT, or as INTEGER when it has \ no fraction", @@ -31,7 +31,7 @@ fn given_table_function_arguments_when_checking_the_frame_then_fractional_number dataframe: Some("polars"), argument_type: "DEC(10, 2)", expected_error: Some( - "Python function functions/python/smooth.py argument 'amount' is \ + "Python function sql/functions/python/smooth.py argument 'amount' is \ DEC(10, 2), which Snowflake passes to a polars frame as Python Decimal \ objects, a slow object column; declare it as FLOAT, or as INTEGER when it has \ no fraction", @@ -70,7 +70,7 @@ fn given_table_function_arguments_when_checking_the_frame_then_fractional_number ]; assert_eq!( frame_argument_error( - "Python function functions/python/smooth.py", + "Python function sql/functions/python/smooth.py", test_case.dataframe, &arguments ) diff --git a/crates/sqlbuild-attachments/src/functions/tests/test_function_reference_error.rs b/crates/sqlbuild-attachments/src/functions/tests/test_function_reference_error.rs index cbf853f80d..8ebd9b3ac8 100644 --- a/crates/sqlbuild-attachments/src/functions/tests/test_function_reference_error.rs +++ b/crates/sqlbuild-attachments/src/functions/tests/test_function_reference_error.rs @@ -28,7 +28,7 @@ fn given_function_references_when_validating_then_first_unresolved_one_is_report description: "a seed read with __ref names the seed call", references: vec![("ref", "regions")], expected_error: Some( - "SQL function file functions/sql/lookup.sql references seed 'regions' with \ + "SQL function file sql/functions/sql/lookup.sql references seed 'regions' with \ __ref(...). Use __seed(\"regions\") for seed references; __ref only resolves \ models.", ), @@ -37,7 +37,7 @@ fn given_function_references_when_validating_then_first_unresolved_one_is_report description: "a table function called as a scalar UDF", references: vec![("ref", "orders"), ("udf", "open_orders")], expected_error: Some( - "SQL function file functions/sql/lookup.sql references table function \ + "SQL function file sql/functions/sql/lookup.sql references table function \ 'open_orders' with __udf(); use __table_fn()", ), }, @@ -45,7 +45,7 @@ fn given_function_references_when_validating_then_first_unresolved_one_is_report description: "a scalar function called as a table function", references: vec![("table_fn", "score")], expected_error: Some( - "SQL function file functions/sql/lookup.sql references scalar function 'score' \ + "SQL function file sql/functions/sql/lookup.sql references scalar function 'score' \ with __table_fn(); use __udf() for scalar UDFs", ), }, @@ -53,8 +53,12 @@ fn given_function_references_when_validating_then_first_unresolved_one_is_report for test_case in test_cases { assert_eq!( - function_reference_error("functions/sql/lookup.sql", &test_case.references, &known) - .as_deref(), + function_reference_error( + "sql/functions/sql/lookup.sql", + &test_case.references, + &known + ) + .as_deref(), test_case.expected_error, "{}", test_case.description diff --git a/crates/sqlbuild-attachments/src/functions/tests/test_parse_function_header.rs b/crates/sqlbuild-attachments/src/functions/tests/test_parse_function_header.rs index defb691353..11e39edd72 100644 --- a/crates/sqlbuild-attachments/src/functions/tests/test_parse_function_header.rs +++ b/crates/sqlbuild-attachments/src/functions/tests/test_parse_function_header.rs @@ -55,7 +55,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re expected_header: FunctionHeader { failure: failure( HeaderStage::Start, - "SQL function file functions/f.sql must declare returns", + "SQL function file sql/functions/f.sql must declare returns", ), ..empty_header() }, @@ -75,7 +75,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re arguments: vec![named("id", "id", "INTEGER")], failure: failure( HeaderStage::Arguments, - "SQL function file functions/f.sql argument ' value ' must declare a type", + "SQL function file sql/functions/f.sql argument ' value ' must declare a type", ), ..empty_header() }, @@ -89,7 +89,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re returns: Some(FunctionReturns::Table(Vec::new())), failure: failure( HeaderStage::Returns, - "SQL function file functions/f.sql returns must be a type string or table \ + "SQL function file sql/functions/f.sql returns must be a type string or table \ column declaration", ), ..empty_header() @@ -113,7 +113,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re returns: Some(FunctionReturns::Table(vec![named("id", "id", "INTEGER")])), failure: failure( HeaderStage::Returns, - "SQL function file functions/f.sql has an invalid return column name", + "SQL function file sql/functions/f.sql has an invalid return column name", ), ..empty_header() }, @@ -127,7 +127,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re returns: Some(FunctionReturns::Table(Vec::new())), failure: failure( HeaderStage::Returns, - "SQL function file functions/f.sql returns table must declare at least one \ + "SQL function file sql/functions/f.sql returns table must declare at least one \ column", ), ..empty_header() @@ -148,7 +148,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re expected_header: FunctionHeader { failure: failure( HeaderStage::Start, - "Python function file functions/f.sql must declare returns", + "Python function file sql/functions/f.sql must declare returns", ), ..empty_header() }, @@ -167,7 +167,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re runtime_version: Some("3.12".to_owned()), failure: failure( HeaderStage::PythonValues, - "Python function file functions/f.sql must declare entry_point", + "Python function file sql/functions/f.sql must declare entry_point", ), ..empty_header() }, @@ -188,7 +188,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re entry_point: Some("label".to_owned()), failure: failure( HeaderStage::PythonValues, - "Python function file functions/f.sql packages entries must be non-empty \ + "Python function file sql/functions/f.sql packages entries must be non-empty \ strings", ), ..empty_header() @@ -207,7 +207,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re returns: Some(FunctionReturns::Type("STRING".to_owned())), failure: failure( HeaderStage::Metadata, - "SQL function file functions/f.sql tags must be a list", + "SQL function file sql/functions/f.sql tags must be a list", ), ..empty_header() }, @@ -224,7 +224,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re returns: Some(FunctionReturns::Type("STRING".to_owned())), failure: failure( HeaderStage::Metadata, - "SQL function file functions/f.sql description must be a string", + "SQL function file sql/functions/f.sql description must be a string", ), ..empty_header() }, @@ -260,7 +260,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re returns: Some(FunctionReturns::Table(Vec::new())), failure: failure( HeaderStage::Returns, - "Python function file functions/f.sql returns must map each column name to its type", + "Python function file sql/functions/f.sql returns must map each column name to its type", ), ..empty_header() }, @@ -274,7 +274,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re returns: Some(FunctionReturns::Table(Vec::new())), failure: failure( HeaderStage::Returns, - "Python function file functions/f.sql returns must map each column name to its type", + "Python function file sql/functions/f.sql returns must map each column name to its type", ), ..empty_header() }, @@ -287,7 +287,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re expected_header: FunctionHeader { failure: failure( HeaderStage::Start, - "Python function file functions/f.sql must declare returns", + "Python function file sql/functions/f.sql must declare returns", ), ..empty_header() }, @@ -300,7 +300,7 @@ fn given_function_headers_when_parsing_then_python_values_and_first_error_are_re &test_case.header, test_case.language, test_case.table_function, - "functions/f.sql" + "sql/functions/f.sql" ), test_case.expected_header, "{}", diff --git a/crates/sqlbuild-attachments/src/functions/tests/test_table_function_arity_error.rs b/crates/sqlbuild-attachments/src/functions/tests/test_table_function_arity_error.rs index f2c60f7267..ab0541ac38 100644 --- a/crates/sqlbuild-attachments/src/functions/tests/test_table_function_arity_error.rs +++ b/crates/sqlbuild-attachments/src/functions/tests/test_table_function_arity_error.rs @@ -22,7 +22,7 @@ fn given_table_function_calls_when_checking_arity_then_first_mismatch_is_reporte description: "one declared argument reads in the singular", calls: vec![("table_fn", "customer_orders", Some(2))], expected_error: Some( - "Model file models/report.sql table function 'customer_orders' expects 1 \ + "Model file sql/models/report.sql table function 'customer_orders' expects 1 \ argument but received 2", ), }, @@ -30,7 +30,7 @@ fn given_table_function_calls_when_checking_arity_then_first_mismatch_is_reporte description: "an unknown count reads as Python's None", calls: vec![("table_fn", "order_window", None)], expected_error: Some( - "Model file models/report.sql table function 'order_window' expects 2 \ + "Model file sql/models/report.sql table function 'order_window' expects 2 \ arguments but received None", ), }, @@ -38,8 +38,12 @@ fn given_table_function_calls_when_checking_arity_then_first_mismatch_is_reporte for test_case in test_cases { assert_eq!( - table_function_arity_error("Model file models/report.sql", &test_case.calls, &counts) - .as_deref(), + table_function_arity_error( + "Model file sql/models/report.sql", + &test_case.calls, + &counts + ) + .as_deref(), test_case.expected_error, "{}", test_case.description diff --git a/crates/sqlbuild-attachments/src/functions/tests/test_table_function_partition_error.rs b/crates/sqlbuild-attachments/src/functions/tests/test_table_function_partition_error.rs index 86effcc911..5154ec0b03 100644 --- a/crates/sqlbuild-attachments/src/functions/tests/test_table_function_partition_error.rs +++ b/crates/sqlbuild-attachments/src/functions/tests/test_table_function_partition_error.rs @@ -23,7 +23,7 @@ fn given_table_function_calls_when_checking_partitions_then_first_unpartitioned_ ("table_fn", "smooth_readings", false), ], expected_error: Some( - "Model file models/report.sql calls Python table function 'smooth_readings' \ + "Model file sql/models/report.sql calls Python table function 'smooth_readings' \ without OVER (PARTITION BY ...); it receives one whole partition per call, so \ add OVER (PARTITION BY ) after the call", ), @@ -38,7 +38,7 @@ fn given_table_function_calls_when_checking_partitions_then_first_unpartitioned_ for test_case in test_cases { assert_eq!( table_function_partition_error( - "Model file models/report.sql", + "Model file sql/models/report.sql", &test_case.calls, &whole_partition ) diff --git a/crates/sqlbuild-cache/src/artifacts/tests/test_remove_stale.rs b/crates/sqlbuild-cache/src/artifacts/tests/test_remove_stale.rs index 8f4683dcfe..b79ce7f947 100644 --- a/crates/sqlbuild-cache/src/artifacts/tests/test_remove_stale.rs +++ b/crates/sqlbuild-cache/src/artifacts/tests/test_remove_stale.rs @@ -9,8 +9,8 @@ use crate::artifacts::tests::helpers::{ use crate::artifacts::tests::test_types::{StampedTreeTestCase, WalkRaceTestCase}; const MANAGED: [&str; 3] = [ - "models/orders.sql", - "models/marts/customers.sql", + "sql/models/orders.sql", + "sql/models/marts/customers.sql", "tests/t.sql", ]; @@ -26,8 +26,8 @@ fn given_stamped_tree_when_cleaning_again_then_only_changed_trees_are_walked() { expected_stamped: true, expected_removed: 0, expected_files: &[ - "models/marts/customers.sql", - "models/orders.sql", + "sql/models/marts/customers.sql", + "sql/models/orders.sql", "tests/t.sql", ], }, @@ -40,8 +40,8 @@ fn given_stamped_tree_when_cleaning_again_then_only_changed_trees_are_walked() { expected_stamped: true, expected_removed: 1, expected_files: &[ - "models/marts/customers.sql", - "models/orders.sql", + "sql/models/marts/customers.sql", + "sql/models/orders.sql", "tests/t.sql", ], }, @@ -54,20 +54,20 @@ fn given_stamped_tree_when_cleaning_again_then_only_changed_trees_are_walked() { expected_stamped: true, expected_removed: 1, expected_files: &[ - "models/marts/customers.sql", - "models/orders.sql", + "sql/models/marts/customers.sql", + "sql/models/orders.sql", "tests/t.sql", ], }, StampedTreeTestCase { description: "a managed file no longer managed", change: |_| {}, - managed_after: &["models/orders.sql", "models/marts/customers.sql"], + managed_after: &["sql/models/orders.sql", "sql/models/marts/customers.sql"], racy_window_ns: 0, layout: plain_compiled_root, expected_stamped: true, expected_removed: 1, - expected_files: &["models/marts/customers.sql", "models/orders.sql"], + expected_files: &["sql/models/marts/customers.sql", "sql/models/orders.sql"], }, StampedTreeTestCase { description: "the stamp file damaged", @@ -81,8 +81,8 @@ fn given_stamped_tree_when_cleaning_again_then_only_changed_trees_are_walked() { expected_stamped: true, expected_removed: 1, expected_files: &[ - "models/marts/customers.sql", - "models/orders.sql", + "sql/models/marts/customers.sql", + "sql/models/orders.sql", "tests/t.sql", ], }, @@ -95,8 +95,8 @@ fn given_stamped_tree_when_cleaning_again_then_only_changed_trees_are_walked() { expected_stamped: false, expected_removed: 1, expected_files: &[ - "models/marts/customers.sql", - "models/orders.sql", + "sql/models/marts/customers.sql", + "sql/models/orders.sql", "tests/t.sql", ], }, @@ -109,8 +109,8 @@ fn given_stamped_tree_when_cleaning_again_then_only_changed_trees_are_walked() { expected_stamped: false, expected_removed: 1, expected_files: &[ - "models/marts/customers.sql", - "models/orders.sql", + "sql/models/marts/customers.sql", + "sql/models/orders.sql", "tests/t.sql", ], }, @@ -124,7 +124,7 @@ fn given_stamped_tree_when_cleaning_again_then_only_changed_trees_are_walked() { for path in MANAGED { place(&compiled.join(path), b"select 1\n"); } - place(&compiled.join("models/stale.sql"), b"select 0\n"); + place(&compiled.join("sql/models/stale.sql"), b"select 0\n"); let first: HashSet = MANAGED.iter().map(|path| compiled.join(path)).collect(); let removed = remove_stale_unless_unchanged(&compiled, &first, &stamp, test_case.racy_window_ns) @@ -173,7 +173,9 @@ fn given_folder_changed_during_the_walk_when_recording_then_no_stamp_is_kept() { let test_cases = [ WalkRaceTestCase { description: "folder changed after the walk started", - change_during_walk: |compiled| place(&compiled.join("models/stray.sql"), b"select 0\n"), + change_during_walk: |compiled| { + place(&compiled.join("sql/models/stray.sql"), b"select 0\n") + }, expected_stamped: false, }, WalkRaceTestCase { @@ -187,11 +189,13 @@ fn given_folder_changed_during_the_walk_when_recording_then_no_stamp_is_kept() { let folder = tempfile::tempdir().expect("target folder"); let compiled: PathBuf = folder.path().join("compiled"); let stamp: PathBuf = folder.path().join("cache/compiled-tree.bin"); - place(&compiled.join("models/orders.sql"), b"select 1\n"); - let managed: HashSet = [compiled.join("models/orders.sql")].into_iter().collect(); + place(&compiled.join("sql/models/orders.sql"), b"select 1\n"); + let managed: HashSet = [compiled.join("sql/models/orders.sql")] + .into_iter() + .collect(); std::thread::sleep(std::time::Duration::from_millis(30)); let since_ns: i64 = now_ns(); - let folders: Vec = vec![compiled.clone(), compiled.join("models")]; + let folders: Vec = vec![compiled.clone(), compiled.join("sql/models")]; std::thread::sleep(std::time::Duration::from_millis(30)); (test_case.change_during_walk)(&compiled); diff --git a/crates/sqlbuild-cache/src/digest/tests/helpers.rs b/crates/sqlbuild-cache/src/digest/tests/helpers.rs index e1a0b87918..b210785a3f 100644 --- a/crates/sqlbuild-cache/src/digest/tests/helpers.rs +++ b/crates/sqlbuild-cache/src/digest/tests/helpers.rs @@ -2,16 +2,19 @@ use std::collections::HashSet; use std::path::Path; /// The model file the fingerprint test project leaves to the cache key. -pub(crate) const EXCLUDED_MODEL: &str = "models/orders.sql"; +pub(crate) const EXCLUDED_MODEL: &str = "sql/models/orders.sql"; /// Write a small project: config, a macro, a model and files in skipped folders. pub(crate) fn write_project(root: &Path) { for (relative_path, contents) in [ ("sqlbuild_project.toml", "name = \"orders\"\n"), - ("macros/cents.py", "def cents(amount):\n return amount\n"), + ( + "sql/macros/cents.py", + "def cents(amount):\n return amount\n", + ), (EXCLUDED_MODEL, "SELECT 1 AS id\n"), ("target/cache/store.bin", "old"), - ("macros/__pycache__/cents.pyc", "bytecode"), + ("sql/macros/__pycache__/cents.pyc", "bytecode"), ("warehouse.duckdb", "pages"), ] { write_file(root, relative_path, contents); diff --git a/crates/sqlbuild-cache/src/digest/tests/test_digest_files.rs b/crates/sqlbuild-cache/src/digest/tests/test_digest_files.rs index 2497649562..adcf3d1d88 100644 --- a/crates/sqlbuild-cache/src/digest/tests/test_digest_files.rs +++ b/crates/sqlbuild-cache/src/digest/tests/test_digest_files.rs @@ -9,22 +9,22 @@ fn given_paths_when_digesting_files_then_readable_files_digest_their_bytes() { let test_cases = [ DigestFilesTestCase { description: "regular file", - path: |root| root.join("macros/cents.py"), + path: |root| root.join("sql/macros/cents.py"), expected_digest_of: Some("def cents(amount):\n return amount\n"), }, DigestFilesTestCase { description: "missing file", - path: |root| root.join("macros/missing.py"), + path: |root| root.join("sql/macros/missing.py"), expected_digest_of: None, }, DigestFilesTestCase { description: "member path inside an archive", - path: |root| root.join("macros/cents.py/inner.py"), + path: |root| root.join("sql/macros/cents.py/inner.py"), expected_digest_of: None, }, DigestFilesTestCase { description: "directory", - path: |root| root.join("macros"), + path: |root| root.join("sql/macros"), expected_digest_of: None, }, ]; @@ -33,7 +33,7 @@ fn given_paths_when_digesting_files_then_readable_files_digest_their_bytes() { let project = tempfile::tempdir().expect("temporary project"); write_file( project.path(), - "macros/cents.py", + "sql/macros/cents.py", "def cents(amount):\n return amount\n", ); let path: PathBuf = (test_case.path)(project.path()); diff --git a/crates/sqlbuild-cache/src/digest/tests/test_fingerprint_project_files.rs b/crates/sqlbuild-cache/src/digest/tests/test_fingerprint_project_files.rs index c6d80d70fd..d7853d83a6 100644 --- a/crates/sqlbuild-cache/src/digest/tests/test_fingerprint_project_files.rs +++ b/crates/sqlbuild-cache/src/digest/tests/test_fingerprint_project_files.rs @@ -19,7 +19,7 @@ fn given_project_edit_when_fingerprinting_then_only_covered_content_changes_it() edit: |root| { write_file( root, - "macros/cents.py", + "sql/macros/cents.py", "def cents(amount):\n return 1\n", ) }, @@ -27,19 +27,22 @@ fn given_project_edit_when_fingerprinting_then_only_covered_content_changes_it() }, FingerprintProjectFilesTestCase { description: "helper module added", - edit: |root| write_file(root, "macros/_rounding.py", "SCALE = 2\n"), + edit: |root| write_file(root, "sql/macros/_rounding.py", "SCALE = 2\n"), expected_changed: true, }, FingerprintProjectFilesTestCase { description: "macro file removed", - edit: |root| std::fs::remove_file(root.join("macros/cents.py")).expect("removed"), + edit: |root| std::fs::remove_file(root.join("sql/macros/cents.py")).expect("removed"), expected_changed: true, }, FingerprintProjectFilesTestCase { description: "file renamed with the same content", edit: |root| { - std::fs::rename(root.join("macros/cents.py"), root.join("macros/money.py")) - .expect("renamed"); + std::fs::rename( + root.join("sql/macros/cents.py"), + root.join("sql/macros/money.py"), + ) + .expect("renamed"); }, expected_changed: true, }, @@ -50,7 +53,7 @@ fn given_project_edit_when_fingerprinting_then_only_covered_content_changes_it() }, FingerprintProjectFilesTestCase { description: "new model is covered until the caller excludes it", - edit: |root| write_file(root, "models/customers.sql", "SELECT 1 AS id\n"), + edit: |root| write_file(root, "sql/models/customers.sql", "SELECT 1 AS id\n"), expected_changed: true, }, FingerprintProjectFilesTestCase { @@ -60,12 +63,12 @@ fn given_project_edit_when_fingerprinting_then_only_covered_content_changes_it() }, FingerprintProjectFilesTestCase { description: "nested target folder edit", - edit: |root| write_file(root, "macros/target/notes.txt", "covered"), + edit: |root| write_file(root, "sql/macros/target/notes.txt", "covered"), expected_changed: true, }, FingerprintProjectFilesTestCase { description: "bytecode cache edit", - edit: |root| write_file(root, "macros/__pycache__/cents.pyc", "other"), + edit: |root| write_file(root, "sql/macros/__pycache__/cents.pyc", "other"), expected_changed: false, }, FingerprintProjectFilesTestCase { diff --git a/crates/sqlbuild-cache/src/hosted_shapes/constants.rs b/crates/sqlbuild-cache/src/hosted_shapes/constants.rs index f3b2ebaa2a..84a5cc9c93 100644 --- a/crates/sqlbuild-cache/src/hosted_shapes/constants.rs +++ b/crates/sqlbuild-cache/src/hosted_shapes/constants.rs @@ -1,7 +1,7 @@ //! The Python shape names of the natively hosted compiler shapes. /// The Python model type a natively hosted compiler shape is captured as. -pub const HOSTED_SHAPE_TYPES: [(&str, &str); 486] = [ +pub const HOSTED_SHAPE_TYPES: [(&str, &str); 487] = [ ( "sqlbuild._native:AlignedInterval", "sqlbuild.cursor_algebra.models:AlignedInterval", @@ -1284,6 +1284,10 @@ pub const HOSTED_SHAPE_TYPES: [(&str, &str); 486] = [ "sqlbuild._native:ProjectPathError", "sqlbuild.compiler.discovery.exceptions:ProjectPathError", ), + ( + "sqlbuild._native:ProjectLayoutError", + "sqlbuild.compiler.discovery.exceptions:ProjectLayoutError", + ), ( "sqlbuild._native:ProjectPythonPathError", "sqlbuild.compiler.discovery.exceptions:ProjectPythonPathError", diff --git a/crates/sqlbuild-cache/src/macro_store_keys/tests/test_store_keys.rs b/crates/sqlbuild-cache/src/macro_store_keys/tests/test_store_keys.rs index 202c48451e..8104fcc157 100644 --- a/crates/sqlbuild-cache/src/macro_store_keys/tests/test_store_keys.rs +++ b/crates/sqlbuild-cache/src/macro_store_keys/tests/test_store_keys.rs @@ -13,7 +13,7 @@ fn given_macro_identity_when_keying_then_matches_python_key_text() { description: "name, path, identity and source digest as compact JSON", value: array(vec![text("tuple"), array(vec![text("a")])]), expected_key: Some( - "[\"cents\",\"macros/money.py\",[\"tuple\",[\"a\"]],\"09b7bf2b19ceac419ff40c8cbe965d0c135424c443d286890f788ec6efb5f92d\"]", + "[\"cents\",\"sql/macros/money.py\",[\"tuple\",[\"a\"]],\"09b7bf2b19ceac419ff40c8cbe965d0c135424c443d286890f788ec6efb5f92d\"]", ), }, StoreKeyTestCase { @@ -25,7 +25,7 @@ fn given_macro_identity_when_keying_then_matches_python_key_text() { for test_case in test_cases { let key = macro_store_token( - (text("cents"), text("macros/money.py")), + (text("cents"), text("sql/macros/money.py")), test_case.value, "SELECT 1", ) diff --git a/crates/sqlbuild-cache/src/project_reuse/tests/helpers.rs b/crates/sqlbuild-cache/src/project_reuse/tests/helpers.rs index 4359a23b90..51b51eeda6 100644 --- a/crates/sqlbuild-cache/src/project_reuse/tests/helpers.rs +++ b/crates/sqlbuild-cache/src/project_reuse/tests/helpers.rs @@ -29,7 +29,7 @@ pub(crate) fn stored_inputs() -> StoredInputs { modules: vec![("/site/orders.py".to_owned(), 5, 10)], project_files: vec![ StoredProjectFile { - stamp: stamp("models/orders.sql", "f", None), + stamp: stamp("sql/models/orders.sql", "f", None), digest: Some("b3:model".to_owned()), racy: true, }, diff --git a/crates/sqlbuild-cache/src/project_reuse/tests/test_file_changes.rs b/crates/sqlbuild-cache/src/project_reuse/tests/test_file_changes.rs index 09358c1ac4..9fe10dc666 100644 --- a/crates/sqlbuild-cache/src/project_reuse/tests/test_file_changes.rs +++ b/crates/sqlbuild-cache/src/project_reuse/tests/test_file_changes.rs @@ -103,7 +103,7 @@ fn given_linked_inputs_when_targets_change_then_compile_reuse_is_invalidated() { LinkChangeTestCase { description: "add file through directory link", change: |_, outside| { - std::fs::write(outside.join("models/customers.sql"), b"SELECT 1") + std::fs::write(outside.join("sql/models/customers.sql"), b"SELECT 1") .expect("added model"); }, expected_unchanged: false, @@ -119,7 +119,8 @@ fn given_linked_inputs_when_targets_change_then_compile_reuse_is_invalidated() { for test_case in test_cases { let project = tempfile::tempdir().expect("project"); let outside = tempfile::tempdir().expect("linked resources"); - std::fs::create_dir(outside.path().join("models")).expect("model directory"); + std::fs::create_dir_all(outside.path().join("sql/models")).expect("model directory"); + std::fs::create_dir_all(project.path().join("sql")).expect("sql directory"); std::fs::write(outside.path().join("orders.sql"), b"SELECT 1").expect("target"); std::fs::write(outside.path().join("other.sql"), b"SELECT 1").expect("other target"); symlink( @@ -127,8 +128,11 @@ fn given_linked_inputs_when_targets_change_then_compile_reuse_is_invalidated() { project.path().join("orders.sql"), ) .expect("file link"); - symlink(outside.path().join("models"), project.path().join("models")) - .expect("directory link"); + symlink( + outside.path().join("sql/models"), + project.path().join("sql/models"), + ) + .expect("directory link"); let stored: Vec = snapshot_project_files(project.path(), &SnapshotRules::default()) .into_iter() diff --git a/crates/sqlbuild-cache/src/project_reuse/tests/test_project_image.rs b/crates/sqlbuild-cache/src/project_reuse/tests/test_project_image.rs index cdabaf37dc..7e385d573d 100644 --- a/crates/sqlbuild-cache/src/project_reuse/tests/test_project_image.rs +++ b/crates/sqlbuild-cache/src/project_reuse/tests/test_project_image.rs @@ -206,7 +206,7 @@ fn given_project_file_when_computing_delta_changes_then_only_content_changes_cou racy: false, mtime_shift_ns: 1, current_digest: Some("b3:two"), - expected_changed: &["models/orders.sql"], + expected_changed: &["sql/models/orders.sql"], }, ChangedFileTestCase { description: "racy equal stamp with new bytes is changed", @@ -214,7 +214,7 @@ fn given_project_file_when_computing_delta_changes_then_only_content_changes_cou racy: true, mtime_shift_ns: 0, current_digest: Some("b3:two"), - expected_changed: &["models/orders.sql"], + expected_changed: &["sql/models/orders.sql"], }, ChangedFileTestCase { description: "moved stamp without a stored digest is changed", @@ -222,7 +222,7 @@ fn given_project_file_when_computing_delta_changes_then_only_content_changes_cou racy: false, mtime_shift_ns: 1, current_digest: Some("b3:one"), - expected_changed: &["models/orders.sql"], + expected_changed: &["sql/models/orders.sql"], }, ChangedFileTestCase { description: "unreadable moved file is changed", @@ -230,21 +230,21 @@ fn given_project_file_when_computing_delta_changes_then_only_content_changes_cou racy: false, mtime_shift_ns: 1, current_digest: None, - expected_changed: &["models/orders.sql"], + expected_changed: &["sql/models/orders.sql"], }, ]; for test_case in test_cases { let stored = vec![StoredProjectFile { - stamp: stamp("models/orders.sql", "f", None), + stamp: stamp("sql/models/orders.sql", "f", None), digest: test_case.stored_digest.map(str::to_owned), racy: test_case.racy, }]; - let mut current = stamp("models/orders.sql", "f", None); + let mut current = stamp("sql/models/orders.sql", "f", None); current.mtime_ns += test_case.mtime_shift_ns; - let current = vec![current, stamp("models/customers.sql", "f", None)]; + let current = vec![current, stamp("sql/models/customers.sql", "f", None)]; let digests: HashMap = test_case .current_digest - .map(|digest| HashMap::from([("models/orders.sql".to_owned(), digest.to_owned())])) + .map(|digest| HashMap::from([("sql/models/orders.sql".to_owned(), digest.to_owned())])) .unwrap_or_default(); let unverified: HashSet = unverified_paths(&stored, ¤t); @@ -258,7 +258,7 @@ fn given_project_file_when_computing_delta_changes_then_only_content_changes_cou assert_eq!( (changes.added, changes.removed), ( - vec!["models/customers.sql".to_owned()], + vec!["sql/models/customers.sql".to_owned()], Vec::::new() ), "{}", diff --git a/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs b/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs index c9c835f6ea..327cb225e6 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs @@ -31,25 +31,30 @@ pub(super) fn owned_plan( pub(super) fn orders_publication() -> std::sync::Arc { let resources = vec![ - resource("model:stg_orders", &[], &["orders"], Some("models/staging")), + resource( + "model:stg_orders", + &[], + &["orders"], + Some("sql/models/staging"), + ), resource( "model:orders", &["model:stg_orders"], &["orders"], - Some("models/marts"), + Some("sql/models/marts"), ), - resource("model:customers", &[], &[], Some("models/marts")), + resource("model:customers", &[], &[], Some("sql/models/marts")), resource( "asset:partner_orders_file", &["model:orders"], &["orders"], - Some("python/orders/partner_export"), + Some("python/nodes/orders/partner_export"), ), resource( "asset:request_carrier_collection", &["asset:partner_orders_file"], &["orders"], - Some("python/fulfillment/carrier_sync"), + Some("python/nodes/fulfillment/carrier_sync"), ), PlannerResource { loader: Some("raw_shipments".to_owned()), @@ -59,15 +64,20 @@ pub(super) fn orders_publication() "model:shipments", &["source:raw_shipments"], &[], - Some("models/marts"), + Some("sql/models/marts"), ), resource( "loader:raw_shipments", &["loader:stage_shipments"], &[], - Some("python/loaders"), + Some("python/nodes/loaders"), + ), + resource( + "loader:stage_shipments", + &[], + &[], + Some("python/nodes/loaders"), ), - resource("loader:stage_shipments", &[], &[], Some("python/loaders")), ]; let jobs = sqlbuild_orchestration::runs::models::PublishedJobs { selections: std::collections::BTreeMap::from([( diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs index 392c280e50..228272cb29 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs @@ -18,15 +18,15 @@ fn given_ad_hoc_commands_when_planned_then_flags_follow_the_allowlist_and_select "model:orders", &["source:shop.raw_orders", "seed:currencies"], &["daily"], - Some("models/marts"), + Some("sql/models/marts"), ), resource( "model:order_totals", &["model:orders"], &["daily"], - Some("models/marts"), + Some("sql/models/marts"), ), - resource("model:customers", &[], &[], Some("models/staging")), + resource("model:customers", &[], &[], Some("sql/models/staging")), resource("source:shop.raw_orders", &[], &[], None), resource("seed:currencies", &[], &[], None), resource("sql_test:orders_keep_amounts", &["model:orders"], &[], None), @@ -161,7 +161,7 @@ fn given_ad_hoc_commands_when_planned_then_flags_follow_the_allowlist_and_select }, AdhocPlanTestCase { description: "path selectors use the published folder", - command: &["build", "-s", "path:models/staging"], + command: &["build", "-s", "path:sql/models/staging"], expected_plan: Ok((&["model:customers"], json!({}))), }, AdhocPlanTestCase { @@ -361,25 +361,30 @@ fn given_ad_hoc_commands_when_planned_then_flags_follow_the_allowlist_and_select #[test] fn given_published_python_nodes_when_planned_then_selectors_resolve_as_on_the_command_line() { let resources = [ - resource("model:stg_orders", &[], &["orders"], Some("models/staging")), + resource( + "model:stg_orders", + &[], + &["orders"], + Some("sql/models/staging"), + ), resource( "model:orders", &["model:stg_orders"], &["orders"], - Some("models/marts"), + Some("sql/models/marts"), ), - resource("model:customers", &[], &[], Some("models/marts")), + resource("model:customers", &[], &[], Some("sql/models/marts")), resource( "asset:partner_orders_file", &["model:orders"], &["orders"], - Some("python/orders/partner_export"), + Some("python/nodes/orders/partner_export"), ), resource( "asset:request_carrier_collection", &["asset:partner_orders_file"], &["orders"], - Some("python/fulfillment/carrier_sync"), + Some("python/nodes/fulfillment/carrier_sync"), ), PlannerResource { loader: Some("raw_shipments".to_owned()), @@ -389,15 +394,20 @@ fn given_published_python_nodes_when_planned_then_selectors_resolve_as_on_the_co "model:shipments", &["source:raw_shipments"], &[], - Some("models/marts"), + Some("sql/models/marts"), ), resource( "loader:raw_shipments", &["loader:stage_shipments"], &[], - Some("python/loaders"), + Some("python/nodes/loaders"), + ), + resource( + "loader:stage_shipments", + &[], + &[], + Some("python/nodes/loaders"), ), - resource("loader:stage_shipments", &[], &[], Some("python/loaders")), ]; let jobs: PublishedJobs = PublishedJobs { selections: BTreeMap::from([( @@ -448,7 +458,7 @@ fn given_published_python_nodes_when_planned_then_selectors_resolve_as_on_the_co }, AdhocPlanTestCase { description: "a python folder selects the nodes under it", - command: &["build", "--select", "python/orders"], + command: &["build", "--select", "python/nodes/orders"], expected_plan: Ok((&["asset:partner_orders_file"], json!({}))), }, AdhocPlanTestCase { diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs index 75ecbf32e4..4881f3b611 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs @@ -115,15 +115,17 @@ fn given_a_publication_when_its_vocabulary_is_read_then_each_value_counts_the_no description: "a folder counts the nodes below it at any depth", entries_of: |vocabulary| &vocabulary.paths, expected_entries: &[ - ("models", 4), - ("models/marts", 3), - ("models/staging", 1), ("python", 4), - ("python/fulfillment", 1), - ("python/fulfillment/carrier_sync", 1), - ("python/loaders", 2), - ("python/orders", 1), - ("python/orders/partner_export", 1), + ("python/nodes", 4), + ("python/nodes/fulfillment", 1), + ("python/nodes/fulfillment/carrier_sync", 1), + ("python/nodes/loaders", 2), + ("python/nodes/orders", 1), + ("python/nodes/orders/partner_export", 1), + ("sql", 4), + ("sql/models", 4), + ("sql/models/marts", 3), + ("sql/models/staging", 1), ], }, VocabularyTestCase { @@ -167,9 +169,9 @@ fn given_refused_selectors_when_evaluated_then_the_refused_part_its_type_and_val }, RefusedPartTestCase { description: "a folder with no models", - select: "path:models/mart", + select: "path:sql/models/mart", expected_code: Some("S009"), - expected_refused: Some(("path:models/mart", 0, "path", "models/mart")), + expected_refused: Some(("path:sql/models/mart", 0, "path", "sql/models/mart")), }, RefusedPartTestCase { description: "an unknown job", diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs b/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs index ec5e86b2ce..e4a1c23884 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs @@ -156,7 +156,7 @@ pub(super) fn secrets_reported( .into_iter() .map(|(provider, variables)| UnsetProviderSecrets { provider: provider.to_owned(), - path: format!("providers/{provider}.py"), + path: format!("python/providers/{provider}.py"), settings: variables .into_iter() .zip(9..) @@ -181,12 +181,12 @@ pub(super) fn failed_compile() -> Vec { messages.push(ScreenMessage::Child(DevEvent::Failed { generation: 1, message: - "[D001] models/marts/fct_orders.sql:42:7: column net_amount_usd does not exist in \ + "[D001] sql/models/marts/fct_orders.sql:42:7: column net_amount_usd does not exist in \ stg_payments; the column was renamed to amount_usd_net when the payments source \ moved to the v2 export, and fct_orders still selects the old name" .to_owned(), position: Some(SourcePosition { - path: "models/marts/fct_orders.sql".to_owned(), + path: "sql/models/marts/fct_orders.sql".to_owned(), line: 42, column: 7, }), diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/test_apply_screen_message.rs b/crates/sqlbuild-cli/src/dev_screen/tests/test_apply_screen_message.rs index 299c427753..6fbf48fd38 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/test_apply_screen_message.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/test_apply_screen_message.rs @@ -56,8 +56,8 @@ fn given_a_session_when_drawn_then_the_viewport_matches_the_snapshot() { "\u{2713} Started UI server 0.1s http://127.0.0.1:8640", "\u{2713} Started scheduler 0.1s triggers start paused", "\u{2717} Discovering project 0.2s 1 error", - "\u{2717} error models/marts/fct_orders.sql D001", - " at models/marts/fct_orders.sql:42:7", + "\u{2717} error sql/models/marts/fct_orders.sql D001", + " at sql/models/marts/fct_orders.sql:42:7", " why column net_amount_usd does not exist in stg_payments; the column was", " renamed to amount_usd_net when the payments source moved to the v2", " export, and fct_orders still selects the old name", diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs b/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs index f8676f87cb..386dc91857 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs @@ -17,8 +17,8 @@ fn given_providers_missing_secrets_when_health_is_read_then_a_warning_names_them reports: vec![vec![("region", vec!["REGION_TOKEN", "REGION_CODE"])]], expected_tail: vec![ "\u{26a0} warn 1 provider has missing secrets missing secret", - " at providers/region.py:9 region_token \u{2190} REGION_TOKEN", - " providers/region.py:10 region_code \u{2190} REGION_CODE", + " at python/providers/region.py:9 region_token \u{2190} REGION_TOKEN", + " python/providers/region.py:10 region_code \u{2190} REGION_CODE", " why runs that use it stop at the provider check, before the warehouse; 2", " nodes need it (raw_regions, stg_regions)", " fix set them in config/dev.env and press r, or set them in the environment", @@ -43,7 +43,7 @@ fn given_providers_missing_secrets_when_health_is_read_then_a_warning_names_them reports: vec![vec![("region", vec!["REGION_TOKEN"])]], expected_tail: vec![ "\u{26a0} warn 1 provider has missing secrets missing secret", - " at providers/region.py:9 region_token \u{2190} REGION_TOKEN", + " at python/providers/region.py:9 region_token \u{2190} REGION_TOKEN", " why runs that use it stop at the provider check, before the warehouse; 7", " nodes need it (raw_regions, a, b, c, d and 2 more)", " fix set it in the environment you start sqb dev from, then quit and run", @@ -75,7 +75,7 @@ fn given_providers_missing_secrets_when_health_is_read_then_a_warning_names_them expected_tail: vec![ " triggers 41 paused", "\u{26a0} warn 1 provider has missing secrets missing secret", - " at providers/region.py:9 region_token \u{2190} REGION_TOKEN", + " at python/providers/region.py:9 region_token \u{2190} REGION_TOKEN", " why runs that use it stop at the provider check, before the warehouse", " fix set it in .env and press r, or set it in the environment you start sqb", " dev from, then quit and run sqb dev again", diff --git a/crates/sqlbuild-cli/src/diff_report/tests/test_command.rs b/crates/sqlbuild-cli/src/diff_report/tests/test_command.rs index ed284add8f..db08c8d9d9 100644 --- a/crates/sqlbuild-cli/src/diff_report/tests/test_command.rs +++ b/crates/sqlbuild-cli/src/diff_report/tests/test_command.rs @@ -138,11 +138,11 @@ fn given_blocked_models_when_building_guard_report_then_names_sizes_and_commands SizeGuardTestCase { description: "model without cursor omits bounded command and quotes key flags", request: request(|facts| { - facts.select = strings(&["tag:daily", "path:models/marts"]); + facts.select = strings(&["tag:daily", "path:sql/models/marts"]); facts.unique_key_override = strings(&["order_id", "line number"]); }), has_cursor: false, - expected_full: "sqb diff prod:dev --full --select tag:daily path:models/marts --key order_id 'line number'", + expected_full: "sqb diff prod:dev --full --select tag:daily path:sql/models/marts --key order_id 'line number'", expected_bounded: None, expected_fragments: &["; no cursor"], }, diff --git a/crates/sqlbuild-cli/src/dispatch/constants.rs b/crates/sqlbuild-cli/src/dispatch/constants.rs index 97bd005245..445dfe454c 100644 --- a/crates/sqlbuild-cli/src/dispatch/constants.rs +++ b/crates/sqlbuild-cli/src/dispatch/constants.rs @@ -840,4 +840,4 @@ pub(crate) const SCENARIO_CAPTURE_ROUTE: Route = routed( ); /// The setting a user raises when lifecycle event export runs out of time at exit. -pub(crate) const SHUTDOWN_TIMEOUT_SETTING: &str = "sinks.lifecycle.shutdown_timeout"; +pub(crate) const SHUTDOWN_TIMEOUT_SETTING: &str = "event_sinks.lifecycle.shutdown_timeout"; diff --git a/crates/sqlbuild-cli/src/dispatch/main/event_export_warning.rs b/crates/sqlbuild-cli/src/dispatch/main/event_export_warning.rs index b8c3c861e6..26e12fdb01 100644 --- a/crates/sqlbuild-cli/src/dispatch/main/event_export_warning.rs +++ b/crates/sqlbuild-cli/src/dispatch/main/event_export_warning.rs @@ -5,10 +5,11 @@ use sqlbuild_core::event_export::constants::DEFAULT_EVENT_EXPORT_INVOCATION_TIME use crate::dispatch::constants::SHUTDOWN_TIMEOUT_SETTING; use crate::dispatch::models::{ExportSummary, ExporterLoss}; -/// One warning line when lifecycle events were dropped or failed, else `None`. +/// One warning line when lifecycle events were dropped or failed or a sink provider's teardown raised, else `None`. #[must_use] pub fn event_export_warning(summary: &ExportSummary, command_succeeded: bool) -> Option { - if summary.dropped == 0 && summary.failed == 0 { + let lost: bool = summary.dropped > 0 || summary.failed > 0; + if !lost && summary.teardown_failures.is_empty() { return None; } let affected: Vec<&ExporterLoss> = summary @@ -32,11 +33,22 @@ pub fn event_export_warning(summary: &ExportSummary, command_succeeded: bool) -> } else { "Warning: lifecycle event export was incomplete" }; - Some(format!( - "{prefix}: {} of {} {unit} dropped, {} failed ({sink_label} {names}). \ - Check sink health: a sink call slower than {DEFAULT_EVENT_EXPORT_INVOCATION_TIMEOUT_SECONDS}s \ - drops that sink's events until it returns; events still queued at exit need a longer \ - {SHUTDOWN_TIMEOUT_SETTING}.", - summary.dropped, summary.accepted, summary.failed - )) + let mut parts: Vec = Vec::new(); + if lost { + parts.push(format!( + "{} of {} {unit} dropped, {} failed ({sink_label} {names}). \ + Check sink health: a sink call slower than {DEFAULT_EVENT_EXPORT_INVOCATION_TIMEOUT_SECONDS}s \ + drops that sink's events until it returns; events still queued at exit need a longer \ + {SHUTDOWN_TIMEOUT_SETTING}.", + summary.dropped, summary.accepted, summary.failed + )); + } + if !summary.teardown_failures.is_empty() { + parts.push(format!( + "sink provider teardown failed ({}); events the provider still held may not have \ + been delivered.", + summary.teardown_failures.join(", ") + )); + } + Some(format!("{prefix}: {}", parts.join(" "))) } diff --git a/crates/sqlbuild-cli/src/dispatch/main/export_summary.rs b/crates/sqlbuild-cli/src/dispatch/main/export_summary.rs new file mode 100644 index 0000000000..fdd2348b34 --- /dev/null +++ b/crates/sqlbuild-cli/src/dispatch/main/export_summary.rs @@ -0,0 +1,25 @@ +//! `export_summary`: a command's lifecycle export accounting at exit, as its warning reads it. + +use sqlbuild_core::event_export::models::ExportSnapshot; + +use crate::dispatch::models::{ExportSummary, ExporterLoss}; + +/// The accounting of `snapshot`, with each sink provider whose teardown raised. +#[must_use] +pub fn export_summary(snapshot: &ExportSnapshot, teardown_failures: Vec) -> ExportSummary { + ExportSummary { + accepted: snapshot.aggregate.accepted, + dropped: snapshot.aggregate.dropped, + failed: snapshot.aggregate.failed, + per_exporter: snapshot + .per_exporter + .iter() + .map(|(name, counts)| ExporterLoss { + exporter_name: name.clone(), + dropped: counts.dropped, + failed: counts.failed, + }) + .collect(), + teardown_failures, + } +} diff --git a/crates/sqlbuild-cli/src/dispatch/main/mod.rs b/crates/sqlbuild-cli/src/dispatch/main/mod.rs index 594f4fab79..aa35cfde57 100644 --- a/crates/sqlbuild-cli/src/dispatch/main/mod.rs +++ b/crates/sqlbuild-cli/src/dispatch/main/mod.rs @@ -1,6 +1,7 @@ pub mod closing_status; pub mod command_dispatch; pub mod event_export_warning; +pub mod export_summary; pub mod failure_report; pub mod invocation_policy; pub mod selector_file_selectors; diff --git a/crates/sqlbuild-cli/src/dispatch/models.rs b/crates/sqlbuild-cli/src/dispatch/models.rs index 117b2de3d9..4b61dca4ae 100644 --- a/crates/sqlbuild-cli/src/dispatch/models.rs +++ b/crates/sqlbuild-cli/src/dispatch/models.rs @@ -162,4 +162,6 @@ pub struct ExportSummary { pub dropped: u64, pub failed: u64, pub per_exporter: Vec, + /// Each sink provider whose teardown raised, with its error type. + pub teardown_failures: Vec, } diff --git a/crates/sqlbuild-cli/src/dispatch/tests/helpers.rs b/crates/sqlbuild-cli/src/dispatch/tests/helpers.rs index 6a923ff94c..d7c233f033 100644 --- a/crates/sqlbuild-cli/src/dispatch/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/dispatch/tests/helpers.rs @@ -30,6 +30,7 @@ pub(super) fn failure(message: &str, code: &'static str) -> DispatchFailure { /// An export summary of `(name, accepted, delivered, failed, dropped)` sinks. pub(super) fn export_summary(exporters: &[(&str, u64, u64, u64, u64)]) -> ExportSummary { ExportSummary { + teardown_failures: Vec::new(), accepted: exporters.iter().map(|exporter| exporter.1).sum(), dropped: exporters.iter().map(|exporter| exporter.4).sum(), failed: exporters.iter().map(|exporter| exporter.3).sum(), diff --git a/crates/sqlbuild-cli/src/dispatch/tests/test_event_export_warning.rs b/crates/sqlbuild-cli/src/dispatch/tests/test_event_export_warning.rs index ae9ff3eb88..543563868a 100644 --- a/crates/sqlbuild-cli/src/dispatch/tests/test_event_export_warning.rs +++ b/crates/sqlbuild-cli/src/dispatch/tests/test_event_export_warning.rs @@ -1,4 +1,5 @@ use crate::dispatch::main::event_export_warning::event_export_warning; +use crate::dispatch::models::ExportSummary; use crate::dispatch::tests::helpers::export_summary; use crate::dispatch::tests::test_types::EventExportWarningTestCase; @@ -20,7 +21,7 @@ fn given_final_export_summary_when_formatting_warning_then_reports_loss_only() { incomplete: 140 of 248 events dropped, 0 failed (sink 'orders_events'). \ Check sink health: a sink call slower than 1s drops that sink's events until it \ returns; events still queued at exit need a longer \ - sinks.lifecycle.shutdown_timeout.", + event_sinks.lifecycle.shutdown_timeout.", ), }, EventExportWarningTestCase { @@ -32,7 +33,7 @@ fn given_final_export_summary_when_formatting_warning_then_reports_loss_only() { 1 failed (sink 'orders_events'). \ Check sink health: a sink call slower than 1s drops that sink's events until it \ returns; events still queued at exit need a longer \ - sinks.lifecycle.shutdown_timeout.", + event_sinks.lifecycle.shutdown_timeout.", ), }, EventExportWarningTestCase { @@ -47,7 +48,37 @@ fn given_final_export_summary_when_formatting_warning_then_reports_loss_only() { incomplete: 4 of 40 event deliveries dropped, 1 failed (sink 'orders_events'). \ Check sink health: a sink call slower than 1s drops that sink's events until it \ returns; events still queued at exit need a longer \ - sinks.lifecycle.shutdown_timeout.", + event_sinks.lifecycle.shutdown_timeout.", + ), + }, + EventExportWarningTestCase { + description: "a sink provider teardown that raised", + summary: ExportSummary { + teardown_failures: vec!["'kafka' (KafkaProducer) raised KafkaException".into()], + ..export_summary(&[("orders_events", 10, 10, 0, 0)]) + }, + command_succeeded: true, + expected_warning: Some( + "Warning: command completed successfully, but lifecycle event export was \ + incomplete: sink provider teardown failed ('kafka' (KafkaProducer) raised \ + KafkaException); events the provider still held may not have been delivered.", + ), + }, + EventExportWarningTestCase { + description: "drops and a failed teardown together", + summary: ExportSummary { + teardown_failures: vec!["'kafka' (KafkaProducer) raised KafkaException".into()], + ..export_summary(&[("orders_events", 10, 9, 1, 0)]) + }, + command_succeeded: false, + expected_warning: Some( + "Warning: lifecycle event export was incomplete: 0 of 10 events dropped, \ + 1 failed (sink 'orders_events'). \ + Check sink health: a sink call slower than 1s drops that sink's events until it \ + returns; events still queued at exit need a longer \ + event_sinks.lifecycle.shutdown_timeout. sink provider teardown failed \ + ('kafka' (KafkaProducer) raised KafkaException); events the provider still held \ + may not have been delivered.", ), }, ]; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs index 298e78e019..77318687d8 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs @@ -12,7 +12,9 @@ use sqlbuild_core::git_revisions::main::head_commit::head_commit; use sqlbuild_rules::project_tree::main::project_real_path::project_real_path; use tokio::time::Instant; -use crate::native_commands::constants::{DEVELOPMENT_OUTPUT_FOLDER, LOCATION_COMMIT_CHECK_SECONDS}; +use crate::native_commands::constants::{ + DEVELOPMENT_CONTROL_FILE, DEVELOPMENT_OUTPUT_FOLDER, LOCATION_COMMIT_CHECK_SECONDS, +}; use crate::native_commands::errors::PythonNeeded; use crate::native_commands::models::{LocationWatch, ProjectLocation}; use crate::replay::main::output_file_identities::output_file_identities; @@ -20,7 +22,7 @@ use crate::replay::main::output_file_identities::output_file_identities; /// Observe the same project inputs as compiler reuse, excluding redirected command output. pub(crate) fn location_watch(root: &Path) -> LocationWatch { let rules = location_rules(); - let files: Vec = std::env::var_os("SQLBUILD_DEVELOPMENT_CONTROL_FILE") + let files: Vec = std::env::var_os(DEVELOPMENT_CONTROL_FILE) .into_iter() .map(|path| path.to_string_lossy().into_owned()) .collect(); diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/project_facts.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/project_facts.rs index f18e45d69d..137068227b 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/project_facts.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/project_facts.rs @@ -14,8 +14,7 @@ use sqlbuild_orchestration::store::errors::ControlError; use crate::native_commands::main::effective_target::effective_target; use crate::native_commands::constants::{ - CONFIG_ERROR_CODE, CUSTOM_RULES_DIRECTORY, EVENT_EXPORTERS_DIRECTORY, LIFECYCLE_SINK_PATH, - SINKS_DIRECTORY, + CONFIG_ERROR_CODE, CUSTOM_RULES_DIRECTORY, EVENT_SINKS_DIRECTORY, LIFECYCLE_SINK_PATH, }; pub(crate) fn object_field<'a>(built: &'a Built, name: &str) -> Option<&'a Built> { @@ -42,9 +41,7 @@ fn names_lifecycle_sinks(config: &Built) -> bool { /// Whether `discover_runtime_extensions` would import nothing and accept the project file. pub(crate) fn has_no_runtime_extensions(project_dir: &Path) -> bool { - if project_dir.join(EVENT_EXPORTERS_DIRECTORY).exists() - || project_dir.join(SINKS_DIRECTORY).is_dir() - { + if project_dir.join(EVENT_SINKS_DIRECTORY).is_dir() { return false; } let paths: ConfigPaths = project_config_paths(project_dir); diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/development_written.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/development_written.rs new file mode 100644 index 0000000000..70eafd2415 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/development_written.rs @@ -0,0 +1,26 @@ +//! The files `sqb dev` writes inside a project, as the variables its location and workers read. + +use std::path::{Path, PathBuf}; + +use sqlbuild_orchestration::store::errors::ControlError; +use sqlbuild_orchestration::store::models::ControlStore; + +use crate::native_commands::constants::{DEVELOPMENT_CONTROL_FILE, DEVELOPMENT_OUTPUT_FOLDER}; + +/// The SQLite control store file and the run output folder `sqb dev` writes, as the variables naming them. +pub(crate) fn development_written( + store: &ControlStore, + output: Option<&Path>, +) -> Result, ControlError> { + let mut written: Vec<(&'static str, PathBuf)> = Vec::new(); + if let ControlStore::Sqlite(path) = store { + written.push(( + DEVELOPMENT_CONTROL_FILE, + std::env::current_dir()?.join(path), + )); + } + if let Some(folder) = output { + written.push((DEVELOPMENT_OUTPUT_FOLDER, folder.to_path_buf())); + } + Ok(written) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs index baa19bb055..4d9da35442 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs @@ -41,6 +41,7 @@ use crate::native_commands::_helpers::location::dev_exposure::{ use crate::native_commands::_helpers::location::dev_supervision::{ DevRoles, supervise_development_roles, }; +use crate::native_commands::_helpers::location::development_written::development_written; use crate::native_commands::_helpers::location::dynamic_resume::resume_expired_holds; use crate::native_commands::_helpers::location::env_reload::env_file_summary; use crate::native_commands::_helpers::location::provider_secrets::report_provider_secrets; @@ -55,7 +56,9 @@ use crate::native_commands::constants::{ METADATA_SYNC_CHECK_SECONDS, SAFETY_SYNC_ENV, SCHEDULER_COMMAND, UNCAUGHT_EXCEPTION_STATUS, UNKNOWN_COMMAND, }; -use crate::native_commands::constants::{DEVELOPMENT_OUTPUT_FOLDER, PLAN_NOT_PRODUCED}; +use crate::native_commands::constants::{ + DEVELOPMENT_CONTROL_FILE, DEVELOPMENT_OUTPUT_FOLDER, PLAN_NOT_PRODUCED, +}; use crate::native_commands::constants::{OPENING_STORE, STORE_READY}; use crate::native_commands::errors::PythonNeeded; use crate::native_commands::main::_run_admin::run_admin; @@ -168,11 +171,13 @@ pub(crate) async fn run_development_roles( let opened_to: Option = exposure(listening, &scope); let location_id = scope.location_id; let target = scope.target.clone(); + let output: OutputStore = open_output_store(&OutputSettings::default(), &store)?; + let written: Vec<(&'static str, PathBuf)> = development_written(&store, output.local_folder())?; let workers = open_development_workers( (location_id, target.clone()), project.clone(), executable.clone(), - url.clone(), + (url.clone(), written.clone()), )?; let (stop, shutdown) = watch::channel(false); let mut roles: DevRoles = DevRoles::default(); @@ -181,7 +186,6 @@ pub(crate) async fn run_development_roles( detail: String::new(), })); let api_ready = messages.clone(); - let output: OutputStore = open_output_store(&OutputSettings::default(), &store)?; roles.spawn( Some("UI server"), serve_api( @@ -218,7 +222,7 @@ pub(crate) async fn run_development_roles( let (location, pipes) = development_location_role( (&project, &executable), (location_id, &target), - (&url, &store, output.local_folder()), + (&url, &written), shutdown.clone(), )?; roles.spawn(Some("code location"), location); @@ -286,7 +290,7 @@ async fn development_stopped(mut shutdown: watch::Receiver) { fn development_location_role( (project, executable): (&Path, &Path), (location_id, target): (Uuid, &str), - (url, store, output): (&str, &ControlStore, Option<&Path>), + (url, written): (&str, &[(&'static str, PathBuf)]), shutdown: watch::Receiver, ) -> Result< ( @@ -315,7 +319,7 @@ fn development_location_role( .env_remove("SQLBUILD_PLATFORM_WEBHOOK_URL") .env_remove(SECURITY_AUDIT_WEBHOOK_VARIABLE) .env_remove(RUN_TOKEN_VARIABLE) - .env_remove("SQLBUILD_DEVELOPMENT_CONTROL_FILE") + .env_remove(DEVELOPMENT_CONTROL_FILE) .env_remove(DEVELOPMENT_OUTPUT_FOLDER) .env(DEV_EVENTS_VARIABLE, DEV_EVENTS_ON) .stdin(Stdio::piped()) @@ -324,15 +328,7 @@ fn development_location_role( .kill_on_drop(true); #[cfg(unix)] command.process_group(0); - if let ControlStore::Sqlite(path) = store { - command.env( - "SQLBUILD_DEVELOPMENT_CONTROL_FILE", - std::env::current_dir()?.join(path), - ); - } - if let Some(folder) = output { - command.env(DEVELOPMENT_OUTPUT_FOLDER, folder); - } + command.envs(written.iter().cloned()); let mut child = command.spawn()?; let group: Option = child.id(); if let Some(group) = group { diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs index 490625aafd..21b7f0eb8e 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs @@ -6,6 +6,7 @@ pub(crate) mod dev_cancel; pub(crate) mod dev_exposure; pub(crate) mod dev_start; pub(crate) mod dev_supervision; +pub(crate) mod development_written; pub(crate) mod discovery_state; pub(crate) mod dynamic_resume; pub(crate) mod env_reload; diff --git a/crates/sqlbuild-cli/src/native_commands/constants.rs b/crates/sqlbuild-cli/src/native_commands/constants.rs index da3c86e875..46c99e2b84 100644 --- a/crates/sqlbuild-cli/src/native_commands/constants.rs +++ b/crates/sqlbuild-cli/src/native_commands/constants.rs @@ -106,9 +106,7 @@ pub(crate) const RULES_LIST_ACTION: &str = "list"; pub(crate) const RULES_SHOW_ACTION: &str = "show"; /// Project directories holding Python the command would import. -pub(crate) const EVENT_EXPORTERS_DIRECTORY: &str = "event_exporters"; - -pub(crate) const SINKS_DIRECTORY: &str = "sinks"; +pub(crate) const EVENT_SINKS_DIRECTORY: &str = sqlbuild_core::constants::EVENT_SINKS_PATH; pub(crate) const CUSTOM_RULES_DIRECTORY: &str = "rules"; @@ -157,7 +155,7 @@ pub(crate) const PYTHON_INT_MAX_STR_DIGITS: usize = 4300; pub(crate) const DIGIT_SEPARATOR: char = '_'; /// Where a loaded project configuration names its lifecycle sinks. -pub(crate) const LIFECYCLE_SINK_PATH: [&str; 3] = ["sinks", "lifecycle", "named"]; +pub(crate) const LIFECYCLE_SINK_PATH: [&str; 3] = ["event_sinks", "lifecycle", "named"]; /// CPython's default buffer size for a piped stdout. pub(crate) const PYTHON_STDOUT_BUFFER_SIZE: usize = 8192; @@ -271,4 +269,8 @@ pub(crate) const REPUBLISH_POLL_SECONDS: u64 = 10; pub(crate) const REPUBLISH_TIMEOUT_SECONDS: u64 = 600; /// How `sqb dev` hands its location the resolved folder of run output, which the watch leaves out. -pub(crate) const DEVELOPMENT_OUTPUT_FOLDER: &str = "SQLBUILD_DEVELOPMENT_OUTPUT_FOLDER"; +pub(crate) const DEVELOPMENT_OUTPUT_FOLDER: &str = + sqlbuild_core::constants::DEVELOPMENT_OUTPUT_FOLDER_ENV; +/// How `sqb dev` hands its location the SQLite control store file, which the watch leaves out. +pub(crate) const DEVELOPMENT_CONTROL_FILE: &str = + sqlbuild_core::constants::DEVELOPMENT_CONTROL_FILE_ENV; diff --git a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs index 25f3934a60..9394f51da7 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs @@ -226,7 +226,7 @@ pub(super) fn kept_plans(count: usize, limits: (usize, usize)) -> Mutex), ) -> Result { Ok(Workers { configuration: Launchers { @@ -24,6 +24,7 @@ pub(crate) fn open_development_workers( project_dir, executable, pool_caps: Default::default(), + written, }], docker: Vec::new(), }, diff --git a/crates/sqlbuild-cli/src/workers/models.rs b/crates/sqlbuild-cli/src/workers/models.rs index 09ae7aa202..19709a9208 100644 --- a/crates/sqlbuild-cli/src/workers/models.rs +++ b/crates/sqlbuild-cli/src/workers/models.rs @@ -66,6 +66,9 @@ pub(super) struct LocalLauncher { /// Lowers a project's pool limits for this location and target; never raises them. #[serde(default)] pub(super) pool_caps: BTreeMap, + /// What `sqb dev` hands each worker about the files it writes inside the project. + #[serde(skip)] + pub(super) written: Vec<(&'static str, PathBuf)>, } /// The installation chooses the daemon and location container; the snapshot pins the worker image. diff --git a/crates/sqlbuild-cli/tests/native_commands/test_control.rs b/crates/sqlbuild-cli/tests/native_commands/test_control.rs index 00d39f57e7..f09a128696 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_control.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_control.rs @@ -379,13 +379,13 @@ fn given_a_control_store_when_running_server_migrate_then_dry_run_lists_and_migr StoreMigrationCommandTestCase { description: "migrate an empty store", arguments: &["server", "migrate"], - expected_stdout: "The control store is empty: created schema version 9.\n", + expected_stdout: "The control store is empty: created schema version 11.\n", expected_store: true, }, StoreMigrationCommandTestCase { description: "dry run on a current store", arguments: &["server", "migrate", "--dry-run"], - expected_stdout: "The control store is at schema version 9: nothing to migrate.\n", + expected_stdout: "The control store is at schema version 11: nothing to migrate.\n", expected_store: true, }, ]; diff --git a/crates/sqlbuild-config/src/env_file/_helpers/choice.rs b/crates/sqlbuild-config/src/env_file/_helpers/choice.rs index c3a31982b7..eec590263f 100644 --- a/crates/sqlbuild-config/src/env_file/_helpers/choice.rs +++ b/crates/sqlbuild-config/src/env_file/_helpers/choice.rs @@ -58,6 +58,19 @@ pub(crate) fn configured_source( } } +/// Every non-empty `env_file` the project and its targets set, as written. +pub(crate) fn named_texts(project: &Built) -> Vec { + let targets: Vec<&Built> = match field(project, "targets") { + Some(Built::Dict(entries)) => entries.iter().map(|(_, target)| target).collect(), + _ => Vec::new(), + }; + std::iter::once(project) + .chain(targets) + .filter_map(|config| text(field(config, "env_file"))) + .filter(|written| !written.is_empty()) + .collect() +} + /// The path to read, relative to the project directory unless absolute; `""` turns loading off. pub(crate) fn choice(source: ChoiceSource) -> EnvFileChoice { let configured: bool = source.text.is_some(); diff --git a/crates/sqlbuild-config/src/env_file/main/mod.rs b/crates/sqlbuild-config/src/env_file/main/mod.rs index 5ade495f1e..4498850a65 100644 --- a/crates/sqlbuild-config/src/env_file/main/mod.rs +++ b/crates/sqlbuild-config/src/env_file/main/mod.rs @@ -1 +1,2 @@ pub mod load_env_file; +pub mod named_env_files; diff --git a/crates/sqlbuild-config/src/env_file/main/named_env_files.rs b/crates/sqlbuild-config/src/env_file/main/named_env_files.rs new file mode 100644 index 0000000000..74c6f0cd9b --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/main/named_env_files.rs @@ -0,0 +1,20 @@ +//! `named_env_files`: every env file the project's configuration names. + +use std::path::{Path, PathBuf}; + +use crate::env_file::_helpers::choice::named_texts; +use crate::project::main::load_project_config::load_project_config; +use crate::project::main::project_config_paths::project_config_paths; + +/// The project's and each target's `env_file`, as written; none without a valid project file. +#[must_use] +pub fn named_env_files(project_dir: &Path) -> Vec { + load_project_config(&project_config_paths(project_dir)) + .map(|project| { + named_texts(&project) + .into_iter() + .map(PathBuf::from) + .collect() + }) + .unwrap_or_default() +} diff --git a/crates/sqlbuild-config/src/project/_helpers/defaults.rs b/crates/sqlbuild-config/src/project/_helpers/defaults.rs index 86e1bb42e9..600bf12565 100644 --- a/crates/sqlbuild-config/src/project/_helpers/defaults.rs +++ b/crates/sqlbuild-config/src/project/_helpers/defaults.rs @@ -21,6 +21,7 @@ use crate::project::errors::ConfigFailure; use crate::project::models::{Built, ConfigFile}; use crate::project::types::{Entries, Fields, Loaded}; use sqlbuild_core::constants::PROJECT_CONFIG_FILENAME; +use sqlbuild_core::constants::SQL_DIRECTORY; use sqlbuild_core::constants::ZERO_DAY_DURATION; /// A retention or table-type field: where it lives and whether `'inherit'` is accepted. @@ -228,12 +229,14 @@ fn normalize_path_key(path_key: &str, file: ConfigFile) -> Loaded { "is invalid. Path defaults cannot contain empty path segments.", )); } - if parts[0] == MODELS_DIRECTORY_NAME { + if parts[0] == MODELS_DIRECTORY_NAME + || (parts[0] == SQL_DIRECTORY && parts.get(1) == Some(&MODELS_DIRECTORY_NAME)) + { return Err(invalid_path_key( file, path_key, - "uses redundant 'models/' prefix. Use a model-relative path such as 'staging' or \ - 'staging/nested'.", + "uses a redundant 'sql/models/' prefix. Use a model-relative path such as 'staging' \ + or 'staging/nested'.", )); } let unsupported: Vec<&str> = parts @@ -317,7 +320,7 @@ pub(crate) fn load_path_defaults(payload: Option<&ConfigValue>, file: ConfigFile format!( "path_defaults defines both '{path_key}' and another key that normalize to \ '{normalized}'. Use only the canonical model-relative form without a \ - leading 'models/' prefix." + leading 'sql/models/' prefix." ), )); } diff --git a/crates/sqlbuild-config/src/project/_helpers/documents.rs b/crates/sqlbuild-config/src/project/_helpers/documents.rs index 04a2ca9100..d1a4317972 100644 --- a/crates/sqlbuild-config/src/project/_helpers/documents.rs +++ b/crates/sqlbuild-config/src/project/_helpers/documents.rs @@ -7,7 +7,7 @@ use crate::project::_helpers::defaults::{ }; use crate::project::_helpers::fields::{ coerce_mapping, get, has, object, optional_mapping, optional_str, optional_text_allowing_empty, - require_str, string_mapping, text_or_none, + require_str, string_mapping, string_sequence, text_or_none, }; use crate::project::_helpers::help::{ Setting, SettingValue, join_helps, setting_help, setting_note, @@ -25,9 +25,10 @@ use crate::project::_helpers::targets::{ }; use crate::project::_helpers::values::is_truthy; use crate::project::constants::{ - ALLOW_MISSING_SECRETS_KEY, COLUMN_CONTRACT_MODES, ENV_FILE_KEY, - LEGACY_COLUMN_CONTRACT_MODE_KEY, LEGACY_EVENT_EXPORTERS_KEY, LOCAL_CONFIG_FILENAME, POOLS_KEY, - QUERY_CHANGE_TRACKING_KEY, REQUIRE_SQL_ANALYSIS_KEY, SHARED_POLICY_SETTINGS, SQL_ANALYSIS_KEY, + ALLOW_MISSING_SECRETS_KEY, COLUMN_CONTRACT_MODES, ENV_FILE_KEY, EXTRA_PATHS_KEY, + LEGACY_COLUMN_CONTRACT_MODE_KEY, LOCAL_CONFIG_FILENAME, PARENT_SEGMENT, POOLS_KEY, + QUERY_CHANGE_TRACKING_KEY, RENAMED_SECTIONS, REQUIRE_SQL_ANALYSIS_KEY, SHARED_POLICY_SETTINGS, + SQL_ANALYSIS_KEY, }; use crate::project::errors::{ConfigFailure, FailureClass, LoadFailure, MessagePiece}; use crate::project::models::{ @@ -284,16 +285,19 @@ fn operations(payload: &Entries) -> Loaded { load_scenario(get(payload, "scenario"), PROJECT_FILE)?, ), ("dbt", load_dbt(get(payload, "dbt"), PROJECT_FILE)?), - ("sinks", load_sinks(get(payload, "sinks"), PROJECT_FILE)?), + ( + "event_sinks", + load_sinks(get(payload, "event_sinks"), PROJECT_FILE)?, + ), ]) } fn project_fields(payload: &Entries) -> Loaded { - if get(payload, LEGACY_EVENT_EXPORTERS_KEY).is_some() { - return Err(ConfigFailure::at( - PROJECT_FILE, - "event_exporters was replaced by sinks.lifecycle", - )); + if let Some((key, message)) = RENAMED_SECTIONS + .iter() + .find(|(key, _)| get(payload, key).is_some()) + { + return Err(ConfigFailure::at(PROJECT_FILE, format!("{key} {message}"))); } if let Some(recall) = get(payload, RECALL_SECTION) { recall_section(recall, RECALL_SECTION) @@ -316,6 +320,7 @@ fn project_fields(payload: &Entries) -> Loaded { ENV_FILE_KEY, optional_text_allowing_empty(payload, ENV_FILE_KEY)?, )); + fields.push((EXTRA_PATHS_KEY, Built::Tuple(extra_paths(payload)?))); Ok(fields) } @@ -581,3 +586,31 @@ fn legacy_column_contract_mode(table: &ConfigValue) -> Option { .find(|(value, _)| value == mode) .map(|(_, checked)| *checked) } + +/// `extra_paths`: the relative entries inside the project that the layout check allows. +fn extra_paths(payload: &Entries) -> Loaded> { + let paths: Vec = string_sequence( + get(payload, EXTRA_PATHS_KEY), + Place { + file: PROJECT_FILE, + label: EXTRA_PATHS_KEY, + }, + )?; + for path in &paths { + let normalized: String = path.replace('\\', "/"); + let escapes: bool = normalized.starts_with('/') + || normalized.contains(':') + || normalized.split('/').any(|part| part == PARENT_SEGMENT) + || normalized.trim_matches('/').is_empty(); + if escapes { + return Err(ConfigFailure::at( + PROJECT_FILE, + format!( + "{EXTRA_PATHS_KEY} entry '{path}' must be a path relative to the project \ + directory, inside it" + ), + )); + } + } + Ok(paths) +} diff --git a/crates/sqlbuild-config/src/project/_helpers/sinks.rs b/crates/sqlbuild-config/src/project/_helpers/sinks.rs index 2e3765594f..0f4c269e1b 100644 --- a/crates/sqlbuild-config/src/project/_helpers/sinks.rs +++ b/crates/sqlbuild-config/src/project/_helpers/sinks.rs @@ -1,4 +1,4 @@ -//! Loader for `[sinks]` and its lifecycle event sinks. +//! Loader for `[event_sinks]` and its lifecycle event sinks. use crate::models::ConfigValue; use crate::project::_helpers::fields::{get, key_name, object}; @@ -90,7 +90,7 @@ fn named_filters(config: &Entries, file: ConfigFile) -> Loaded { Some(_) => { return Err(ConfigFailure::at( file, - "sinks.lifecycle.named must be a mapping", + "event_sinks.lifecycle.named must be a mapping", )); } }; @@ -100,10 +100,10 @@ fn named_filters(config: &Entries, file: ConfigFile) -> Loaded { if name.is_empty() { return Err(ConfigFailure::at( file, - "sinks.lifecycle.named contains an invalid name", + "event_sinks.lifecycle.named contains an invalid name", )); } - let label = format!("sinks.lifecycle.named.{name}"); + let label = format!("event_sinks.lifecycle.named.{name}"); let ConfigValue::Map(entries) = value else { return Err(ConfigFailure::at( file, @@ -135,7 +135,7 @@ fn shutdown_timeout(config: &Entries, file: ConfigFile) -> Loaded<(Built, Built) ConfigFailure::at( file, format!( - "sinks.lifecycle.{SHUTDOWN_TIMEOUT_KEY} must be a fixed duration from '0s' to \ + "event_sinks.lifecycle.{SHUTDOWN_TIMEOUT_KEY} must be a fixed duration from '0s' to \ '10m' such as '30s'" ), ) @@ -158,11 +158,16 @@ fn lifecycle(payload: Option<&ConfigValue>, file: ConfigFile) -> Loaded { let config = match payload { None => return Ok(object("LifecycleEventSinksConfig", Vec::new())), Some(ConfigValue::Map(entries)) => entries, - Some(_) => return Err(ConfigFailure::at(file, "sinks.lifecycle must be a mapping")), + Some(_) => { + return Err(ConfigFailure::at( + file, + "event_sinks.lifecycle must be a mapping", + )); + } }; let place = Place { file, - label: "sinks.lifecycle", + label: "event_sinks.lifecycle", }; validate_allowed_keys(config, &EVENT_SINK_KEYS, place)?; let named = named_filters(config, file)?; @@ -188,14 +193,14 @@ pub(crate) fn load_sinks(payload: Option<&ConfigValue>, file: ConfigFile) -> Loa let mapping = match payload { None => return Ok(object("SinksConfig", Vec::new())), Some(ConfigValue::Map(entries)) => entries, - Some(_) => return Err(ConfigFailure::at(file, "sinks must be a mapping")), + Some(_) => return Err(ConfigFailure::at(file, "event_sinks must be a mapping")), }; validate_allowed_keys( mapping, &["lifecycle"], Place { file, - label: "sinks", + label: "event_sinks", }, )?; Ok(object( diff --git a/crates/sqlbuild-config/src/project/constants.rs b/crates/sqlbuild-config/src/project/constants.rs index 33a6a19bda..0976e837ff 100644 --- a/crates/sqlbuild-config/src/project/constants.rs +++ b/crates/sqlbuild-config/src/project/constants.rs @@ -23,7 +23,6 @@ pub(crate) const OLD_NAME_VIEWS_KEY: &str = "old_name_views"; pub(crate) const USD_PER_CREDIT_KEY: &str = "usd_per_credit"; pub(crate) const RUN_NAMESPACE_KEY: &str = "run_namespace"; pub(crate) const SHUTDOWN_TIMEOUT_KEY: &str = "shutdown_timeout"; -pub(crate) const LEGACY_EVENT_EXPORTERS_KEY: &str = "event_exporters"; pub(crate) const MAX_FULL_ROWS_KEY: &str = "max_full_rows"; pub(crate) const DBT_DEFER_CLONE_KEY: &str = "defer_clone_from"; pub(crate) const DBT_REUSE_KEYS: [&str; 2] = ["reuse_from", "production_ref"]; @@ -59,6 +58,10 @@ pub(crate) const IGNORE_AUDIT_FAILURES_KEY: &str = "ignore_audit_failures"; pub(crate) const PAUSE_DYNAMIC_KEY: &str = "pause_dynamic"; /// The env file a project or target loads into the environment at start-up; `""` turns it off. pub(crate) const ENV_FILE_KEY: &str = "env_file"; +/// Project entries the layout check allows beside the expected folders. +pub(crate) const EXTRA_PATHS_KEY: &str = "extra_paths"; +/// The path segment that would lead an `extra_paths` entry out of the project. +pub(crate) const PARENT_SEGMENT: &str = ".."; /// Whether each run records the machine it ran on in the runs state table. pub(crate) const RECORD_RUN_HOST_KEY: &str = "record_run_host"; pub(crate) const DEFAULT_TEST_TIMEOUT: &str = "30s"; @@ -335,3 +338,8 @@ pub(crate) const MICROBATCH_CONCURRENCY_KEY: &str = "microbatch_concurrency"; pub(crate) const REFERENCES_SECTION: &str = "references"; pub(crate) const ENFORCE_EXPLICIT_KEY: &str = "enforce_explicit"; pub(crate) const MICROBATCH_CONCURRENCY_PURPOSE: &str = "to run microbatches concurrently"; +/// Top-level sections an earlier release read, and what replaced each. +pub(crate) const RENAMED_SECTIONS: [(&str, &str); 2] = [ + ("event_exporters", "was replaced by event_sinks.lifecycle"), + ("sinks", "was renamed event_sinks"), +]; diff --git a/crates/sqlbuild-config/src/project/tests/test_guidance.rs b/crates/sqlbuild-config/src/project/tests/test_guidance.rs index f8277f5fb6..db9afeca3b 100644 --- a/crates/sqlbuild-config/src/project/tests/test_guidance.rs +++ b/crates/sqlbuild-config/src/project/tests/test_guidance.rs @@ -57,7 +57,7 @@ fn given_setting_guidance_when_rendering_then_text_matches_python() { rendered: ( snippet_help_text( "to describe it", - "add this to seeds/lookups.yml", + "add this to sql/seeds/lookups.yml", &[ "- name: product_types".to_owned(), " description: Types".to_owned(), @@ -65,7 +65,7 @@ fn given_setting_guidance_when_rendering_then_text_matches_python() { ), String::new(), ), - expected_note: "to describe it, add this to seeds/lookups.yml:\n - name: product_types\n description: Types", + expected_note: "to describe it, add this to sql/seeds/lookups.yml:\n - name: product_types\n description: Types", expected_help: "", }, ]; diff --git a/crates/sqlbuild-config/src/project/tests/test_load_config.rs b/crates/sqlbuild-config/src/project/tests/test_load_config.rs index 2c769a872b..018fef3b48 100644 --- a/crates/sqlbuild-config/src/project/tests/test_load_config.rs +++ b/crates/sqlbuild-config/src/project/tests/test_load_config.rs @@ -22,7 +22,7 @@ fn given_project_files_when_loading_then_rejections_match_python_loader() { ProjectFailureTestCase { description: "a valid project and local file load", project: "name = 'orders'\nadapter = 'duckdb'\n[settings]\nconcurrency = 4\n\ - [targets.dev]\nschema = 'analytics'\n[sinks.lifecycle]\nshutdown_timeout = '10m'\n", + [targets.dev]\nschema = 'analytics'\n[event_sinks.lifecycle]\nshutdown_timeout = '10m'\n", local: "target = 'dev'\n[settings]\nmax_concurrency = 2\n", expected_failure: None, }, @@ -190,11 +190,11 @@ fn given_project_files_when_loading_then_rejections_match_python_loader() { }, ProjectFailureTestCase { description: "a shutdown timeout over ten minutes is rejected", - project: "name = 'orders'\nadapter = 'duckdb'\n[sinks.lifecycle]\nshutdown_timeout = '601s'\n", + project: "name = 'orders'\nadapter = 'duckdb'\n[event_sinks.lifecycle]\nshutdown_timeout = '601s'\n", local: "", expected_failure: failure_at( ConfigFile::Project, - "sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m' such as '30s'", + "event_sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m' such as '30s'", None, ), }, @@ -236,7 +236,7 @@ fn given_project_files_when_loading_then_rejections_match_python_loader() { ConfigFile::Project, "path_defaults defines both ' staging ' and another key that normalize to \ 'staging'. Use only the canonical model-relative form without a leading \ - 'models/' prefix.", + 'sql/models/' prefix.", None, ), }, diff --git a/crates/sqlbuild-core/src/cli_text/tests/helpers.rs b/crates/sqlbuild-core/src/cli_text/tests/helpers.rs index 441a5d4032..84281b7848 100644 --- a/crates/sqlbuild-core/src/cli_text/tests/helpers.rs +++ b/crates/sqlbuild-core/src/cli_text/tests/helpers.rs @@ -2,10 +2,10 @@ use crate::cli_text::models::{ DiagnosticText, DisplayLimit, LocationText, ModelPlanText, PlanTextReport, }; -/// A location in `models/a.sql`, whose text has a CRLF line, a non-ASCII name and a vertical tab. +/// A location in `sql/models/a.sql`, whose text has a CRLF line, a non-ASCII name and a vertical tab. pub(super) fn location(line: i64, column: i64, end: (Option, Option)) -> LocationText { LocationText { - path: "models/a.sql".to_owned(), + path: "sql/models/a.sql".to_owned(), line, column, end_line: end.0, diff --git a/crates/sqlbuild-core/src/cli_text/tests/test_cli_text.rs b/crates/sqlbuild-core/src/cli_text/tests/test_cli_text.rs index 511bd83618..743cbbfe81 100644 --- a/crates/sqlbuild-core/src/cli_text/tests/test_cli_text.rs +++ b/crates/sqlbuild-core/src/cli_text/tests/test_cli_text.rs @@ -36,13 +36,13 @@ fn given_diagnostics_when_rendering_then_matches_python_text() { ..diagnostic("error", "C001", "bad column") }, DiagnosticText { - path: Some("models/b.sql".to_owned()), + path: Some("sql/models/b.sql".to_owned()), occurrences: 2, ..diagnostic("warning", "W001", "careful") }, ], style: CliStyle { use_color: true }, - expected_text: "\x1b[38;5;167merror[C001]: bad column\x1b[0m\n sql test: orders_test\n --> models/a.sql:2:3\n |\n 2 | FROM orders\u{e9} x\n | ^^^^\n\n declared here:\n --> models/a.sql:1:1\n |\n 1 | SELECT 1\n | ^^^^^^^^ here\n \x1b[2m= note:\x1b[0m n1\n \x1b[2m= affected Rules:\x1b[0m R1, R2\n \x1b[2m= help:\x1b[0m fix it\n\n\x1b[33mwarning[W001]: careful\x1b[0m\n --> models/b.sql\n = 2 occurrences; all retained in JSON and the warning count", + expected_text: "\x1b[38;5;167merror[C001]: bad column\x1b[0m\n sql test: orders_test\n --> sql/models/a.sql:2:3\n |\n 2 | FROM orders\u{e9} x\n | ^^^^\n\n declared here:\n --> sql/models/a.sql:1:1\n |\n 1 | SELECT 1\n | ^^^^^^^^ here\n \x1b[2m= note:\x1b[0m n1\n \x1b[2m= affected Rules:\x1b[0m R1, R2\n \x1b[2m= help:\x1b[0m fix it\n\n\x1b[33mwarning[W001]: careful\x1b[0m\n --> sql/models/b.sql\n = 2 occurrences; all retained in JSON and the warning count", }]; for test_case in test_cases { @@ -386,23 +386,23 @@ fn given_coded_error_when_formatting_then_renders_consistently() { description: "renders multiline coded error without color unchanged", parts: ( "D012", - "Provider 'slack_provider' in providers/slack.py has invalid settings:\n1 validation error for SlackProvider\nSLACK_TOKEN", + "Provider 'slack_provider' in python/providers/slack.py has invalid settings:\n1 validation error for SlackProvider\nSLACK_TOKEN", None, ), include_error_label: true, style: plain, - expected_rendered: "error[D012]: Provider 'slack_provider' in providers/slack.py has invalid settings:\n1 validation error for SlackProvider\nSLACK_TOKEN", + expected_rendered: "error[D012]: Provider 'slack_provider' in python/providers/slack.py has invalid settings:\n1 validation error for SlackProvider\nSLACK_TOKEN", }, CodedErrorTestCase { description: "renders multiline coded error with muted continuation lines", parts: ( "D012", - "Provider 'slack_provider' in providers/slack.py has invalid settings:\n1 validation error for SlackProvider\nSLACK_TOKEN", + "Provider 'slack_provider' in python/providers/slack.py has invalid settings:\n1 validation error for SlackProvider\nSLACK_TOKEN", None, ), include_error_label: true, style: color, - expected_rendered: "\x1b[38;5;167m\x1b[1merror[D012]:\x1b[0m Provider 'slack_provider' in providers/slack.py has invalid settings:\n\x1b[2m1 validation error for SlackProvider\x1b[0m\n\x1b[2mSLACK_TOKEN\x1b[0m", + expected_rendered: "\x1b[38;5;167m\x1b[1merror[D012]:\x1b[0m Provider 'slack_provider' in python/providers/slack.py has invalid settings:\n\x1b[2m1 validation error for SlackProvider\x1b[0m\n\x1b[2mSLACK_TOKEN\x1b[0m", }, ]; diff --git a/crates/sqlbuild-core/src/constants.rs b/crates/sqlbuild-core/src/constants.rs index 5ea4219c11..9fcf7a603c 100644 --- a/crates/sqlbuild-core/src/constants.rs +++ b/crates/sqlbuild-core/src/constants.rs @@ -14,8 +14,84 @@ pub const SETTINGS_SECTION: &str = "settings"; pub const TABLE_PROMOTION_MODE_SETTING_KEY: &str = "table_promotion_mode"; /// Table promotion mode that builds into a staging relation before swapping. pub const STAGED_PROMOTION_MODE: &str = "staged"; -/// Project directory holding Python node modules. -pub const PYTHON_NODE_ROOT: &str = "python"; +/// Project folder holding everything the warehouse runs. +pub const SQL_DIRECTORY: &str = "sql"; +/// Project folder holding everything SQLBuild imports as Python, imported as the `python` package. +pub const PYTHON_DIRECTORY: &str = "python"; +/// Project folder of SQL models. +pub const MODELS_PATH: &str = "sql/models"; +/// Project folder of seeds. +pub const SEEDS_PATH: &str = "sql/seeds"; +/// Project folder of sources. +pub const SOURCES_PATH: &str = "sql/sources"; +/// Project folder of project-wide macros. +pub const MACROS_PATH: &str = "sql/macros"; +/// Project folder of functions. +pub const FUNCTIONS_PATH: &str = "sql/functions"; +/// Project folder of project-wide enums. +pub const ENUMS_PATH: &str = "sql/enums"; +/// Project folder of project-wide constants. +pub const CONSTANTS_PATH: &str = "sql/constants"; +/// Project folder of project-wide audits. +pub const AUDITS_PATH: &str = "sql/audits"; +/// Project folder of project-wide hooks. +pub const HOOKS_PATH: &str = "sql/hooks"; +/// Project folder of project-wide schemas. +pub const SCHEMAS_PATH: &str = "sql/schemas"; +/// The folders `sql/` may hold. +pub const SQL_CHILDREN: [&str; 10] = [ + "models", + "seeds", + "sources", + "macros", + "functions", + "enums", + "constants", + "audits", + "hooks", + "schemas", +]; +/// Project folder holding Python node modules. +pub const PYTHON_NODE_ROOT: &str = "python/nodes"; +/// Project folder of providers. +pub const PROVIDERS_PATH: &str = "python/providers"; +/// Project folder of lifecycle event and command output event sinks. +pub const EVENT_SINKS_PATH: &str = "python/event_sinks"; +/// Project folder of custom materializations. +pub const MATERIALIZATIONS_PATH: &str = "python/materializations"; +/// Project folder of custom adapters. +pub const ADAPTERS_PATH: &str = "python/adapters"; +/// Project file of a single custom adapter. +pub const ADAPTER_FILE_PATH: &str = "python/adapter.py"; +/// The entries `python/` may hold. +pub const PYTHON_CHILDREN: [&str; 7] = [ + "nodes", + "providers", + "event_sinks", + "materializations", + "adapters", + "adapter.py", + "__init__.py", +]; +/// Project folder of jobs, job groups, calendars and sensors. +pub const ORCHESTRATION_PATH: &str = "orchestration"; +/// Project folder of custom rules. +pub const RULES_PATH: &str = "rules"; +/// Project folder of SQL tests, scenarios and Python tests. +pub const TESTS_PATH: &str = "tests"; +/// Project folder of SQL unit tests. +pub const UNIT_TESTS_PATH: &str = "tests/unit"; +/// Project folder of SQL scenarios. +pub const SCENARIOS_PATH: &str = "tests/scenarios"; +/// The folders a project's top level may hold. +pub const TOP_LEVEL_DIRECTORIES: [&str; 5] = ["sql", "python", "orchestration", "rules", "tests"]; +/// The files a project's top level may hold. +pub const TOP_LEVEL_FILES: [&str; 4] = [ + "sqlbuild_project.toml", + "sqlbuild_local.toml", + "roles.toml", + "README.md", +]; /// Stem of a Python package's initializer module. pub const PYTHON_INIT_MODULE_STEM: &str = "__init__"; /// State table of model, seed and hook fingerprints. @@ -69,3 +145,7 @@ pub const STATE_TABLE_NAMES: [&str; 14] = [ pub const ZERO_DAY_DURATION: &str = "0d"; /// Node key of a common table expression in the polyglot SQL AST. pub const CTE_AST_KIND: &str = "cte"; +/// How `sqb dev` hands its location the SQLite control store file it writes. +pub const DEVELOPMENT_CONTROL_FILE_ENV: &str = "SQLBUILD_DEVELOPMENT_CONTROL_FILE"; +/// How `sqb dev` hands its location the folder it writes run output to. +pub const DEVELOPMENT_OUTPUT_FOLDER_ENV: &str = "SQLBUILD_DEVELOPMENT_OUTPUT_FOLDER"; diff --git a/crates/sqlbuild-core/src/contract_command/tests/test_contract_command.rs b/crates/sqlbuild-core/src/contract_command/tests/test_contract_command.rs index 19cc1e4357..795edbe8a5 100644 --- a/crates/sqlbuild-core/src/contract_command/tests/test_contract_command.rs +++ b/crates/sqlbuild-core/src/contract_command/tests/test_contract_command.rs @@ -20,10 +20,10 @@ fn given_comparison_when_rendering_then_reports_text_json_and_exit_code() { relation: "raw.orders".to_owned(), findings: Vec::new(), }], - written_paths: vec!["sources/raw.yml".to_owned()], + written_paths: vec!["sql/sources/raw.yml".to_owned()], }, - expected_text: "Contract comparison from target 'prod'\n OK source:raw_orders\n\nUpdated repository declarations:\n sources/raw.yml\n\n0 contract difference(s)\n", - expected_json: "{\n \"differences\": 0,\n \"from_target\": \"prod\",\n \"resources\": [\n {\n \"findings\": [],\n \"relation\": \"raw.orders\",\n \"resource_name\": \"raw_orders\",\n \"resource_type\": \"source\"\n }\n ],\n \"written_paths\": [\n \"sources/raw.yml\"\n ]\n}\n", + expected_text: "Contract comparison from target 'prod'\n OK source:raw_orders\n\nUpdated repository declarations:\n sql/sources/raw.yml\n\n0 contract difference(s)\n", + expected_json: "{\n \"differences\": 0,\n \"from_target\": \"prod\",\n \"resources\": [\n {\n \"findings\": [],\n \"relation\": \"raw.orders\",\n \"resource_name\": \"raw_orders\",\n \"resource_type\": \"source\"\n }\n ],\n \"written_paths\": [\n \"sql/sources/raw.yml\"\n ]\n}\n", expected_exit_code: 0, }, ReportTestCase { diff --git a/crates/sqlbuild-core/src/cost_report/_helpers/breakdown.rs b/crates/sqlbuild-core/src/cost_report/_helpers/breakdown.rs index b38d65ee71..32a82f2450 100644 --- a/crates/sqlbuild-core/src/cost_report/_helpers/breakdown.rs +++ b/crates/sqlbuild-core/src/cost_report/_helpers/breakdown.rs @@ -3,8 +3,8 @@ use crate::cli_text::models::CliStyle; use crate::cost_report::_helpers::decimal_text::fixed; use crate::cost_report::constants::{ - COLLECTION_FAILED_STATUS, COMPLETE_STATUS, DEFAULT_RATE_SOURCE, ESTIMATE_NOTE, RATE_ADVICE, - RATE_PLACES, WARNING_STATUSES, + COLLECTION_FAILED_STATUS, COMPLETE_STATUS, DEFAULT_RATE_SOURCE, ESTIMATE_NOTE, + LIST_PRICE_RATE_SOURCE, RATE_ADVICE, RATE_PLACES, RATE_SHEET_RATE_SOURCE, WARNING_STATUSES, }; use crate::cost_report::models::{CostRun, CostSummary}; @@ -22,13 +22,15 @@ pub(crate) fn styled_status(style: CliStyle, status: &str) -> String { style.muted(status) } -/// The credit rate, flagged when it is the default. +/// The credit rate and where it came from; the default and the list price are flagged as estimates. pub(crate) fn rate_note(style: CliStyle, cost: &CostSummary) -> String { let rate: String = fixed(&cost.usd_per_credit, RATE_PLACES); - if cost.rate_source == DEFAULT_RATE_SOURCE { - return style.warning(&format!("default ${rate}/credit")); + match cost.rate_source.as_str() { + DEFAULT_RATE_SOURCE => style.warning(&format!("default ${rate}/credit")), + LIST_PRICE_RATE_SOURCE => style.warning(&format!("${rate}/credit est. (list price)")), + RATE_SHEET_RATE_SOURCE => style.muted(&format!("${rate}/credit (rate sheet)")), + _ => style.muted(&format!("${rate}/credit")), } - style.muted(&format!("${rate}/credit")) } /// The `Run ` line, when shown. @@ -53,7 +55,7 @@ pub(crate) fn trailer(style: CliStyle, run: &CostRun, limit: Option) -> V if let Some(message) = cost.message.as_ref().filter(|message| !message.is_empty()) { lines.push(style.muted(message)); } - if cost.rate_source == DEFAULT_RATE_SOURCE { + if [DEFAULT_RATE_SOURCE, LIST_PRICE_RATE_SOURCE].contains(&cost.rate_source.as_str()) { lines.push(style.warning(RATE_ADVICE)); } lines.extend( diff --git a/crates/sqlbuild-core/src/cost_report/constants.rs b/crates/sqlbuild-core/src/cost_report/constants.rs index 2be6918ced..f95a6c5c87 100644 --- a/crates/sqlbuild-core/src/cost_report/constants.rs +++ b/crates/sqlbuild-core/src/cost_report/constants.rs @@ -5,6 +5,10 @@ pub(crate) const OUTPUT_SCHEMA_VERSION: i64 = 1; pub(crate) const LATEST_SELECTOR: &str = "latest"; pub(crate) const RUNNING_BUILD_STATUS: &str = "running"; pub(crate) const DEFAULT_RATE_SOURCE: &str = "default"; +/// The list price for the account's region and edition: an estimate. +pub(crate) const LIST_PRICE_RATE_SOURCE: &str = "list_price"; +/// The account's contract price, from Snowflake's rate sheet. +pub(crate) const RATE_SHEET_RATE_SOURCE: &str = "rate_sheet"; pub(crate) const COMPLETE_STATUS: &str = "complete"; pub(crate) const COLLECTION_FAILED_STATUS: &str = "collection_failed"; pub(crate) const WARNING_STATUSES: [&str; 2] = ["partial", "pending"]; @@ -49,8 +53,7 @@ pub(crate) const WIDE_HEADINGS: [&str; 6] = [ "Attributed credits", "Est. cost", ]; -pub(crate) const RATE_ADVICE: &str = - "Configure cost.usd_per_credit with your Snowflake contract rate."; +pub(crate) const RATE_ADVICE: &str = "Configure cost.usd_per_credit with your Snowflake contract rate, or let the connection's role read SNOWFLAKE.ORGANIZATION_USAGE.RATE_SHEET_DAILY."; pub(crate) const ESTIMATE_NOTE: &str = "Estimate uses fair-share visible warehouse busy time; it is not Snowflake-billed credits or invoice reconciliation."; pub(crate) const MICROS_PER_SECOND: i128 = 1_000_000; pub(crate) const SECONDS_PER_DAY: i128 = 86_400; diff --git a/crates/sqlbuild-core/src/cost_report/tests/helpers.rs b/crates/sqlbuild-core/src/cost_report/tests/helpers.rs index 67c9632d08..709e00915e 100644 --- a/crates/sqlbuild-core/src/cost_report/tests/helpers.rs +++ b/crates/sqlbuild-core/src/cost_report/tests/helpers.rs @@ -47,3 +47,9 @@ pub(super) fn run(completed_at: &str, resources: Vec) -> CostRun { had_executable_work: Some(true), } } + +/// `run` priced from `source`. +pub(crate) fn priced(mut run: CostRun, source: &str) -> CostRun { + run.cost.rate_source = source.to_owned(); + run +} diff --git a/crates/sqlbuild-core/src/cost_report/tests/test_cost_report.rs b/crates/sqlbuild-core/src/cost_report/tests/test_cost_report.rs index 9c2486e26c..10274fcfc1 100644 --- a/crates/sqlbuild-core/src/cost_report/tests/test_cost_report.rs +++ b/crates/sqlbuild-core/src/cost_report/tests/test_cost_report.rs @@ -1,7 +1,7 @@ use crate::cost_report::main::format_cost_breakdown::format_cost_breakdown; use crate::cost_report::main::format_cost_history::format_cost_history; use crate::cost_report::models::BreakdownOptions; -use crate::cost_report::tests::helpers::{resource, run}; +use crate::cost_report::tests::helpers::{priced, resource, run}; use crate::cost_report::tests::test_types::{BreakdownTestCase, HistoryTestCase}; #[test] @@ -18,7 +18,7 @@ fn given_cost_runs_when_formatting_breakdown_then_table_matches_python_layout() ), limit: None, terminal_width: 140, - expected_text: "Cost $0.0206 estimated | 0.006858 attributed credits | default $3.00/credit\nRun run-1\n\nModel Warehouse Busy share Scanned Attributed credits Est. cost\norders TRANSFORM_WH 12.34s 5.0 TiB 0.003429 $0.0103\ncustomers TRANSFORM_WH 12.34s 1.5 KiB 0.003429 $0.0000\nTOTAL 24.69s 1.5 KiB 0.006858 $0.0206\nConfigure cost.usd_per_credit with your Snowflake contract rate.\nEstimate uses fair-share visible warehouse busy time; it is not Snowflake-billed credits or invoice reconciliation.", + expected_text: "Cost $0.0206 estimated | 0.006858 attributed credits | default $3.00/credit\nRun run-1\n\nModel Warehouse Busy share Scanned Attributed credits Est. cost\norders TRANSFORM_WH 12.34s 5.0 TiB 0.003429 $0.0103\ncustomers TRANSFORM_WH 12.34s 1.5 KiB 0.003429 $0.0000\nTOTAL 24.69s 1.5 KiB 0.006858 $0.0206\nConfigure cost.usd_per_credit with your Snowflake contract rate, or let the connection's role read SNOWFLAKE.ORGANIZATION_USAGE.RATE_SHEET_DAILY.\nEstimate uses fair-share visible warehouse busy time; it is not Snowflake-billed credits or invoice reconciliation.", }, BreakdownTestCase { description: "a narrow limited table notes the hidden resources", @@ -31,7 +31,33 @@ fn given_cost_runs_when_formatting_breakdown_then_table_matches_python_layout() ), limit: Some(1), terminal_width: 80, - expected_text: "Cost $0.0206 estimated | 0.006858 attributed credits | default $3.00/credit\nRun run-1\n\nModel Attributed credits Est. cost\norders_with_a_very_long_model... 0.003429 $2.5000\nTOTAL 0.006858 $0.0206\nShowing 1 of 2 by estimated cost; `sqb cost run-1` for all models (1 more).\nConfigure cost.usd_per_credit with your Snowflake contract rate.\nEstimate uses fair-share visible warehouse busy time; it is not Snowflake-billed credits or invoice reconciliation.", + expected_text: "Cost $0.0206 estimated | 0.006858 attributed credits | default $3.00/credit\nRun run-1\n\nModel Attributed credits Est. cost\norders_with_a_very_long_model... 0.003429 $2.5000\nTOTAL 0.006858 $0.0206\nShowing 1 of 2 by estimated cost; `sqb cost run-1` for all models (1 more).\nConfigure cost.usd_per_credit with your Snowflake contract rate, or let the connection's role read SNOWFLAKE.ORGANIZATION_USAGE.RATE_SHEET_DAILY.\nEstimate uses fair-share visible warehouse busy time; it is not Snowflake-billed credits or invoice reconciliation.", + }, + BreakdownTestCase { + description: "a list price reads as an estimate and names its source", + run: priced( + run( + "2026-09-01T10:05:00+02:00", + vec![resource("orders", "0.5", 0)], + ), + "list_price", + ), + limit: None, + terminal_width: 80, + expected_text: "Cost $0.0206 estimated | 0.006858 attributed credits | $3.00/credit est. (list price)\nRun run-1\n\nModel Attributed credits Est. cost\norders 0.003429 $0.5000\nTOTAL 0.006858 $0.0206\nConfigure cost.usd_per_credit with your Snowflake contract rate, or let the connection's role read SNOWFLAKE.ORGANIZATION_USAGE.RATE_SHEET_DAILY.\nEstimate uses fair-share visible warehouse busy time; it is not Snowflake-billed credits or invoice reconciliation.", + }, + BreakdownTestCase { + description: "the rate sheet's price names its source, with no advice", + run: priced( + run( + "2026-09-01T10:05:00+02:00", + vec![resource("orders", "0.5", 0)], + ), + "rate_sheet", + ), + limit: None, + terminal_width: 80, + expected_text: "Cost $0.0206 estimated | 0.006858 attributed credits | $3.00/credit (rate sheet)\nRun run-1\n\nModel Attributed credits Est. cost\norders 0.003429 $0.5000\nTOTAL 0.006858 $0.0206\nEstimate uses fair-share visible warehouse busy time; it is not Snowflake-billed credits or invoice reconciliation.", }, ]; diff --git a/crates/sqlbuild-core/src/debug_report/tests/helpers.rs b/crates/sqlbuild-core/src/debug_report/tests/helpers.rs index f9d3f1ec52..af9e4a39ac 100644 --- a/crates/sqlbuild-core/src/debug_report/tests/helpers.rs +++ b/crates/sqlbuild-core/src/debug_report/tests/helpers.rs @@ -17,7 +17,7 @@ pub(super) fn sample_report() -> DebugReport { DebugLine::checked("providers", "1", (DebugStatus::Ok, Some("discovered"))), DebugLine::checked( "marker_provider", - "providers/marker.py:MarkerProvider", + "python/providers/marker.py:MarkerProvider", (DebugStatus::Ok, Some("valid settings")), ), ], @@ -48,7 +48,7 @@ pub(super) fn line_summary(line: &DebugLine) -> (&str, &str, Option<&str>) { pub(super) fn provider(name: &str, secrets: &[(&str, bool)]) -> DebugProvider { DebugProvider { name: name.to_owned(), - relative_path: format!("providers/{name}/provider.py"), + relative_path: format!("python/providers/{name}/provider.py"), class_name: "Provider".to_owned(), secrets: secrets .iter() diff --git a/crates/sqlbuild-core/src/debug_report/tests/test_debug_report.rs b/crates/sqlbuild-core/src/debug_report/tests/test_debug_report.rs index 17eb30cb64..014c3c7d18 100644 --- a/crates/sqlbuild-core/src/debug_report/tests/test_debug_report.rs +++ b/crates/sqlbuild-core/src/debug_report/tests/test_debug_report.rs @@ -18,8 +18,8 @@ fn given_debug_report_when_formatting_then_matches_python_outputs() { let test_cases = [FormatTestCase { description: "renders diagnostics sections and json sections", report: sample_report(), - expected_text: "\nSQLBuild Diagnostics\n\nRuntime:\n sqlbuild version: 0.2.1\n\nConfiguration:\n project file: /repo/sqlbuild_project.toml [OK found and valid]\n\nProviders:\n providers: 1 [OK discovered]\n marker_provider: providers/marker.py:MarkerProvider [OK valid settings]\n\nConnection:\n token: ****\n connection test: [ERROR authentication failed]\n query test: [SKIP connection failed]\n\n", - expected_json: r#"{"configuration": [{"label": "project file", "message": "/repo/sqlbuild_project.toml", "status": "OK", "status_message": "found and valid"}], "connection": [{"label": "token", "message": "****"}, {"label": "connection test", "message": "", "status": "ERROR", "status_message": "authentication failed"}, {"label": "query test", "message": "", "status": "SKIP", "status_message": "connection failed"}], "history_reads_wake_compute": false, "local_files": ["/repo/warehouse.db"], "missing_secrets": 0, "providers": [{"label": "providers", "message": "1", "status": "OK", "status_message": "discovered"}, {"label": "marker_provider", "message": "providers/marker.py:MarkerProvider", "status": "OK", "status_message": "valid settings"}], "runtime": [{"label": "sqlbuild version", "message": "0.2.1"}], "success": false}"#, + expected_text: "\nSQLBuild Diagnostics\n\nRuntime:\n sqlbuild version: 0.2.1\n\nConfiguration:\n project file: /repo/sqlbuild_project.toml [OK found and valid]\n\nProviders:\n providers: 1 [OK discovered]\n marker_provider: python/providers/marker.py:MarkerProvider [OK valid settings]\n\nConnection:\n token: ****\n connection test: [ERROR authentication failed]\n query test: [SKIP connection failed]\n\n", + expected_json: r#"{"configuration": [{"label": "project file", "message": "/repo/sqlbuild_project.toml", "status": "OK", "status_message": "found and valid"}], "connection": [{"label": "token", "message": "****"}, {"label": "connection test", "message": "", "status": "ERROR", "status_message": "authentication failed"}, {"label": "query test", "message": "", "status": "SKIP", "status_message": "connection failed"}], "history_reads_wake_compute": false, "local_files": ["/repo/warehouse.db"], "missing_secrets": 0, "providers": [{"label": "providers", "message": "1", "status": "OK", "status_message": "discovered"}, {"label": "marker_provider", "message": "python/providers/marker.py:MarkerProvider", "status": "OK", "status_message": "valid settings"}], "runtime": [{"label": "sqlbuild version", "message": "0.2.1"}], "success": false}"#, expected_color_fragments: &[ "\x1b[34m\x1b[1mSQLBuild Diagnostics\x1b[0m", "\x1b[1mRuntime:\x1b[0m", diff --git a/crates/sqlbuild-core/src/format_command/constants.rs b/crates/sqlbuild-core/src/format_command/constants.rs index de784794c6..23798ffa70 100644 --- a/crates/sqlbuild-core/src/format_command/constants.rs +++ b/crates/sqlbuild-core/src/format_command/constants.rs @@ -1,16 +1,9 @@ //! Formatter-owned folders, selector syntax and report layout. /// The project folders whose SQL files the formatter owns, in collection order. -pub const LINT_DIRECTORY_NAMES: [&str; 9] = [ - "models", - "tests", - "audits", - "functions", - "enums", - "constants", - "hooks", - "schemas", - "macros", +pub const LINT_DIRECTORY_NAMES: [&str; 2] = [ + crate::constants::SQL_DIRECTORY, + crate::constants::TESTS_PATH, ]; pub(crate) const PATH_SELECTOR_PREFIX: &str = "path:"; pub(crate) const PATH_SEPARATOR: char = '/'; diff --git a/crates/sqlbuild-core/src/format_command/tests/helpers.rs b/crates/sqlbuild-core/src/format_command/tests/helpers.rs index 95751b256c..309bbebd45 100644 --- a/crates/sqlbuild-core/src/format_command/tests/helpers.rs +++ b/crates/sqlbuild-core/src/format_command/tests/helpers.rs @@ -20,7 +20,7 @@ pub(super) fn sample_report() -> LintReport { findings: vec![ LintFinding { file: "/p/models/orders.sql".to_owned(), - display_path: "models/orders.sql".to_owned(), + display_path: "sql/models/orders.sql".to_owned(), line: 2, column: 8, end_line: Some(2), diff --git a/crates/sqlbuild-core/src/format_command/tests/test_format_command.rs b/crates/sqlbuild-core/src/format_command/tests/test_format_command.rs index 0360237550..f16ccf8cb6 100644 --- a/crates/sqlbuild-core/src/format_command/tests/test_format_command.rs +++ b/crates/sqlbuild-core/src/format_command/tests/test_format_command.rs @@ -14,7 +14,7 @@ fn given_format_report_when_rendering_then_text_and_json_match_python() { let test_cases = [ReportTestCase { description: "excerpt, wrapped help, location-only warning and a Rule fix", report: sample_report(), - expected_text: "Formatted files:\n /p/models/orders.sql\n\nerror[SQLCLEAN004]: Avoid LIMIT\n --> models/orders.sql:2:8\n |\n2 | SELECT\t1 LIMIT 5\n | \t^^^^^^^\n |\n = help: Remove the LIMIT clause from the model body because the model must return every row it is\n expected to produce downstream.\n\nwarning[description-present]: Missing\n --> /other/x.sql:1:1\n\nAPPLIED SQLCLEAN002 /p/models/orders.sql:4: ok\nCompleted. FAULT=1 WARN=1 FILES=3\n", + expected_text: "Formatted files:\n /p/models/orders.sql\n\nerror[SQLCLEAN004]: Avoid LIMIT\n --> sql/models/orders.sql:2:8\n |\n2 | SELECT\t1 LIMIT 5\n | \t^^^^^^^\n |\n = help: Remove the LIMIT clause from the model body because the model must return every row it is\n expected to produce downstream.\n\nwarning[description-present]: Missing\n --> /other/x.sql:1:1\n\nAPPLIED SQLCLEAN002 /p/models/orders.sql:4: ok\nCompleted. FAULT=1 WARN=1 FILES=3\n", expected_json: "{\"faults\":1,\"files_checked\":3,\"formatted_files\":[\"/p/models/orders.sql\"],\"rule_fixes\":[{\"code\":\"SQLCLEAN002\",\"file\":\"/p/models/orders.sql\",\"line\":4,\"reason\":\"ok\",\"status\":\"applied\"}],\"violations\":[{\"code\":\"SQLCLEAN004\",\"column\":8,\"end_column\":15,\"end_line\":2,\"engine\":\"native\",\"file\":\"/p/models/orders.sql\",\"line\":2,\"message\":\"Avoid LIMIT\",\"remediation\":\"Remove the LIMIT clause from the model body because the model must return every row it is expected to produce downstream.\",\"severity\":\"fault\"},{\"code\":\"description-present\",\"column\":1,\"end_column\":null,\"end_line\":null,\"engine\":\"sqlbuild\",\"file\":\"/other/x.sql\",\"line\":1,\"message\":\"Missing\",\"remediation\":null,\"severity\":\"warning\"}],\"warnings\":1}\n", }]; @@ -40,9 +40,9 @@ fn given_selectors_when_classifying_then_paths_and_models_match_python() { let test_cases = [ SelectorTestCase { description: "path selectors and backslashes become prefixes", - selectors: texts(&["path:models/staging/ tests\\unit"]), - expected_prefixes: Some(texts(&["models/staging", "tests/unit"])), - expected_partition: (texts(&["models/staging", "tests/unit"]), Vec::new()), + selectors: texts(&["path:sql/models/staging/ tests\\unit"]), + expected_prefixes: Some(texts(&["sql/models/staging", "tests/unit"])), + expected_partition: (texts(&["sql/models/staging", "tests/unit"]), Vec::new()), expected_names: None, }, SelectorTestCase { @@ -54,10 +54,10 @@ fn given_selectors_when_classifying_then_paths_and_models_match_python() { }, SelectorTestCase { description: "graph operators keep a token a model selector", - selectors: texts(&["path:models/staging +orders", "models/a.sql"]), + selectors: texts(&["path:sql/models/staging +orders", "sql/models/a.sql"]), expected_prefixes: None, expected_partition: ( - texts(&["models/staging", "models/a.sql"]), + texts(&["sql/models/staging", "sql/models/a.sql"]), texts(&["+orders"]), ), expected_names: None, diff --git a/crates/sqlbuild-core/src/git_revisions/main/is_dependency_file.rs b/crates/sqlbuild-core/src/git_revisions/main/is_dependency_file.rs new file mode 100644 index 0000000000..9998418e12 --- /dev/null +++ b/crates/sqlbuild-core/src/git_revisions/main/is_dependency_file.rs @@ -0,0 +1,9 @@ +//! `is_dependency_file`: whether a file name is a Python dependency manifest or lock file. + +use crate::git_revisions::_helpers::dependency_files; + +/// Whether `name`, such as `uv.lock` or `requirements-dev.txt`, records a project's Python dependencies. +#[must_use] +pub fn is_dependency_file(name: &str) -> bool { + dependency_files::is_dependency_file(name) +} diff --git a/crates/sqlbuild-core/src/git_revisions/main/mod.rs b/crates/sqlbuild-core/src/git_revisions/main/mod.rs index 6aa837e767..e6842ec999 100644 --- a/crates/sqlbuild-core/src/git_revisions/main/mod.rs +++ b/crates/sqlbuild-core/src/git_revisions/main/mod.rs @@ -2,6 +2,7 @@ pub mod base_dependency_files; pub mod current_dependency_files; pub mod export_git_tree; pub mod head_commit; +pub mod is_dependency_file; pub mod resolve_git_base; pub mod resolve_since_reference; pub mod short_commit; diff --git a/crates/sqlbuild-core/src/init_command/constants.rs b/crates/sqlbuild-core/src/init_command/constants.rs index 7ef28d0aa1..c662c1f524 100644 --- a/crates/sqlbuild-core/src/init_command/constants.rs +++ b/crates/sqlbuild-core/src/init_command/constants.rs @@ -2,22 +2,22 @@ /// Each resource directory, in creation order. pub const SCAFFOLD_DIRECTORIES: [&str; 16] = [ - "models/staging", - "models/marts", - "schemas", - "sources", - "seeds", - "python", - "hooks/sql", - "hooks/python", + "sql/models/staging", + "sql/models/marts", + "sql/schemas", + "sql/sources", + "sql/seeds", + "python/nodes", + "sql/hooks/sql", + "sql/hooks/python", "tests/unit", "tests/scenarios", - "functions/sql", - "functions/python", - "macros/sql", - "macros/python", - "audits/generic", - "audits/singular", + "sql/functions/sql", + "sql/functions/python", + "sql/macros/sql", + "sql/macros/python", + "sql/audits/generic", + "sql/audits/singular", ]; /// The placeholder file kept in otherwise empty directories. @@ -25,12 +25,12 @@ pub const GITKEEP_FILE: &str = ".gitkeep"; /// The numbered next steps before the compile and build commands. pub const NEXT_STEPS: [&str; 6] = [ - " 1. Add sources to sources/", - " 2. Add seeds to seeds/", - " 3. Add Python loaders, assets, checks, and factories to python/", - " 4. Add SQL hooks to hooks/sql/, Python hooks to hooks/python/, functions to functions/, or macros to macros/sql/ or macros/python/", - " 5. Add models to models/staging/ and models/marts/", - " 6. Add tests to tests/unit/ or tests/scenarios/, reusable audits to audits/generic/, or standalone audits to audits/singular/", + " 1. Add sources to sql/sources/", + " 2. Add seeds to sql/seeds/", + " 3. Add Python loaders, assets, checks, and factories to python/nodes/", + " 4. Add SQL hooks to sql/hooks/sql/, Python hooks to sql/hooks/python/, functions to sql/functions/, or macros to sql/macros/sql/ or sql/macros/python/", + " 5. Add models to sql/models/staging/ and sql/models/marts/", + " 6. Add tests to tests/unit/ or tests/scenarios/, reusable audits to sql/audits/generic/, or standalone audits to sql/audits/singular/", ]; /// The git ignore file `sqb init` and the playground add the env file to. diff --git a/crates/sqlbuild-core/src/init_command/tests/test_init_command.rs b/crates/sqlbuild-core/src/init_command/tests/test_init_command.rs index fb7d093669..43af086947 100644 --- a/crates/sqlbuild-core/src/init_command/tests/test_init_command.rs +++ b/crates/sqlbuild-core/src/init_command/tests/test_init_command.rs @@ -35,7 +35,7 @@ fn given_project_name_when_scaffolding_then_writes_config_and_summary() { description: "a plain project", project_name: "demo", expected_toml_start: "name = \"demo\"\nadapter = \"duckdb\"\ndefault_target = \"dev\"\n\n[connections.developer]\ndatabase = \"demo.duckdb\"\n", - expected_summary_start: "SQLBuild project created\n\n Project: demo\n Config: sqlbuild_project.toml\n\nNext steps:\n 1. Add sources to sources/\n", + expected_summary_start: "SQLBuild project created\n\n Project: demo\n Config: sqlbuild_project.toml\n\nNext steps:\n 1. Add sources to sql/sources/\n", }]; for test_case in test_cases { diff --git a/crates/sqlbuild-core/src/lifecycle_events/constants.rs b/crates/sqlbuild-core/src/lifecycle_events/constants.rs index 0091735078..1bef321972 100644 --- a/crates/sqlbuild-core/src/lifecycle_events/constants.rs +++ b/crates/sqlbuild-core/src/lifecycle_events/constants.rs @@ -687,7 +687,7 @@ pub(crate) const LIFECYCLE_EVENT_CATALOG_V1: [EventDefinition; 20] = [ ]; /// The schema version 2 catalogue in declaration order. -pub(crate) const LIFECYCLE_EVENT_CATALOG_V2: [EventDefinition; 23] = [ +pub(crate) const LIFECYCLE_EVENT_CATALOG_V2: [EventDefinition; 24] = [ EventDefinition { event_type: "invocation_started", required_correlations: &[], @@ -718,6 +718,13 @@ pub(crate) const LIFECYCLE_EVENT_CATALOG_V2: [EventDefinition; 23] = [ ], terminal: true, }, + EventDefinition { + event_type: "invocation_phase", + required_correlations: &[], + required_payload: &["phase"], + allowed_payload: &["count", "detail", "duration_ms", "name", "phase"], + terminal: false, + }, EventDefinition { event_type: "run_started", required_correlations: &["run_id"], diff --git a/crates/sqlbuild-core/src/scenario_command/_helpers/paths.rs b/crates/sqlbuild-core/src/scenario_command/_helpers/paths.rs index 64645fb473..69c9d94656 100644 --- a/crates/sqlbuild-core/src/scenario_command/_helpers/paths.rs +++ b/crates/sqlbuild-core/src/scenario_command/_helpers/paths.rs @@ -30,29 +30,19 @@ pub(crate) fn safe_file_stem(name: &str) -> String { name.replace(['/', '\\'], "__") } -/// A model's artifact path, always under `models/`. +/// A model's artifact path, always under `sql/models/`. pub(crate) fn model_output_path(relative_path: &Path) -> PathBuf { let path: PathBuf = normalized(relative_path); - if path - .components() - .next() - .is_some_and(|first| first.as_os_str() == MODELS_DIR) - { + if path.starts_with(MODELS_DIR) { return path; } Path::new(MODELS_DIR).join(path) } -/// A function's artifact path under `functions//`, with a `.sql` suffix. +/// A function's artifact path under `sql/functions//`, with a `.sql` suffix. pub(crate) fn function_output_path(relative_path: &Path, language: &str) -> PathBuf { let path: PathBuf = normalized(relative_path); - let mut parts = path.components(); - let under_language: bool = parts - .next() - .is_some_and(|first| first.as_os_str() == FUNCTIONS_DIR) - && parts - .next() - .is_some_and(|second| second.as_os_str() == language); + let under_language: bool = path.starts_with(Path::new(FUNCTIONS_DIR).join(language)); let mut output: PathBuf = if under_language { path } else { diff --git a/crates/sqlbuild-core/src/scenario_command/constants.rs b/crates/sqlbuild-core/src/scenario_command/constants.rs index 7fd8d20293..b94f6f1c91 100644 --- a/crates/sqlbuild-core/src/scenario_command/constants.rs +++ b/crates/sqlbuild-core/src/scenario_command/constants.rs @@ -44,10 +44,10 @@ pub(crate) const GRAPH_SELECTOR_PATH_MARKER: char = '~'; pub(crate) const SQL_EXTENSION: &str = "sql"; pub(crate) const SCENARIO_ROOT: [&str; 2] = ["tests", "scenarios"]; -pub(crate) const MODELS_DIR: &str = "models"; -pub(crate) const FUNCTIONS_DIR: &str = "functions"; +pub(crate) const MODELS_DIR: &str = crate::constants::MODELS_PATH; +pub(crate) const FUNCTIONS_DIR: &str = crate::constants::FUNCTIONS_PATH; pub(crate) const FIXTURES_DIR: &str = "fixtures"; -pub(crate) const SEEDS_DIR: &str = "seeds"; +pub(crate) const SEEDS_DIR: &str = crate::constants::SEEDS_PATH; pub(crate) const EXPECTATIONS_DIR: &str = "expectations"; pub(crate) const CLEANUP_DIR: &str = "cleanup"; diff --git a/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_rows.rs b/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_rows.rs index 76219f235a..5dfef4b357 100644 --- a/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_rows.rs +++ b/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_rows.rs @@ -249,7 +249,7 @@ fn given_warehouse_run_when_building_artifacts_then_orders_and_terminates_statem model_entries: vec![ ModelArtifactEntry { name: "orders".to_owned(), - relative_path: PathBuf::from("models/marts/orders.sql"), + relative_path: PathBuf::from("sql/models/marts/orders.sql"), }, ModelArtifactEntry { name: "staging".to_owned(), @@ -269,15 +269,15 @@ fn given_warehouse_run_when_building_artifacts_then_orders_and_terminates_statem "CREATE TABLE f AS SELECT 1;", ), ( - PathBuf::from("seeds/countries.sql"), + PathBuf::from("sql/seeds/countries.sql"), "INSERT INTO c VALUES (1);\n\n ", ), ( - PathBuf::from("models/marts/orders.sql"), + PathBuf::from("sql/models/marts/orders.sql"), "CREATE TABLE o AS SELECT 1;", ), ( - PathBuf::from("models/staging.sql"), + PathBuf::from("sql/models/staging.sql"), "CREATE VIEW s AS SELECT 1;", ), ( @@ -315,7 +315,7 @@ fn given_local_replay_when_building_artifacts_then_writes_loads_functions_and_mo }], functions: vec![ FunctionStatements { - relative_path: PathBuf::from("functions/sql/add_one.sql"), + relative_path: PathBuf::from("sql/functions/sql/add_one.sql"), language: "sql".to_owned(), statements: statements(&["CREATE MACRO add_one(x) AS x + 1"]), }, @@ -334,14 +334,14 @@ fn given_local_replay_when_building_artifacts_then_writes_loads_functions_and_mo "-- loaded from /p/tests/_scenario_snapshots/s/sources/raw_orders.jsonl\n-- rows: 2\nCREATE TABLE \"__sqb_local__source__raw_orders\" AS SELECT * FROM '/p/tests/_scenario_snapshots/s/sources/raw_orders.jsonl';", ), ( - PathBuf::from("functions/sql/add_one.sql"), + PathBuf::from("sql/functions/sql/add_one.sql"), "CREATE MACRO add_one(x) AS x + 1;", ), ( - PathBuf::from("functions/python/util/score.sql"), + PathBuf::from("sql/functions/python/util/score.sql"), "CREATE FUNCTION score();\n\nSELECT 1;", ), - (PathBuf::from("models/orders.sql"), "SELECT 1\n\n"), + (PathBuf::from("sql/models/orders.sql"), "SELECT 1\n\n"), ( PathBuf::from("expectations/expected__order_totals.sql"), "SELECT 1 EXCEPT SELECT 2", diff --git a/crates/sqlbuild-core/src/screen_text/tests/helpers.rs b/crates/sqlbuild-core/src/screen_text/tests/helpers.rs index d5be35044c..8679f2e0ed 100644 --- a/crates/sqlbuild-core/src/screen_text/tests/helpers.rs +++ b/crates/sqlbuild-core/src/screen_text/tests/helpers.rs @@ -148,7 +148,7 @@ pub(super) fn semantic_group(total: usize) -> TreeGroup { entry( "fct_revenue", &[ - ("at", "models/finance/fct_revenue.sql:42:7", Tone::Muted), + ("at", "sql/models/finance/fct_revenue.sql:42:7", Tone::Muted), ("error", "unknown column net_amount_usd", Tone::Error), ], ), @@ -160,7 +160,7 @@ pub(super) fn semantic_group(total: usize) -> TreeGroup { /// Every row any renderer draws at `facts`, with whether it is live (cut) rather than lasting (wrapped). pub(super) fn every_row(facts: &ScreenFacts) -> Vec<(bool, String)> { - let long: &str = "Python nodes 287/412 \u{b7} models/marts/finance/fct_revenue_by_region.sql \ + let long: &str = "Python nodes 287/412 \u{b7} sql/models/marts/finance/fct_revenue_by_region.sql \ \u{b7} a_very_long_identifier_without_any_spaces_in_it_at_all_whatsoever"; let mut rows: Vec<(bool, String)> = Vec::new(); for state in [ diff --git a/crates/sqlbuild-core/src/screen_text/tests/test_screen_text.rs b/crates/sqlbuild-core/src/screen_text/tests/test_screen_text.rs index ba6d972ec4..0043d5a2c9 100644 --- a/crates/sqlbuild-core/src/screen_text/tests/test_screen_text.rs +++ b/crates/sqlbuild-core/src/screen_text/tests/test_screen_text.rs @@ -487,7 +487,7 @@ fn given_tree_group_when_rendering_then_rows_are_bounded_with_overflow_line() { "\u{2502} \u{251c}\u{2500}\u{2500} reason reads open input orders__mart__fulfilment_monitoring", "\u{2502} \u{2514}\u{2500}\u{2500} fix declare the input shape, then sqb compile --no-cache", "\u{251c}\u{2500}\u{2500} fct_revenue", - "\u{2502} \u{251c}\u{2500}\u{2500} at models/finance/fct_revenue.sql:42:7", + "\u{2502} \u{251c}\u{2500}\u{2500} at sql/models/finance/fct_revenue.sql:42:7", "\u{2502} \u{2514}\u{2500}\u{2500} error unknown column net_amount_usd", "\u{2514}\u{2500}\u{2500} \u{2026} 3 more (--verbose)", ], @@ -502,7 +502,7 @@ fn given_tree_group_when_rendering_then_rows_are_bounded_with_overflow_line() { "\u{2502} \u{251c}\u{2500}\u{2500} reason reads open input orders__mart__fulfilment_m\u{2026}", "\u{2502} \u{2514}\u{2500}\u{2500} fix declare the input shape, then sqb compile -\u{2026}", "\u{2514}\u{2500}\u{2500} fct_revenue", - " \u{251c}\u{2500}\u{2500} at models/finance/fct_revenue.sql:42:7", + " \u{251c}\u{2500}\u{2500} at sql/models/finance/fct_revenue.sql:42:7", " \u{2514}\u{2500}\u{2500} error unknown column net_amount_usd", ], }, diff --git a/crates/sqlbuild-discovery/Cargo.toml b/crates/sqlbuild-discovery/Cargo.toml index 5ca9425e61..57e771b29a 100644 --- a/crates/sqlbuild-discovery/Cargo.toml +++ b/crates/sqlbuild-discovery/Cargo.toml @@ -11,6 +11,7 @@ rust-version.workspace = true rayon.workspace = true serde.workspace = true serde_json.workspace = true +ignore.workspace = true sqlbuild-cache.workspace = true sqlbuild-config.workspace = true sqlbuild-core.workspace = true diff --git a/crates/sqlbuild-discovery/src/constants.rs b/crates/sqlbuild-discovery/src/constants.rs index 5991fd2adb..76b4c48760 100644 --- a/crates/sqlbuild-discovery/src/constants.rs +++ b/crates/sqlbuild-discovery/src/constants.rs @@ -1,7 +1,7 @@ //! Project layout names shared by native discovery. /// Root of SQL model files. -pub const MODELS_DIRECTORY: &str = "models"; +pub const MODELS_DIRECTORY: &str = sqlbuild_core::constants::MODELS_PATH; /// Root of code-location orchestration declarations, never imported by the scheduler. pub const ORCHESTRATION_DIRECTORY: &str = "orchestration"; /// Suffix of SQL files. @@ -19,11 +19,11 @@ pub const SCOPED_DECLARATION_DIRECTORIES: [&str; 6] = [ ]; /// Resource trees that may hold scoped declarations, in Python's lookup order. pub const CANONICAL_AUTHORED_ROOTS: [&[&str]; 5] = [ - &["models"], + &["sql", "models"], &["tests", "unit"], &["tests", "scenarios"], - &["functions", "sql"], - &["sources"], + &["sql", "functions", "sql"], + &["sql", "sources"], ]; /// The SQL test root, whose `macros/` SQL files are tests rather than declarations. pub const SQL_TESTS_ROOT: &[&str] = &["tests", "unit"]; @@ -33,6 +33,8 @@ pub const SQL_SCENARIOS_ROOT: &str = "tests/scenarios"; pub const MACRO_TESTS_DIRECTORY: &str = "macros"; /// Inherited declaration directories, which may also be project-wide global roots. pub const GLOBAL_DECLARATION_DIRECTORIES: [&str; 3] = ["macros", "enums", "constants"]; +/// The project folder holding the project-wide declaration and named roles. +pub const GLOBAL_ROLE_PARENT: &str = sqlbuild_core::constants::SQL_DIRECTORY; /// Folder-local declaration directories. pub const LOCAL_DECLARATION_DIRECTORIES: [&str; 3] = ["_macros", "_enums", "_constants"]; /// Directories a declaration group may hold for named declarations. @@ -49,6 +51,8 @@ pub const PYTHON_MACROS_DIRECTORY: &str = "python"; pub const SQL_MACROS_DIRECTORY: &str = "sql"; /// The project-wide audit role directory. pub const AUDIT_ROLE_DIRECTORY: &str = "audits"; +/// The project-wide audit role folder. +pub const AUDIT_ROLE_PATH: &str = sqlbuild_core::constants::AUDITS_PATH; /// The folder-local audit role directory inside a declaration group. pub const LOCAL_AUDIT_ROLE_DIRECTORY: &str = "_audits"; /// The singular audit directory below an audit role. diff --git a/crates/sqlbuild-discovery/src/declaration_files/_helpers/listing/collections.rs b/crates/sqlbuild-discovery/src/declaration_files/_helpers/listing/collections.rs index 704c80284e..9badf73c2e 100644 --- a/crates/sqlbuild-discovery/src/declaration_files/_helpers/listing/collections.rs +++ b/crates/sqlbuild-discovery/src/declaration_files/_helpers/listing/collections.rs @@ -51,11 +51,11 @@ impl NamedKind { /// `GLOBAL_NAMED_DECLARATION_ROOTS`, in Python's dict order. const GLOBAL_NAMED_ROOTS: [(&str, NamedKind); 5] = [ - ("audits/generic", NamedKind::Audit), - ("audits/singular", NamedKind::SingularAudit), - ("schemas", NamedKind::Schema), - ("hooks/sql", NamedKind::SqlHook), - ("hooks/python", NamedKind::PythonHook), + ("sql/audits/generic", NamedKind::Audit), + ("sql/audits/singular", NamedKind::SingularAudit), + ("sql/schemas", NamedKind::Schema), + ("sql/hooks/sql", NamedKind::SqlHook), + ("sql/hooks/python", NamedKind::PythonHook), ]; /// `GROUPED_NAMED_DECLARATION_ROLES`, in Python's dict order. @@ -71,8 +71,8 @@ const GROUPED_NAMED_ROLES: [(&str, NamedKind, &str); 9] = [ ("_hooks/python", NamedKind::PythonHook, "local"), ]; -const FUNCTIONS_ROOT: &str = "functions/sql"; -const SEEDS_ROOT: &str = "seeds"; +const FUNCTIONS_ROOT: &str = "sql/functions/sql"; +const SEEDS_ROOT: &str = sqlbuild_core::constants::SEEDS_PATH; const SEED_FILE_SUFFIX: &str = ".csv"; /// The macro, enum or constant files of `kind`, from the whole layout or `kind`'s alone. diff --git a/crates/sqlbuild-discovery/src/declaration_files/constants.rs b/crates/sqlbuild-discovery/src/declaration_files/constants.rs index 769949697b..a1fedf71ef 100644 --- a/crates/sqlbuild-discovery/src/declaration_files/constants.rs +++ b/crates/sqlbuild-discovery/src/declaration_files/constants.rs @@ -1,6 +1,6 @@ //! Directories and names Python module discovery lists. /// The directory whose `*.py` files define warehouse Python functions. -pub const PYTHON_FUNCTIONS_ROOT: &str = "functions/python"; +pub const PYTHON_FUNCTIONS_ROOT: &str = "sql/functions/python"; /// The prefix of a path part that keeps a module out of public module discovery. pub const PRIVATE_PREFIX: char = '_'; diff --git a/crates/sqlbuild-discovery/src/declaration_files/tests/test_discovery_session.rs b/crates/sqlbuild-discovery/src/declaration_files/tests/test_discovery_session.rs index 3258dd0e12..acf44365e3 100644 --- a/crates/sqlbuild-discovery/src/declaration_files/tests/test_discovery_session.rs +++ b/crates/sqlbuild-discovery/src/declaration_files/tests/test_discovery_session.rs @@ -4,20 +4,20 @@ use crate::declaration_files::tests::test_types::SessionReadTestCase; const FILES: &[(&str, &str)] = &[ ( - "enums/status.sql", + "sql/enums/status.sql", "ENUM (name order_status, members [PLACED]);\n", ), ( - "constants/limits.sql", + "sql/constants/limits.sql", "CONSTANT (name max_orders, value 10);\n", ), ( - "macros/python/cents.py", + "sql/macros/python/cents.py", "def cents(value):\n return value\n", ), - ("schemas/orders.sql", "SCHEMA (name orders_shape);\n"), + ("sql/schemas/orders.sql", "SCHEMA (name orders_shape);\n"), ( - "audits/generic/positive.sql", + "sql/audits/generic/positive.sql", "AUDIT (name positive);\nSELECT 1\n", ), ]; diff --git a/crates/sqlbuild-discovery/src/declarations/_helpers/declaration_groups.rs b/crates/sqlbuild-discovery/src/declarations/_helpers/declaration_groups.rs index eadeaabf5b..09b630022d 100644 --- a/crates/sqlbuild-discovery/src/declarations/_helpers/declaration_groups.rs +++ b/crates/sqlbuild-discovery/src/declarations/_helpers/declaration_groups.rs @@ -54,8 +54,8 @@ pub(crate) fn validate_declaration_groups(tree: &ProjectTree) -> Result<(), Scan if parent(&group.directory) == group.root { return Err(declaration_failure(format!( "Grouped declaration root {}/ must be below a concrete owner directory; use the \ - project-wide macros/, enums/, constants/, audits/, schemas/, or hooks/ root \ - instead", + project-wide sql/macros/, sql/enums/, sql/constants/, sql/audits/, sql/schemas/, \ + or sql/hooks/ root instead", shown(&group.directory) ))); } diff --git a/crates/sqlbuild-discovery/src/declarations/_helpers/declaration_tree.rs b/crates/sqlbuild-discovery/src/declarations/_helpers/declaration_tree.rs index 78c9ec4059..b3a7968495 100644 --- a/crates/sqlbuild-discovery/src/declarations/_helpers/declaration_tree.rs +++ b/crates/sqlbuild-discovery/src/declarations/_helpers/declaration_tree.rs @@ -2,11 +2,11 @@ use crate::constants::{ CANONICAL_AUTHORED_ROOTS, DECLARATION_GROUP_DIRECTORY, GLOBAL_DECLARATION_DIRECTORIES, - LOCAL_DECLARATION_DIRECTORIES, PYTHON_FILE_SUFFIX, PYTHON_MACROS_DIRECTORY, + GLOBAL_ROLE_PARENT, LOCAL_DECLARATION_DIRECTORIES, PYTHON_FILE_SUFFIX, PYTHON_MACROS_DIRECTORY, SCOPED_DECLARATION_DIRECTORIES, SQL_FILE_SUFFIX, SQL_MACROS_DIRECTORY, }; use crate::declarations::_helpers::declaration_groups::validate_declaration_groups; -use crate::declarations::_helpers::paths::{directory_facts, name, parent, stem}; +use crate::declarations::_helpers::paths::{directory_facts, join, name, parent, stem}; use crate::declarations::_helpers::scan::{declaration_failure, shown}; use crate::declarations::errors::ScanError; use crate::declarations::models::{DeclarationFileFact, DeclarationKind, ScopeKind}; @@ -46,13 +46,14 @@ pub(crate) fn declaration_file_facts( let mut facts: Vec = Vec::new(); let mut global: Vec<&str> = GLOBAL_DECLARATION_DIRECTORIES.to_vec(); global.sort_unstable(); - for directory in global { - if is_kind(kind, directory) && tree.is_dir(directory) { + for name in global { + let directory: String = join(GLOBAL_ROLE_PARENT, name); + if is_kind(kind, name) && tree.is_dir(&directory) { facts.extend(files_under_root( tree, &DeclarationRoot { - ownership_root: directory, - directory, + ownership_root: &directory, + directory: &directory, owning_path: None, scope_kind: ScopeKind::Global, }, diff --git a/crates/sqlbuild-discovery/src/declarations/_helpers/named_layout.rs b/crates/sqlbuild-discovery/src/declarations/_helpers/named_layout.rs index 323ef60e00..e2721f0bb0 100644 --- a/crates/sqlbuild-discovery/src/declarations/_helpers/named_layout.rs +++ b/crates/sqlbuild-discovery/src/declarations/_helpers/named_layout.rs @@ -1,9 +1,9 @@ //! Validate where named declaration roots may appear in the project layout. use crate::constants::{ - AUDIT_ROLE_DIRECTORY, DECLARATION_GROUP_DIRECTORY, GLOBAL_DECLARATION_DIRECTORIES, - GLOBAL_NAMED_DECLARATION_DIRECTORIES, LOCAL_AUDIT_ROLE_DIRECTORY, - LOCAL_DECLARATION_DIRECTORIES, SINGULAR_AUDIT_DIRECTORY, + AUDIT_ROLE_DIRECTORY, AUDIT_ROLE_PATH, DECLARATION_GROUP_DIRECTORY, + GLOBAL_DECLARATION_DIRECTORIES, GLOBAL_NAMED_DECLARATION_DIRECTORIES, GLOBAL_ROLE_PARENT, + LOCAL_AUDIT_ROLE_DIRECTORY, LOCAL_DECLARATION_DIRECTORIES, SINGULAR_AUDIT_DIRECTORY, }; use crate::declarations::_helpers::declaration_groups::owned_groups; use crate::declarations::_helpers::paths::{join, name}; @@ -29,23 +29,24 @@ struct RoleChildren<'a> { pub(crate) fn named_declaration_groups( tree: &ProjectTree, ) -> Result, ScanError> { - if tree.is_dir(AUDIT_ROLE_DIRECTORY) { + if tree.is_dir(AUDIT_ROLE_PATH) { require_role_children( tree, &RoleChildren { - directory: AUDIT_ROLE_DIRECTORY, + directory: AUDIT_ROLE_PATH, allowed: AUDIT_ROLES, - help_text: "audit files must live in audits/generic/ or audits/singular/", + help_text: "audit files must live in sql/audits/generic/ or sql/audits/singular/", }, )?; } let mut top_levels: Vec<&str> = GLOBAL_NAMED_DECLARATION_DIRECTORIES.to_vec(); top_levels.sort_unstable(); - for top_level in top_levels { - if !tree.is_dir(top_level) { + for name_of_role in top_levels { + let top_level: String = join(GLOBAL_ROLE_PARENT, name_of_role); + if !tree.is_dir(&top_level) { continue; } - if let Some(nested) = directories(tree, top_level)? + if let Some(nested) = directories(tree, &top_level)? .into_iter() .find(|directory| is_nested_role_directory(name(directory))) { diff --git a/crates/sqlbuild-discovery/src/declarations/tests/test_declaration_layout.rs b/crates/sqlbuild-discovery/src/declarations/tests/test_declaration_layout.rs index 168118888f..30bd500094 100644 --- a/crates/sqlbuild-discovery/src/declarations/tests/test_declaration_layout.rs +++ b/crates/sqlbuild-discovery/src/declarations/tests/test_declaration_layout.rs @@ -9,77 +9,84 @@ fn given_declaration_layouts_when_scanning_then_facts_and_failures_match_python( kind: None, description: "global, inherited, grouped and local roots sort by relative path", files: &[ - "macros/python/text.py", - "macros/python/__init__.py", - "macros/__init__.py", - "macros/sql/totals.sql", - "enums/status.sql", - "models/marts/_enums/local.sql", - "models/marts/_sqlbuild/constants/limits.sql", - "models/marts/_sqlbuild/audits/generic/positive.sql", + "sql/macros/python/text.py", + "sql/macros/python/__init__.py", + "sql/macros/__init__.py", + "sql/macros/sql/totals.sql", + "sql/enums/status.sql", + "sql/models/marts/_enums/local.sql", + "sql/models/marts/_sqlbuild/constants/limits.sql", + "sql/models/marts/_sqlbuild/audits/generic/positive.sql", ], directories: &[], expected_facts: Ok(&[ - ("enums/status.sql", "enum", "global", "enums", None, "enums"), ( - "macros/python/text.py", + "sql/enums/status.sql", + "enum", + "global", + "sql/enums", + None, + "sql/enums", + ), + ( + "sql/macros/python/text.py", "macro", "global", - "macros", + "sql/macros", None, - "macros", + "sql/macros", ), ( - "macros/sql/totals.sql", + "sql/macros/sql/totals.sql", "macro", "global", - "macros", + "sql/macros", None, - "macros", + "sql/macros", ), ( - "models/marts/_enums/local.sql", + "sql/models/marts/_enums/local.sql", "enum", "local", - "models", - Some("models/marts"), - "models/marts/_enums", + "sql/models", + Some("sql/models/marts"), + "sql/models/marts/_enums", ), ( - "models/marts/_sqlbuild/constants/limits.sql", + "sql/models/marts/_sqlbuild/constants/limits.sql", "constant", "inherited", - "models", - Some("models/marts"), - "models/marts/_sqlbuild/constants", + "sql/models", + Some("sql/models/marts"), + "sql/models/marts/_sqlbuild/constants", ), ]), - expected_groups: Ok(&[("models", "models/marts/_sqlbuild")]), + expected_groups: Ok(&[("sql/models", "sql/models/marts/_sqlbuild")]), }, LayoutTestCase { kind: None, description: "a declaration group directly below a canonical root fails", - files: &["models/_sqlbuild/macros/text.py"], + files: &["sql/models/_sqlbuild/macros/text.py"], directories: &[], expected_facts: Err( - "Grouped declaration root models/_sqlbuild/ must be below a concrete owner \ - directory; use the project-wide macros/, enums/, constants/, audits/, \ - schemas/, or hooks/ root instead", + "Grouped declaration root sql/models/_sqlbuild/ must be below a concrete owner \ + directory; use the project-wide sql/macros/, sql/enums/, sql/constants/, sql/audits/, \ + sql/schemas/, or sql/hooks/ root instead", ), expected_groups: Ok(&[]), }, LayoutTestCase { kind: None, description: "a nested declaration root fails in both scans", - files: &["models/a/_enums/macros/x.py"], - directories: &["schemas/enums"], + files: &["sql/models/a/_enums/macros/x.py"], + directories: &["sql/schemas/enums"], expected_facts: Err( - "Declaration root models/a/_enums/macros/ is nested inside another declaration \ + "Declaration root sql/models/a/_enums/macros/ is nested inside another declaration \ tree", ), expected_groups: Err( - "Declaration directory schemas/enums/ is not allowed inside the project-wide \ - schemas/ role; scoped declarations belong under /_sqlbuild/ below a \ + "Declaration directory sql/schemas/enums/ is not allowed inside the project-wide \ + sql/schemas/ role; scoped declarations belong under /_sqlbuild/ below a \ resource tree", ), }, @@ -87,18 +94,18 @@ fn given_declaration_layouts_when_scanning_then_facts_and_failures_match_python( kind: None, description: "unsupported group and role entries list every entry", files: &[ - "models/a/_sqlbuild/notes.txt", - "audits/x.sql", - "audits/.keep", + "sql/models/a/_sqlbuild/notes.txt", + "sql/audits/x.sql", + "sql/audits/.keep", ], - directories: &["models/a/_sqlbuild/extra"], + directories: &["sql/models/a/_sqlbuild/extra"], expected_facts: Err( - "Declaration group models/a/_sqlbuild/ contains unsupported entries: \ - models/a/_sqlbuild/extra, models/a/_sqlbuild/notes.txt", + "Declaration group sql/models/a/_sqlbuild/ contains unsupported entries: \ + sql/models/a/_sqlbuild/extra, sql/models/a/_sqlbuild/notes.txt", ), expected_groups: Err( - "Unsupported entries in audits/: audits/x.sql; audit files must live in \ - audits/generic/ or audits/singular/", + "Unsupported entries in sql/audits/: sql/audits/x.sql; audit files must live in \ + sql/audits/generic/ or sql/audits/singular/", ), }, LayoutTestCase { @@ -106,12 +113,12 @@ fn given_declaration_layouts_when_scanning_then_facts_and_failures_match_python( description: "local singular audits and unknown hook roles fail the named layout", files: &[], directories: &[ - "models/a/_sqlbuild/_audits/singular", - "models/b/_sqlbuild/hooks/x", + "sql/models/a/_sqlbuild/_audits/singular", + "sql/models/b/_sqlbuild/hooks/x", ], expected_facts: Ok(&[]), expected_groups: Err( - "models/a/_sqlbuild/_audits/singular/ is invalid: singular audits are never used \ + "sql/models/a/_sqlbuild/_audits/singular/ is invalid: singular audits are never used \ by name, so folder-only visibility has no meaning; use \ _sqlbuild/audits/singular/", ), @@ -119,23 +126,23 @@ fn given_declaration_layouts_when_scanning_then_facts_and_failures_match_python( LayoutTestCase { kind: None, description: "a macro file directly below a macro root names its kind folder", - files: &["models/marts/_sqlbuild/_macros/text.py"], + files: &["sql/models/marts/_sqlbuild/_macros/text.py"], directories: &[], expected_facts: Err( - "macro file models/marts/_sqlbuild/_macros/text.py must live in \ - models/marts/_sqlbuild/_macros/python/ or models/marts/_sqlbuild/_macros/sql/\n \ - --> models/marts/_sqlbuild/_macros/text.py", + "macro file sql/models/marts/_sqlbuild/_macros/text.py must live in \ + sql/models/marts/_sqlbuild/_macros/python/ or sql/models/marts/_sqlbuild/_macros/sql/\n \ + --> sql/models/marts/_sqlbuild/_macros/text.py", ), - expected_groups: Ok(&[("models", "models/marts/_sqlbuild")]), + expected_groups: Ok(&[("sql/models", "sql/models/marts/_sqlbuild")]), }, LayoutTestCase { kind: None, description: "a macro file in the other kind folder fails", - files: &["macros/python/totals.sql"], + files: &["sql/macros/python/totals.sql"], directories: &[], expected_facts: Err( - "macro file macros/python/totals.sql must live in macros/python/ or \ - macros/sql/\n --> macros/python/totals.sql", + "macro file sql/macros/python/totals.sql must live in sql/macros/python/ or \ + sql/macros/sql/\n --> sql/macros/python/totals.sql", ), expected_groups: Ok(&[]), }, @@ -154,20 +161,27 @@ fn given_declaration_layouts_when_scanning_then_facts_and_failures_match_python( description: "an isolated kind skips the misplaced roots of other kinds", files: &[ "_macros/text.py", - "enums/status.sql", - "models/a/macros/x.py", + "sql/enums/status.sql", + "sql/models/a/macros/x.py", ], directories: &[], - expected_facts: Ok(&[("enums/status.sql", "enum", "global", "enums", None, "enums")]), + expected_facts: Ok(&[( + "sql/enums/status.sql", + "enum", + "global", + "sql/enums", + None, + "sql/enums", + )]), expected_groups: Ok(&[]), }, LayoutTestCase { kind: Some(DeclarationKind::Constant), description: "an isolated kind still rejects a root nested in its own tree", - files: &["models/a/constants/_enums/x.sql"], + files: &["sql/models/a/constants/_enums/x.sql"], directories: &[], expected_facts: Err( - "Declaration root models/a/constants/_enums/ is nested inside another \ + "Declaration root sql/models/a/constants/_enums/ is nested inside another \ declaration tree", ), expected_groups: Ok(&[]), diff --git a/crates/sqlbuild-discovery/src/header_changes/tests/helpers.rs b/crates/sqlbuild-discovery/src/header_changes/tests/helpers.rs index a3b65c38e5..1c58d859f5 100644 --- a/crates/sqlbuild-discovery/src/header_changes/tests/helpers.rs +++ b/crates/sqlbuild-discovery/src/header_changes/tests/helpers.rs @@ -7,7 +7,7 @@ use crate::header_changes::tests::test_types::HeaderChangeTestCase; use crate::model_files::main::model_file_options::model_file_options; use crate::model_files::main::parse_model_text::parse_model_text; -const RELATIVE_PATH: &str = "models/orders.sql"; +const RELATIVE_PATH: &str = "sql/models/orders.sql"; const UPSTREAM: [(&str, &str); 1] = [("model", "customers")]; /// The change of a recorded model after its file is rewritten, or deleted when none is given. diff --git a/crates/sqlbuild-discovery/src/header_changes/tests/test_custom_rule_reads.rs b/crates/sqlbuild-discovery/src/header_changes/tests/test_custom_rule_reads.rs index 4b3a805e39..84558e2bc5 100644 --- a/crates/sqlbuild-discovery/src/header_changes/tests/test_custom_rule_reads.rs +++ b/crates/sqlbuild-discovery/src/header_changes/tests/test_custom_rule_reads.rs @@ -13,7 +13,7 @@ fn given_custom_rule_facts_when_a_header_changes_then_reads_of_changed_keys_are_ }, CustomRuleReadsTestCase { description: "a model's enum column types are decided by its columns", - fact_key: vec!["columns.enum_types", "models/orders.sql"], + fact_key: vec!["columns.enum_types", "sql/models/orders.sql"], changed: vec!["columns"], expected_reason: Some("a custom rule reads orders's columns"), }, @@ -25,7 +25,7 @@ fn given_custom_rule_facts_when_a_header_changes_then_reads_of_changed_keys_are_ }, CustomRuleReadsTestCase { description: "a fact no changed key decides is ignored", - fact_key: vec!["materialized", "models/orders.sql"], + fact_key: vec!["materialized", "sql/models/orders.sql"], changed: vec!["description"], expected_reason: None, }, @@ -42,7 +42,7 @@ fn given_custom_rule_facts_when_a_header_changes_then_reads_of_changed_keys_are_ assert_eq!( custom_rule_reads( &facts, - ("models/orders.sql", "orders"), + ("sql/models/orders.sql", "orders"), &keys(&test_case.changed) ) .as_deref(), diff --git a/crates/sqlbuild-discovery/src/header_changes/tests/test_header_change.rs b/crates/sqlbuild-discovery/src/header_changes/tests/test_header_change.rs index a919ad92fd..b7263c6e09 100644 --- a/crates/sqlbuild-discovery/src/header_changes/tests/test_header_change.rs +++ b/crates/sqlbuild-discovery/src/header_changes/tests/test_header_change.rs @@ -14,7 +14,7 @@ fn given_an_edited_model_header_when_compared_then_the_change_is_classified() { edited_contents: Some(STORED), recorded: false, expected_change: HeaderChange::Unsupported( - "models/orders.sql has no recorded header".to_owned(), + "sql/models/orders.sql has no recorded header".to_owned(), ), }, HeaderChangeTestCase { @@ -48,7 +48,8 @@ fn given_an_edited_model_header_when_compared_then_the_change_is_classified() { ), recorded: true, expected_change: HeaderChange::Unsupported( - "models/orders.sql changed its materialization beyond views and tables".to_owned(), + "sql/models/orders.sql changed its materialization beyond views and tables" + .to_owned(), ), }, HeaderChangeTestCase { @@ -59,7 +60,7 @@ fn given_an_edited_model_header_when_compared_then_the_change_is_classified() { ), recorded: true, expected_change: HeaderChange::Unsupported( - "models/orders.sql changed its unique_key header key".to_owned(), + "sql/models/orders.sql changed its unique_key header key".to_owned(), ), }, HeaderChangeTestCase { @@ -70,7 +71,7 @@ fn given_an_edited_model_header_when_compared_then_the_change_is_classified() { ), recorded: true, expected_change: HeaderChange::Unsupported( - "models/orders.sql changed what it references".to_owned(), + "sql/models/orders.sql changed what it references".to_owned(), ), }, ]; diff --git a/crates/sqlbuild-discovery/src/lib.rs b/crates/sqlbuild-discovery/src/lib.rs index 8bb9b900a0..6d045a4369 100644 --- a/crates/sqlbuild-discovery/src/lib.rs +++ b/crates/sqlbuild-discovery/src/lib.rs @@ -10,7 +10,9 @@ pub mod header_changes; pub mod key_checks; pub mod model_files; pub mod models; +pub mod node_files; pub mod orchestration_files; +pub mod project_layout; pub mod project_validation; pub mod python_paths; pub mod sql_tests; diff --git a/crates/sqlbuild-discovery/src/model_files/tests/helpers.rs b/crates/sqlbuild-discovery/src/model_files/tests/helpers.rs index 084d8f1953..4a9b947b70 100644 --- a/crates/sqlbuild-discovery/src/model_files/tests/helpers.rs +++ b/crates/sqlbuild-discovery/src/model_files/tests/helpers.rs @@ -86,7 +86,7 @@ pub(super) fn failed(message: &str, help: Option<&str>) -> ModelSummary { pub(super) fn parsed_header_facts(contents: &str) -> HeaderFacts { let model: DiscoveredModelFile = parse_model_text(FILE_PATH, contents.to_owned(), &options()) .unwrap_or_else(|failure| panic!("{}", failure.message)); - header_facts(&model.header_values, "models/orders.sql") + header_facts(&model.header_values, "sql/models/orders.sql") } fn macro_path(path: &MacroPath) -> Option> { diff --git a/crates/sqlbuild-discovery/src/model_files/tests/test_model_file_stem.rs b/crates/sqlbuild-discovery/src/model_files/tests/test_model_file_stem.rs index aae2d1b2c2..ff00880d2f 100644 --- a/crates/sqlbuild-discovery/src/model_files/tests/test_model_file_stem.rs +++ b/crates/sqlbuild-discovery/src/model_files/tests/test_model_file_stem.rs @@ -6,17 +6,17 @@ fn given_relative_paths_when_naming_models_then_stems_match_python() { let test_cases = [ ModelFileStemTestCase { description: "a final suffix is dropped", - relative_path: "models/orders.sql", + relative_path: "sql/models/orders.sql", expected_stem: "orders", }, ModelFileStemTestCase { description: "only the last suffix is dropped", - relative_path: "models/marts/orders.v2.sql", + relative_path: "sql/models/marts/orders.v2.sql", expected_stem: "orders.v2", }, ModelFileStemTestCase { description: "a leading dot is not a suffix", - relative_path: "models/.hidden", + relative_path: "sql/models/.hidden", expected_stem: ".hidden", }, ModelFileStemTestCase { diff --git a/crates/sqlbuild-discovery/src/node_files/_helpers/mod.rs b/crates/sqlbuild-discovery/src/node_files/_helpers/mod.rs new file mode 100644 index 0000000000..18396bb147 --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/_helpers/mod.rs @@ -0,0 +1 @@ +pub(crate) mod problems; diff --git a/crates/sqlbuild-discovery/src/node_files/_helpers/problems.rs b/crates/sqlbuild-discovery/src/node_files/_helpers/problems.rs new file mode 100644 index 0000000000..547477a824 --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/_helpers/problems.rs @@ -0,0 +1,92 @@ +//! Where one module declares its nodes, and which declaration files share a unit folder. + +use std::collections::BTreeMap; + +use crate::node_files::constants::{ + CHECKS_FILE, KIND_FILES, MIXED_FACTORY_FILE, SINGLE_NODE_FILES, +}; +use crate::node_files::models::{KindFiles, NodeModule}; + +/// The first file-name problem of one module, if any. +pub(crate) fn module_problem(module: &NodeModule) -> Option { + let path: &str = &module.relative_path; + let file: &str = path.rsplit('/').next().unwrap_or(path); + for (name, kind) in &module.direct { + let expected: &str = files(kind).direct; + if file != expected { + return Some(format!( + "@{kind} '{name}' is declared in {path}; an @{kind} is declared in {expected}" + )); + } + } + for (name, kinds) in &module.factories { + let (expected, made): (&str, String) = match kinds.as_slice() { + [] => continue, + [kind] => (files(kind).factory, format!("only {}", files(kind).plural)), + _ => ( + MIXED_FACTORY_FILE, + kinds + .iter() + .map(|kind| files(kind).plural) + .collect::>() + .join(" and "), + ), + }; + if file != expected { + let rule: String = if kinds.len() == 1 { + format!("a factory that makes {made} is declared in {expected}") + } else { + format!("a factory that makes more than one kind is declared in {expected}") + }; + return Some(format!("@factory '{name}' in {path} makes {made}; {rule}")); + } + } + if SINGLE_NODE_FILES.contains(&file) && module.direct.len() > 1 { + let names: Vec<&str> = module + .direct + .iter() + .map(|(name, _)| name.as_str()) + .collect(); + return Some(format!( + "{path} declares {} nodes ({}); {file} declares exactly one, so give each its own \ + unit folder or use a factory", + names.len(), + names.join(", ") + )); + } + None +} + +/// Two node declaration files in one unit folder; `checks.py` may sit beside one. +pub(crate) fn unit_folder_problem(modules: &[NodeModule]) -> Option { + let mut folders: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); + for module in modules { + if module.direct.is_empty() && module.factories.iter().all(|(_, kinds)| kinds.is_empty()) { + continue; + } + let (folder, file) = module + .relative_path + .rsplit_once('/') + .unwrap_or(("", module.relative_path.as_str())); + if file != CHECKS_FILE { + folders.entry(folder).or_default().push(file); + } + } + folders + .into_iter() + .find(|(_, files)| files.len() > 1) + .map(|(folder, files)| { + format!( + "{folder}/ holds {}; a unit folder holds one node declaration file, plus checks.py", + files.join(" and ") + ) + }) +} + +/// The files of `kind`; every kind discovery reports is in the table. +fn files(kind: &str) -> KindFiles { + KIND_FILES + .into_iter() + .find(|files| files.kind == kind) + .unwrap_or(KIND_FILES[0]) +} diff --git a/crates/sqlbuild-discovery/src/node_files/constants.rs b/crates/sqlbuild-discovery/src/node_files/constants.rs new file mode 100644 index 0000000000..f2130d3349 --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/constants.rs @@ -0,0 +1,31 @@ +//! The file each Python node declaration belongs in. + +use crate::node_files::models::KindFiles; + +/// Where each kind of node is declared, directly or by a factory of that kind only. +pub(crate) const KIND_FILES: [KindFiles; 3] = [ + KindFiles { + kind: "loader", + direct: "loader.py", + factory: "loaders.py", + plural: "loaders", + }, + KindFiles { + kind: "asset", + direct: "asset.py", + factory: "assets.py", + plural: "assets", + }, + KindFiles { + kind: "check", + direct: "checks.py", + factory: "checks.py", + plural: "checks", + }, +]; +/// The file of a factory that makes nodes of more than one kind. +pub(crate) const MIXED_FACTORY_FILE: &str = "factory.py"; +/// Declaration files that hold exactly one node. +pub(crate) const SINGLE_NODE_FILES: [&str; 2] = ["loader.py", "asset.py"]; +/// The file of a unit's checks, which may sit beside its node declaration file. +pub(crate) const CHECKS_FILE: &str = "checks.py"; diff --git a/crates/sqlbuild-discovery/src/node_files/main/mod.rs b/crates/sqlbuild-discovery/src/node_files/main/mod.rs new file mode 100644 index 0000000000..99f168a5f4 --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/main/mod.rs @@ -0,0 +1 @@ +pub mod node_file_problems; diff --git a/crates/sqlbuild-discovery/src/node_files/main/node_file_problems.rs b/crates/sqlbuild-discovery/src/node_files/main/node_file_problems.rs new file mode 100644 index 0000000000..946da62eef --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/main/node_file_problems.rs @@ -0,0 +1,15 @@ +//! Python node files named after what they declare, one declaration file per unit folder. + +use crate::node_files::_helpers::problems::{module_problem, unit_folder_problem}; +use crate::node_files::models::NodeModule; + +/// The first problem with where `modules` declare their nodes, as a message, if any. +#[must_use] +pub fn node_file_problems(modules: &[NodeModule]) -> Option { + for module in modules { + if let Some(problem) = module_problem(module) { + return Some(problem); + } + } + unit_folder_problem(modules) +} diff --git a/crates/sqlbuild-discovery/src/node_files/mod.rs b/crates/sqlbuild-discovery/src/node_files/mod.rs new file mode 100644 index 0000000000..1e64f3d116 --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/mod.rs @@ -0,0 +1,7 @@ +pub(crate) mod _helpers; +pub(crate) mod constants; +pub mod main; +pub mod models; + +#[cfg(test)] +mod tests; diff --git a/crates/sqlbuild-discovery/src/node_files/models.rs b/crates/sqlbuild-discovery/src/node_files/models.rs new file mode 100644 index 0000000000..7f84a21d7c --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/models.rs @@ -0,0 +1,23 @@ +//! What one imported `python/nodes/` module declares. + +/// The nodes one module declares directly and through its factories. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NodeModule { + /// The project-relative path, `/`-separated. + pub relative_path: String, + /// Each decorated node's name and kind (`loader`, `asset` or `check`). + pub direct: Vec<(String, &'static str)>, + /// Each factory's name and the kinds of the nodes it returned, without repeats. + pub factories: Vec<(String, Vec<&'static str>)>, +} + +/// The files one kind of node is declared in, and its plural as messages name it. +#[derive(Clone, Copy, Debug)] +pub(crate) struct KindFiles { + pub(crate) kind: &'static str, + /// The file of one direct declaration. + pub(crate) direct: &'static str, + /// The file of a factory that makes only this kind. + pub(crate) factory: &'static str, + pub(crate) plural: &'static str, +} diff --git a/crates/sqlbuild-discovery/src/node_files/tests.rs b/crates/sqlbuild-discovery/src/node_files/tests.rs new file mode 100644 index 0000000000..dd94a6c259 --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/tests.rs @@ -0,0 +1,6 @@ +#[path = "tests/helpers.rs"] +mod helpers; +#[path = "tests/test_node_file_problems.rs"] +mod node_file_problems; +#[path = "tests/test_types.rs"] +mod test_types; diff --git a/crates/sqlbuild-discovery/src/node_files/tests/helpers.rs b/crates/sqlbuild-discovery/src/node_files/tests/helpers.rs new file mode 100644 index 0000000000..7cd83b7c41 --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/tests/helpers.rs @@ -0,0 +1,22 @@ +//! Node module fixtures for the file-name check. + +use crate::node_files::models::NodeModule; + +/// A module at `path` with its direct declarations and its factories' kinds. +pub(super) fn module( + path: &str, + direct: &[(&str, &'static str)], + factories: &[(&str, &[&'static str])], +) -> NodeModule { + NodeModule { + relative_path: path.to_owned(), + direct: direct + .iter() + .map(|(name, kind)| ((*name).to_owned(), *kind)) + .collect(), + factories: factories + .iter() + .map(|(name, kinds)| ((*name).to_owned(), kinds.to_vec())) + .collect(), + } +} diff --git a/crates/sqlbuild-discovery/src/node_files/tests/test_node_file_problems.rs b/crates/sqlbuild-discovery/src/node_files/tests/test_node_file_problems.rs new file mode 100644 index 0000000000..a6962a455c --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/tests/test_node_file_problems.rs @@ -0,0 +1,127 @@ +use crate::node_files::main::node_file_problems::node_file_problems; +use crate::node_files::tests::helpers::module; +use crate::node_files::tests::test_types::NodeFilesTestCase; + +#[test] +fn given_node_modules_when_checking_file_names_then_each_declaration_sits_in_its_kind_file() { + let test_cases = [ + NodeFilesTestCase { + description: "kind-named files and checks beside a node", + modules: vec![ + module( + "python/nodes/sales/orders/asset.py", + &[("orders", "asset")], + &[], + ), + module( + "python/nodes/sales/orders/checks.py", + &[("orders_ok", "check")], + &[], + ), + module( + "python/nodes/raw/load/loaders.py", + &[], + &[("make", &["loader"])], + ), + module( + "python/nodes/mix/build/factory.py", + &[], + &[("make", &["asset", "check"])], + ), + module("python/nodes/sales/helpers.py", &[], &[]), + ], + expected_problem: None, + }, + NodeFilesTestCase { + description: "an asset in node.py", + modules: vec![module( + "python/nodes/sales/orders/node.py", + &[("orders", "asset")], + &[], + )], + expected_problem: Some( + "@asset 'orders' is declared in python/nodes/sales/orders/node.py; an @asset is \ + declared in asset.py", + ), + }, + NodeFilesTestCase { + description: "an asset in loader.py", + modules: vec![module( + "python/nodes/raw/x/loader.py", + &[("x", "asset")], + &[], + )], + expected_problem: Some( + "@asset 'x' is declared in python/nodes/raw/x/loader.py; an @asset is declared in \ + asset.py", + ), + }, + NodeFilesTestCase { + description: "a loaders.py factory returning an asset", + modules: vec![module( + "python/nodes/raw/x/loaders.py", + &[], + &[("make", &["asset"])], + )], + expected_problem: Some( + "@factory 'make' in python/nodes/raw/x/loaders.py makes only assets; a factory \ + that makes only assets is declared in assets.py", + ), + }, + NodeFilesTestCase { + description: "a factory.py making one kind", + modules: vec![module( + "python/nodes/raw/x/factory.py", + &[], + &[("make", &["loader"])], + )], + expected_problem: Some( + "@factory 'make' in python/nodes/raw/x/factory.py makes only loaders; a factory \ + that makes only loaders is declared in loaders.py", + ), + }, + NodeFilesTestCase { + description: "a mixed factory outside factory.py", + modules: vec![module( + "python/nodes/raw/x/assets.py", + &[], + &[("make", &["asset", "check"])], + )], + expected_problem: Some( + "@factory 'make' in python/nodes/raw/x/assets.py makes assets and checks; a \ + factory that makes more than one kind is declared in factory.py", + ), + }, + NodeFilesTestCase { + description: "two assets in asset.py", + modules: vec![module( + "python/nodes/s/o/asset.py", + &[("a", "asset"), ("b", "asset")], + &[], + )], + expected_problem: Some( + "python/nodes/s/o/asset.py declares 2 nodes (a, b); asset.py declares exactly \ + one, so give each its own unit folder or use a factory", + ), + }, + NodeFilesTestCase { + description: "two declaration files in one folder", + modules: vec![ + module("python/nodes/s/o/asset.py", &[("a", "asset")], &[]), + module("python/nodes/s/o/loader.py", &[("b", "loader")], &[]), + ], + expected_problem: Some( + "python/nodes/s/o/ holds asset.py and loader.py; a unit folder holds one node \ + declaration file, plus checks.py", + ), + }, + ]; + for test_case in test_cases { + assert_eq!( + node_file_problems(&test_case.modules).as_deref(), + test_case.expected_problem, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-discovery/src/node_files/tests/test_types.rs b/crates/sqlbuild-discovery/src/node_files/tests/test_types.rs new file mode 100644 index 0000000000..633adb9642 --- /dev/null +++ b/crates/sqlbuild-discovery/src/node_files/tests/test_types.rs @@ -0,0 +1,8 @@ +use crate::node_files::models::NodeModule; + +/// Modules and the problem the file-name check reports for them. +pub(super) struct NodeFilesTestCase { + pub(super) description: &'static str, + pub(super) modules: Vec, + pub(super) expected_problem: Option<&'static str>, +} diff --git a/crates/sqlbuild-discovery/src/orchestration_files/tests/test_orchestration_inventory.rs b/crates/sqlbuild-discovery/src/orchestration_files/tests/test_orchestration_inventory.rs index 17a94f2f0d..865e9630c6 100644 --- a/crates/sqlbuild-discovery/src/orchestration_files/tests/test_orchestration_inventory.rs +++ b/crates/sqlbuild-discovery/src/orchestration_files/tests/test_orchestration_inventory.rs @@ -81,7 +81,7 @@ fn given_projects_when_inventorying_then_reads_each_kind_and_names_them() { }, InventoryTestCase { description: "no orchestration folder", - files: vec![("models/orders.sql", "select 1")], + files: vec![("sql/models/orders.sql", "select 1")], expected_names: Vec::new(), expected_modules: Vec::new(), expected_empty: true, diff --git a/crates/sqlbuild-discovery/src/orchestration_files/tests/test_read_files.rs b/crates/sqlbuild-discovery/src/orchestration_files/tests/test_read_files.rs index b5bdcb4b33..f77eea7047 100644 --- a/crates/sqlbuild-discovery/src/orchestration_files/tests/test_read_files.rs +++ b/crates/sqlbuild-discovery/src/orchestration_files/tests/test_read_files.rs @@ -15,7 +15,7 @@ const DEPENDENCY_GROUP: &str = "name = \"nightly_job_group\"\ndescription = \"d\ const FULL_JOB: &str = r#"name = "orders_export_job" description = "Write the daily partner file." -select = "python/orders/partner_export" +select = "python/nodes/orders/partner_export" exclude = "tag:slow" targets = ["production"] owner = "Orders team" @@ -42,7 +42,7 @@ fn given_job_files_when_reading_then_types_every_field_and_keeps_positions() { description: "a job using every key", text: FULL_JOB, expected_name: written("orders_export_job", 1, 8), - expected_select: written("python/orders/partner_export", 3, 10), + expected_select: written("python/nodes/orders/partner_export", 3, 10), expected_exclude: Some("tag:slow"), expected_overlap: Overlap::Skip, expected_pools: &[("supplier_api", 1), ("warehouse", 2)], diff --git a/crates/sqlbuild-discovery/src/project_layout/_helpers/folders.rs b/crates/sqlbuild-discovery/src/project_layout/_helpers/folders.rs new file mode 100644 index 0000000000..dc360bb226 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/_helpers/folders.rs @@ -0,0 +1,95 @@ +//! The entries of one folder that the project layout does not allow. + +use std::fs; +use std::path::{Path, PathBuf}; + +use sqlbuild_core::git_revisions::main::is_dependency_file::is_dependency_file; + +use crate::project_layout::_helpers::ignored::IgnoreRules; +use crate::project_layout::constants::{ + DATABASE_COMPANION_SUFFIXES, DATABASE_FILE_SUFFIXES, HIDDEN_PREFIX, OUTPUT_DIRECTORIES, + PYTHON_CACHE_DIRECTORY, +}; +use crate::project_layout::models::{Checked, LayoutProblem}; + +/// The entries of one checked folder that the layout does not allow. +pub(crate) fn folder_problems( + root: &Path, + checked: &Checked<'_>, + (ignored, extra): (&IgnoreRules, &[String]), +) -> Vec { + let directory: PathBuf = checked + .folder + .map_or(root.to_path_buf(), |name| root.join(name)); + let Ok(entries) = fs::read_dir(&directory) else { + return Vec::new(); + }; + let mut problems: Vec = Vec::new(); + for entry in entries.flatten() { + let name: String = entry.file_name().to_string_lossy().into_owned(); + let is_dir: bool = fs::metadata(entry.path()).is_ok_and(|meta| meta.is_dir()); + let relative: String = checked + .folder + .map_or(name.clone(), |folder| format!("{folder}/{name}")); + let expected: bool = if is_dir { + checked.directories.contains(&name.as_str()) + } else { + checked.files.contains(&name.as_str()) + }; + if expected + || always_allowed(checked.folder, &name, is_dir) + || extra.contains(&relative) + || ignored.is_ignored(&entry.path(), is_dir) + { + continue; + } + problems.push(LayoutProblem { + path: if is_dir { + format!("{relative}/") + } else { + relative + }, + folder: checked.folder, + allowed: allowed(checked), + }); + } + problems +} + +/// Hidden entries, bytecode caches, top-level output folders, database and Python dependency files. +fn always_allowed(folder: Option<&str>, name: &str, is_dir: bool) -> bool { + if name.starts_with(HIDDEN_PREFIX) || name == PYTHON_CACHE_DIRECTORY { + return true; + } + if folder.is_some() { + return false; + } + if is_dir { + OUTPUT_DIRECTORIES.contains(&name) + } else { + is_database_file(name) || is_dependency_file(name) + } +} + +/// A local database file, or the log, shared-memory or journal file beside one. +fn is_database_file(name: &str) -> bool { + let base: &str = DATABASE_COMPANION_SUFFIXES + .iter() + .find_map(|suffix| name.strip_suffix(suffix)) + .unwrap_or(name); + DATABASE_FILE_SUFFIXES + .iter() + .any(|suffix| base.ends_with(suffix)) +} + +/// The folders `checked` may hold, as the help lists them. +fn allowed(checked: &Checked<'_>) -> Vec { + checked + .directories + .iter() + .map(|name| match checked.folder { + Some(folder) => format!("{folder}/{name}/"), + None => format!("{name}/"), + }) + .collect() +} diff --git a/crates/sqlbuild-discovery/src/project_layout/_helpers/ignored.rs b/crates/sqlbuild-discovery/src/project_layout/_helpers/ignored.rs new file mode 100644 index 0000000000..85599fc099 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/_helpers/ignored.rs @@ -0,0 +1,61 @@ +//! The gitignore rules from the project up to the repository root, with `info/exclude`. + +use std::path::{Path, PathBuf}; + +use ignore::Match; +use ignore::gitignore::{Gitignore, GitignoreBuilder}; + +use crate::project_layout::constants::{GIT_DIRECTORY, GIT_EXCLUDE_FILE, GITIGNORE_FILE}; + +/// Gitignore matchers, deepest folder first. +pub(crate) struct IgnoreRules { + matchers: Vec, +} + +impl IgnoreRules { + /// The rules that apply inside `project_dir`. + pub(crate) fn read(project_dir: &Path) -> Self { + let mut matchers: Vec = Vec::new(); + let mut folder: Option = Some(project_dir.to_path_buf()); + while let Some(current) = folder { + let mut builder = GitignoreBuilder::new(¤t); + let file: PathBuf = current.join(GITIGNORE_FILE); + if file.is_file() { + let _ = builder.add(&file); + } + let git: PathBuf = current.join(GIT_DIRECTORY); + let repository_root: bool = git.exists(); + if git.is_dir() { + let exclude: PathBuf = GIT_EXCLUDE_FILE + .iter() + .fold(git.clone(), |path, part| path.join(part)); + if exclude.is_file() { + let _ = builder.add(&exclude); + } + } + if let Ok(matcher) = builder.build() + && !matcher.is_empty() + { + matchers.push(matcher); + } + folder = if repository_root { + None + } else { + current.parent().map(Path::to_path_buf) + }; + } + Self { matchers } + } + + /// Whether `path`, or a folder above it, is ignored; a deeper rule file decides first. + pub(crate) fn is_ignored(&self, path: &Path, is_dir: bool) -> bool { + for matcher in &self.matchers { + match matcher.matched_path_or_any_parents(path, is_dir) { + Match::Ignore(_) => return true, + Match::Whitelist(_) => return false, + Match::None => {} + } + } + false + } +} diff --git a/crates/sqlbuild-discovery/src/project_layout/_helpers/mod.rs b/crates/sqlbuild-discovery/src/project_layout/_helpers/mod.rs new file mode 100644 index 0000000000..3741840851 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/_helpers/mod.rs @@ -0,0 +1,3 @@ +pub(crate) mod folders; +pub(crate) mod ignored; +pub(crate) mod written; diff --git a/crates/sqlbuild-discovery/src/project_layout/_helpers/written.rs b/crates/sqlbuild-discovery/src/project_layout/_helpers/written.rs new file mode 100644 index 0000000000..b4355be04c --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/_helpers/written.rs @@ -0,0 +1,52 @@ +//! The top-level entries of a project that hold given paths. + +use std::path::{Component, Path, PathBuf}; + +/// The top-level entry of `root` holding each of `written`, relative paths read from `root`. +pub(crate) fn entries_holding(root: &Path, written: &[PathBuf]) -> Vec { + let real_root: PathBuf = resolved(root); + written + .iter() + .filter_map(|path| top_entry(&real_root, &resolved(&root.join(path)))) + .collect() +} + +/// The first component of `path` below `root`, if `path` lies inside it. +fn top_entry(root: &Path, path: &Path) -> Option { + if !path.starts_with(root) { + return None; + } + match path.components().nth(root.components().count())? { + Component::Normal(name) => Some(name.to_string_lossy().into_owned()), + _ => None, + } +} + +/// `path` with its deepest existing ancestor canonicalized, so a missing path matches its root. +fn resolved(path: &Path) -> PathBuf { + let mut existing: PathBuf = path.to_path_buf(); + let mut rest: Vec> = Vec::new(); + let mut components = path.components(); + let base: PathBuf = loop { + if let Ok(real) = std::fs::canonicalize(&existing) { + break real; + } + match components.next_back() { + Some(component) => { + rest.push(component); + existing = components.as_path().to_path_buf(); + } + None => break PathBuf::new(), + } + }; + rest.into_iter().rev().fold(base, |mut joined, component| { + match component { + Component::CurDir => {} + Component::ParentDir => { + joined.pop(); + } + other => joined.push(other.as_os_str()), + } + joined + }) +} diff --git a/crates/sqlbuild-discovery/src/project_layout/constants.rs b/crates/sqlbuild-discovery/src/project_layout/constants.rs new file mode 100644 index 0000000000..624bb563d0 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/constants.rs @@ -0,0 +1,18 @@ +//! The entries a project may hold without listing them, and the folders the check reads. + +/// Folders SQLBuild itself writes into a project: build artifacts and logs. +pub(crate) const OUTPUT_DIRECTORIES: [&str; 2] = ["target", "logs"]; +/// Suffixes of local warehouse files a DuckDB or SQLite connection keeps beside the project. +pub(crate) const DATABASE_FILE_SUFFIXES: [&str; 4] = [".duckdb", ".db", ".sqlite", ".sqlite3"]; +/// Suffixes of the write-ahead log, shared-memory and journal files beside a database file. +pub(crate) const DATABASE_COMPANION_SUFFIXES: [&str; 4] = [".wal", "-wal", "-shm", "-journal"]; +/// Python's bytecode cache folder. +pub(crate) const PYTHON_CACHE_DIRECTORY: &str = "__pycache__"; +/// The prefix of a hidden entry, such as `.gitignore`, `.env` or `.agents/`. +pub(crate) const HIDDEN_PREFIX: &str = "."; +/// Git's ignore file name. +pub(crate) const GITIGNORE_FILE: &str = ".gitignore"; +/// The folder marking a Git repository root. +pub(crate) const GIT_DIRECTORY: &str = ".git"; +/// A repository's own exclude file, below its `.git` folder. +pub(crate) const GIT_EXCLUDE_FILE: [&str; 2] = ["info", "exclude"]; diff --git a/crates/sqlbuild-discovery/src/project_layout/main/env_file_entries.rs b/crates/sqlbuild-discovery/src/project_layout/main/env_file_entries.rs new file mode 100644 index 0000000000..5ba8fc7611 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/main/env_file_entries.rs @@ -0,0 +1,14 @@ +//! `env_file_entries`: the project's top-level entries that hold the env files it names. + +use std::path::{Path, PathBuf}; + +use sqlbuild_config::env_file::main::named_env_files::named_env_files; + +use crate::project_layout::_helpers::written::entries_holding; + +/// The top-level entries of `root` holding an env file its `env_file` settings name. +#[must_use] +pub fn env_file_entries(root: &Path) -> Vec { + let named: Vec = named_env_files(root); + entries_holding(root, &named) +} diff --git a/crates/sqlbuild-discovery/src/project_layout/main/layout_problems.rs b/crates/sqlbuild-discovery/src/project_layout/main/layout_problems.rs new file mode 100644 index 0000000000..c9edad9b7f --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/main/layout_problems.rs @@ -0,0 +1,56 @@ +//! Every project entry outside the layout, at the top level and inside `sql/` and `python/`. + +use std::fs; +use std::path::{Path, PathBuf}; + +use sqlbuild_core::constants::{ + PYTHON_CHILDREN, PYTHON_DIRECTORY, SQL_CHILDREN, SQL_DIRECTORY, TOP_LEVEL_DIRECTORIES, + TOP_LEVEL_FILES, +}; + +use crate::project_layout::_helpers::folders::folder_problems; +use crate::project_layout::_helpers::ignored::IgnoreRules; +use crate::project_layout::models::{Checked, LayoutProblem}; + +/// Each entry of `project_dir` the layout does not allow, other than `extra_paths`, sorted by path. +pub fn layout_problems(project_dir: &Path, extra_paths: &[String]) -> Vec { + let root: PathBuf = fs::canonicalize(project_dir).unwrap_or_else(|_| project_dir.to_path_buf()); + let ignored: IgnoreRules = IgnoreRules::read(&root); + let extra: Vec = extra_paths + .iter() + .map(|path| path.replace('\\', "/").trim_end_matches('/').to_owned()) + .collect(); + let python_directories: Vec<&str> = PYTHON_CHILDREN + .iter() + .copied() + .filter(|name| !name.ends_with(".py")) + .collect(); + let python_files: Vec<&str> = PYTHON_CHILDREN + .iter() + .copied() + .filter(|name| name.ends_with(".py")) + .collect(); + let checked: [Checked<'_>; 3] = [ + Checked { + folder: None, + directories: &TOP_LEVEL_DIRECTORIES, + files: &TOP_LEVEL_FILES, + }, + Checked { + folder: Some(SQL_DIRECTORY), + directories: &SQL_CHILDREN, + files: &[], + }, + Checked { + folder: Some(PYTHON_DIRECTORY), + directories: &python_directories, + files: &python_files, + }, + ]; + let mut problems: Vec = Vec::new(); + for folder in &checked { + problems.extend(folder_problems(&root, folder, (&ignored, &extra))); + } + problems.sort_by(|left, right| left.path.cmp(&right.path)); + problems +} diff --git a/crates/sqlbuild-discovery/src/project_layout/main/mod.rs b/crates/sqlbuild-discovery/src/project_layout/main/mod.rs new file mode 100644 index 0000000000..b3681cb693 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/main/mod.rs @@ -0,0 +1,3 @@ +pub mod env_file_entries; +pub mod layout_problems; +pub mod written_entries; diff --git a/crates/sqlbuild-discovery/src/project_layout/main/written_entries.rs b/crates/sqlbuild-discovery/src/project_layout/main/written_entries.rs new file mode 100644 index 0000000000..4c1287bb58 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/main/written_entries.rs @@ -0,0 +1,18 @@ +//! `written_entries`: the project's top-level entries that hold what `sqb dev` writes itself. + +use std::path::{Path, PathBuf}; + +use sqlbuild_core::constants::{DEVELOPMENT_CONTROL_FILE_ENV, DEVELOPMENT_OUTPUT_FOLDER_ENV}; + +use crate::project_layout::_helpers::written::entries_holding; + +/// The top-level entries of `root` holding the control store file and run output `sqb dev` names. +#[must_use] +pub fn written_entries(root: &Path) -> Vec { + let written: Vec = [DEVELOPMENT_CONTROL_FILE_ENV, DEVELOPMENT_OUTPUT_FOLDER_ENV] + .into_iter() + .filter_map(std::env::var_os) + .map(PathBuf::from) + .collect(); + entries_holding(root, &written) +} diff --git a/crates/sqlbuild-discovery/src/project_layout/mod.rs b/crates/sqlbuild-discovery/src/project_layout/mod.rs new file mode 100644 index 0000000000..1e64f3d116 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/mod.rs @@ -0,0 +1,7 @@ +pub(crate) mod _helpers; +pub(crate) mod constants; +pub mod main; +pub mod models; + +#[cfg(test)] +mod tests; diff --git a/crates/sqlbuild-discovery/src/project_layout/models.rs b/crates/sqlbuild-discovery/src/project_layout/models.rs new file mode 100644 index 0000000000..be4ce0a58a --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/models.rs @@ -0,0 +1,20 @@ +//! One project entry outside the expected layout. + +/// An entry the project layout does not allow, with what its folder may hold instead. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LayoutProblem { + /// The project-relative path, `/`-separated, with a trailing `/` for a folder. + pub path: String, + /// The folder holding the entry, or `None` at the project's top level. + pub folder: Option<&'static str>, + /// What that folder may hold, each folder with a trailing `/`. + pub allowed: Vec, +} + +/// One folder the check reads and the entries it may hold. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Checked<'a> { + pub(crate) folder: Option<&'static str>, + pub(crate) directories: &'a [&'a str], + pub(crate) files: &'a [&'a str], +} diff --git a/crates/sqlbuild-discovery/src/project_layout/tests.rs b/crates/sqlbuild-discovery/src/project_layout/tests.rs new file mode 100644 index 0000000000..55396e7064 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/tests.rs @@ -0,0 +1,6 @@ +#[path = "tests/test_layout_problems.rs"] +mod layout_problems; +#[path = "tests/test_types.rs"] +mod test_types; +#[path = "tests/test_written_entries.rs"] +mod written_entries; diff --git a/crates/sqlbuild-discovery/src/project_layout/tests/test_layout_problems.rs b/crates/sqlbuild-discovery/src/project_layout/tests/test_layout_problems.rs new file mode 100644 index 0000000000..9bc72d0975 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/tests/test_layout_problems.rs @@ -0,0 +1,127 @@ +use std::fs; + +use crate::project_layout::main::layout_problems::layout_problems; +use crate::project_layout::tests::test_types::LayoutTestCase; + +#[test] +fn given_project_entries_when_checking_layout_then_only_unexpected_entries_are_reported() { + let test_cases = [ + LayoutTestCase { + description: "expected layout", + files: &[ + "sqlbuild_project.toml", + "sqlbuild_local.toml", + "README.md", + "sql/models/a.sql", + "sql/schemas/s.yml", + "python/__init__.py", + "python/adapter.py", + "python/nodes/sales/orders/asset.py", + "python/event_sinks/s.py", + "rules/r.py", + "tests/unit/t.sql", + "warehouse.duckdb", + "warehouse.duckdb.wal", + "shop.sqlite-journal", + "shop.db-wal", + ".env", + ], + folders: &["orchestration", "target", "logs", ".agents", "__pycache__"], + gitignore: "", + extra_paths: &[], + expected_paths: &[], + }, + LayoutTestCase { + description: "unknown entries at every checked level", + files: &[ + "sqlbuild_project.toml", + "notes.txt", + "migrations/map.json", + "models/a.sql", + "sql/misc/x.sql", + "sql/readme.md", + "python/orders/asset.py", + "python/helpers.py", + "python/nodes/deep/unchecked/thing.json", + ], + folders: &[], + gitignore: "", + extra_paths: &[], + expected_paths: &[ + "migrations/", + "models/", + "notes.txt", + "python/helpers.py", + "python/orders/", + "sql/misc/", + "sql/readme.md", + ], + }, + LayoutTestCase { + description: "extra paths and gitignored entries are allowed", + files: &[ + "sqlbuild_project.toml", + "migrations/map.json", + "sql/notes/n.md", + "scratch/x.sql", + "build.log", + ], + folders: &["data"], + gitignore: "scratch/\n*.log\n", + extra_paths: &["migrations/", "sql/notes", "data"], + expected_paths: &[], + }, + LayoutTestCase { + description: "Python dependency manifests and lock files are allowed at the top level", + files: &[ + "sqlbuild_project.toml", + "pyproject.toml", + "uv.lock", + "poetry.lock", + "pdm.lock", + "Pipfile.lock", + "requirements.txt", + "requirements-dev.txt", + "sql/uv.lock", + ], + folders: &[], + gitignore: "", + extra_paths: &[], + expected_paths: &["sql/uv.lock"], + }, + ]; + for test_case in test_cases { + let directory = std::env::temp_dir().join(format!( + "sqlbuild-project-layout-{}-{}", + std::process::id(), + test_case.description.replace(' ', "-") + )); + let _ = fs::remove_dir_all(&directory); + let _ = fs::create_dir_all(&directory); + let _ = fs::create_dir_all(directory.join(".git")); + for file in test_case.files { + let path = directory.join(file); + let _ = fs::create_dir_all(path.parent().unwrap_or(&directory)); + let _ = fs::write(&path, ""); + } + for folder in test_case.folders { + let _ = fs::create_dir_all(directory.join(folder)); + } + let _ = fs::write(directory.join(".gitignore"), test_case.gitignore); + let extra: Vec = test_case + .extra_paths + .iter() + .map(|path| (*path).to_owned()) + .collect(); + let reported: Vec = layout_problems(&directory, &extra) + .into_iter() + .map(|problem| problem.path) + .collect(); + let _ = fs::remove_dir_all(&directory); + assert_eq!( + reported, test_case.expected_paths, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-discovery/src/project_layout/tests/test_types.rs b/crates/sqlbuild-discovery/src/project_layout/tests/test_types.rs new file mode 100644 index 0000000000..297629c1eb --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/tests/test_types.rs @@ -0,0 +1,23 @@ +/// One project's entries, its extra paths, and the entries the layout check reports. +pub(super) struct LayoutTestCase { + pub(super) description: &'static str, + pub(super) files: &'static [&'static str], + pub(super) folders: &'static [&'static str], + pub(super) gitignore: &'static str, + pub(super) extra_paths: &'static [&'static str], + pub(super) expected_paths: &'static [&'static str], +} + +/// Paths SQLBuild writes, from inside or outside a project, and the top-level entries they exempt. +pub(super) struct WrittenEntriesTestCase { + pub(super) description: &'static str, + pub(super) written: &'static [&'static str], + pub(super) expected_entries: &'static [&'static str], +} + +/// The env file settings of a project and the top-level entries they allow. +pub(super) struct EnvFileEntriesTestCase { + pub(super) description: &'static str, + pub(super) config: &'static str, + pub(super) expected_entries: &'static [&'static str], +} diff --git a/crates/sqlbuild-discovery/src/project_layout/tests/test_written_entries.rs b/crates/sqlbuild-discovery/src/project_layout/tests/test_written_entries.rs new file mode 100644 index 0000000000..5bbb7efdc9 --- /dev/null +++ b/crates/sqlbuild-discovery/src/project_layout/tests/test_written_entries.rs @@ -0,0 +1,65 @@ +use std::path::PathBuf; + +use crate::project_layout::_helpers::written::entries_holding; +use crate::project_layout::main::env_file_entries::env_file_entries; +use crate::project_layout::tests::test_types::{EnvFileEntriesTestCase, WrittenEntriesTestCase}; + +#[test] +fn given_paths_sqlbuild_writes_when_reading_entries_then_only_those_inside_the_project_count() { + let test_cases = [ + WrittenEntriesTestCase { + description: "a control store file and an output folder inside the project", + written: &["custom-control.sqlite3", "output", "data/runs/output"], + expected_entries: &["custom-control.sqlite3", "output", "data"], + }, + WrittenEntriesTestCase { + description: "the project itself and paths outside it", + written: &[".", "..", "../elsewhere/output"], + expected_entries: &[], + }, + ]; + let root: PathBuf = + std::env::temp_dir().join(format!("sqlbuild-written-entries-{}", std::process::id())); + let _ = std::fs::create_dir_all(&root); + for test_case in test_cases { + let written: Vec = test_case.written.iter().map(PathBuf::from).collect(); + let entries: Vec = entries_holding(&root, &written); + assert_eq!( + entries, test_case.expected_entries, + "{}", + test_case.description + ); + } + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn given_env_file_settings_when_reading_entries_then_each_named_file_inside_the_project_counts() { + let test_cases = [ + EnvFileEntriesTestCase { + description: "the project's env file and a target's, one outside the project", + config: "name = \"p\"\nadapter = \"duckdb\"\nenv_file = \"development.env\"\n\n\ + [targets.prod]\nenv_file = \"secrets/prod.env\"\n\n\ + [targets.ci]\nenv_file = \"../shared.env\"\n", + expected_entries: &["development.env", "secrets"], + }, + EnvFileEntriesTestCase { + description: "loading turned off names nothing", + config: "name = \"p\"\nadapter = \"duckdb\"\nenv_file = \"\"\n", + expected_entries: &[], + }, + ]; + let root: PathBuf = + std::env::temp_dir().join(format!("sqlbuild-env-file-entries-{}", std::process::id())); + let _ = std::fs::create_dir_all(&root); + for test_case in test_cases { + std::fs::write(root.join("sqlbuild_project.toml"), test_case.config).expect("config"); + let entries: Vec = env_file_entries(&root); + assert_eq!( + entries, test_case.expected_entries, + "{}", + test_case.description + ); + } + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/sqlbuild-discovery/src/project_validation/_helpers/seeds.rs b/crates/sqlbuild-discovery/src/project_validation/_helpers/seeds.rs index 7f9fe73367..c7009a99e7 100644 --- a/crates/sqlbuild-discovery/src/project_validation/_helpers/seeds.rs +++ b/crates/sqlbuild-discovery/src/project_validation/_helpers/seeds.rs @@ -36,7 +36,7 @@ pub(crate) fn validate_declared_seed_files(facts: &ProjectFacts) -> Result<(), V match matching { [] => { return Err(seed_error(format!( - "Seed declaration '{}' in {} has no matching CSV file under seeds/", + "Seed declaration '{}' in {} has no matching CSV file under sql/seeds/", entry.name, schema.path ))); } @@ -58,7 +58,7 @@ pub(crate) fn validate_declared_seed_files(facts: &ProjectFacts) -> Result<(), V for seed in &facts.seeds { if !declared.contains(seed.file.name.as_str()) { return Err(seed_error(format!( - "Seed CSV {} has no matching declaration for seed '{}' under seeds/**/*.yml", + "Seed CSV {} has no matching declaration for seed '{}' under sql/seeds/**/*.yml", seed.file.path, seed.file.name ))); } diff --git a/crates/sqlbuild-discovery/src/project_validation/constants.rs b/crates/sqlbuild-discovery/src/project_validation/constants.rs index ff52224157..b515d5ccd9 100644 --- a/crates/sqlbuild-discovery/src/project_validation/constants.rs +++ b/crates/sqlbuild-discovery/src/project_validation/constants.rs @@ -1,7 +1,7 @@ //! Names and limits cross-file discovery validation checks against. /// The prefix discovery strips from model paths before matching path defaults. -pub(crate) const MODELS_PREFIX: &str = "models/"; +pub(crate) const MODELS_PREFIX: &str = "sql/models/"; /// `str(Path(...).parent)` of a path with no folder. pub(crate) const CURRENT_DIRECTORY: &str = "."; /// How many known model folders an unmatched path default lists. diff --git a/crates/sqlbuild-discovery/src/project_validation/tests/helpers.rs b/crates/sqlbuild-discovery/src/project_validation/tests/helpers.rs index 8a9482cd03..debd8c5c37 100644 --- a/crates/sqlbuild-discovery/src/project_validation/tests/helpers.rs +++ b/crates/sqlbuild-discovery/src/project_validation/tests/helpers.rs @@ -28,11 +28,11 @@ pub(super) fn seed_header_outcome(csv_text: &str, columns: &[&str]) -> Result<() std::fs::write(&csv_path, csv_text).expect("the seed CSV is writable"); let facts = ProjectFacts { seeds: vec![SeedFileFact { - file: named("countries", "seeds/countries.csv"), + file: named("countries", "sql/seeds/countries.csv"), absolute_path: csv_path.to_string_lossy().into_owned(), }], schemas: vec![SchemaFileFact { - path: "seeds/countries.yml".to_owned(), + path: "sql/seeds/countries.yml".to_owned(), model_names: Vec::new(), seeds: vec![SeedEntryFact { name: "countries".to_owned(), @@ -61,14 +61,14 @@ pub(super) fn model_at(name: &str, path: &str) -> ModelFact { } pub(super) fn model(name: &str) -> ModelFact { - model_at(name, &format!("models/{name}.sql")) + model_at(name, &format!("sql/models/{name}.sql")) } pub(super) fn node(kind: NodeKind, name: &str, depends_on: Vec) -> NodeFact { NodeFact { kind, name: name.to_owned(), - path: format!("python/{name}.py"), + path: format!("python/nodes/{name}.py"), decorator_config: false, depends_on, } diff --git a/crates/sqlbuild-discovery/src/project_validation/tests/test_validate_orchestration_names.rs b/crates/sqlbuild-discovery/src/project_validation/tests/test_validate_orchestration_names.rs index f58a33ad7a..69f4943004 100644 --- a/crates/sqlbuild-discovery/src/project_validation/tests/test_validate_orchestration_names.rs +++ b/crates/sqlbuild-discovery/src/project_validation/tests/test_validate_orchestration_names.rs @@ -33,7 +33,7 @@ fn given_orchestration_names_when_validating_then_they_share_the_project_namespa ..ProjectFacts::default() }, expected_failure: collision( - "Project resource name 'orders' is declared as both model in models/orders.sql \ + "Project resource name 'orders' is declared as both model in sql/models/orders.sql \ and job in orchestration/daily.py", RENAME_DECLARATION, ), @@ -57,13 +57,13 @@ fn given_orchestration_names_when_validating_then_they_share_the_project_namespa ValidationTestCase { description: "a calendar named like a provider", facts: ProjectFacts { - providers: vec![named("fulfillment", "providers/fulfillment.py")], + providers: vec![named("fulfillment", "python/providers/fulfillment.py")], orchestration: vec![declared("fulfillment", "calendar")], ..ProjectFacts::default() }, expected_failure: collision( "Project resource name 'fulfillment' is declared as both provider in \ - providers/fulfillment.py and calendar in orchestration/daily.py", + python/providers/fulfillment.py and calendar in orchestration/daily.py", RENAME_DECLARATION, ), }, @@ -78,7 +78,7 @@ fn given_orchestration_names_when_validating_then_they_share_the_project_namespa ..ProjectFacts::default() }, expected_failure: collision( - "Project resource name 'orders' is declared as both model in models/orders.sql \ + "Project resource name 'orders' is declared as both model in sql/models/orders.sql \ and unit test in tests/orders.sql", "", ), diff --git a/crates/sqlbuild-discovery/src/project_validation/tests/test_validate_project_inputs.rs b/crates/sqlbuild-discovery/src/project_validation/tests/test_validate_project_inputs.rs index ea4cdd05f6..bd0c39d0b4 100644 --- a/crates/sqlbuild-discovery/src/project_validation/tests/test_validate_project_inputs.rs +++ b/crates/sqlbuild-discovery/src/project_validation/tests/test_validate_project_inputs.rs @@ -28,7 +28,7 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { }, expected_failure: failure( FailureKind::ResourceIdentity, - "Invalid model identity 'Orders' in models/Orders.sql; use snake_case 'orders'", + "Invalid model identity 'Orders' in sql/models/Orders.sql; use snake_case 'orders'", ), }, ValidationTestCase { @@ -39,7 +39,7 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { }, expected_failure: failure( FailureKind::ResourceIdentity, - "Invalid model identity '_chain_' in models/_chain_.sql; use snake_case 'chain'", + "Invalid model identity '_chain_' in sql/models/_chain_.sql; use snake_case 'chain'", ), }, ValidationTestCase { @@ -47,7 +47,7 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { facts: ProjectFacts { models: vec![model("orders")], sources: vec![SourceFileFact { - path: "sources/shop.yml".to_owned(), + path: "sql/sources/shop.yml".to_owned(), entries: vec![SourceFact { name: "orders".to_owned(), ..SourceFact::default() @@ -57,8 +57,8 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { }, expected_failure: failure( FailureKind::Conflict, - "Logical relation name 'orders' is declared as both model in models/orders.sql \ - and source in sources/shop.yml", + "Logical relation name 'orders' is declared as both model in sql/models/orders.sql \ + and source in sql/sources/shop.yml", ), }, ValidationTestCase { @@ -94,21 +94,21 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { description: "an undeclared seed CSV", facts: ProjectFacts { seeds: vec![SeedFileFact { - file: named("countries", "seeds/countries.csv"), + file: named("countries", "sql/seeds/countries.csv"), absolute_path: "/missing/seeds/countries.csv".to_owned(), }], ..ProjectFacts::default() }, expected_failure: failure( FailureKind::Seed, - "Seed CSV seeds/countries.csv has no matching declaration for seed 'countries' \ - under seeds/**/*.yml", + "Seed CSV sql/seeds/countries.csv has no matching declaration for seed 'countries' \ + under sql/seeds/**/*.yml", ), }, ValidationTestCase { description: "an unmatched path default lists known folders", facts: ProjectFacts { - models: vec![model_at("orders", "models/marts/orders.sql")], + models: vec![model_at("orders", "sql/models/marts/orders.sql")], path_default_keys: vec!["staging".to_owned()], ..ProjectFacts::default() }, @@ -121,11 +121,11 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { ValidationTestCase { description: "a path default matching only undiscovered project models passes", facts: ProjectFacts { - models: vec![model_at("orders", "models/marts/orders.sql")], + models: vec![model_at("orders", "sql/models/marts/orders.sql")], path_default_keys: vec!["staging".to_owned()], project_model_paths: Some(vec![ - "models/marts/orders.sql".to_owned(), - "models/staging/customers.sql".to_owned(), + "sql/models/marts/orders.sql".to_owned(), + "sql/models/staging/customers.sql".to_owned(), ]), ..ProjectFacts::default() }, @@ -133,13 +133,13 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { }, ValidationTestCase { description: "accepts Windows-style model paths that match path defaults", - facts: path_default_facts(&["models\\staging\\orders.sql"], &["staging"]), + facts: path_default_facts(&["sql\\models\\staging\\orders.sql"], &["staging"]), expected_failure: Ok(()), }, ValidationTestCase { description: "accepts recursive glob matching nested staging prefix", facts: path_default_facts( - &["models/commerce/partner_feed/staging/orders.sql"], + &["sql/models/commerce/partner_feed/staging/orders.sql"], &["commerce/**/staging"], ), expected_failure: Ok(()), @@ -147,7 +147,7 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { ValidationTestCase { description: "accepts recursive glob matching zero segments", facts: path_default_facts( - &["models/commerce/staging/orders.sql"], + &["sql/models/commerce/staging/orders.sql"], &["commerce/**/staging"], ), expected_failure: Ok(()), @@ -155,7 +155,7 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { ValidationTestCase { description: "counts broad glob as matched when a literal wins selection", facts: path_default_facts( - &["models/commerce/partner_feed/staging/orders.sql"], + &["sql/models/commerce/partner_feed/staging/orders.sql"], &["commerce/**/staging", "commerce/partner_feed/staging"], ), expected_failure: Ok(()), @@ -163,7 +163,7 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { ValidationTestCase { description: "rejects recursive glob matching no model paths", facts: path_default_facts( - &["models/commerce/partner_feed/marts/orders.sql"], + &["sql/models/commerce/partner_feed/marts/orders.sql"], &["commerce/**/staging"], ), expected_failure: failure( @@ -175,7 +175,7 @@ fn given_discovered_facts_when_validating_then_reports_python_first_conflict() { ValidationTestCase { description: "rejects equally specific matching globs during discovery", facts: path_default_facts( - &["models/commerce/eu/staging/orders.sql"], + &["sql/models/commerce/eu/staging/orders.sql"], &["commerce/*/staging", "commerce/eu/*"], ), expected_failure: failure( @@ -210,7 +210,7 @@ fn given_seed_csv_headers_when_validating_then_reports_python_tuple_reprs() { declared_columns: &["code"], expected_failure: failure( FailureKind::Seed, - "seeds/countries.csv header ('code', 'label') does not match declared seed \ + "sql/seeds/countries.csv header ('code', 'label') does not match declared seed \ columns ('code',) for 'countries'", ), }, @@ -220,7 +220,7 @@ fn given_seed_csv_headers_when_validating_then_reports_python_tuple_reprs() { declared_columns: &["code", "code"], expected_failure: failure( FailureKind::Seed, - "seeds/countries.csv contains duplicate CSV header column 'code'", + "sql/seeds/countries.csv contains duplicate CSV header column 'code'", ), }, SeedHeaderTestCase { @@ -229,7 +229,7 @@ fn given_seed_csv_headers_when_validating_then_reports_python_tuple_reprs() { declared_columns: &["code"], expected_failure: failure( FailureKind::Seed, - "seeds/countries.csv must contain a CSV header row", + "sql/seeds/countries.csv must contain a CSV header row", ), }, ]; diff --git a/crates/sqlbuild-discovery/src/python_paths/_helpers/supported.rs b/crates/sqlbuild-discovery/src/python_paths/_helpers/supported.rs index fdcd731dc2..5185c507a7 100644 --- a/crates/sqlbuild-discovery/src/python_paths/_helpers/supported.rs +++ b/crates/sqlbuild-discovery/src/python_paths/_helpers/supported.rs @@ -1,23 +1,13 @@ //! Whether one project Python file lives under a documented executable root. use crate::constants::{CANONICAL_AUTHORED_ROOTS, SCOPED_DECLARATION_DIRECTORIES}; -use crate::python_paths::constants::{ - DIRECT_PYTHON_ROOTS, GROUPED_PYTHON_HOOK_ROLES, LANGUAGE_PYTHON_ROOTS, SUPPORTED_ROOT_FILES, -}; +use crate::python_paths::constants::{GROUPED_PYTHON_HOOK_ROLES, PYTHON_ROOTS}; /// Whether the file at relative `parts` is supported project Python. pub(crate) fn is_supported(parts: &[String]) -> bool { - let Some(first) = parts.first() else { - return false; - }; - if parts.len() == 1 && SUPPORTED_ROOT_FILES.contains(&first.as_str()) { - return true; - } - if DIRECT_PYTHON_ROOTS.contains(&first.as_str()) { - return true; - } - if let [root, language, ..] = parts - && LANGUAGE_PYTHON_ROOTS.contains(&(root.as_str(), language.as_str())) + if PYTHON_ROOTS + .iter() + .any(|root| parts.len() > root.len() && starts_with(parts, root)) { return true; } diff --git a/crates/sqlbuild-discovery/src/python_paths/constants.rs b/crates/sqlbuild-discovery/src/python_paths/constants.rs index 0d199455f5..a03f9171e9 100644 --- a/crates/sqlbuild-discovery/src/python_paths/constants.rs +++ b/crates/sqlbuild-discovery/src/python_paths/constants.rs @@ -2,27 +2,19 @@ use crate::constants::ORCHESTRATION_DIRECTORY; -/// Top-level directories whose Python files are always supported. -pub(crate) const DIRECT_PYTHON_ROOTS: [&str; 11] = [ - "adapters", - "materializations", - "providers", - "python", - "rules", - "sinks", - "macros", - "enums", - "constants", - "event_exporters", - ORCHESTRATION_DIRECTORY, +/// Project folders whose Python files are always supported, as path parts. +pub(crate) const PYTHON_ROOTS: [&[&str]; 8] = [ + &["python"], + &["rules"], + &[ORCHESTRATION_DIRECTORY], + &["sql", "macros"], + &["sql", "enums"], + &["sql", "constants"], + &["sql", "functions", "python"], + &["sql", "hooks", "python"], ]; -/// `(root, language)` directory pairs whose Python files are supported. -pub(crate) const LANGUAGE_PYTHON_ROOTS: [(&str, &str); 2] = - [("functions", "python"), ("hooks", "python")]; /// Top-level directories the walk does not enter. pub(crate) const IGNORED_ROOTS: [&str; 4] = ["logs", "target", "tests", "venv"]; -/// Root-level Python files that are supported. -pub(crate) const SUPPORTED_ROOT_FILES: [&str; 1] = ["adapter.py"]; /// Directories the walk never enters. pub(crate) const PYTHON_CACHE_DIRECTORY: &str = "__pycache__"; /// Grouped hook roles whose Python files are supported inside an authored tree. @@ -33,8 +25,8 @@ pub(crate) const GROUPED_PYTHON_HOOK_ROLES: [[&str; 3]; 2] = [ /// The prefix of a hidden directory the walk skips. pub(crate) const HIDDEN_PREFIX: &str = "."; /// The folders holding project Python tests, each mirroring the project folder its second part names. -pub(crate) const PYTHON_TEST_ROOTS: [[&str; 2]; 3] = [ - ["tests", ORCHESTRATION_DIRECTORY], - ["tests", "providers"], - ["tests", "python"], +pub(crate) const PYTHON_TEST_ROOTS: [&[&str]; 3] = [ + &["tests", ORCHESTRATION_DIRECTORY], + &["tests", "python", "providers"], + &["tests", "python", "nodes"], ]; diff --git a/crates/sqlbuild-discovery/src/python_paths/main/python_test_paths.rs b/crates/sqlbuild-discovery/src/python_paths/main/python_test_paths.rs index e31a823221..5294ed4eff 100644 --- a/crates/sqlbuild-discovery/src/python_paths/main/python_test_paths.rs +++ b/crates/sqlbuild-discovery/src/python_paths/main/python_test_paths.rs @@ -5,7 +5,7 @@ use std::path::Path; use crate::python_paths::_helpers::python_files::python_files; use crate::python_paths::constants::PYTHON_TEST_ROOTS; -/// Each Python file under `tests/orchestration/`, `tests/providers/` or `tests/python/` as relative parts, sorted part by part. +/// Each Python file under `tests/orchestration/`, `tests/python/providers/` or `tests/python/nodes/` as relative parts, sorted part by part. pub fn python_test_paths(project_dir: &Path) -> Vec> { PYTHON_TEST_ROOTS .iter() diff --git a/crates/sqlbuild-discovery/src/python_paths/tests/test_python_test_paths.rs b/crates/sqlbuild-discovery/src/python_paths/tests/test_python_test_paths.rs index e6ca36990c..2a69a8369c 100644 --- a/crates/sqlbuild-discovery/src/python_paths/tests/test_python_test_paths.rs +++ b/crates/sqlbuild-discovery/src/python_paths/tests/test_python_test_paths.rs @@ -9,25 +9,25 @@ fn given_project_tests_when_listing_python_test_paths_then_only_mirrored_test_ro description: "tests/python, tests/providers and tests/orchestration, skipping SQL test folders, caches and hidden folders", files: &[ "tests/orchestration/sensors/orders/test_restock.py", - "tests/python/orders/import/test_main.py", - "tests/providers/storefront/test_provider.py", - "tests/python/orders/_test_types.py", + "tests/python/nodes/orders/import/test_main.py", + "tests/python/providers/storefront/test_provider.py", + "tests/python/nodes/orders/_test_types.py", "tests/rules/test_rule.py", "tests/unit/orders.py", - "tests/python/__pycache__/test_main.py", - "tests/python/.hidden/test_main.py", - "python/orders/import/main.py", + "tests/python/nodes/__pycache__/test_main.py", + "tests/python/nodes/.hidden/test_main.py", + "python/nodes/orders/import/main.py", ], expected_tests: &[ "tests/orchestration/sensors/orders/test_restock.py", - "tests/providers/storefront/test_provider.py", - "tests/python/orders/_test_types.py", - "tests/python/orders/import/test_main.py", + "tests/python/providers/storefront/test_provider.py", + "tests/python/nodes/orders/_test_types.py", + "tests/python/nodes/orders/import/test_main.py", ], }, TestPathsTestCase { description: "a project without Python tests", - files: &["python/orders/import/main.py"], + files: &["python/nodes/orders/import/main.py"], expected_tests: &[], }, ]; diff --git a/crates/sqlbuild-discovery/src/python_paths/tests/test_supported_python_paths.rs b/crates/sqlbuild-discovery/src/python_paths/tests/test_supported_python_paths.rs index 409d0c0420..22bb9e41ac 100644 --- a/crates/sqlbuild-discovery/src/python_paths/tests/test_supported_python_paths.rs +++ b/crates/sqlbuild-discovery/src/python_paths/tests/test_supported_python_paths.rs @@ -7,23 +7,23 @@ fn given_project_python_when_listing_supported_paths_then_only_documented_roots_ SupportedPathsTestCase { description: "documented roots sorted by parts, skipping hidden, generated and undocumented files", files: &[ - "python/orders/main.py", - "adapter.py", + "python/nodes/orders/main.py", + "python/adapter.py", "orchestration/sensors/stock.py", - "functions/python/f.py", - "models/a/_sqlbuild/hooks/python/h.py", + "sql/functions/python/f.py", + "sql/models/a/_sqlbuild/hooks/python/h.py", "helpers.py", - "models/x.py", + "sql/models/x.py", ".hidden/x.py", "target/x.py", - "python/__pycache__/main.py", + "python/nodes/__pycache__/main.py", ], expected_supported: &[ - "adapter.py", - "functions/python/f.py", - "models/a/_sqlbuild/hooks/python/h.py", "orchestration/sensors/stock.py", - "python/orders/main.py", + "python/adapter.py", + "python/nodes/orders/main.py", + "sql/functions/python/f.py", + "sql/models/a/_sqlbuild/hooks/python/h.py", ], }, SupportedPathsTestCase { diff --git a/crates/sqlbuild-discovery/src/python_paths/tests/test_unsupported_python_paths.rs b/crates/sqlbuild-discovery/src/python_paths/tests/test_unsupported_python_paths.rs index 9a4843ec44..b75761bb00 100644 --- a/crates/sqlbuild-discovery/src/python_paths/tests/test_unsupported_python_paths.rs +++ b/crates/sqlbuild-discovery/src/python_paths/tests/test_unsupported_python_paths.rs @@ -9,14 +9,14 @@ fn given_project_python_when_listing_unsupported_paths_then_only_undocumented_ro PythonPathsTestCase { description: "documented roots", files: &[ - "adapter.py", - "python/orders.py", + "python/adapter.py", + "python/nodes/orders.py", "orchestration/jobs.py", "orchestration/nested/calendar.py", - "functions/python/f.py", - "macros/m.py", - "models/_macros/m.py", - "models/a/_sqlbuild/hooks/python/h.py", + "sql/functions/python/f.py", + "sql/macros/m.py", + "sql/models/_macros/m.py", + "sql/models/a/_sqlbuild/hooks/python/h.py", "tests/unit/x.py", ".hidden/x.py", "target/x.py", @@ -28,16 +28,16 @@ fn given_project_python_when_listing_unsupported_paths_then_only_undocumented_ro files: &[ "a-b.py", "a/b.py", - "models/x.py", - "functions/sql/f.py", + "sql/models/x.py", "helpers.py", + "sql/functions/sql/f.py", ], expected_unsupported: &[ "a/b.py", "a-b.py", - "functions/sql/f.py", "helpers.py", - "models/x.py", + "sql/functions/sql/f.py", + "sql/models/x.py", ], }, ]; diff --git a/crates/sqlbuild-discovery/src/yaml_entries/main/parse_schema_document.rs b/crates/sqlbuild-discovery/src/yaml_entries/main/parse_schema_document.rs index b43b787b86..eadbdfbc21 100644 --- a/crates/sqlbuild-discovery/src/yaml_entries/main/parse_schema_document.rs +++ b/crates/sqlbuild-discovery/src/yaml_entries/main/parse_schema_document.rs @@ -37,7 +37,7 @@ pub fn parse_schema_document( let seeds: Option<&N> = get(&entries, "seeds"); if seeds.is_some_and(truthy) && !in_seeds_directory { return Err(ConfigError::compile(format!( - "{path} declares seeds, but seed declarations must live under seeds/**/*.yml" + "{path} declares seeds, but seed declarations must live under sql/seeds/**/*.yml" ))); } if in_seeds_directory { diff --git a/crates/sqlbuild-discovery/src/yaml_entries/models.rs b/crates/sqlbuild-discovery/src/yaml_entries/models.rs index 5824b05d4e..2dc5d63f60 100644 --- a/crates/sqlbuild-discovery/src/yaml_entries/models.rs +++ b/crates/sqlbuild-discovery/src/yaml_entries/models.rs @@ -35,7 +35,7 @@ pub struct ParsedCsvSettings { pub keep_default_na: Option, } -/// One seed declaration of a `seeds/**/*.yml` file. +/// One seed declaration of a `sql/seeds/**/*.yml` file. #[derive(Clone, Debug, PartialEq)] pub struct ParsedSeedEntry { pub name: N, diff --git a/crates/sqlbuild-discovery/src/yaml_entries/tests/test_parse_schema_document.rs b/crates/sqlbuild-discovery/src/yaml_entries/tests/test_parse_schema_document.rs index 2e595925c1..2ee6dac3d6 100644 --- a/crates/sqlbuild-discovery/src/yaml_entries/tests/test_parse_schema_document.rs +++ b/crates/sqlbuild-discovery/src/yaml_entries/tests/test_parse_schema_document.rs @@ -40,7 +40,7 @@ fn given_schema_documents_when_parsing_then_matches_python_seeds_and_errors() { in_seeds_directory: false, expected_seeds: parse_error( "/project/seeds/countries.yml declares seeds, but seed declarations must live \ - under seeds/**/*.yml", + under sql/seeds/**/*.yml", ), }, SchemaDocumentTestCase { diff --git a/crates/sqlbuild-discovery/src/yaml_files/constants.rs b/crates/sqlbuild-discovery/src/yaml_files/constants.rs index 726dfc8b1c..ce536a349a 100644 --- a/crates/sqlbuild-discovery/src/yaml_files/constants.rs +++ b/crates/sqlbuild-discovery/src/yaml_files/constants.rs @@ -1,9 +1,9 @@ //! Where authored source and schema YAML files live. /// The directory whose direct YAML children declare sources. -pub(crate) const SOURCES_DIRECTORY: &str = "sources"; -pub(crate) const MODELS_DIRECTORY: &str = "models"; -pub(crate) const SEEDS_DIRECTORY: &str = "seeds"; +pub(crate) const SOURCES_DIRECTORY: &str = sqlbuild_core::constants::SOURCES_PATH; +pub(crate) const MODELS_DIRECTORY: &str = sqlbuild_core::constants::MODELS_PATH; +pub(crate) const SEEDS_DIRECTORY: &str = sqlbuild_core::constants::SEEDS_PATH; /// Python's `YAML_FILE_SUFFIXES`. pub(crate) const YAML_FILE_SUFFIXES: [&str; 2] = [".yml", ".yaml"]; /// Python's `SCHEMA_FILE_NAME`. diff --git a/crates/sqlbuild-discovery/src/yaml_files/tests/test_yaml_paths.rs b/crates/sqlbuild-discovery/src/yaml_files/tests/test_yaml_paths.rs index 075258031b..fae60a2df8 100644 --- a/crates/sqlbuild-discovery/src/yaml_files/tests/test_yaml_paths.rs +++ b/crates/sqlbuild-discovery/src/yaml_files/tests/test_yaml_paths.rs @@ -8,19 +8,19 @@ use crate::yaml_files::tests::test_types::YamlPathsTestCase; fn given_sources_directory_when_listing_source_yaml_then_direct_yaml_children_are_sorted() { let test_cases = [ YamlPathsTestCase { - description: "yml and yaml files directly below sources/ in path order", + description: "yml and yaml files directly below sql/sources/ in path order", files: &[ - "sources/b.yaml", - "sources/a.yml", - "sources/notes.txt", - "sources/.yml", - "sources/nested/c.yml", + "sql/sources/b.yaml", + "sql/sources/a.yml", + "sql/sources/notes.txt", + "sql/sources/.yml", + "sql/sources/nested/c.yml", ], - expected_paths: Ok(owned_paths(&["sources/a.yml", "sources/b.yaml"])), + expected_paths: Ok(owned_paths(&["sql/sources/a.yml", "sql/sources/b.yaml"])), }, YamlPathsTestCase { description: "no sources directory", - files: &["models/orders.sql"], + files: &["sql/models/orders.sql"], expected_paths: Ok(Vec::new()), }, ]; @@ -42,25 +42,25 @@ fn given_models_and_seeds_when_listing_schema_yaml_then_unscoped_schemas_and_see YamlPathsTestCase { description: "unscoped schema files then seed declarations, each in path order", files: &[ - "models/marts/schema.yml", - "models/schema.yml", - "models/marts/_sqlbuild/schemas/schema.yml", - "models/other.yml", - "seeds/products.yml", - "seeds/customers/customers.yml", + "sql/models/marts/schema.yml", + "sql/models/schema.yml", + "sql/models/marts/_sqlbuild/schemas/schema.yml", + "sql/models/other.yml", + "sql/seeds/products.yml", + "sql/seeds/customers/customers.yml", ], expected_paths: Ok(owned_paths(&[ - "models/marts/schema.yml", - "models/schema.yml", - "seeds/customers/customers.yml", - "seeds/products.yml", + "sql/models/marts/schema.yml", + "sql/models/schema.yml", + "sql/seeds/customers/customers.yml", + "sql/seeds/products.yml", ])), }, YamlPathsTestCase { description: "a seed declaration using .yaml fails naming the first one", - files: &["seeds/b.yaml", "seeds/a.yaml", "seeds/c.yml"], + files: &["sql/seeds/b.yaml", "sql/seeds/a.yaml", "sql/seeds/c.yml"], expected_paths: Err(YamlPathFailure::YamlSeedDeclaration( - "seeds/a.yaml".to_owned(), + "sql/seeds/a.yaml".to_owned(), )), }, ]; diff --git a/crates/sqlbuild-host/src/entries/_helpers/executor.rs b/crates/sqlbuild-host/src/entries/_helpers/executor.rs index dce3fc7ba2..2dc98d5953 100644 --- a/crates/sqlbuild-host/src/entries/_helpers/executor.rs +++ b/crates/sqlbuild-host/src/entries/_helpers/executor.rs @@ -749,6 +749,11 @@ pub(crate) const ENTRIES: &[HostEntry] = &[ kind: HostKind::Function, edge: HostEdge::Executor, }, + HostEntry { + name: "current_event_dispatcher", + kind: HostKind::Function, + edge: HostEdge::Executor, + }, HostEntry { name: "diagnostic_log_to_json", kind: HostKind::Function, diff --git a/crates/sqlbuild-host/src/entries/_helpers/user_code.rs b/crates/sqlbuild-host/src/entries/_helpers/user_code.rs index 4d90ecd389..d18ee4e48f 100644 --- a/crates/sqlbuild-host/src/entries/_helpers/user_code.rs +++ b/crates/sqlbuild-host/src/entries/_helpers/user_code.rs @@ -60,7 +60,7 @@ pub(crate) const ENTRIES: &[HostEntry] = &[ edge: HostEdge::UserCode, }, HostEntry { - name: "load_sink_module", + name: "load_event_sink_module", kind: HostKind::Function, edge: HostEdge::UserCode, }, diff --git a/crates/sqlbuild-host/src/entries/models.rs b/crates/sqlbuild-host/src/entries/models.rs index e993faf7a2..586d081e7d 100644 --- a/crates/sqlbuild-host/src/entries/models.rs +++ b/crates/sqlbuild-host/src/entries/models.rs @@ -140,7 +140,7 @@ pub enum UserCodeHost { LoadMaterializeFunction, LoadProviderModule, LoadPythonNodeModule, - LoadSinkModule, + LoadEventSinkModule, LoadOrchestrationModule, ModuleFunctions, ModuleProviderClasses, @@ -358,6 +358,7 @@ pub enum ExecutorHost { ObservabilityValidationError, CreateLifecycleEvent, CurrentExecutionIdentity, + CurrentEventDispatcher, DiagnosticLogToJson, DispatcherScope, InvocationExternalContextScope, diff --git a/crates/sqlbuild-model-config/src/declarations/tests/test_declarations.rs b/crates/sqlbuild-model-config/src/declarations/tests/test_declarations.rs index 812284a7f7..c1553fd269 100644 --- a/crates/sqlbuild-model-config/src/declarations/tests/test_declarations.rs +++ b/crates/sqlbuild-model-config/src/declarations/tests/test_declarations.rs @@ -34,7 +34,7 @@ fn given_model_header_enums_when_validating_then_python_rules_apply() { RawSqlValue::List(vec![RawSqlValue::Str("ACTIVE".to_owned())]), ), expected_scalar_types: Err(DeclarationFailure::Identity( - "Invalid model-local enum identity 'Status' in models/a.sql; use snake_case \ + "Invalid model-local enum identity 'Status' in sql/models/a.sql; use snake_case \ '_status'" .to_owned(), crate::header_metadata::constants::IDENTITY_HELP.to_owned(), @@ -47,7 +47,7 @@ fn given_model_header_enums_when_validating_then_python_rules_apply() { RawSqlValue::List(vec![RawSqlValue::Str("active".to_owned())]), ), expected_scalar_types: Err(DeclarationFailure::Parse( - "models/a.sql enum '_status' member identifiers must be uppercase: 'active'" + "sql/models/a.sql enum '_status' member identifiers must be uppercase: 'active'" .to_owned(), )), }, @@ -55,7 +55,7 @@ fn given_model_header_enums_when_validating_then_python_rules_apply() { for test_case in test_cases { let site = DeclarationSite { - file_path: "models/a.sql", + file_path: "sql/models/a.sql", model_name: Some("a"), }; diff --git a/crates/sqlbuild-model-config/src/header_metadata/tests/helpers.rs b/crates/sqlbuild-model-config/src/header_metadata/tests/helpers.rs index ddbbf800bf..fa61cf4670 100644 --- a/crates/sqlbuild-model-config/src/header_metadata/tests/helpers.rs +++ b/crates/sqlbuild-model-config/src/header_metadata/tests/helpers.rs @@ -110,7 +110,7 @@ fn text(value: Option<&Value>) -> String { pub(super) fn dynamic_summary(raw: &Value) -> Result, String> { crate::header_metadata::main::parse_dynamic_columns::parse_dynamic_columns( raw, - ("orders", "models/orders.sql"), + ("orders", "sql/models/orders.sql"), ) .map(|families| { families @@ -132,7 +132,7 @@ pub(super) fn dynamic_summary(raw: &Value) -> Result, String> { pub(super) fn factory_summary(raw: &Value) -> Result, String> { crate::header_metadata::main::audit_factory_references::audit_factory_references( raw, - ("orders", "models/orders.sql"), + ("orders", "sql/models/orders.sql"), &["freshness".to_owned(), "daily_checks".to_owned()], ) .map_err(stop_summary) diff --git a/crates/sqlbuild-model-config/src/header_metadata/tests/test_header_extensions.rs b/crates/sqlbuild-model-config/src/header_metadata/tests/test_header_extensions.rs index 406b9798f5..36ef7ad4b8 100644 --- a/crates/sqlbuild-model-config/src/header_metadata/tests/test_header_extensions.rs +++ b/crates/sqlbuild-model-config/src/header_metadata/tests/test_header_extensions.rs @@ -16,7 +16,7 @@ fn given_dynamic_columns_when_parsing_then_families_or_first_error_are_returned( description: "empty block", raw: map(&[]), expected_families: Err( - "model 'orders' dynamic_columns must be a non-empty named block in models/orders.sql", + "model 'orders' dynamic_columns must be a non-empty named block in sql/models/orders.sql", ), }, DynamicColumnsTestCase { @@ -78,27 +78,27 @@ fn given_audit_factories_when_resolving_then_references_or_first_error_are_retur FactoryReferencesTestCase { description: "a tuple is not a list", raw: Value::Tuple(vec![Value::Str("freshness")]), - expected_references: Err("models/orders.sql model audit_factories must be a list"), + expected_references: Err("sql/models/orders.sql model audit_factories must be a list"), }, FactoryReferencesTestCase { description: "dotted entry", raw: Value::List(vec![Value::Str("pkg.freshness")]), expected_references: Err( - "models/orders.sql model audit_factories entry 'pkg.freshness' must be a bare identifier", + "sql/models/orders.sql model audit_factories entry 'pkg.freshness' must be a bare identifier", ), }, FactoryReferencesTestCase { description: "repeated entry", raw: Value::List(vec![Value::Str("freshness"), Value::Str("freshness")]), expected_references: Err( - "model 'orders' in models/orders.sql references audit factory 'freshness' more than once", + "model 'orders' in sql/models/orders.sql references audit factory 'freshness' more than once", ), }, FactoryReferencesTestCase { description: "unknown entry lists sorted factories", raw: Value::List(vec![Value::Str("volume")]), expected_references: Err( - "model 'orders' in models/orders.sql references unknown audit factory 'volume'. \ + "model 'orders' in sql/models/orders.sql references unknown audit factory 'volume'. \ Available audit factories: daily_checks, freshness", ), }, diff --git a/crates/sqlbuild-model-config/src/model_validation/tests/helpers.rs b/crates/sqlbuild-model-config/src/model_validation/tests/helpers.rs index aabfa836a3..16ff21a2ed 100644 --- a/crates/sqlbuild-model-config/src/model_validation/tests/helpers.rs +++ b/crates/sqlbuild-model-config/src/model_validation/tests/helpers.rs @@ -29,7 +29,7 @@ pub(super) fn validation_outcome( .collect(); let facts = ModelValidationFacts { model_name: "orders_daily", - relative_path: "models/marts/orders_daily.sql", + relative_path: "sql/models/marts/orders_daily.sql", references: &references, declared_columns: None, query_sql, diff --git a/crates/sqlbuild-model-config/src/model_validation/tests/test_validate_model_config.rs b/crates/sqlbuild-model-config/src/model_validation/tests/test_validate_model_config.rs index 6362687338..a03d95c90f 100644 --- a/crates/sqlbuild-model-config/src/model_validation/tests/test_validate_model_config.rs +++ b/crates/sqlbuild-model-config/src/model_validation/tests/test_validate_model_config.rs @@ -24,14 +24,14 @@ fn given_effective_configs_when_validating_natively_then_python_outcomes_result( config: vec![("materialized", Value::Str("table"))], references: &["ref:invoices"], query_sql: "select 1", - expected_outcome: "Model file models/marts/orders_daily.sql references unknown model 'invoices'", + expected_outcome: "Model file sql/models/marts/orders_daily.sql references unknown model 'invoices'", }, ValidateTestCase { description: "a table function called as a scalar function", config: vec![], references: &["udf:order_lines"], query_sql: "select 1", - expected_outcome: "Model file models/marts/orders_daily.sql references table function 'order_lines' with __udf(); use __table_fn() in SQL contexts that support table-valued functions", + expected_outcome: "Model file sql/models/marts/orders_daily.sql references table function 'order_lines' with __udf(); use __table_fn() in SQL contexts that support table-valued functions", }, ValidateTestCase { description: "a model marked critical for review", diff --git a/crates/sqlbuild-model-config/src/path_defaults/constants.rs b/crates/sqlbuild-model-config/src/path_defaults/constants.rs index df9b7f4ef6..5d07a54127 100644 --- a/crates/sqlbuild-model-config/src/path_defaults/constants.rs +++ b/crates/sqlbuild-model-config/src/path_defaults/constants.rs @@ -5,7 +5,7 @@ pub const SINGLE_SEGMENT_GLOB: &str = "*"; /// A segment matching any number of path segments. pub const RECURSIVE_SEGMENT_GLOB: &str = "**"; /// The project-relative folder prefix model paths drop before matching. -pub const MODELS_PREFIX: &str = "models/"; +pub const MODELS_PREFIX: &str = "sql/models/"; /// The help a path-default conflict shows. pub const CONFLICT_HELP: &str = "Make one pattern narrower by adding literal or '*' path segments, \ or remove the overlap. Path-default selection never depends on declaration order."; diff --git a/crates/sqlbuild-model-config/src/path_defaults/tests/test_select_path_default.rs b/crates/sqlbuild-model-config/src/path_defaults/tests/test_select_path_default.rs index 08d632294d..5b91057779 100644 --- a/crates/sqlbuild-model-config/src/path_defaults/tests/test_select_path_default.rs +++ b/crates/sqlbuild-model-config/src/path_defaults/tests/test_select_path_default.rs @@ -9,7 +9,7 @@ fn given_path_default_keys_when_selecting_then_the_python_choice_is_made() { let test_cases = [ SelectTestCase { description: "the deepest literal prefix wins", - model_path: "models/staging/orders/orders.sql", + model_path: "sql/models/staging/orders/orders.sql", keys: &["staging", "staging/orders", "*/orders"], expected_choice: PathDefaultChoice::Selected(Some("staging/orders".to_owned())), }, @@ -21,7 +21,7 @@ fn given_path_default_keys_when_selecting_then_the_python_choice_is_made() { }, SelectTestCase { description: "the most literal wildcard wins", - model_path: "models\\marts\\finance\\revenue.sql", + model_path: "sql\\models\\marts\\finance\\revenue.sql", keys: &["**/finance", "marts/*", "marts/**/finance"], expected_choice: PathDefaultChoice::Selected(Some("marts/**/finance".to_owned())), }, @@ -47,19 +47,19 @@ fn given_path_default_keys_when_selecting_then_the_python_choice_is_made() { }, SelectTestCase { description: "a single glob consumes exactly one segment", - model_path: "models/commerce/eu/partner_feed/staging/orders.sql", + model_path: "sql/models/commerce/eu/partner_feed/staging/orders.sql", keys: &["commerce/*/staging"], expected_choice: PathDefaultChoice::Selected(None), }, SelectTestCase { description: "a single glob outranks a recursive glob", - model_path: "models/commerce/partner_feed/staging/orders.sql", + model_path: "sql/models/commerce/partner_feed/staging/orders.sql", keys: &["commerce/**/staging", "commerce/*/staging"], expected_choice: PathDefaultChoice::Selected(Some("commerce/*/staging".to_owned())), }, SelectTestCase { description: "a literal prefix outranks a recursive glob on a Windows path", - model_path: "models\\commerce\\partner_feed\\staging\\orders.sql", + model_path: "sql\\models\\commerce\\partner_feed\\staging\\orders.sql", keys: &["commerce/**/staging", "commerce/partner_feed/staging"], expected_choice: PathDefaultChoice::Selected(Some( "commerce/partner_feed/staging".to_owned(), diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs index e46e0fd342..919cda0d3a 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs @@ -284,6 +284,14 @@ pub(crate) fn person_routes() -> Router { "/api/control/locations/{location_id}/targets/{target}/cost", get(crate::api::_helpers::resources::person_reads::cost_summary), ) + .route( + "/api/control/locations/{location_id}/targets/{target}/cost/selection", + get(crate::api::_helpers::resources::person_cost::cost_selection), + ) + .route( + "/api/control/locations/{location_id}/targets/{target}/cost/series", + get(crate::api::_helpers::resources::person_cost::cost_series), + ) .route( "/api/control/locations/{location_id}/targets/{target}/nodes/{node_key}/cost", get(crate::api::_helpers::resources::person_reads::node_costs), diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs index 6722f3cc50..cf6038ae5b 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs @@ -11,6 +11,7 @@ pub(crate) mod location_health; pub(crate) mod location_work; pub(crate) mod person_bootstrap; pub(crate) mod person_checks; +pub(crate) mod person_cost; pub(crate) mod person_location_work; pub(crate) mod person_maintenance; pub(crate) mod person_node_sql; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_cost.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_cost.rs new file mode 100644 index 0000000000..61cb56abd5 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_cost.rs @@ -0,0 +1,92 @@ +//! A person reads the estimated query cost of a selection, and daily series for groups of it. + +use std::sync::Arc; + +use axum::extract::{Path, Query, State}; +use axum::{Extension, Json}; +use uuid::Uuid; + +use crate::api::errors::ApiError; +use crate::api::models::{CostSelectionQuery, CostSeriesQuery}; +use crate::credentials::models::{AuditContext, AuthenticatedPerson, DefaultRole}; +use crate::runs::types::CommandPlanner; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; +use crate::warehouse_history::main::read_person_cost_selection::read_person_cost_selection; +use crate::warehouse_history::main::read_person_cost_series::read_person_cost_series; +use crate::warehouse_history::models::{CostSelectionRecord, CostSeriesBatch, CostSeriesGroup}; + +/// Default and largest cost window, in days. +const COST_DAYS: (u32, u32) = (7, 90); + +fn days(days: Option) -> u32 { + days.unwrap_or(COST_DAYS.0).clamp(1, COST_DAYS.1) +} + +#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/cost/selection", operation_id = "readCostSelection", + params(("location_id" = Uuid, Path), ("target" = String, Path), + ("days" = Option, Query, description = "Builds that started in the last this many whole UTC days, today included; defaults to 7, capped at 90"), + ("select" = Option, Query, description = "Space-separated selectors, as `sqb build -s` takes them; empty selects every node"), + ("exclude" = Option, Query, description = "Space-separated selectors, as `--exclude` takes them")), + responses((status = 200, body = CostSelectionRecord, description = "The selection's cost job by node, against the period before, with daily series by job and top-level folder"), + (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn cost_selection( + (State(store), Extension(context)): (State, Extension), + (Path((location_id, target)), Query(query)): (Path<(Uuid, String)>, Query), + (Extension(AuthenticatedPerson(principal, _)), Extension(planner)): ( + Extension, + Extension>, + ), + Extension(default_role): Extension, +) -> Result, ApiError> { + Ok(Json( + read_person_cost_selection( + &store, + (planner.as_ref(), (&context, principal)), + (location_id, &target), + ( + (&query.select, &query.exclude), + days(query.days), + default_role, + ), + ) + .await?, + )) +} + +#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/cost/series", operation_id = "readCostSeries", + params(("location_id" = Uuid, Path), ("target" = String, Path), + ("days" = Option, Query, description = "As `readCostSelection`"), + ("select" = Option, Query, description = "As `readCostSelection`"), + ("exclude" = Option, Query, description = "As `readCostSelection`"), + ("groups" = String, Query, description = "A JSON array of at most 200 `CostSeriesGroup`s")), + responses((status = 200, body = CostSeriesBatch, description = "Each group's credits per day, in the groups' order"), + (status = 400, body = crate::api::models::ApiErrorBody), + (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn cost_series( + (State(store), Extension(context)): (State, Extension), + (Path((location_id, target)), Query(query)): (Path<(Uuid, String)>, Query), + (Extension(AuthenticatedPerson(principal, _)), Extension(planner)): ( + Extension, + Extension>, + ), + Extension(default_role): Extension, +) -> Result, ApiError> { + let groups: Vec = serde_json::from_str(&query.groups) + .map_err(|error| ControlError::Invalid(format!("groups: {error}")))?; + Ok(Json( + read_person_cost_series( + &store, + (planner.as_ref(), (&context, principal)), + (location_id, &target), + ( + (&query.select, &query.exclude), + (days(query.days), &groups), + default_role, + ), + ) + .await?, + )) +} diff --git a/crates/sqlbuild-orchestration/src/api/models.rs b/crates/sqlbuild-orchestration/src/api/models.rs index b27a555096..92e3af5a3f 100644 --- a/crates/sqlbuild-orchestration/src/api/models.rs +++ b/crates/sqlbuild-orchestration/src/api/models.rs @@ -10,9 +10,10 @@ use crate::api::_helpers::authentication::password_sessions; use crate::api::_helpers::authentication::{cli_login, oidc}; use crate::api::_helpers::resources::{ administrators, audit, changed_builds, changes, location_health, location_work, - person_bootstrap, person_checks, person_location_work, person_maintenance, person_node_sql, - person_operations, person_plans, person_reads, person_republish, person_selection, run_reads, - runs, service_accounts, snapshots, trigger_reads, warehouse_metadata, + person_bootstrap, person_checks, person_cost, person_location_work, person_maintenance, + person_node_sql, person_operations, person_plans, person_reads, person_republish, + person_selection, run_reads, runs, service_accounts, snapshots, trigger_reads, + warehouse_metadata, }; #[derive(Debug, utoipa::OpenApi)] @@ -51,6 +52,8 @@ use crate::api::_helpers::resources::{ person_reads::run_ignored_audits, person_reads::run_cost, person_reads::cost_summary, + person_cost::cost_selection, + person_cost::cost_series, person_reads::node_costs, person_reads::run_statement_sql, person_reads::run_output, @@ -179,6 +182,29 @@ pub(crate) struct CostQuery { pub(crate) limit: Option, } +/// A selection's cost read: its window in days and the selection, as `sqb build` takes it. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct CostSelectionQuery { + pub(crate) days: Option, + #[serde(default)] + pub(crate) select: String, + #[serde(default)] + pub(crate) exclude: String, +} + +/// A batch of daily cost series: the selection's read and the groups, as JSON. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct CostSeriesQuery { + pub(crate) days: Option, + #[serde(default)] + pub(crate) select: String, + #[serde(default)] + pub(crate) exclude: String, + pub(crate) groups: String, +} + #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub(crate) struct RunEventsQuery { diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/constants.rs b/crates/sqlbuild-orchestration/src/discovered_sets/constants.rs index e21db6699c..9d4dd5c745 100644 --- a/crates/sqlbuild-orchestration/src/discovered_sets/constants.rs +++ b/crates/sqlbuild-orchestration/src/discovered_sets/constants.rs @@ -2,6 +2,8 @@ /// The snapshot document that keeps every discovered set. pub const DISCOVERED_DOCUMENT: &str = "discovered"; +/// The snapshot document that names, for each discovered set, the `for_each` assets that read it. +pub const DISCOVERED_ASSETS_DOCUMENT: &str = "discovered_assets"; /// The longest item ID, in characters. pub const ITEM_ID_MAX_CHARS: usize = 200; /// The characters an item ID may use besides ASCII letters and digits. diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/discovered_readback.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/discovered_readback.rs index a852097f7c..954d5f52e9 100644 --- a/crates/sqlbuild-orchestration/src/discovered_sets/main/discovered_readback.rs +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/discovered_readback.rs @@ -1,30 +1,77 @@ -//! Each discovered set as a deploy reads it back: status, times, digest, tags and item count. +//! Each discovered set as a deploy reads it back: status, times, digest, tags, items and their nodes. use std::collections::BTreeMap; +use serde_json::Value; + use crate::discovered_sets::_helpers::item_graph::item_count; -use crate::discovered_sets::models::DiscoveredResult; +use crate::discovered_sets::constants::PLACEHOLDER_ITEM; +use crate::discovered_sets::main::item_node_name::item_node_name; +use crate::discovered_sets::models::DiscoveredSet; use crate::discovered_sets::types::DiscoveredSets; -use crate::platform::models::DiscoveredSetReadback; +use crate::platform::models::{DiscoveredNodeReadback, DiscoveredSetReadback}; -/// The sets by name, each with the tags of the result it serves. -pub fn discovered_readback(sets: &DiscoveredSets) -> Vec { - sets.iter() - .map(|(name, set)| DiscoveredSetReadback { +/// The sets by name, each with the tags of the result it serves and the nodes `assets` made of it. +pub fn discovered_readback( + sets: &DiscoveredSets, + assets: &BTreeMap>, +) -> Vec { + let mut readback: Vec = Vec::with_capacity(sets.len()); + for (name, set) in sets { + let readers: Vec = assets.get(name).cloned().unwrap_or_default(); + let mut nodes: Vec = Vec::new(); + for asset in &readers { + nodes.extend(item_nodes(set, asset)); + } + readback.push(DiscoveredSetReadback { name: name.clone(), status: set.status, fetched_at: set.fetched_at, last_good_at: set.last_good_at, digest: set.digest.clone(), - tags: set.result.as_ref().map(served_tags).unwrap_or_default(), + tags: set + .result + .as_ref() + .map(|result| texts(&result.tags)) + .unwrap_or_default(), items: item_count(set), error: set.error.clone(), check_every_seconds: set.check_every_seconds, - }) - .collect() + assets: readers, + nodes, + }); + } + readback } -/// The tags of the result a set serves. -fn served_tags(result: &DiscoveredResult) -> BTreeMap { - result.tags.clone() +/// The node each item of `set` became under `asset`, or the asset's one placeholder. +fn item_nodes(set: &DiscoveredSet, asset: &str) -> Vec { + let node = |step: &str, args: BTreeMap| DiscoveredNodeReadback { + key: format!("asset:{}", item_node_name(asset, Some(step))), + asset: asset.to_owned(), + step: step.to_owned(), + args, + }; + match &set.result { + Some(result) => result + .items + .iter() + .map(|item| node(&item.id, texts(&item.args))) + .collect(), + None => vec![node(PLACEHOLDER_ITEM, BTreeMap::new())], + } +} + +/// Each value as text: a string as it is, anything else as its JSON. +fn texts(values: &BTreeMap) -> BTreeMap { + values + .iter() + .map(|(key, value)| { + let text: String = match value { + Value::String(text) => text.clone(), + other => other.to_string(), + }; + (key.clone(), text) + }) + .collect() } diff --git a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_discovered.rs b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_discovered.rs index c16bbe039d..60f27f96b1 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_discovered.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_discovered.rs @@ -4,7 +4,9 @@ use uuid::Uuid; use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; -use crate::discovered_sets::constants::DISCOVERED_DOCUMENT; +use std::collections::BTreeMap; + +use crate::discovered_sets::constants::{DISCOVERED_ASSETS_DOCUMENT, DISCOVERED_DOCUMENT}; use crate::discovered_sets::main::discovered_readback::discovered_readback; use crate::discovered_sets::types::DiscoveredSets; use crate::platform::models::DiscoveredReadback; @@ -36,7 +38,7 @@ pub async fn read_person_discovered( let (transaction, documents) = read_snapshot_documents( transaction, snapshot.snapshot_id, - Some(&[DISCOVERED_DOCUMENT]), + Some(&[DISCOVERED_DOCUMENT, DISCOVERED_ASSETS_DOCUMENT]), ) .await?; commit(transaction).await?; @@ -48,10 +50,18 @@ pub async fn read_person_discovered( })?, None => DiscoveredSets::new(), }; + let assets: BTreeMap> = match documents.get(DISCOVERED_ASSETS_DOCUMENT) { + Some(document) => serde_json::from_value(document.clone()).map_err(|error| { + ControlError::Invalid(format!( + "the snapshot's discovered set assets are unreadable: {error}" + )) + })?, + None => BTreeMap::new(), + }; Ok(Some(DiscoveredReadback { snapshot_id: snapshot.snapshot_id, generation: snapshot.generation, published_at: snapshot.published_at, - sets: discovered_readback(&sets), + sets: discovered_readback(&sets, &assets), })) } diff --git a/crates/sqlbuild-orchestration/src/platform/models.rs b/crates/sqlbuild-orchestration/src/platform/models.rs index 486ef3ec7a..0e5e4355b2 100644 --- a/crates/sqlbuild-orchestration/src/platform/models.rs +++ b/crates/sqlbuild-orchestration/src/platform/models.rs @@ -1049,14 +1049,29 @@ pub struct DiscoveredSetReadback { pub last_good_at: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub digest: Option, - /// The tags of the result the set serves: its newest, or its last good one after a failure. - #[schema(value_type = Object)] - pub tags: std::collections::BTreeMap, + /// The tags of the result the set serves (its newest, or its last good one), each as text. + pub tags: std::collections::BTreeMap, pub items: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub check_every_seconds: Option, + /// The `for_each` assets that read the set. + pub assets: Vec, + /// The node each served item became under each of `assets`, or each asset's placeholder. + pub nodes: Vec, +} + +/// The node one item of a discovered set became under one `for_each` asset. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct DiscoveredNodeReadback { + /// The node key, `asset:[]`. + pub key: String, + pub asset: String, + /// The item's ID, or `*` for the placeholder of a set that never succeeded. + pub step: String, + /// The item's arguments; one that is not a string reads as its JSON text. + pub args: std::collections::BTreeMap, } /// The discovered sets of a target's current snapshot; empty when it saved none. diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/index.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/index.rs index aa752a0eb7..5ee3e52556 100644 --- a/crates/sqlbuild-orchestration/src/run_output/_helpers/index.rs +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/index.rs @@ -118,11 +118,12 @@ async fn record_segment( let before: StoredNodeLines = rows.into_iter().next().unwrap_or_default(); let node_line: i64 = before.node_lines + 1; let (mut transaction, _) = query(transaction, - "INSERT INTO sqb_run_output_segments (run_id, chunk, node_key, stream, run_line, node_line, line_count, text_offset, text_bytes) \ - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", + "INSERT INTO sqb_run_output_segments (run_id, chunk, node_key, stream, run_line, node_line, line_count, text_offset, text_bytes, read_at) \ + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)", vec![Parameter::Id(run_id), Parameter::Integer(chunk), node.clone(), Parameter::Text(stream.into()), Parameter::Integer(run_line), Parameter::Integer(node_line), Parameter::Integer(segment.line_count), - Parameter::Integer(segment.text_offset), Parameter::Integer(segment.text_bytes)]).await?; + Parameter::Integer(segment.text_offset), Parameter::Integer(segment.text_bytes), + Parameter::Time(segment.read_at)]).await?; let room: usize = MARKED_LINES.saturating_sub(usize::try_from(before.stream_marks).unwrap_or(MARKED_LINES)); let marks = &segment.marks[..segment.marks.len().min(room)]; diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/lines.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/lines.rs index 28b5015811..0d2bf6b145 100644 --- a/crates/sqlbuild-orchestration/src/run_output/_helpers/lines.rs +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/lines.rs @@ -87,7 +87,7 @@ impl<'a> ViewReader<'a> { number, node_key: segment.node_key.clone(), stream: segment.stream, - at: segment.received_at, + at: segment.read_at, level: level_of(text), text: text.to_owned(), omitted_before: match self.gap { diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/prepare.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/prepare.rs index 7c5f259b51..022ae1863a 100644 --- a/crates/sqlbuild-orchestration/src/run_output/_helpers/prepare.rs +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/prepare.rs @@ -59,6 +59,7 @@ pub(crate) fn prepared( line_count: line_count(&segment.text), text_offset: counter(text.len())?, text_bytes: counter(segment.text.len())?, + read_at: segment.read_at, marks, }); dropped = dropped.saturating_add(segment.dropped_bytes); diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/upload.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/upload.rs index 77d6f796b6..c32cb182c4 100644 --- a/crates/sqlbuild-orchestration/src/run_output/_helpers/upload.rs +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/upload.rs @@ -4,6 +4,8 @@ use std::cell::RefCell; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Instant; +use chrono::{DateTime, SubsecRound, Utc}; + use crate::api::errors::ClientError; use crate::run_output::constants::{ BATCH_TEXT_BYTES, BATCH_WINDOW, MAX_BATCH_SEGMENTS, MAX_PARTIAL_LINE_BYTES, MAX_QUEUED_BATCHES, @@ -33,8 +35,12 @@ impl UploadShared { } impl UploadState { - /// Take `data` for `node`'s `stream`, holding a line until its newline unless it outgrows its limit and is cut between characters. - pub(crate) fn append(&mut self, (node, stream): (String, OutputStream), data: &[u8]) { + /// Take `data`, read at `read_at`, for `node`'s `stream`, holding a line until its newline unless it outgrows its limit. + pub(crate) fn append( + &mut self, + (node, stream): (String, OutputStream), + (data, read_at): (&[u8], DateTime), + ) { if self.closing.is_some() { self.summary.dropped_bytes += data.len() as u64; return; @@ -55,37 +61,46 @@ impl UploadState { self.partial.insert(key.clone(), rest); } if !buffer.is_empty() { - self.push_lines(key, &String::from_utf8_lossy(&buffer)); + self.push_lines(key, (&String::from_utf8_lossy(&buffer), read_at)); } } /// End every held partial line, as when the run finishes. pub(crate) fn end_lines(&mut self) { + let read_at: DateTime = read_now(); for (key, mut buffer) in std::mem::take(&mut self.partial) { buffer.push(b'\n'); - self.push_lines(key, &String::from_utf8_lossy(&buffer)); + self.push_lines(key, (&String::from_utf8_lossy(&buffer), read_at)); } } /// Add complete lines, sealing the batch before a line would overflow its size or a segment its count. - fn push_lines(&mut self, (node, stream): (String, OutputStream), text: &str) { + fn push_lines( + &mut self, + (node, stream): (String, OutputStream), + (text, read_at): (&str, DateTime), + ) { let node_key: Option = Some(node).filter(|node| !node.is_empty()); for line in text.split_inclusive('\n') { for piece in line_pieces(line) { - self.push_piece((&node_key, stream), &piece); + self.push_piece((&node_key, stream), (&piece, read_at)); } } } - fn push_piece(&mut self, (node_key, stream): (&Option, OutputStream), piece: &str) { + /// A piece joins the open segment only when it has the same node, stream and read time. + fn push_piece( + &mut self, + (node_key, stream): (&Option, OutputStream), + (piece, read_at): (&str, DateTime), + ) { if self.batch_bytes + piece.len() > BATCH_TEXT_BYTES { self.seal(); } let joins: bool = self.unreported_drops == 0 - && self - .segments - .last() - .is_some_and(|last| last.node_key == *node_key && last.stream == stream); + && self.segments.last().is_some_and(|last| { + last.node_key == *node_key && last.stream == stream && last.read_at == read_at + }); if joins { if let Some(last) = self.segments.last_mut() { last.text.push_str(piece); @@ -98,6 +113,7 @@ impl UploadState { node_key: node_key.clone(), stream, text: piece.to_owned(), + read_at, dropped_bytes: std::mem::take(&mut self.unreported_drops), }); } @@ -288,3 +304,8 @@ fn retryable(error: &ClientError) -> bool { _ => false, } } + +/// Now, to the millisecond: lines read within one millisecond share a segment. +pub(crate) fn read_now() -> DateTime { + Utc::now().trunc_subsecs(3) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/views.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/views.rs index 5e86823c09..43c40dd743 100644 --- a/crates/sqlbuild-orchestration/src/run_output/_helpers/views.rs +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/views.rs @@ -29,28 +29,28 @@ pub(crate) async fn view_segments( let sql: &str = match (view.node.is_some(), direction) { (true, SearchDirection::Forward) => { "SELECT s.node_line AS first_line, s.line_count, s.node_key, s.stream, s.text_offset, s.text_bytes, \ - c.object_key, c.text_bytes AS chunk_text_bytes, c.received_at FROM sqb_run_output_segments s \ + c.object_key, c.text_bytes AS chunk_text_bytes, COALESCE(s.read_at, c.received_at) AS read_at FROM sqb_run_output_segments s \ JOIN sqb_run_output_chunks c ON c.run_id=s.run_id AND c.chunk=s.chunk \ WHERE s.run_id=$1 AND s.node_key=$2 AND ($3 IS NULL OR s.stream=$3) AND s.node_line+s.line_count>$4 \ ORDER BY s.node_line ASC LIMIT $5" } (true, SearchDirection::Backward) => { "SELECT s.node_line AS first_line, s.line_count, s.node_key, s.stream, s.text_offset, s.text_bytes, \ - c.object_key, c.text_bytes AS chunk_text_bytes, c.received_at FROM sqb_run_output_segments s \ + c.object_key, c.text_bytes AS chunk_text_bytes, COALESCE(s.read_at, c.received_at) AS read_at FROM sqb_run_output_segments s \ JOIN sqb_run_output_chunks c ON c.run_id=s.run_id AND c.chunk=s.chunk \ WHERE s.run_id=$1 AND s.node_key=$2 AND ($3 IS NULL OR s.stream=$3) AND s.node_line<$4 \ ORDER BY s.node_line DESC LIMIT $5" } (false, SearchDirection::Forward) => { "SELECT s.run_line AS first_line, s.line_count, s.node_key, s.stream, s.text_offset, s.text_bytes, \ - c.object_key, c.text_bytes AS chunk_text_bytes, c.received_at FROM sqb_run_output_segments s \ + c.object_key, c.text_bytes AS chunk_text_bytes, COALESCE(s.read_at, c.received_at) AS read_at FROM sqb_run_output_segments s \ JOIN sqb_run_output_chunks c ON c.run_id=s.run_id AND c.chunk=s.chunk \ WHERE s.run_id=$1 AND $2 IS NULL AND ($3 IS NULL OR s.stream=$3) AND s.run_line+s.line_count>$4 \ ORDER BY s.run_line ASC LIMIT $5" } (false, SearchDirection::Backward) => { "SELECT s.run_line AS first_line, s.line_count, s.node_key, s.stream, s.text_offset, s.text_bytes, \ - c.object_key, c.text_bytes AS chunk_text_bytes, c.received_at FROM sqb_run_output_segments s \ + c.object_key, c.text_bytes AS chunk_text_bytes, COALESCE(s.read_at, c.received_at) AS read_at FROM sqb_run_output_segments s \ JOIN sqb_run_output_chunks c ON c.run_id=s.run_id AND c.chunk=s.chunk \ WHERE s.run_id=$1 AND $2 IS NULL AND ($3 IS NULL OR s.stream=$3) AND s.run_line<$4 \ ORDER BY s.run_line DESC LIMIT $5" diff --git a/crates/sqlbuild-orchestration/src/run_output/main/forward_output.rs b/crates/sqlbuild-orchestration/src/run_output/main/forward_output.rs index dcb8ad4b64..fea2aec5fe 100644 --- a/crates/sqlbuild-orchestration/src/run_output/main/forward_output.rs +++ b/crates/sqlbuild-orchestration/src/run_output/main/forward_output.rs @@ -1,6 +1,6 @@ //! Hand bytes a process stream accepted to this process's run output, under the node running on this thread. -use crate::run_output::_helpers::upload::{OUTPUT_NODE, attached}; +use crate::run_output::_helpers::upload::{OUTPUT_NODE, attached, read_now}; use crate::run_output::models::OutputStream; /// Never waits: call it under the lock that orders output, then `wait_for_output_room` outside it; a no-op outside a worker. @@ -11,6 +11,10 @@ pub fn forward_output(stream: OutputStream, data: &[u8]) { let node: String = OUTPUT_NODE .with(|node| node.borrow().clone()) .unwrap_or_default(); - uploader.shared.locked().append((node, stream), data); + let read_at = read_now(); + uploader + .shared + .locked() + .append((node, stream), (data, read_at)); uploader.shared.wake.notify_all(); } diff --git a/crates/sqlbuild-orchestration/src/run_output/models.rs b/crates/sqlbuild-orchestration/src/run_output/models.rs index 2b7d6ca348..e45bda5d9d 100644 --- a/crates/sqlbuild-orchestration/src/run_output/models.rs +++ b/crates/sqlbuild-orchestration/src/run_output/models.rs @@ -84,6 +84,8 @@ pub struct OutputSegment { pub node_key: Option, pub stream: OutputStream, pub text: String, + /// When the worker read these lines from the command's output, to the millisecond. + pub read_at: chrono::DateTime, /// Bytes the worker dropped just before these lines because it could not send them fast enough. #[serde(default)] pub dropped_bytes: u64, @@ -302,6 +304,7 @@ pub(crate) struct PreparedSegment { pub(crate) line_count: i64, pub(crate) text_offset: i64, pub(crate) text_bytes: i64, + pub(crate) read_at: chrono::DateTime, /// Each marked line's offset within the segment, level and text. pub(crate) marks: Vec<(i64, OutputLevel, String)>, } @@ -317,7 +320,7 @@ pub(crate) struct StoredSegment { pub(crate) text_bytes: i64, pub(crate) object_key: String, pub(crate) chunk_text_bytes: i64, - pub(crate) received_at: chrono::DateTime, + pub(crate) read_at: chrono::DateTime, } /// A node's line count and its marks so far in one stream, before a segment adds to them. diff --git a/crates/sqlbuild-orchestration/src/runs/main/requests/mod.rs b/crates/sqlbuild-orchestration/src/runs/main/requests/mod.rs index f030aae726..f5173a1677 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/requests/mod.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/requests/mod.rs @@ -6,3 +6,4 @@ pub mod read_selection_vocabulary; pub mod request_job_run; pub mod request_person_run; pub mod request_rerun; +pub mod select_viewed_nodes; diff --git a/crates/sqlbuild-orchestration/src/runs/main/requests/select_viewed_nodes.rs b/crates/sqlbuild-orchestration/src/runs/main/requests/select_viewed_nodes.rs new file mode 100644 index 0000000000..44ba381f7d --- /dev/null +++ b/crates/sqlbuild-orchestration/src/runs/main/requests/select_viewed_nodes.rs @@ -0,0 +1,62 @@ +//! Resolve a selection to every node it picks in the current publication, for a person who may view it. + +use std::collections::BTreeSet; + +use uuid::Uuid; + +use crate::credentials::models::{AuditContext, DefaultRole}; +use crate::runs::_helpers::lifecycle::publications::viewed_publication; +use crate::runs::models::{SelectionProblem, ViewedSelection}; +use crate::runs::types::CommandPlanner; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; + +/// Every key `sqb build --select … --exclude …` picks; an empty selection is every node, even unpublished ones. +pub async fn select_viewed_nodes( + store: &ControlStore, + (planner, credentials): (&dyn CommandPlanner, (&AuditContext, Uuid)), + (location_id, target): (Uuid, &str), + ((select, exclude), default_role): ((&str, &str), DefaultRole), +) -> Result { + let current = viewed_publication( + store, + (planner, credentials), + (location_id, target), + default_role, + ) + .await?; + let snapshot_id: Option = current.as_ref().map(|(snapshot, _)| snapshot.snapshot_id); + if select.trim().is_empty() && exclude.trim().is_empty() { + return Ok(ViewedSelection { + snapshot_id, + keys: None, + error: None, + }); + } + let Some((_, publication)) = current else { + return Ok(ViewedSelection { + snapshot_id, + keys: Some(BTreeSet::new()), + error: Some(SelectionProblem { + code: None, + message: "this target has no publication yet".into(), + help: None, + location: None, + suggestions: Vec::new(), + refused: None, + }), + }); + }; + Ok(match publication.prepared.evaluate(select, exclude) { + Ok(keys) => ViewedSelection { + snapshot_id, + keys: Some(keys.into_iter().collect()), + error: None, + }, + Err(problem) => ViewedSelection { + snapshot_id, + keys: Some(BTreeSet::new()), + error: Some(*problem), + }, + }) +} diff --git a/crates/sqlbuild-orchestration/src/runs/models.rs b/crates/sqlbuild-orchestration/src/runs/models.rs index 0e4ed5c66b..c166f8f6ad 100644 --- a/crates/sqlbuild-orchestration/src/runs/models.rs +++ b/crates/sqlbuild-orchestration/src/runs/models.rs @@ -481,7 +481,7 @@ pub struct RunEventRecord { pub outcome: Option, pub row_count: Option, pub affected_rows: Option, - /// A summary the scheduler writes for a group run's member events, such as a member retry; never error or SQL text. + /// A summary of what an event names, such as a member retry or the command a worker started; never error or SQL text. #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, /// For a check's result: its name as declared, its ID and this result's, and the rows it found; never its SQL or rows. @@ -493,6 +493,15 @@ pub struct RunEventRecord { pub check_result_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub check_rows: Option, + /// For a phase of a worker's command, such as `compiled` or `planned`: what it counted, what it is about and its sub-steps. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub phase: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub phase_count: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub phase_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub phase_detail: Option, } /// One error-severity audit failure a run or one of its current members let through; never its SQL or evidence. @@ -1182,3 +1191,14 @@ pub struct VocabularyEntry { pub value: String, pub count: u64, } + +/// The nodes a selection picks in the current publication, as a person may view them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ViewedSelection { + /// The publication evaluated; None before the first one. + pub snapshot_id: Option, + /// Every picked key; None for an empty selection, which is every node. + pub keys: Option>, + /// Why `sqb` refuses the selection; then no key is picked. + pub error: Option, +} diff --git a/crates/sqlbuild-orchestration/src/snapshots/constants.rs b/crates/sqlbuild-orchestration/src/snapshots/constants.rs index 4b8347da56..eadad9db86 100644 --- a/crates/sqlbuild-orchestration/src/snapshots/constants.rs +++ b/crates/sqlbuild-orchestration/src/snapshots/constants.rs @@ -1,6 +1,6 @@ //! Snapshot retention keeps recent publications per location and target, collected in small batches. -use crate::discovered_sets::constants::DISCOVERED_DOCUMENT; +use crate::discovered_sets::constants::{DISCOVERED_ASSETS_DOCUMENT, DISCOVERED_DOCUMENT}; pub(crate) const DEFAULT_SNAPSHOT_RETENTION_COUNT: u16 = 10; pub(crate) const SNAPSHOT_RETENTION_BATCH: usize = 10; @@ -13,7 +13,7 @@ pub(crate) const PUBLISH_TIMEOUT_SECONDS: u64 = 300; /// The target's non-secret connection settings, a `ConnectionDetails`. pub const CONNECTION_DOCUMENT: &str = "connection"; /// Snapshot document kinds: per-snapshot metadata that never changes a node hash or node change. -pub(crate) const SNAPSHOT_DOCUMENT_KINDS: [&str; 9] = [ +pub(crate) const SNAPSHOT_DOCUMENT_KINDS: [&str; 10] = [ "jobs", "groups", "triggers", @@ -23,6 +23,7 @@ pub(crate) const SNAPSHOT_DOCUMENT_KINDS: [&str; 9] = [ "providers", CONNECTION_DOCUMENT, DISCOVERED_DOCUMENT, + DISCOVERED_ASSETS_DOCUMENT, ]; /// Connection keys that may name the signed-in user, in preference order. pub(crate) const USER_KEYS: [&str; 3] = ["user", "username", "login"]; diff --git a/crates/sqlbuild-orchestration/src/store/schema.sql b/crates/sqlbuild-orchestration/src/store/schema.sql index 7aa63f518f..117718fc8d 100644 --- a/crates/sqlbuild-orchestration/src/store/schema.sql +++ b/crates/sqlbuild-orchestration/src/store/schema.sql @@ -56,7 +56,7 @@ CREATE TABLE sqb_snapshot_sources ( ); CREATE TABLE sqb_snapshot_documents ( snapshot_id {uuid} NOT NULL REFERENCES sqb_snapshots(snapshot_id), - kind TEXT NOT NULL CHECK (kind IN ('jobs', 'groups', 'triggers', 'roles', 'lineage', 'columns', 'providers', 'connection', 'discovered')), + kind TEXT NOT NULL CHECK (kind IN ('jobs', 'groups', 'triggers', 'roles', 'lineage', 'columns', 'providers', 'connection', 'discovered', 'discovered_assets')), document_hash TEXT NOT NULL REFERENCES sqb_documents(document_hash), PRIMARY KEY (snapshot_id, kind) ); @@ -231,6 +231,7 @@ CREATE TABLE sqb_run_output_segments ( line_count BIGINT NOT NULL, text_offset BIGINT NOT NULL, text_bytes BIGINT NOT NULL, + read_at {time}, PRIMARY KEY (run_id, run_line), FOREIGN KEY (run_id, chunk) REFERENCES sqb_run_output_chunks(run_id, chunk) ); diff --git a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs index d2e6a5a163..69f1bd6955 100644 --- a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs +++ b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs @@ -64,6 +64,18 @@ pub(crate) const MIGRATIONS: &[StoreMigration] = &[ postgres: include_str!("../sql/0009_service_accounts.postgres.sql"), step: None, }, + StoreMigration { + name: "run_output_read_times", + sqlite: include_str!("../sql/0010_run_output_read_times.sqlite.sql"), + postgres: include_str!("../sql/0010_run_output_read_times.postgres.sql"), + step: None, + }, + StoreMigration { + name: "discovered_assets_document", + sqlite: include_str!("../sql/0011_discovered_assets_document.sqlite.sql"), + postgres: include_str!("../sql/0011_discovered_assets_document.postgres.sql"), + step: None, + }, ]; /// The schema version a store created by this build has. diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0010_run_output_read_times.postgres.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0010_run_output_read_times.postgres.sql new file mode 100644 index 0000000000..1ab8950c95 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0010_run_output_read_times.postgres.sql @@ -0,0 +1,3 @@ +-- When the worker read the lines of each output segment. Segments stored before this have none +-- and read as the time their batch arrived. +ALTER TABLE sqb_run_output_segments ADD COLUMN read_at {time}; diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0010_run_output_read_times.sqlite.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0010_run_output_read_times.sqlite.sql new file mode 100644 index 0000000000..1ab8950c95 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0010_run_output_read_times.sqlite.sql @@ -0,0 +1,3 @@ +-- When the worker read the lines of each output segment. Segments stored before this have none +-- and read as the time their batch arrived. +ALTER TABLE sqb_run_output_segments ADD COLUMN read_at {time}; diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0011_discovered_assets_document.postgres.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0011_discovered_assets_document.postgres.sql new file mode 100644 index 0000000000..3a455ad81b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0011_discovered_assets_document.postgres.sql @@ -0,0 +1,5 @@ +-- Snapshots name the for_each assets reading each discovered set in a new 'discovered_assets' +-- document. +ALTER TABLE sqb_snapshot_documents DROP CONSTRAINT sqb_snapshot_documents_kind_check; + +ALTER TABLE sqb_snapshot_documents ADD CONSTRAINT sqb_snapshot_documents_kind_check CHECK (kind IN ('jobs', 'groups', 'triggers', 'roles', 'lineage', 'columns', 'providers', 'connection', 'discovered', 'discovered_assets')); diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0011_discovered_assets_document.sqlite.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0011_discovered_assets_document.sqlite.sql new file mode 100644 index 0000000000..08b01a5d70 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0011_discovered_assets_document.sqlite.sql @@ -0,0 +1,16 @@ +-- Snapshots name the for_each assets reading each discovered set in a new 'discovered_assets' +-- document. +CREATE TABLE sqb_snapshot_documents_v2 ( + snapshot_id {uuid} NOT NULL REFERENCES sqb_snapshots(snapshot_id), + kind TEXT NOT NULL CHECK (kind IN ('jobs', 'groups', 'triggers', 'roles', 'lineage', 'columns', 'providers', 'connection', 'discovered', 'discovered_assets')), + document_hash TEXT NOT NULL REFERENCES sqb_documents(document_hash), + PRIMARY KEY (snapshot_id, kind) +); + +INSERT INTO sqb_snapshot_documents_v2 (snapshot_id, kind, document_hash) SELECT snapshot_id, kind, document_hash FROM sqb_snapshot_documents; + +DROP TABLE sqb_snapshot_documents; + +ALTER TABLE sqb_snapshot_documents_v2 RENAME TO sqb_snapshot_documents; + +CREATE INDEX IF NOT EXISTS sqb_snapshot_documents_hash ON sqb_snapshot_documents(document_hash); diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_selection.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_selection.rs new file mode 100644 index 0000000000..63b8a5f060 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_selection.rs @@ -0,0 +1,231 @@ +//! A selection's cost rows over a period and the one before it: each with its job, node, folder and day. + +use std::collections::{BTreeMap, BTreeSet}; + +use chrono::{DateTime, Duration, NaiveDate, Utc}; +use uuid::Uuid; + +use crate::credentials::models::{AuditContext, DefaultRole}; +use crate::runs::main::requests::select_viewed_nodes::select_viewed_nodes; +use crate::runs::models::{SelectionProblem, ViewedSelection}; +use crate::runs::types::CommandPlanner; +use crate::snapshots::main::reads::read_snapshot_nodes::read_snapshot_nodes; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit}; +use crate::store::models::{ControlStore, TransactionMode}; +use crate::warehouse_history::_helpers::costs::{ + PENDING_STATUSES, TOTAL_RESOURCE_TYPE, amount, latest_costs_in, price_source, +}; + +/// The folder of nodes whose path the publication doesn't give, such as nodes no longer deployed. +pub(crate) const OTHER_FOLDER: &str = "other"; +/// The layout root of SQL models, which folders leave out. +const MODELS_ROOT: &str = "sql/models"; + +/// A period of whole UTC days ending today, and the one before it. +pub(crate) struct CostPeriod { + pub(crate) days: u32, + pub(crate) first_day: NaiveDate, + pub(crate) since: DateTime, + pub(crate) previous_since: DateTime, +} + +impl CostPeriod { + pub(crate) fn ending(now: DateTime, days: u32) -> Self { + let first_day: NaiveDate = now.date_naive() - Duration::days(i64::from(days) - 1); + let since: DateTime = first_day.and_time(chrono::NaiveTime::MIN).and_utc(); + Self { + days, + first_day, + since, + previous_since: since - Duration::days(i64::from(days)), + } + } + + /// The period's days as `YYYY-MM-DD`, oldest first. + pub(crate) fn dates(&self) -> Vec { + (0..i64::from(self.days)) + .map(|day| { + (self.first_day + Duration::days(day)) + .format("%Y-%m-%d") + .to_string() + }) + .collect() + } + + /// The day of the period a build started on; None for the period before. + fn day(&self, started: DateTime) -> Option { + if started < self.since { + return None; + } + let offset: u64 = (started.date_naive() - self.first_day) + .num_days() + .unsigned_abs(); + let day: usize = usize::try_from(offset).unwrap_or(usize::MAX); + (day < self.days as usize).then_some(day) + } +} + +/// One cost row of a selected node. +pub(crate) struct CostRow { + pub(crate) run_id: String, + pub(crate) job: Option, + pub(crate) node_key: String, + pub(crate) folder: String, + /// The day of the period; None for a row of the period before. + pub(crate) day: Option, + pub(crate) credits: f64, + pub(crate) usd: Option, + /// Where the row's price came from. + pub(crate) source: Option, + pub(crate) seconds: f64, + pub(crate) queries: i64, + pub(crate) bytes_scanned: i64, +} + +/// The selection's rows, the builds whose cost is still pending, and the publication evaluated. +pub(crate) struct SelectionCosts { + pub(crate) snapshot_id: Option, + pub(crate) error: Option, + pub(crate) rows: Vec, + pub(crate) pending_runs: BTreeSet, +} + +/// A node's folder: its directory, without `sql/models/` (empty at its top); other roots as published. +pub(crate) fn cost_folder(path: Option<&str>) -> String { + let Some(path) = path else { + return OTHER_FOLDER.to_owned(); + }; + let directory: &str = path.rsplit_once('/').map_or("", |(directory, _)| directory); + if directory == MODELS_ROOT { + return String::new(); + } + directory + .strip_prefix(MODELS_ROOT) + .and_then(|rest| rest.strip_prefix('/')) + .unwrap_or(directory) + .to_owned() +} + +/// The period of the last `days` whole UTC days to now, and the selection's cost rows over it. +pub(crate) async fn selection_costs_in_days( + store: &ControlStore, + (planner, credentials): (&dyn CommandPlanner, (&AuditContext, Uuid)), + (location_id, target): (Uuid, &str), + ((select, exclude), days, default_role): ((&str, &str), u32, DefaultRole), +) -> Result<(CostPeriod, SelectionCosts), ControlError> { + let period: CostPeriod = CostPeriod::ending(Utc::now(), days); + let costs: SelectionCosts = selection_costs( + store, + (planner, credentials), + (location_id, target), + ((select, exclude), &period, default_role), + ) + .await?; + Ok((period, costs)) +} + +/// The cost rows of the nodes a selection picks over `period` and the one before, or why it's refused. +async fn selection_costs( + store: &ControlStore, + (planner, credentials): (&dyn CommandPlanner, (&AuditContext, Uuid)), + (location_id, target): (Uuid, &str), + ((select, exclude), period, default_role): ((&str, &str), &CostPeriod, DefaultRole), +) -> Result { + let viewed: ViewedSelection = select_viewed_nodes( + store, + (planner, credentials), + (location_id, target), + ((select, exclude), default_role), + ) + .await?; + let mut result = SelectionCosts { + snapshot_id: viewed.snapshot_id, + error: viewed.error, + rows: Vec::new(), + pending_runs: BTreeSet::new(), + }; + if result.error.is_some() { + return Ok(result); + } + let selected: Option> = viewed.keys; + let transaction = begin(store, TransactionMode::Read).await?; + let (transaction, costs) = latest_costs_in( + transaction, + (location_id, target), + period.previous_since, + None, + ) + .await?; + let mut keys: BTreeSet = BTreeSet::new(); + for cost in &costs { + let record = &cost.record; + if record.resource_type == TOTAL_RESOURCE_TYPE { + if PENDING_STATUSES.contains(&record.status.as_str()) { + result.pending_runs.insert(record.run_id.clone()); + } + continue; + } + let key: String = format!("{}:{}", record.resource_type, record.resource_name); + if selected + .as_ref() + .is_none_or(|selected| selected.contains(&key)) + { + keys.insert(key); + } + } + let (transaction, nodes) = match &result.snapshot_id { + Some(snapshot_id) => read_snapshot_nodes(transaction, *snapshot_id, Some(&keys)).await?, + None => (transaction, BTreeMap::new()), + }; + commit(transaction).await?; + let folders: BTreeMap<&String, String> = keys + .iter() + .map(|key| { + let path = nodes + .get(key) + .and_then(|node| node.definition["path"].as_str()); + (key, cost_folder(path)) + }) + .collect(); + for cost in costs { + let record = cost.record; + if record.resource_type == TOTAL_RESOURCE_TYPE { + continue; + } + let node_key: String = format!("{}:{}", record.resource_type, record.resource_name); + let Some(folder) = folders.get(&node_key) else { + continue; + }; + result.rows.push(CostRow { + source: price_source(&record).map(str::to_owned), + folder: folder.clone(), + day: period.day(record.run_started_at), + run_id: record.run_id, + job: cost.job_key, + credits: amount(&record.estimated_credits), + usd: record.estimated_usd.as_deref().map(amount), + seconds: amount(&record.attributed_seconds), + queries: record.query_count, + bytes_scanned: record.bytes_scanned, + node_key, + }); + } + Ok(result) +} + +/// A dollar total that stays unknown once any part of it is. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Dollars(pub(crate) Option); + +impl Default for Dollars { + fn default() -> Self { + Self(Some(0.0)) + } +} + +impl Dollars { + pub(crate) fn add(&mut self, usd: Option) { + self.0 = self.0.zip(usd).map(|(total, usd)| total + usd); + } +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_summary.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_summary.rs new file mode 100644 index 0000000000..9a192bf4f0 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_summary.rs @@ -0,0 +1,199 @@ +//! A selection's cost rows summed job by node, with daily series by job and top-level folder. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::warehouse_history::_helpers::cost_selection::{ + CostPeriod, CostRow, Dollars, SelectionCosts, +}; +use crate::warehouse_history::_helpers::costs::combined_source; +use crate::warehouse_history::models::{ + CostFactRecord, CostPrice, CostSelectionRecord, CostSeriesGroup, CostSeriesRecord, +}; + +/// One job's cost on one node, as rows add up. +#[derive(Default)] +struct Fact { + credits: f64, + previous_credits: f64, + usd: Dollars, + previous_usd: Dollars, + seconds: f64, + runs: BTreeSet, + queries: i64, + bytes_scanned: i64, +} + +impl Fact { + fn add(&mut self, row: &CostRow) { + if row.day.is_none() { + self.previous_credits += row.credits; + self.previous_usd.add(row.usd); + return; + } + self.credits += row.credits; + self.usd.add(row.usd); + self.seconds += row.seconds; + self.runs.insert(row.run_id.clone()); + self.queries += row.queries; + self.bytes_scanned += row.bytes_scanned; + } + + fn record(self, (job, node_key, folder): (Option, String, String)) -> CostFactRecord { + CostFactRecord { + job, + node_key, + folder, + credits: self.credits, + previous_credits: self.previous_credits, + usd: self.usd.0, + previous_usd: self.previous_usd.0, + seconds: self.seconds, + runs: count(self.runs.len()), + queries: self.queries, + bytes_scanned: self.bytes_scanned, + } + } +} + +fn count(n: usize) -> i64 { + i64::try_from(n).unwrap_or(i64::MAX) +} + +/// Credits per day of the period by `key`, for the period's rows. +fn daily( + period: &CostPeriod, + rows: &[CostRow], + key: impl Fn(&CostRow) -> K, +) -> BTreeMap> { + let mut series: BTreeMap> = BTreeMap::new(); + for row in rows { + if let Some(day) = row.day { + series + .entry(key(row)) + .or_insert_with(|| vec![0.0; period.days as usize])[day] += row.credits; + } + } + series +} + +/// The facts, most expensive first. +fn facts(rows: &[CostRow]) -> Vec { + let mut facts: BTreeMap<(Option, String), (String, Fact)> = BTreeMap::new(); + for row in rows { + facts + .entry((row.job.clone(), row.node_key.clone())) + .or_insert_with(|| (row.folder.clone(), Fact::default())) + .1 + .add(row); + } + let mut records: Vec = facts + .into_iter() + .map(|((job, node_key), (folder, fact))| fact.record((job, node_key, folder))) + .collect(); + records.sort_by(|left, right| right.credits.total_cmp(&left.credits)); + records +} + +/// The record of a selection's rows over `period`. +pub(crate) fn summarise(period: &CostPeriod, costs: SelectionCosts) -> CostSelectionRecord { + let facts: Vec = facts(&costs.rows); + let (mut usd, mut previous_usd) = (Dollars::default(), Dollars::default()); + let mut runs: BTreeSet<&str> = BTreeSet::new(); + let mut sources: BTreeSet = BTreeSet::new(); + for row in &costs.rows { + if row.day.is_some() { + usd.add(row.usd); + runs.insert(&row.run_id); + sources.extend(row.source.clone()); + } else { + previous_usd.add(row.usd); + } + } + let credits: f64 = facts.iter().map(|fact| fact.credits).sum(); + let usd: Option = usd.0.filter(|_| !runs.is_empty()); + let incomplete: usize = runs + .iter() + .filter(|run| costs.pending_runs.contains(**run)) + .count(); + let job_daily = daily(period, &costs.rows, |row| row.job.clone()); + let folder_daily = daily(period, &costs.rows, |row| { + row.folder.split('/').next().unwrap_or_default().to_owned() + }); + CostSelectionRecord { + snapshot_id: costs.snapshot_id, + since: period.since, + days: period.days, + dates: period.dates(), + error: costs.error, + price: usd.filter(|_| credits.is_normal()).map(|usd| CostPrice { + usd_per_credit: usd / credits, + source: combined_source(&sources).unwrap_or_default(), + }), + credits, + previous_credits: facts.iter().map(|fact| fact.previous_credits).sum(), + usd, + previous_usd: previous_usd.0, + runs: count(runs.len()), + incomplete_runs: count(incomplete), + queries: facts.iter().map(|fact| fact.queries).sum(), + seconds: facts.iter().map(|fact| fact.seconds).sum(), + bytes_scanned: facts.iter().map(|fact| fact.bytes_scanned).sum(), + job_daily: job_daily + .into_iter() + .map(|(key, credits)| CostSeriesRecord { key, credits }) + .collect(), + folder_daily: folder_daily + .into_iter() + .map(|(key, credits)| CostSeriesRecord { + key: Some(key), + credits, + }) + .collect(), + facts, + } +} + +/// Each group's credits per day of the period, in the groups' order. +pub(crate) fn group_series( + period: &CostPeriod, + rows: &[CostRow], + groups: &[CostSeriesGroup], +) -> Vec> { + let mut series: Vec> = vec![vec![0.0; period.days as usize]; groups.len()]; + for row in rows { + let Some(day) = row.day else { + continue; + }; + for (group, values) in groups.iter().zip(series.iter_mut()) { + if in_group(group, row) { + values[day] += row.credits; + } + } + } + series +} + +/// Whether `row` is in `group`: every field the group gives matches. +fn in_group(group: &CostSeriesGroup, row: &CostRow) -> bool { + let job: bool = if group.manual { + row.job.is_none() + } else { + group + .job + .as_ref() + .is_none_or(|job| row.job.as_ref() == Some(job)) + }; + let folder: bool = group.folder.as_ref().is_none_or(|folder| { + folder.is_empty() + || row.folder == *folder + || row + .folder + .strip_prefix(folder.as_str()) + .is_some_and(|rest| rest.starts_with('/')) + }); + let node: bool = group + .node_key + .as_ref() + .is_none_or(|node_key| row.node_key == *node_key); + job && folder && node +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/costs.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/costs.rs index 2d0069d8f7..5d47a97d8b 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/costs.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/costs.rs @@ -8,6 +8,9 @@ use uuid::Uuid; use crate::store::errors::ControlError; use crate::store::main::query::query; use crate::store::models::{ControlTransaction, Parameter}; +use crate::warehouse_history::constants::{ + CONFIG_PRICE_SOURCE, LIST_PRICE_SOURCE, MIXED_PRICE_SOURCE, +}; use crate::warehouse_history::models::{CostGroup, NodeCostRecord}; use crate::warehouse_metadata::models::WarehouseResourceCostRecord; @@ -68,6 +71,24 @@ pub(crate) async fn latest_costs_in( Ok((transaction, costs)) } +/// Where a row's price came from; a priced row recorded before prices were is the project's. +pub(crate) fn price_source(record: &WarehouseResourceCostRecord) -> Option<&str> { + record + .usd_per_credit_source + .as_deref() + .or(record.estimated_usd.as_ref().map(|_| CONFIG_PRICE_SOURCE)) +} + +/// Several prices' one source: theirs if they agree, else `list_price` if any is one, else `mixed`. +pub(crate) fn combined_source(sources: &BTreeSet) -> Option { + match sources.len() { + 0 => None, + 1 => sources.first().cloned(), + _ if sources.contains(LIST_PRICE_SOURCE) => Some(LIST_PRICE_SOURCE.to_owned()), + _ => Some(MIXED_PRICE_SOURCE.to_owned()), + } +} + /// A decimal text as a number; an unreadable value counts as zero. pub(crate) fn amount(text: &str) -> f64 { text.trim().parse().unwrap_or(0.0) @@ -82,9 +103,15 @@ pub(crate) struct Accumulator { unpriced: bool, seconds: f64, runs: BTreeSet, + sources: BTreeSet, } impl Accumulator { + /// Where the group's prices came from, as one source; none when any of it is unpriced. + pub(crate) fn source(&self) -> Option { + combined_source(&self.sources).filter(|_| !self.unpriced) + } + pub(crate) fn add(&mut self, cost: &LatestCost) { let record = &cost.record; self.credits += amount(&record.estimated_credits); @@ -92,6 +119,9 @@ impl Accumulator { Some(usd) => self.usd += amount(usd), None => self.unpriced = true, } + if let Some(source) = price_source(record) { + self.sources.insert(source.to_owned()); + } self.seconds += amount(&record.attributed_seconds); self.runs.insert(record.run_id.clone()); } @@ -107,6 +137,9 @@ impl Accumulator { } } +/// Accumulated cost by group key. +pub(crate) type CostGroups = BTreeMap, Accumulator>; + /// Groups as records, most expensive first. pub(crate) fn ranked(groups: BTreeMap, Accumulator>) -> Vec { let mut ranked: Vec = groups @@ -136,9 +169,13 @@ pub(crate) fn node_builds(costs: &[LatestCost], limit: u32) -> Vec>'command'"), + ("started_target", "payload->>'target'"), + ("started_selected", "payload->>'selection_count'"), + ("started_version", "producer_version"), +]; + /// The payload fields that name the node of an event in `NODE_EVENTS`, as `(column, JSON path)`. const NODE_FIELDS: [(&str, &str); 5] = [ ("node_key", "payload->'change'->'change'->>'node_key'"), @@ -256,7 +268,11 @@ pub(crate) async fn run_events_in( CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN payload->>'binding_key' END AS check_binding_key, \ CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN payload->>'result_id' END AS check_result_id, \ CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN CAST(payload->>'violation_count' AS BIGINT) END AS check_rows, \ - {} FROM events WHERE {filter} AND storage_id>${next} ORDER BY storage_id LIMIT ${}", node_columns(), next + 1) + CASE WHEN event_type='{INVOCATION_PHASE_EVENT}' THEN payload->>'phase' END AS phase, \ + CASE WHEN event_type='{INVOCATION_PHASE_EVENT}' THEN CAST(payload->>'count' AS BIGINT) END AS phase_count, \ + CASE WHEN event_type='{INVOCATION_PHASE_EVENT}' THEN payload->>'name' END AS phase_name, \ + CASE WHEN event_type='{INVOCATION_PHASE_EVENT}' THEN payload->>'detail' END AS phase_detail, \ + {}, {} FROM events WHERE {filter} AND storage_id>${next} ORDER BY storage_id LIMIT ${}", node_columns(), start_columns(), next + 1) }, vec![ Parameter::Integer(after), @@ -266,10 +282,14 @@ pub(crate) async fn run_events_in( |row: &mut Row| { let payload = row.remove("member_payload").unwrap_or(Value::Null); let launched = row.get("event_type").and_then(Value::as_str) == Some(RUN_LAUNCHED_EVENT); + let started: Option = start_message(row); + for (column, _) in START_FIELDS { + row.remove(column); + } let message = if launched { launch_message(&payload)? } else { - member_message(&payload)? + started.or(member_message(&payload)?) }; if let Some(message) = message { row.insert("message".into(), Value::String(message)); @@ -338,6 +358,45 @@ pub(crate) fn node_of(row: &Row) -> Option<(String, String)> { Some((kind.into(), name.into())) } +/// What started an invocation, read only from an `invocation_started` event's payload and version. +fn start_columns() -> String { + START_FIELDS + .iter() + .map(|(column, value)| { + format!( + "CASE WHEN event_type='{INVOCATION_STARTED_EVENT}' THEN {value} END AS {column}" + ) + }) + .collect::>() + .join(", ") +} + +/// An invocation's command, target, selection and version, such as `sqb build · target uat · 93 selected · SQLBuild 0.259.0`. +pub(crate) fn start_message(row: &Row) -> Option { + let [command, target, selected, version] = + START_FIELDS.map(|(column, _)| row.get(column).and_then(shown)); + let command = command?; + let parts: Vec = [ + Some(format!("sqb {command}")), + target.map(|target| format!("target {target}")), + selected.map(|count| format!("{count} selected")), + version.map(|version| format!("SQLBuild {version}")), + ] + .into_iter() + .flatten() + .collect(); + Some(parts.join(" · ")) +} + +/// A text or number column as text; `None` when null or empty. +fn shown(value: &Value) -> Option { + match value { + Value::String(text) if !text.is_empty() => Some(text.clone()), + Value::Number(number) => Some(number.to_string()), + _ => None, + } +} + /// The scheduler's summary of a member retry or recovery on its group run, from its own payload. fn member_message(payload: &Value) -> Result, ControlError> { Ok(event_payload(payload)?.as_ref().and_then(member_summary)) diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/constants.rs b/crates/sqlbuild-orchestration/src/warehouse_history/constants.rs new file mode 100644 index 0000000000..7263cac60f --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/constants.rs @@ -0,0 +1,10 @@ +//! Limits of the warehouse history reads. + +/// The most groups one batch of daily cost series may ask for. +pub const COST_SERIES_GROUPS: usize = 200; +/// The price source of dollars from the project's `[cost] usd_per_credit`. +pub(crate) const CONFIG_PRICE_SOURCE: &str = "config"; +/// The price source of the list price for the account's region: an estimate. +pub(crate) const LIST_PRICE_SOURCE: &str = "list_price"; +/// The source of a total whose rows were priced from different sources, none an estimate. +pub(crate) const MIXED_PRICE_SOURCE: &str = "mixed"; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs index 522a16759f..bb0e548fd0 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs @@ -3,6 +3,8 @@ pub mod read_node_check_counts; pub mod read_person_check; pub mod read_person_check_evidence; pub mod read_person_check_sql; +pub mod read_person_cost_selection; +pub mod read_person_cost_series; pub mod read_person_cost_summary; pub mod read_person_maintenance; pub mod read_person_microbatch_coverage; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_selection.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_selection.rs new file mode 100644 index 0000000000..850307ccfd --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_selection.rs @@ -0,0 +1,28 @@ +//! A selection's estimated query cost over a period, job by node, with daily series by job and top-level folder. + +use uuid::Uuid; + +use crate::credentials::models::{AuditContext, DefaultRole}; +use crate::runs::types::CommandPlanner; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; +use crate::warehouse_history::_helpers::cost_selection::selection_costs_in_days; +use crate::warehouse_history::_helpers::cost_summary::summarise; +use crate::warehouse_history::models::CostSelectionRecord; + +/// The cost of the nodes `select` and `exclude` pick over the last `days` whole UTC days and the days before. +pub async fn read_person_cost_selection( + store: &ControlStore, + (planner, credentials): (&dyn CommandPlanner, (&AuditContext, Uuid)), + (location_id, target): (Uuid, &str), + ((select, exclude), days, default_role): ((&str, &str), u32, DefaultRole), +) -> Result { + let (period, costs) = selection_costs_in_days( + store, + (planner, credentials), + (location_id, target), + ((select, exclude), days, default_role), + ) + .await?; + Ok(summarise(&period, costs)) +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_series.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_series.rs new file mode 100644 index 0000000000..ded5325317 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_series.rs @@ -0,0 +1,41 @@ +//! Daily cost series of a selection, for a batch of groups by job, folder and node. + +use uuid::Uuid; + +use crate::credentials::models::{AuditContext, DefaultRole}; +use crate::runs::types::CommandPlanner; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; +use crate::warehouse_history::_helpers::cost_selection::selection_costs_in_days; +use crate::warehouse_history::_helpers::cost_summary::group_series; +use crate::warehouse_history::constants::COST_SERIES_GROUPS; +use crate::warehouse_history::models::{CostSeriesBatch, CostSeriesGroup}; + +/// Each group's credits per day of the last `days` whole UTC days, for the nodes `select` and `exclude` pick. +pub async fn read_person_cost_series( + store: &ControlStore, + (planner, credentials): (&dyn CommandPlanner, (&AuditContext, Uuid)), + (location_id, target): (Uuid, &str), + ((select, exclude), (days, groups), default_role): ( + (&str, &str), + (u32, &[CostSeriesGroup]), + DefaultRole, + ), +) -> Result { + if groups.len() > COST_SERIES_GROUPS { + return Err(ControlError::Invalid(format!( + "at most {COST_SERIES_GROUPS} groups per request" + ))); + } + let (period, costs) = selection_costs_in_days( + store, + (planner, credentials), + (location_id, target), + ((select, exclude), days, default_role), + ) + .await?; + Ok(CostSeriesBatch { + dates: period.dates(), + series: group_series(&period, &costs.rows, groups), + }) +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs index 42d1183223..05254f85c9 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; -use chrono::{Duration, Utc}; +use chrono::{DateTime, Duration, Utc}; use uuid::Uuid; use crate::authorization::main::decisions::authorize_listing::authorize_listing; @@ -11,7 +11,7 @@ use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; use crate::store::models::{ControlStore, TransactionMode}; use crate::warehouse_history::_helpers::costs::{ - Accumulator, PENDING_STATUSES, TOTAL_RESOURCE_TYPE, latest_costs_in, ranked, + Accumulator, CostGroups, PENDING_STATUSES, TOTAL_RESOURCE_TYPE, latest_costs_in, ranked, }; use crate::warehouse_history::models::{CostGroup, CostSummaryRecord}; @@ -58,15 +58,28 @@ pub async fn read_person_cost_summary( .or_default() .add(cost); } + Ok(summary_record( + (since, total, incomplete_runs), + (by_job, by_size, by_node), + )) +} + +/// The summary of the window's total and its groups, most expensive first. +fn summary_record( + (since, total, incomplete_runs): (DateTime, Accumulator, i64), + (by_job, by_size, by_node): (CostGroups, CostGroups, CostGroups), +) -> CostSummaryRecord { + let source: Option = total.source(); let total: CostGroup = total.group(None); - Ok(CostSummaryRecord { + CostSummaryRecord { since, credits: total.credits, + usd_per_credit_source: source, usd: total.usd, runs: total.runs, incomplete_runs, by_job: ranked(by_job), by_warehouse_size: ranked(by_size), by_node: ranked(by_node), - }) + } } diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/mod.rs index 01e47f17a0..4f4f5d0a46 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/mod.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/mod.rs @@ -1,6 +1,7 @@ //! Person reads of warehouse-owned history mirrored into the control store: checks, maintenance and microbatch coverage. pub(crate) mod _helpers; +pub mod constants; pub mod main; pub mod models; pub(crate) mod types; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/models.rs b/crates/sqlbuild-orchestration/src/warehouse_history/models.rs index e00488310a..f8c659a7df 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/models.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/models.rs @@ -212,6 +212,8 @@ pub struct CostSummaryRecord { pub since: DateTime, pub credits: f64, pub usd: Option, + /// `config`, `rate_sheet`, `list_price` (also when only some are) or `mixed`; None without dollars. + pub usd_per_credit_source: Option, pub runs: i64, /// Runs whose cost is still pending or partial, which a later build re-reads. pub incomplete_runs: i64, @@ -231,6 +233,96 @@ pub struct NodeCostRecord { pub status: String, pub credits: f64, pub usd: Option, + /// Where the build's price per credit came from: `config`, `rate_sheet` or `list_price`. + pub usd_per_credit_source: Option, pub seconds: f64, pub query_count: i64, } + +/// The price the dollars of a cost read use, and where it came from. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct CostPrice { + pub usd_per_credit: f64, + /// `config` (`[cost] usd_per_credit`), `rate_sheet`, `list_price` (also when only some) or `mixed`. + pub source: String, +} + +/// One job's estimated query cost on one node: in the period, and in the period before it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct CostFactRecord { + /// None for builds no server run started. + pub job: Option, + /// `:`, like catalog node keys. + pub node_key: String, + /// The node's folder as `costFolder` names it; empty at the top of `sql/models`. + pub folder: String, + pub credits: f64, + pub previous_credits: f64, + pub usd: Option, + pub previous_usd: Option, + pub seconds: f64, + /// Builds in the period, counted once each. + pub runs: i64, + pub queries: i64, + pub bytes_scanned: i64, +} + +/// Credits per day of the period, oldest first, for one group. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct CostSeriesRecord { + /// The job, or top-level folder; None for builds no server run started. + pub key: Option, + pub credits: Vec, +} + +/// A selection's estimated query cost over a period, job by node, with daily series. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct CostSelectionRecord { + /// The publication the selection was evaluated against; None before the first one. + pub snapshot_id: Option, + pub since: DateTime, + pub days: u32, + /// The period's days, `YYYY-MM-DD` in UTC, oldest first; every series follows them. + pub dates: Vec, + /// Why `sqb` refuses the selection; facts and series are then empty. + pub error: Option, + /// None when any observation had no configured credit price. + pub price: Option, + pub credits: f64, + pub previous_credits: f64, + pub usd: Option, + pub previous_usd: Option, + /// Builds in the period that spent cost on a selected node. + pub runs: i64, + /// Of those, builds whose cost is still pending or partial. + pub incomplete_runs: i64, + pub queries: i64, + pub seconds: f64, + pub bytes_scanned: i64, + pub facts: Vec, + pub job_daily: Vec, + pub folder_daily: Vec, +} + +/// One group a batch of daily series asks for: the cost of selected nodes matching every field given. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(deny_unknown_fields)] +pub struct CostSeriesGroup { + #[serde(default)] + pub job: Option, + /// Builds no server run started. + #[serde(default)] + pub manual: bool, + /// The folder or one under it. + #[serde(default)] + pub folder: Option, + #[serde(default)] + pub node_key: Option, +} + +/// Daily series for a batch of groups, in their order. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct CostSeriesBatch { + pub dates: Vec, + pub series: Vec>, +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_metadata/models.rs b/crates/sqlbuild-orchestration/src/warehouse_metadata/models.rs index ca888807dc..2b15a4023c 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_metadata/models.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_metadata/models.rs @@ -311,6 +311,12 @@ pub struct WarehouseResourceCostRecord { pub bytes_scanned: i64, pub estimated_credits: String, pub estimated_usd: Option, + /// The price per credit `estimated_usd` used; None on rows recorded before prices were. + #[serde(default)] + pub usd_per_credit: Option, + /// `config`, `rate_sheet` or `list_price` (an estimate); None on rows recorded before prices were. + #[serde(default)] + pub usd_per_credit_source: Option, pub status: String, pub statements_expected: i64, pub statements_observed: i64, diff --git a/crates/sqlbuild-orchestration/tests/api/test_contracts.rs b/crates/sqlbuild-orchestration/tests/api/test_contracts.rs index b4ff0f78fe..ac18367f26 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_contracts.rs @@ -66,6 +66,8 @@ mod test_column_lineage; mod test_compression; #[path = "test_contract.rs"] mod test_contract; +#[path = "test_cost_selection.rs"] +mod test_cost_selection; #[path = "test_custom_roles.rs"] mod test_custom_roles; #[path = "test_denials.rs"] diff --git a/crates/sqlbuild-orchestration/tests/api/test_cost_selection.rs b/crates/sqlbuild-orchestration/tests/api/test_cost_selection.rs new file mode 100644 index 0000000000..c57a117813 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/api/test_cost_selection.rs @@ -0,0 +1,277 @@ +//! A selection's estimated query cost through the public API: job by node, the period before, folders and daily series. + +use reqwest::StatusCode; +use serde_json::{Value, json}; + +use crate::api::tests::helpers::stop_api; +use crate::api::tests::test_types::{CostFolderTestCase, CostSelectionTestCase}; +use crate::api::tests::warehouse_history_helpers::{ + batch, cost_facts as facts, cost_observations, cost_selection_observations as observations, + get, login, percent_encoded as urlencoding, seed_target, series_totals as totals, + start_password_api, +}; +use crate::runs::tests::helpers::{request, request_run, rows, snapshot}; +use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::snapshots::models::SnapshotNode; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; +use crate::warehouse_history::_helpers::cost_selection::cost_folder; +use crate::warehouse_metadata::main::ingest::ingest_resource_costs::ingest_resource_costs; + +#[test] +fn given_job_and_manual_builds_when_people_read_a_selections_cost_then_it_splits_job_by_node_with_daily_series() + { + let test_cases = [ + CostSelectionTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_all: vec![ + ( + json!("daily"), + json!("model:orders"), + json!("staging"), + 0.10, + 0.20, + ), + ( + json!("daily"), + json!("model:customers"), + json!(""), + 0.05, + 0.0, + ), + ( + Value::Null, + json!("model:orders"), + json!("staging"), + 0.04, + 0.0, + ), + ], + expected_series: vec![0.15, 0.04, 0.14, 0.05], + }, + CostSelectionTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_all: vec![ + ( + json!("daily"), + json!("model:orders"), + json!("staging"), + 0.10, + 0.20, + ), + ( + json!("daily"), + json!("model:customers"), + json!(""), + 0.05, + 0.0, + ), + ( + Value::Null, + json!("model:orders"), + json!("staging"), + 0.04, + 0.0, + ), + ], + expected_series: vec![0.15, 0.04, 0.14, 0.05], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture_store) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture_store.store; + let (location, session_id) = seed_target(store).await; + let mut input = snapshot(location); + input.generation = 2; + input.nodes = [ + ("orders", "sql/models/staging/orders.sql"), + ("customers", "sql/models/customers.sql"), + ] + .into_iter() + .map(|(name, path)| { + ( + format!("model:{name}"), + SnapshotNode { + kind: "model".into(), + definition: json!({"materialization": "table", "path": path}), + raw_sql: None, + compiled_sql: Some("select 1 as id".into()), + python_source: None, + }, + ) + }) + .collect(); + let published = publish_snapshot(store, &input).await.expect("snapshot"); + let mut runs = Vec::new(); + for id in [0x1654_u128, 0x1655] { + let mut daily = + request((location, published.snapshot_id), id, 0, &["model:orders"]); + daily.job_key = Some("daily".into()); + assert!(request_run(store, &daily).await.expect("daily run")); + runs.push(daily.run_id); + } + let mut costs = batch( + session_id, + "resource_costs", + cost_observations(&observations(runs[0], runs[1])), + ); + // The batch reads the second publication's state. + costs.generation = 2; + ingest_resource_costs(store, (location, "development"), &costs) + .await + .expect("cost ingestion"); + assert!( + !rows( + store, + "SELECT event_id FROM sqb_warehouse_resource_costs", + vec![] + ) + .await + .is_empty() + ); + + let (api, client) = start_password_api(store).await; + let viewer = login(&client, &api.url, "orders-viewer").await; + let path = format!("/api/control/locations/{location}/targets/development/cost"); + + let (status, all) = get( + &client, + (&api.url, &viewer), + &format!("{path}/selection?days=7"), + ) + .await; + assert_eq!(status, StatusCode::OK, "{}: {all}", test_case.description); + assert_eq!( + facts(&all), + test_case.expected_all, + "{}: job by node, the folder under sql/models, and the period before", + test_case.description + ); + assert_eq!( + ( + all["dates"].as_array().map(Vec::len), + all["runs"].clone(), + all["price"]["source"].clone() + ), + (Some(7), json!(2), json!("list_price")), + "{}: an estimate among the prices makes the total one", + test_case.description + ); + assert_eq!( + (totals(&all["job_daily"]), totals(&all["folder_daily"])), + (vec![0.04, 0.15], vec![0.05, 0.14]), + "{}: daily series by job (none, then daily) and top-level folder (top, then staging)", + test_case.description + ); + + let (_, customers) = get( + &client, + (&api.url, &viewer), + &format!("{path}/selection?select=model:customers"), + ) + .await; + assert_eq!( + customers["price"]["source"], + json!("config"), + "{}: rows recorded before prices were, with dollars, were priced from the project", + test_case.description + ); + let (_, orders) = get( + &client, + (&api.url, &viewer), + &format!("{path}/selection?select=model:orders"), + ) + .await; + assert_eq!( + facts(&orders).len(), + 2, + "{}: only the selected node", + test_case.description + ); + let (status, refused) = get( + &client, + (&api.url, &viewer), + &format!("{path}/selection?select=model:invoices"), + ) + .await; + assert_eq!( + ( + status, + refused["error"]["message"].is_string(), + refused["facts"].clone() + ), + (StatusCode::OK, true, json!([])), + "{}: a refused selection says why", + test_case.description + ); + + let groups = json!([{"job": "daily"}, {"manual": true}, {"folder": "staging"}, {"node_key": "model:customers"}]); + let (_, batch_read) = get( + &client, + (&api.url, &viewer), + &format!("{path}/series?groups={}", urlencoding(&groups.to_string())), + ) + .await; + assert_eq!( + totals(&batch_read["series"]), + test_case.expected_series, + "{}: each group's daily credits", + test_case.description + ); + let too_many = Value::Array(vec![json!({}); 201]).to_string(); + let (status, _) = get( + &client, + (&api.url, &viewer), + &format!("{path}/series?groups={}", urlencoding(&too_many)), + ) + .await; + assert_eq!( + status, + StatusCode::BAD_REQUEST, + "{}: at most 200 groups", + test_case.description + ); + stop_api(api).await; + close_test_store(fixture_store).await; + }); + } +} + +#[test] +fn given_published_paths_when_costs_are_grouped_then_each_node_is_in_its_folder() { + let test_cases = [ + CostFolderTestCase { + description: "a model under sql/models", + path: Some("sql/models/staging/partners/orders.sql"), + expected_folder: "staging/partners", + }, + CostFolderTestCase { + description: "a model at the top of sql/models", + path: Some("sql/models/orders.sql"), + expected_folder: "", + }, + CostFolderTestCase { + description: "a Python node keeps its root", + path: Some("python/nodes/exports/asset.py"), + expected_folder: "python/nodes/exports", + }, + CostFolderTestCase { + description: "a node no longer published", + path: None, + expected_folder: "other", + }, + ]; + for test_case in test_cases { + assert_eq!( + cost_folder(test_case.path), + test_case.expected_folder, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_providers.rs b/crates/sqlbuild-orchestration/tests/api/test_providers.rs index 5499a9e5ca..ee1f4bce35 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_providers.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_providers.rs @@ -87,9 +87,9 @@ fn given_published_providers_when_people_read_them_then_jobs_using_their_nodes_a "providers".into(), json!({"providers": [{ "name": "fulfillment_api", - "class": "providers.fulfillment.FulfillmentApi", + "class": "python.providers.fulfillment.FulfillmentApi", "description": "Client for the fulfillment service.", - "path": "providers/fulfillment.py", + "path": "python/providers/fulfillment.py", "settings": [ {"name": "api_key", "type": "SecretStr", "required": true, "secret": true, "env": "API_KEY", "description": null, "missing": true}, {"name": "endpoint", "type": "str", "required": false, "secret": false, "env": "ENDPOINT", "description": "Base URL"}, @@ -109,9 +109,9 @@ fn given_published_providers_when_people_read_them_then_jobs_using_their_nodes_a json!(read_back.providers), json!([{ "name": "fulfillment_api", - "class": "providers.fulfillment.FulfillmentApi", + "class": "python.providers.fulfillment.FulfillmentApi", "description": "Client for the fulfillment service.", - "path": "providers/fulfillment.py", + "path": "python/providers/fulfillment.py", "settings": [ {"name": "api_key", "type": "SecretStr", "required": true, "secret": true, "env": "API_KEY", "description": null, "missing": true}, {"name": "endpoint", "type": "str", "required": false, "secret": false, "env": "ENDPOINT", "description": "Base URL", "missing": false}, diff --git a/crates/sqlbuild-orchestration/tests/api/test_republish.rs b/crates/sqlbuild-orchestration/tests/api/test_republish.rs index 714721403c..168f4f675e 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_republish.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_republish.rs @@ -17,8 +17,8 @@ use crate::platform::main::work::{ request_republish::request_republish, }; use crate::platform::models::{ - LocationWork, LocationWorkOutcome, LocationWorkRequest, LocationWorkResult, LocationWorkScope, - PersonWorkRequest, RepublishState, + DiscoveredNodeReadback, LocationWork, LocationWorkOutcome, LocationWorkRequest, + LocationWorkResult, LocationWorkScope, PersonWorkRequest, RepublishState, }; use crate::runs::tests::helpers::snapshot; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; @@ -195,7 +195,12 @@ fn given_a_republish_when_requested_claimed_and_completed_then_it_is_authorized_ input.documents.insert( "discovered".into(), json!({"orders_plan": {"status": "ok", "digest": "d-2", - "result": {"items": [{"id": "load", "depends_on": [], "args": {}}], "tags": {"release": "0.58.0"}}}}), + "result": {"items": [{"id": "load", "depends_on": [], "args": {"region": "eu", "attempt": 2}}], + "tags": {"release": "0.58.0", "max_parallel": 4}}}}), + ); + input.documents.insert( + "discovered_assets".into(), + json!({"orders_plan": ["load_orders"]}), ); let published = publish_snapshot(store, &input).await.expect("republish"); let outcome = (test_case.outcome)(published.snapshot_id); @@ -233,16 +238,37 @@ fn given_a_republish_when_requested_claimed_and_completed_then_it_is_authorized_ .await .expect("a viewer reads the sets back") .expect("published"); - let expected_tags: BTreeMap = - [("release".to_owned(), json!("0.58.0"))].into(); + let expected_tags: BTreeMap = [ + ("max_parallel".to_owned(), "4".to_owned()), + ("release".to_owned(), "0.58.0".to_owned()), + ] + .into(); + let expected_nodes = vec![DiscoveredNodeReadback { + key: "asset:load_orders[load]".into(), + asset: "load_orders".into(), + step: "load".into(), + args: [ + ("attempt".to_owned(), "2".to_owned()), + ("region".to_owned(), "eu".to_owned()), + ] + .into(), + }]; assert_eq!( ( readback.generation, readback.sets[0].items, - &readback.sets[0].tags + &readback.sets[0].tags, + &readback.sets[0].assets, + &readback.sets[0].nodes + ), + ( + 2, + 1, + &expected_tags, + &vec!["load_orders".to_owned()], + &expected_nodes ), - (2, 1, &expected_tags), - "{}: the readback shows the new tags", + "{}: the readback shows the new tags, and the node each item became, with its args", test_case.description ); let (transaction, audit) = query( diff --git a/crates/sqlbuild-orchestration/tests/api/test_types.rs b/crates/sqlbuild-orchestration/tests/api/test_types.rs index a74c8c82fd..c61a9205e3 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_types.rs @@ -705,3 +705,24 @@ pub(crate) fn republish_failed(_: uuid::Uuid) -> crate::platform::models::Locati error: "orders does not parse".into(), } } + +/// A selection cost read per store: every fact `(job, node, folder, credits, previous)` and the series batch totals. +pub(crate) struct CostSelectionTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) expected_all: Vec<( + serde_json::Value, + serde_json::Value, + serde_json::Value, + f64, + f64, + )>, + pub(crate) expected_series: Vec, +} + +/// A node's published path and the cost folder it falls in. +pub(crate) struct CostFolderTestCase { + pub(crate) description: &'static str, + pub(crate) path: Option<&'static str>, + pub(crate) expected_folder: &'static str, +} diff --git a/crates/sqlbuild-orchestration/tests/api/warehouse_history/helpers.rs b/crates/sqlbuild-orchestration/tests/api/warehouse_history/helpers.rs index d5fdc1f20c..20caf78bb4 100644 --- a/crates/sqlbuild-orchestration/tests/api/warehouse_history/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/warehouse_history/helpers.rs @@ -282,3 +282,112 @@ pub(crate) fn cost_page<'a>( ) -> BoxFuture<'a, Result> { Box::pin(ingest_resource_costs(store, scope, page)) } + +/// Builds of the `daily` job 2 hours and 9 days ago, and one from the command line 3 hours ago at the list price. +pub(crate) fn cost_selection_observations(daily: Uuid, old_daily: Uuid) -> Value { + let row = + |id: &str, hours: i64, run: Option, (kind, name): (&str, &str), credits: &str| { + json!({"observation_id": id, "hours_ago": hours, "run_id": id.split('/').next(), + "orchestration_run_id": run.map(|run| run.to_string()), "resource_type": kind, + "resource_name": name, "estimated_credits": credits, + "estimated_usd": format!("{:.4}", credits.parse::().expect("credits") * 3.0)}) + }; + let mut data = fixture("resource_cost_history.json"); + data["observations"] = json!([ + row( + "build-a/total", + 2, + Some(daily), + ("_total", "build-a"), + "0.15" + ), + row( + "build-a/orders", + 2, + Some(daily), + ("model", "orders"), + "0.10" + ), + row( + "build-a/customers", + 2, + Some(daily), + ("model", "customers"), + "0.05" + ), + row("build-b/total", 3, None, ("_total", "build-b"), "0.04"), + row("build-b/orders", 3, None, ("model", "orders"), "0.04"), + row( + "build-c/total", + 216, + Some(old_daily), + ("_total", "build-c"), + "0.20" + ), + row( + "build-c/orders", + 216, + Some(old_daily), + ("model", "orders"), + "0.20" + ), + ]); + // The build from the command line was priced from the list price; the job's from the project. + for observation in data["observations"] + .as_array_mut() + .expect("observations") + .iter_mut() + .filter(|observation| observation["run_id"] == json!("build-b")) + { + observation["usd_per_credit"] = json!("3.00"); + observation["usd_per_credit_source"] = json!("list_price"); + } + data +} + +/// `(job, node, folder, credits, previous)` of each fact, amounts rounded to hundredths. +pub(crate) fn cost_facts(read: &Value) -> Vec<(Value, Value, Value, f64, f64)> { + let round = |value: &Value| (value.as_f64().expect("amount") * 100.0).round() / 100.0; + read["facts"] + .as_array() + .expect("facts") + .iter() + .map(|fact| { + ( + fact["job"].clone(), + fact["node_key"].clone(), + fact["folder"].clone(), + round(&fact["credits"]), + round(&fact["previous_credits"]), + ) + }) + .collect() +} + +/// Each series' total, rounded to hundredths. +pub(crate) fn series_totals(series: &Value) -> Vec { + series + .as_array() + .expect("series") + .iter() + .map(|values| { + let values = values.get("credits").unwrap_or(values); + (values + .as_array() + .expect("days") + .iter() + .filter_map(Value::as_f64) + .sum::() + * 100.0) + .round() + / 100.0 + }) + .collect() +} + +/// `text` percent-encoded for a query value. +pub(crate) fn percent_encoded(text: &str) -> String { + let mut url = reqwest::Url::parse("http://query.invalid/").expect("url"); + url.query_pairs_mut().append_pair("v", text); + url.query().expect("query")["v=".len()..].to_owned() +} diff --git a/crates/sqlbuild-orchestration/tests/dev_events/test_dev_events.rs b/crates/sqlbuild-orchestration/tests/dev_events/test_dev_events.rs index 597a3e303c..cc3cb7fa98 100644 --- a/crates/sqlbuild-orchestration/tests/dev_events/test_dev_events.rs +++ b/crates/sqlbuild-orchestration/tests/dev_events/test_dev_events.rs @@ -23,7 +23,7 @@ fn given_each_event_when_encoding_then_one_prefixed_line_reads_back_unchanged() RoundTripTestCase { description: "changed paths keep the count of further files", event: DevEvent::Changed { - paths: vec!["models/orders.sql".to_owned()], + paths: vec!["sql/models/orders.sql".to_owned()], more: 2, }, expected_newlines: 1, @@ -50,7 +50,7 @@ fn given_each_event_when_encoding_then_one_prefixed_line_reads_back_unchanged() generation: 4, message: "unknown column net_amount_usd\nat line 42".to_owned(), position: Some(SourcePosition { - path: "models/finance/fct_revenue.sql".to_owned(), + path: "sql/models/finance/fct_revenue.sql".to_owned(), line: 42, column: 7, }), @@ -167,18 +167,18 @@ fn given_a_failed_generation_when_reported_then_the_first_source_location_is_its let test_cases = [ PositionTestCase { description: "a compile error with line and column", - message: "SQB0101 models/finance/fct_revenue.sql:42:7: unknown column net_amount_usd", + message: "SQB0101 sql/models/finance/fct_revenue.sql:42:7: unknown column net_amount_usd", expected_position: Some(SourcePosition { - path: "models/finance/fct_revenue.sql".to_owned(), + path: "sql/models/finance/fct_revenue.sql".to_owned(), line: 42, column: 7, }), }, PositionTestCase { description: "a Python traceback line without a column, in parentheses", - message: "failed to import (python/orders.py:12) because of a syntax error", + message: "failed to import (python/nodes/orders.py:12) because of a syntax error", expected_position: Some(SourcePosition { - path: "python/orders.py".to_owned(), + path: "python/nodes/orders.py".to_owned(), line: 12, column: 1, }), @@ -190,7 +190,7 @@ fn given_a_failed_generation_when_reported_then_the_first_source_location_is_its }, PositionTestCase { description: "a path without a line is not a position", - message: "models/orders.sql is not valid", + message: "sql/models/orders.sql is not valid", expected_position: None, }, ]; diff --git a/crates/sqlbuild-orchestration/tests/platform/test_compile_failure.rs b/crates/sqlbuild-orchestration/tests/platform/test_compile_failure.rs index 6b32d8ba2b..d03a3e721a 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_compile_failure.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_compile_failure.rs @@ -70,7 +70,7 @@ fn given_rule_findings_when_a_location_reports_a_failed_load_then_only_bounded_l let finding = LocationRuleFinding { code: "SQBRMODEL102".into(), message: "m".repeat(test_case.message_chars), - path: Some("models/orders.sql".into()), + path: Some("sql/models/orders.sql".into()), line: Some(2), }; let report = LocationHealthReport { diff --git a/crates/sqlbuild-orchestration/tests/platform/test_provider_secrets.rs b/crates/sqlbuild-orchestration/tests/platform/test_provider_secrets.rs index d8890e00b9..51cf526555 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_provider_secrets.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_provider_secrets.rs @@ -14,15 +14,15 @@ fn given_providers_missing_secrets_when_a_location_reports_them_then_only_unallo { // A snapshot's providers document: settings carry `missing` and never a value. let document = json!({"providers": [ - {"name": "orders_api", "path": "providers/orders_api.py", "nodes": ["source:raw_orders"], + {"name": "orders_api", "path": "python/providers/orders_api.py", "nodes": ["source:raw_orders"], "settings": [ {"name": "base_url", "env": "ORDERS_API_BASE_URL", "missing": false, "line": 9}, {"name": "api_key", "env": "ORDERS_API_KEY", "missing": true, "line": 12}]}, - {"name": "export_bucket", "path": "providers/storage.py", "nodes": ["asset:export"], + {"name": "export_bucket", "path": "python/providers/storage.py", "nodes": ["asset:export"], "settings": [ {"name": "region", "env": "BUCKET_REGION", "missing": true}, {"name": "secret", "env": "BUCKET_SECRET", "missing": true, "line": 14}]}, - {"name": "ready", "path": "providers/ready.py", "nodes": [], + {"name": "ready", "path": "python/providers/ready.py", "nodes": [], "settings": [{"name": "token", "env": "READY_TOKEN", "missing": false}]} ]}); let test_cases = [ diff --git a/crates/sqlbuild-orchestration/tests/run_output/helpers.rs b/crates/sqlbuild-orchestration/tests/run_output/helpers.rs index 8d9110670a..cd8dea6dd0 100644 --- a/crates/sqlbuild-orchestration/tests/run_output/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/run_output/helpers.rs @@ -84,10 +84,16 @@ pub(crate) fn segment(node_key: Option<&str>, stream: OutputStream, text: &str) node_key: node_key.map(str::to_owned), stream, text: text.into(), + read_at: read_at(0), dropped_bytes: 0, } } +/// A read time `millis` milliseconds after a fixed moment. +pub(crate) fn read_at(millis: i64) -> chrono::DateTime { + chrono::DateTime::from_timestamp_millis(1_795_000_000_000 + millis).expect("read time") +} + pub(crate) fn batch(number: u64, segments: Vec) -> OutputBatch { OutputBatch { batch: number, diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_reads.rs b/crates/sqlbuild-orchestration/tests/run_output/test_reads.rs index 98e8d55ae4..a235f565b2 100644 --- a/crates/sqlbuild-orchestration/tests/run_output/test_reads.rs +++ b/crates/sqlbuild-orchestration/tests/run_output/test_reads.rs @@ -10,16 +10,16 @@ use crate::run_output::main::read_person_output_index::read_person_output_index; use crate::run_output::main::read_person_output_page::read_person_output_page; use crate::run_output::main::search_person_output::search_person_output; use crate::run_output::models::{ - OutputDownloadQuery, OutputLevel, OutputMark, OutputRow, OutputSearch, OutputSearchQuery, - OutputStream, SearchDirection, + OutputDownloadQuery, OutputLevel, OutputLine, OutputMark, OutputRow, OutputSearch, + OutputSearchQuery, OutputSegment, OutputStream, SearchDirection, }; use crate::run_output::tests::helpers::{ - batch, claimed_run, line, line_row, output_store, page_query, reader, segment, similar_row, - timeless, + batch, claimed_run, line, line_row, output_store, page_query, read_at, reader, segment, + similar_row, timeless, }; use crate::run_output::tests::test_types::{ - OutputFoldTestCase, OutputNulTestCase, OutputReadTestCase, OutputSearchTestCase, PageRead, - PageStart, SearchRead, + OutputFoldTestCase, OutputNulTestCase, OutputReadTestCase, OutputSearchTestCase, + OutputStoredReadTimeTestCase, PageRead, PageStart, SearchRead, }; use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; use crate::store::tests::store_test_types::Backend; @@ -662,3 +662,69 @@ fn given_a_node_output_when_searched_either_way_then_small_output_counts_and_wra }); } } + +#[test] +fn given_lines_read_at_different_times_when_a_page_is_read_then_each_line_has_its_read_time() { + let out = OutputStream::Stdout; + let test_cases = [ + OutputStoredReadTimeTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_lines: [("one", 0), ("two", 0), ("loaded", 1_250)], + }, + OutputStoredReadTimeTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_lines: [("one", 0), ("two", 0), ("loaded", 1_250)], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), None); + let (location, claim) = claimed_run(store).await; + let later = OutputSegment { + read_at: read_at(1_250), + ..segment(Some(ORDERS), out, "loaded\n") + }; + let sent = batch(0, vec![segment(Some(ORDERS), out, "one\ntwo\n"), later]); + publish_output_batch(store, &output, (claim.request.run_id, claim.claim_id), sent) + .await + .expect("batch"); + let (context, admin) = reader(store).await; + let person = ( + (&context, admin), + (location, "development", claim.request.run_id), + DefaultRole::None, + ); + let start = PageStart { + from: Some(1), + ..PageStart::default() + }; + let query = page_query((Some(ORDERS), None), start, (10, false, None)); + let page = read_person_output_page(store, &output, person, &query) + .await + .expect("page") + .expect("run"); + assert_eq!( + page.rows, + (1_i64..) + .zip(test_case.expected_lines) + .map(|(number, (text, millis))| OutputRow::Line { + line: OutputLine { + at: read_at(millis), + ..line(number, ORDERS, out, text) + }, + }) + .collect::>(), + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_types.rs b/crates/sqlbuild-orchestration/tests/run_output/test_types.rs index 2668f18cbe..826d204ade 100644 --- a/crates/sqlbuild-orchestration/tests/run_output/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/run_output/test_types.rs @@ -150,3 +150,18 @@ pub(crate) struct OutputDefaultTestCase { /// Absolute, or within the SQLite store's folder; `None` when there is no default. pub(crate) expected_folder: Option<&'static str>, } + +/// Writes read at given milliseconds, and the segments they make with their read times. +pub(crate) struct OutputReadTimeTestCase { + pub(crate) description: &'static str, + pub(crate) writes: Vec<(Vec, i64)>, + pub(crate) expected_segments: Vec<(&'static str, i64)>, +} + +/// A store whose batch holds lines read at different times. +pub(crate) struct OutputStoredReadTimeTestCase { + pub(crate) description: &'static str, + pub(crate) backend: crate::store::tests::store_test_types::Backend, + /// Each line read back: its text and the milliseconds it was read at. + pub(crate) expected_lines: [(&'static str, i64); 3], +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_upload.rs b/crates/sqlbuild-orchestration/tests/run_output/test_upload.rs index 1a496a7808..6029629914 100644 --- a/crates/sqlbuild-orchestration/tests/run_output/test_upload.rs +++ b/crates/sqlbuild-orchestration/tests/run_output/test_upload.rs @@ -2,7 +2,8 @@ use crate::run_output::constants::{MAX_BATCH_SEGMENTS, MAX_BATCH_TEXT_BYTES}; use crate::run_output::models::{OutputStream, UploadState}; -use crate::run_output::tests::test_types::OutputUploadTestCase; +use crate::run_output::tests::helpers::read_at; +use crate::run_output::tests::test_types::{OutputReadTimeTestCase, OutputUploadTestCase}; #[test] fn given_large_or_mixed_output_when_batched_then_every_batch_fits_the_server_and_nothing_is_lost() { @@ -52,7 +53,7 @@ fn given_large_or_mixed_output_when_batched_then_every_batch_fits_the_server_and .refused_before .then(|| "the control server did not accept run output".to_owned()); for (stream, bytes) in &test_case.writes { - state.append(("model:orders".into(), *stream), bytes); + state.append(("model:orders".into(), *stream), (bytes, read_at(0))); } state.end_lines(); state.seal(); @@ -96,3 +97,48 @@ fn given_large_or_mixed_output_when_batched_then_every_batch_fits_the_server_and ); } } + +#[test] +fn given_lines_read_at_different_times_when_batched_then_each_keeps_the_time_it_was_read() { + let out = OutputStream::Stdout; + let test_cases = [ + OutputReadTimeTestCase { + description: "lines read in one millisecond share a segment", + writes: vec![(b"one\ntwo\n".to_vec(), 0), (b"three\n".to_vec(), 0)], + expected_segments: vec![("one\ntwo\nthree\n", 0)], + }, + OutputReadTimeTestCase { + description: "a line read later starts a segment with its own time", + writes: vec![(b"one\n".to_vec(), 0), (b"two\n".to_vec(), 1_250)], + expected_segments: vec![("one\n", 0), ("two\n", 1_250)], + }, + OutputReadTimeTestCase { + description: "a line takes the time the bytes completing it were read", + writes: vec![(b"on".to_vec(), 0), (b"e\n".to_vec(), 40)], + expected_segments: vec![("one\n", 40)], + }, + ]; + for test_case in test_cases { + let mut state = UploadState::default(); + for (bytes, millis) in &test_case.writes { + state.append(("model:orders".into(), out), (bytes, read_at(*millis))); + } + state.seal(); + let segments: Vec<(String, chrono::DateTime)> = state + .queued + .iter() + .flat_map(|batch| batch.segments.iter()) + .map(|segment| (segment.text.clone(), segment.read_at)) + .collect(); + assert_eq!( + segments, + test_case + .expected_segments + .iter() + .map(|(text, millis)| ((*text).to_owned(), read_at(*millis))) + .collect::>(), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs b/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs index dfe01dcb34..cf697c3970 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs @@ -62,6 +62,8 @@ mod test_retries; mod test_run_logs; #[path = "test_selection.rs"] mod test_selection; +#[path = "test_start_message.rs"] +mod test_start_message; #[path = "test_stored_requests.rs"] mod test_stored_requests; #[path = "test_types.rs"] diff --git a/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs b/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs index e099177ba1..f885532543 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs @@ -58,7 +58,8 @@ fn given_a_failed_node_when_people_read_its_error_then_only_evidence_on_that_nod .nodes .get_mut("orders") .expect("orders node") - .definition = json!({"materialization": "table", "path": "models\\orders.sql"}); + .definition = + json!({"materialization": "table", "path": "sql\\models\\orders.sql"}); let published = publish_snapshot(store, &input).await.expect("publish"); queue( store, @@ -125,7 +126,7 @@ fn given_a_failed_node_when_people_read_its_error_then_only_evidence_on_that_nod error.path.as_deref(), message.chars().count() ), - (Some("T002"), Some("models/orders.sql"), 2000), + (Some("T002"), Some("sql/models/orders.sql"), 2000), "{}: code, a portable path, and the bound", test_case.description ); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_start_message.rs b/crates/sqlbuild-orchestration/tests/runs/test_start_message.rs new file mode 100644 index 0000000000..0f2fa2415a --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/runs/test_start_message.rs @@ -0,0 +1,50 @@ +//! A worker's invocation start reads as the command it ran, where and on which version. + +use crate::runs::tests::test_types::StartMessageTestCase; +use crate::store::types::Row; +use crate::warehouse_history::_helpers::run_recall::start_message; + +#[test] +fn given_an_invocation_start_when_its_event_is_read_then_the_message_names_command_target_and_version() + { + let test_cases = [ + StartMessageTestCase { + description: "every field, with the selection count as SQLite returns it", + fields: vec![ + ("started_command", serde_json::json!("build")), + ("started_target", serde_json::json!("uat")), + ("started_selected", serde_json::json!(93)), + ("started_version", serde_json::json!("0.259.0")), + ], + expected_message: Some("sqb build · target uat · 93 selected · SQLBuild 0.259.0"), + }, + StartMessageTestCase { + description: "the selection count as PostgreSQL text, without a target", + fields: vec![ + ("started_command", serde_json::json!("build")), + ("started_target", serde_json::Value::Null), + ("started_selected", serde_json::json!("4")), + ("started_version", serde_json::json!("0.259.0")), + ], + expected_message: Some("sqb build · 4 selected · SQLBuild 0.259.0"), + }, + StartMessageTestCase { + description: "another event has no start columns", + fields: vec![], + expected_message: None, + }, + ]; + for test_case in test_cases { + let row: Row = test_case + .fields + .into_iter() + .map(|(column, value)| (column.to_owned(), value)) + .collect(); + assert_eq!( + start_message(&row).as_deref(), + test_case.expected_message, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/test_types.rs b/crates/sqlbuild-orchestration/tests/runs/test_types.rs index 77f93fcf0a..b9b6195e52 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_types.rs @@ -626,3 +626,10 @@ pub(crate) struct CancelledRerunTestCase { pub(crate) expected_retried: Vec<&'static str>, pub(crate) expected_rerun: Vec<&'static str>, } + +/// The start columns a run's events read selects from an `invocation_started` event, and its message. +pub(crate) struct StartMessageTestCase { + pub(crate) description: &'static str, + pub(crate) fields: Vec<(&'static str, serde_json::Value)>, + pub(crate) expected_message: Option<&'static str>, +} diff --git a/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs b/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs index fd58087e69..ed92b2cd73 100644 --- a/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs +++ b/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs @@ -68,6 +68,14 @@ const SQLITE_CHECKSUMS: &[(i64, &str)] = &[ 9, "53e0dbe5dd3eb23174e46480e8c805d9ede865a65f132c545f989603f0a93695", ), + ( + 10, + "ff56abd4e244e08469861e37cef2ec8a460c3bc9ab2cb42d4e12c5a0cc35f3bb", + ), + ( + 11, + "690b5ac4f64f5d305a5bb7e3716e41ba2806c0e951b220b413c05b85c223c0a4", + ), ]; const POSTGRES_CHECKSUMS: &[(i64, &str)] = &[ ( @@ -107,6 +115,14 @@ const POSTGRES_CHECKSUMS: &[(i64, &str)] = &[ 9, "36e079cd622544e221ddfb9bc8837d8030586f7628aaa77da3c1763abb4c4442", ), + ( + 10, + "05cc81606b55e1e3c7a4482a34c24a94bcaac6bfe74e0dbc4680a9ba92da4eb1", + ), + ( + 11, + "921b33c4e32ed5a89dc009f8ccadb62c6f6f4fa3da14a6f9a6b98183c15b6c53", + ), ]; /// A version 1 store mid-run: a child run holding a concurrency slot, a jobs document and an audit result. const VERSION_1_LIVE_WORK: &str = "ALTER TABLE sqb_schema_version ADD COLUMN version BIGINT; \ diff --git a/crates/sqlbuild-pysource/src/import_rewrites/tests/test_python_import_rewrites.rs b/crates/sqlbuild-pysource/src/import_rewrites/tests/test_python_import_rewrites.rs index 3b37334203..5bda0deec5 100644 --- a/crates/sqlbuild-pysource/src/import_rewrites/tests/test_python_import_rewrites.rs +++ b/crates/sqlbuild-pysource/src/import_rewrites/tests/test_python_import_rewrites.rs @@ -3,8 +3,8 @@ use crate::import_rewrites::models::{ImportEdit, ImportRewrites, ModuleMove, Pyt use crate::import_rewrites::tests::helpers::applied; use crate::import_rewrites::tests::test_types::ImportRewriteTestCase; -const CENTS: &str = "models/staging/_sqlbuild/_macros/cents.py"; -const MOVED_CENTS: &str = "models/finance/_sqlbuild/_macros/cents.py"; +const CENTS: &str = "sql/models/staging/_sqlbuild/_macros/cents.py"; +const MOVED_CENTS: &str = "sql/models/finance/_sqlbuild/_macros/cents.py"; const CENTS_MOVE: &[(&str, &str)] = &[(CENTS, MOVED_CENTS)]; #[test] @@ -15,32 +15,32 @@ fn given_moved_modules_when_rewriting_imports_then_each_import_follows_or_is_ref sources: &[ (CENTS, "def to_cents(x):\n return x\n"), ( - "python/checks/amounts.py", - "from models.staging._sqlbuild._macros.cents import to_cents\n", + "python/nodes/checks/amounts.py", + "from sql.models.staging._sqlbuild._macros.cents import to_cents\n", ), ], moves: CENTS_MOVE, expected_sources: &[( - "python/checks/amounts.py", - "from models.finance._sqlbuild._macros.cents import to_cents\n", + "python/nodes/checks/amounts.py", + "from sql.models.finance._sqlbuild._macros.cents import to_cents\n", )], expected_refusals: &[], }, ImportRewriteTestCase { description: "an aliased module import and a grouped import follow the module", sources: &[( - "python/checks/amounts.py", - "import models.staging._sqlbuild._macros.cents as cents_module\n\ - from models.staging._sqlbuild._macros.cents import (\n to_cents,\n \ - to_dollars,\n)\n\n\ndef check():\n import models.staging._sqlbuild._macros.cents \ + "python/nodes/checks/amounts.py", + "import sql.models.staging._sqlbuild._macros.cents as cents_module\n\ + from sql.models.staging._sqlbuild._macros.cents import (\n to_cents,\n \ + to_dollars,\n)\n\n\ndef check():\n import sql.models.staging._sqlbuild._macros.cents \ as inner\n return inner\n", )], moves: CENTS_MOVE, expected_sources: &[( - "python/checks/amounts.py", - "import models.finance._sqlbuild._macros.cents as cents_module\n\ - from models.finance._sqlbuild._macros.cents import (\n to_cents,\n \ - to_dollars,\n)\n\n\ndef check():\n import models.finance._sqlbuild._macros.cents \ + "python/nodes/checks/amounts.py", + "import sql.models.finance._sqlbuild._macros.cents as cents_module\n\ + from sql.models.finance._sqlbuild._macros.cents import (\n to_cents,\n \ + to_dollars,\n)\n\n\ndef check():\n import sql.models.finance._sqlbuild._macros.cents \ as inner\n return inner\n", )], expected_refusals: &[], @@ -48,13 +48,13 @@ fn given_moved_modules_when_rewriting_imports_then_each_import_follows_or_is_ref ImportRewriteTestCase { description: "a module imported by name from its package moves the package", sources: &[( - "python/checks/amounts.py", - "from models.staging._sqlbuild._macros import cents\n", + "python/nodes/checks/amounts.py", + "from sql.models.staging._sqlbuild._macros import cents\n", )], moves: CENTS_MOVE, expected_sources: &[( - "python/checks/amounts.py", - "from models.finance._sqlbuild._macros import cents\n", + "python/nodes/checks/amounts.py", + "from sql.models.finance._sqlbuild._macros import cents\n", )], expected_refusals: &[], }, @@ -66,9 +66,12 @@ fn given_moved_modules_when_rewriting_imports_then_each_import_follows_or_is_ref "from .rates import RATE\nfrom . import rounding\n\n\n\ def to_cents(x):\n return x * RATE\n", ), - ("models/staging/_sqlbuild/_macros/rates.py", "RATE = 100\n"), ( - "models/staging/_sqlbuild/_macros/totals.py", + "sql/models/staging/_sqlbuild/_macros/rates.py", + "RATE = 100\n", + ), + ( + "sql/models/staging/_sqlbuild/_macros/totals.py", "from .cents import to_cents\n", ), ], @@ -76,13 +79,13 @@ fn given_moved_modules_when_rewriting_imports_then_each_import_follows_or_is_ref expected_sources: &[ ( CENTS, - "from models.staging._sqlbuild._macros.rates import RATE\n\ - from models.staging._sqlbuild._macros import rounding\n\n\n\ + "from sql.models.staging._sqlbuild._macros.rates import RATE\n\ + from sql.models.staging._sqlbuild._macros import rounding\n\n\n\ def to_cents(x):\n return x * RATE\n", ), ( - "models/staging/_sqlbuild/_macros/totals.py", - "from models.finance._sqlbuild._macros.cents import to_cents\n", + "sql/models/staging/_sqlbuild/_macros/totals.py", + "from sql.models.finance._sqlbuild._macros.cents import to_cents\n", ), ], expected_refusals: &[], @@ -90,12 +93,12 @@ fn given_moved_modules_when_rewriting_imports_then_each_import_follows_or_is_ref ImportRewriteTestCase { description: "a sibling move keeps a short relative import", sources: &[( - "macros/money/totals.py", + "sql/macros/money/totals.py", "from ..money.cents import to_cents\nfrom .cents import to_dollars\n", )], - moves: &[("macros/money/cents.py", "macros/text/cents.py")], + moves: &[("sql/macros/money/cents.py", "sql/macros/text/cents.py")], expected_sources: &[( - "macros/money/totals.py", + "sql/macros/money/totals.py", "from ..text.cents import to_cents\nfrom ..text.cents import to_dollars\n", )], expected_refusals: &[], @@ -103,8 +106,8 @@ fn given_moved_modules_when_rewriting_imports_then_each_import_follows_or_is_ref ImportRewriteTestCase { description: "imports of modules that stay are left alone", sources: &[( - "python/checks/amounts.py", - "import os\nfrom models.staging._sqlbuild._macros.rates import RATE\n", + "python/nodes/checks/amounts.py", + "import os\nfrom sql.models.staging._sqlbuild._macros.rates import RATE\n", )], moves: CENTS_MOVE, expected_sources: &[], @@ -113,104 +116,104 @@ fn given_moved_modules_when_rewriting_imports_then_each_import_follows_or_is_ref ImportRewriteTestCase { description: "an import without an alias is refused", sources: &[( - "python/checks/amounts.py", - "import os\nimport models.staging._sqlbuild._macros.cents\n", + "python/nodes/checks/amounts.py", + "import os\nimport sql.models.staging._sqlbuild._macros.cents\n", )], moves: CENTS_MOVE, expected_sources: &[], expected_refusals: &[( - "python/checks/amounts.py:2:8", - "imports models.staging._sqlbuild._macros.cents without an alias", + "python/nodes/checks/amounts.py:2:8", + "imports sql.models.staging._sqlbuild._macros.cents without an alias", )], }, ImportRewriteTestCase { description: "a dynamic import naming the module is refused", sources: &[( - "python/checks/amounts.py", + "python/nodes/checks/amounts.py", "import importlib\n\nCENTS = importlib.import_module(\ - \"models.staging._sqlbuild._macros.cents\")\n", + \"sql.models.staging._sqlbuild._macros.cents\")\n", )], moves: CENTS_MOVE, expected_sources: &[], expected_refusals: &[( - "python/checks/amounts.py:3:9", - "imports models.staging._sqlbuild._macros.cents dynamically by name", + "python/nodes/checks/amounts.py:3:9", + "imports sql.models.staging._sqlbuild._macros.cents dynamically by name", )], }, ImportRewriteTestCase { description: "a star import from the moved module's package is refused", sources: &[( - "python/checks/amounts.py", - "from models.staging._sqlbuild._macros import *\n", + "python/nodes/checks/amounts.py", + "from sql.models.staging._sqlbuild._macros import *\n", )], moves: CENTS_MOVE, expected_sources: &[], expected_refusals: &[( - "python/checks/amounts.py:1:1", - "star-imports the package of models.staging._sqlbuild._macros.cents", + "python/nodes/checks/amounts.py:1:1", + "star-imports the package of sql.models.staging._sqlbuild._macros.cents", )], }, ImportRewriteTestCase { description: "a star import from the moved module itself follows it", sources: &[( - "python/checks/amounts.py", - "from models.staging._sqlbuild._macros.cents import *\n", + "python/nodes/checks/amounts.py", + "from sql.models.staging._sqlbuild._macros.cents import *\n", )], moves: CENTS_MOVE, expected_sources: &[( - "python/checks/amounts.py", - "from models.finance._sqlbuild._macros.cents import *\n", + "python/nodes/checks/amounts.py", + "from sql.models.finance._sqlbuild._macros.cents import *\n", )], expected_refusals: &[], }, ImportRewriteTestCase { description: "a moved module imported beside a name that stays is refused", sources: &[( - "python/checks/amounts.py", - "from models.staging._sqlbuild._macros import cents, rates\n", + "python/nodes/checks/amounts.py", + "from sql.models.staging._sqlbuild._macros import cents, rates\n", )], moves: CENTS_MOVE, expected_sources: &[], expected_refusals: &[( - "python/checks/amounts.py:1:1", - "imports a moved module from models.staging._sqlbuild._macros together with names", + "python/nodes/checks/amounts.py:1:1", + "imports a moved module from sql.models.staging._sqlbuild._macros together with names", )], }, ImportRewriteTestCase { description: "a moved module whose package binds its name is refused", sources: &[ ( - "models/staging/_sqlbuild/_macros/__init__.py", + "sql/models/staging/_sqlbuild/_macros/__init__.py", "from .cents import cents\n", ), ( - "python/checks/amounts.py", - "import os\nfrom models.staging._sqlbuild._macros import cents\n", + "python/nodes/checks/amounts.py", + "import os\nfrom sql.models.staging._sqlbuild._macros import cents\n", ), ], moves: CENTS_MOVE, expected_sources: &[( - "models/staging/_sqlbuild/_macros/__init__.py", - "from models.finance._sqlbuild._macros.cents import cents\n", + "sql/models/staging/_sqlbuild/_macros/__init__.py", + "from sql.models.finance._sqlbuild._macros.cents import cents\n", )], expected_refusals: &[( - "python/checks/amounts.py:2:1", - "imports cents from models.staging._sqlbuild._macros, whose __init__.py also \ + "python/nodes/checks/amounts.py:2:1", + "imports cents from sql.models.staging._sqlbuild._macros, whose __init__.py also \ binds cents", )], }, ImportRewriteTestCase { description: "a module imported by a name the move changes is refused", sources: &[( - "python/checks/amounts.py", - "from models.staging._sqlbuild._macros import cents\n", + "python/nodes/checks/amounts.py", + "from sql.models.staging._sqlbuild._macros import cents\n", )], - moves: &[(CENTS, "models/finance/_sqlbuild/_macros/money.py")], + moves: &[(CENTS, "sql/models/finance/_sqlbuild/_macros/money.py")], expected_sources: &[], expected_refusals: &[( - "python/checks/amounts.py:1:1", - "imports the moved module models.staging._sqlbuild._macros.cents by its name, \ - which becomes models.finance._sqlbuild._macros.money", + "python/nodes/checks/amounts.py:1:1", + "imports the moved module sql.models.staging._sqlbuild._macros.cents by its name, \ + which becomes sql.models.finance._sqlbuild._macros.money", )], }, ]; diff --git a/crates/sqlbuild-pysource/src/macro_modules/tests/test_inventory_macro_modules.rs b/crates/sqlbuild-pysource/src/macro_modules/tests/test_inventory_macro_modules.rs index c7a2ffdd5d..2e1b62aa19 100644 --- a/crates/sqlbuild-pysource/src/macro_modules/tests/test_inventory_macro_modules.rs +++ b/crates/sqlbuild-pysource/src/macro_modules/tests/test_inventory_macro_modules.rs @@ -4,7 +4,7 @@ use crate::macro_modules::tests::test_types::{ }; const SHARED: (&str, &str) = ( - "macros/b.py", + "sql/macros/b.py", "def b():\n pass\n\n\ndef c():\n pass\n", ); @@ -15,11 +15,11 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { description: "a clean project lists exports, signatures, dependencies and load order", sources: &[ ( - "macros/shared.py", + "sql/macros/shared.py", "def shared(value, /, other, *rest, key, **options):\n return value\n", ), ( - "macros/orders.py", + "sql/macros/orders.py", "from .shared import shared as render\n\n\ndef _helper():\n return \ render(1)\n\n\n@decorated\nasync \\\n def orders():\n return _helper()\n", ), @@ -36,8 +36,8 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { ], expected_faults: &[], expected_modules: Some(&[ - (0, "macros.shared", &[]), - (1, "macros.orders", &["macros.shared"]), + (0, "sql.macros.shared", &[]), + (1, "sql.macros.orders", &["sql.macros.shared"]), ]), }, InventoryMacroModulesTestCase { @@ -45,14 +45,14 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { sources: &[ SHARED, ( - "macros/a.py", - "from macros.b import b, c\n_Y = [[c], b]\n\n\ndef a():\n return 1\n", + "sql/macros/a.py", + "from sql.macros.b import b, c\n_Y = [[c], b]\n\n\ndef a():\n return 1\n", ), ], expected_exports: &[("b", 0, &[], 1, &[]), ("c", 0, &[], 5, &[])], expected_faults: &[( 1, - "Macro module 'macros/a.py' uses imported macro 'b' outside an ordinary function \ + "Macro module 'sql/macros/a.py' uses imported macro 'b' outside an ordinary function \ body; call imported macros directly from module-level macro or helper functions", )], expected_modules: None, @@ -62,15 +62,15 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { sources: &[ SHARED, ( - "macros/a.py", - "from macros.b import b, c\nif x:\n pass\nelif c:\n pass\nelse:\n \ + "sql/macros/a.py", + "from sql.macros.b import b, c\nif x:\n pass\nelif c:\n pass\nelse:\n \ b\n\n\ndef a():\n return 1\n", ), ], expected_exports: &[("b", 0, &[], 1, &[]), ("c", 0, &[], 5, &[])], expected_faults: &[( 1, - "Macro module 'macros/a.py' uses imported macro 'c' outside an ordinary function \ + "Macro module 'sql/macros/a.py' uses imported macro 'c' outside an ordinary function \ body; call imported macros directly from module-level macro or helper functions", )], expected_modules: None, @@ -80,14 +80,14 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { sources: &[ SHARED, ( - "macros/a.py", - "from macros.b import b, c\n\n\ndef a():\n return f(b, [c])\n", + "sql/macros/a.py", + "from sql.macros.b import b, c\n\n\ndef a():\n return f(b, [c])\n", ), ], expected_exports: &[("b", 0, &[], 1, &[]), ("c", 0, &[], 5, &[])], expected_faults: &[( 1, - "Macro module 'macros/a.py' uses imported macro 'b' dynamically; call imported \ + "Macro module 'sql/macros/a.py' uses imported macro 'b' dynamically; call imported \ macros directly", )], expected_modules: None, @@ -95,13 +95,13 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { InventoryMacroModulesTestCase { description: "a faulty module is dropped and the rest are still inventoried", sources: &[ - ("macros/bad.py", "PUBLIC = 1\n"), - ("macros/good.py", "def good():\n return 1\n"), + ("sql/macros/bad.py", "PUBLIC = 1\n"), + ("sql/macros/good.py", "def good():\n return 1\n"), ], expected_exports: &[("good", 1, &[], 1, &[])], expected_faults: &[( 0, - "Macro module 'macros/bad.py' declaration 'PUBLIC' must be underscore-private", + "Macro module 'sql/macros/bad.py' declaration 'PUBLIC' must be underscore-private", )], expected_modules: None, }, @@ -109,23 +109,23 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { description: "an import cycle faults, then its importer fails once the cycle is gone", sources: &[ ( - "macros/a.py", - "from macros.b import b\n\n\ndef a():\n return b()\n", + "sql/macros/a.py", + "from sql.macros.b import b\n\n\ndef a():\n return b()\n", ), ( - "macros/b.py", - "from macros.a import a\n\n\ndef b():\n return a()\n", + "sql/macros/b.py", + "from sql.macros.a import a\n\n\ndef b():\n return a()\n", ), ], expected_exports: &[], expected_faults: &[ ( 0, - "Macro import cycle in 'macros/a.py': macros.a -> macros.b -> macros.a", + "Macro import cycle in 'sql/macros/a.py': sql.macros.a -> sql.macros.b -> sql.macros.a", ), ( 1, - "Macro module 'macros/b.py' imports project package 'macros.a' instead of a \ + "Macro module 'sql/macros/b.py' imports project package 'sql.macros.a' instead of a \ macro module", ), ], @@ -134,29 +134,29 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { InventoryMacroModulesTestCase { description: "a local call cycle reachable from an export faults", sources: &[( - "macros/a.py", + "sql/macros/a.py", "def _h():\n return a()\n\n\ndef a():\n return _h()\n", )], expected_exports: &[], - expected_faults: &[(0, "Macro call cycle in 'macros/a.py': a -> _h -> a")], + expected_faults: &[(0, "Macro call cycle in 'sql/macros/a.py': a -> _h -> a")], expected_modules: None, }, InventoryMacroModulesTestCase { description: "modules sharing a dotted name each fault", sources: &[ - ("macros/a/b.py", "def first():\n pass\n"), - ("macros/a.b.py", "def second():\n pass\n"), - ("macros/c.py", "def third():\n pass\n"), + ("sql/macros/a/b.py", "def first():\n pass\n"), + ("sql/macros/a.b.py", "def second():\n pass\n"), + ("sql/macros/c.py", "def third():\n pass\n"), ], expected_exports: &[("third", 2, &[], 1, &[])], expected_faults: &[ ( 0, - "Macro module path collision for 'macros.a.b': macros/a/b.py and macros/a.b.py", + "Macro module path collision for 'sql.macros.a.b': sql/macros/a/b.py and sql/macros/a.b.py", ), ( 1, - "Macro module path collision for 'macros.a.b': macros/a/b.py and macros/a.b.py", + "Macro module path collision for 'sql.macros.a.b': sql/macros/a/b.py and sql/macros/a.b.py", ), ], expected_modules: None, @@ -164,22 +164,22 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { InventoryMacroModulesTestCase { description: "repeated export names fault without blocking the load plan", sources: &[ - ("macros/a.py", "def same():\n pass\n"), - ("macros/b.py", "def same():\n pass\n"), - ("macros/c.py", "def same():\n pass\n"), + ("sql/macros/a.py", "def same():\n pass\n"), + ("sql/macros/b.py", "def same():\n pass\n"), + ("sql/macros/c.py", "def same():\n pass\n"), ], expected_exports: &[], expected_faults: &[ ( 1, - "Macro name collision for 'same': macros/a.py and macros/b.py", + "Macro name collision for 'same': sql/macros/a.py and sql/macros/b.py", ), - (2, "Macro name collision for 'same' at macros/c.py"), + (2, "Macro name collision for 'same' at sql/macros/c.py"), ], expected_modules: Some(&[ - (0, "macros.a", &[]), - (1, "macros.b", &[]), - (2, "macros.c", &[]), + (0, "sql.macros.a", &[]), + (1, "sql.macros.b", &[]), + (2, "sql.macros.c", &[]), ]), }, ]; @@ -201,8 +201,8 @@ fn given_macro_modules_when_inventoried_then_python_analysis_agrees() { fn given_source_ruff_rejects_when_inventoried_then_native_error_names_module() { let test_cases = [NativeParseErrorTestCase { description: "a source CPython was said to accept but ruff rejects is a native error", - sources: &[("macros/a.py", "def a(:\n")], - expected_message_prefix: "Native macro module analysis cannot parse 'macros/a.py', which \ + sources: &[("sql/macros/a.py", "def a(:\n")], + expected_message_prefix: "Native macro module analysis cannot parse 'sql/macros/a.py', which \ CPython accepted: ", }]; for test_case in test_cases { diff --git a/crates/sqlbuild-pysource/src/rule_evidence/tests/test_rule_evidence.rs b/crates/sqlbuild-pysource/src/rule_evidence/tests/test_rule_evidence.rs index 32e2da73e9..018dd78a27 100644 --- a/crates/sqlbuild-pysource/src/rule_evidence/tests/test_rule_evidence.rs +++ b/crates/sqlbuild-pysource/src/rule_evidence/tests/test_rule_evidence.rs @@ -83,24 +83,28 @@ fn given_project_module_when_reading_project_closure_then_lists_imported_project description: "helper modules across directories, transitively", files: vec![ ( - "macros/money.py", - "import os\nfrom macros._rates import RATE\n\ndef cents(x):\n return x\n", + "sql/macros/money.py", + "import os\nfrom sql.macros._rates import RATE\n\ndef cents(x):\n return x\n", ), ( - "macros/_rates.py", - "from python import shared\nRATE = 100\n", + "sql/macros/_rates.py", + "from python.nodes import shared\nRATE = 100\n", ), ("python/__init__.py", ""), - ("python/shared.py", "VALUE = 1\n"), - ("python/unused.py", "VALUE = 2\n"), + ("python/nodes/shared.py", "VALUE = 1\n"), + ("python/nodes/unused.py", "VALUE = 2\n"), + ], + source: "sql/macros/money.py", + expected_closure: vec![ + "python/__init__.py", + "python/nodes/shared.py", + "sql/macros/_rates.py", ], - source: "macros/money.py", - expected_closure: vec!["macros/_rates.py", "python/__init__.py", "python/shared.py"], }, ProjectClosureTestCase { description: "a module importing nothing local has an empty closure", - files: vec![("macros/plain.py", "import json\n")], - source: "macros/plain.py", + files: vec![("sql/macros/plain.py", "import json\n")], + source: "sql/macros/plain.py", expected_closure: vec![], }, ]; diff --git a/crates/sqlbuild-python-base/src/event_exporting/_helpers/scope.rs b/crates/sqlbuild-python-base/src/event_exporting/_helpers/scope.rs index a5e4ea4411..6b55ed08e1 100644 --- a/crates/sqlbuild-python-base/src/event_exporting/_helpers/scope.rs +++ b/crates/sqlbuild-python-base/src/event_exporting/_helpers/scope.rs @@ -6,10 +6,12 @@ use std::collections::HashMap; use std::sync::Mutex; use pyo3::prelude::{ - Bound, Py, PyAny, PyAnyMethods, PyModule, PyModuleMethods, PyResult, Python, pyclass, + Bound, Py, PyAny, PyAnyMethods, PyErr, PyModule, PyModuleMethods, PyResult, Python, pyclass, pyfunction, pymethods, wrap_pyfunction, }; use pyo3::sync::PyOnceLock; + +use crate::event_exporting::constants::UNNAMED_TEARDOWN_FAILURE; use pyo3::types::{PyBool, PyDict, PyDictMethods, PyTuple}; use sqlbuild_host::entries::models::ExecutorHost; @@ -36,6 +38,8 @@ pub(crate) struct ScopeState { pub(crate) providers: Option>, pub(crate) event_exporters: Option>, pub(crate) command_output_sinks: Option>, + /// Each sink provider whose teardown raised at close, with the error type, never its message. + pub(crate) teardown_failures: Vec, } /// Releases and force-closes a provider session on the closing thread once sink delivery is idle. @@ -164,6 +168,17 @@ pub(crate) fn bindings<'py>( Ok((PyTuple::new(py, exporters)?, PyTuple::new(py, sinks)?)) } +/// The providers a failed teardown names with their error types, or a note that closing the session raised. +pub(crate) fn teardown_failures(py: Python<'_>, error: &PyErr) -> Vec { + let named: Vec = native_field(error.value(py), "failures") + .and_then(|failures| failures.extract()) + .unwrap_or_default(); + if named.is_empty() { + return vec![UNNAMED_TEARDOWN_FAILURE.to_owned()]; + } + named +} + #[pymethods] impl ProviderSessionCloser { pub(crate) fn __call__(&self, py: Python<'_>) -> PyResult<()> { diff --git a/crates/sqlbuild-python-base/src/event_exporting/constants.rs b/crates/sqlbuild-python-base/src/event_exporting/constants.rs index 07aaf03de8..1417117f53 100644 --- a/crates/sqlbuild-python-base/src/event_exporting/constants.rs +++ b/crates/sqlbuild-python-base/src/event_exporting/constants.rs @@ -39,3 +39,5 @@ pub const IDLE_WAIT_SECONDS: f64 = 1.0; /// No time left before a deadline. pub const NO_SECONDS: f64 = 0.0; +/// How the export warning names a failed sink provider teardown that named no provider. +pub(crate) const UNNAMED_TEARDOWN_FAILURE: &str = "closing the provider session raised"; diff --git a/crates/sqlbuild-python-base/src/event_exporting/models.rs b/crates/sqlbuild-python-base/src/event_exporting/models.rs index eff0abdada..65be8bf398 100644 --- a/crates/sqlbuild-python-base/src/event_exporting/models.rs +++ b/crates/sqlbuild-python-base/src/event_exporting/models.rs @@ -9,6 +9,7 @@ use crate::event_exporting::_helpers::scope::ScopeState; use crate::event_exporting::_helpers::scope::bindings; use crate::event_exporting::_helpers::scope::optional; use crate::event_exporting::_helpers::scope::providers_missing_secrets; +use crate::event_exporting::_helpers::scope::teardown_failures; use crate::event_exporting::_helpers::scope::tuple_or_empty; use crate::event_exporting::_helpers::values::accounting_repr; use crate::event_exporting::_helpers::values::bound_exporter_arguments; @@ -464,6 +465,7 @@ impl EventExporterCommandScope { providers: None, event_exporters: None, command_output_sinks: None, + teardown_failures: Vec::new(), }), } } @@ -601,12 +603,21 @@ impl EventExporterCommandScope { session }; let closer: Py = Py::new(py, ProviderSessionCloser { session })?; - self.dispatcher + if let Err(error) = self + .dispatcher .bind(py) - .call_method1("finalize_when_idle", (closer,))?; + .call_method1("finalize_when_idle", (closer,)) + { + self.locked()?.teardown_failures = teardown_failures(py, &error); + } Ok(summary) } + /// Each sink provider whose teardown raised when the scope closed, with its error type. + pub fn teardown_failures(&self) -> PyResult> { + Ok(self.locked()?.teardown_failures.clone()) + } + /// Reuse bound sink functions and provider instances for output records. pub(crate) fn export_output(&self, py: Python<'_>, records: &Bound<'_, PyAny>) -> PyResult<()> { self.dispatcher diff --git a/crates/sqlbuild-python-base/src/invocation_phases/constants.rs b/crates/sqlbuild-python-base/src/invocation_phases/constants.rs new file mode 100644 index 0000000000..f94c266cfa --- /dev/null +++ b/crates/sqlbuild-python-base/src/invocation_phases/constants.rs @@ -0,0 +1,19 @@ +//! The phases an invocation reports, and the lifecycle event reporting each. + +/// The lifecycle event of one finished phase. +pub const INVOCATION_PHASE_EVENT: &str = "invocation_phase"; + +/// The project's declarations and Python were read. +pub const DISCOVERED_PHASE: &str = "discovered"; +/// The project compiled. +pub const COMPILED_PHASE: &str = "compiled"; +/// The worker's compile matched the snapshot its run was published from. +pub const MATCHED_PHASE: &str = "matched"; +/// One saved discovered set the run used. +pub const DISCOVERED_SET_PHASE: &str = "discovered_set"; +/// The warehouse connections opened. +pub const CONNECTED_PHASE: &str = "connected"; +/// The warehouse state the plan needs was read. +pub const INSPECTED_PHASE: &str = "inspected"; +/// The plan was generated. +pub const PLANNED_PHASE: &str = "planned"; diff --git a/crates/sqlbuild-python-base/src/invocation_phases/main/mod.rs b/crates/sqlbuild-python-base/src/invocation_phases/main/mod.rs new file mode 100644 index 0000000000..cb988318cb --- /dev/null +++ b/crates/sqlbuild-python-base/src/invocation_phases/main/mod.rs @@ -0,0 +1 @@ +pub mod phase_since; diff --git a/crates/sqlbuild-python-base/src/invocation_phases/main/phase_since.rs b/crates/sqlbuild-python-base/src/invocation_phases/main/phase_since.rs new file mode 100644 index 0000000000..9179966255 --- /dev/null +++ b/crates/sqlbuild-python-base/src/invocation_phases/main/phase_since.rs @@ -0,0 +1,15 @@ +//! `phase_since`: a phase that started at a given instant and has just finished. + +use std::time::Instant; + +use crate::invocation_phases::models::InvocationPhase; + +/// `phase`, timed from `started` to now. +#[must_use] +pub fn phase_since(phase: &str, started: Instant) -> InvocationPhase<'_> { + InvocationPhase { + phase, + duration_ms: Some(started.elapsed().as_secs_f64() * 1000.0), + ..InvocationPhase::default() + } +} diff --git a/crates/sqlbuild-python-base/src/invocation_phases/mod.rs b/crates/sqlbuild-python-base/src/invocation_phases/mod.rs new file mode 100644 index 0000000000..d6f430ebab --- /dev/null +++ b/crates/sqlbuild-python-base/src/invocation_phases/mod.rs @@ -0,0 +1,5 @@ +//! The finished phases of an invocation, published as `invocation_phase` lifecycle events. + +pub mod constants; +pub mod main; +pub mod models; diff --git a/crates/sqlbuild-python-base/src/invocation_phases/models.rs b/crates/sqlbuild-python-base/src/invocation_phases/models.rs new file mode 100644 index 0000000000..996d3e36dd --- /dev/null +++ b/crates/sqlbuild-python-base/src/invocation_phases/models.rs @@ -0,0 +1,15 @@ +//! One finished invocation phase. + +/// What a finished phase reports: its name, how long it took, a count, a subject and sub-steps. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct InvocationPhase<'a> { + /// Such as `discovered`, `compiled`, `matched`, `discovered_set`, `connected`, `inspected` or `planned`. + pub phase: &'a str, + pub duration_ms: Option, + /// What the phase counted: models compiled, nodes selected or a set's items. + pub count: Option, + /// What the phase is about: an adapter, a snapshot version or a discovered set. + pub name: Option, + /// The phase's sub-steps or facts, joined with ` · `. + pub detail: Option, +} diff --git a/crates/sqlbuild-python-base/src/lib.rs b/crates/sqlbuild-python-base/src/lib.rs index cc330292ef..1ed7a8b9ee 100644 --- a/crates/sqlbuild-python-base/src/lib.rs +++ b/crates/sqlbuild-python-base/src/lib.rs @@ -15,6 +15,7 @@ pub mod contracts; pub mod diagnostics; pub mod event_exporting; pub mod frontier; +pub mod invocation_phases; pub mod native_host; pub mod native_threads; pub mod orchestration_reads; diff --git a/crates/sqlbuild-python-base/src/native_host/main/mod.rs b/crates/sqlbuild-python-base/src/native_host/main/mod.rs index 60fcff06ba..fc4ded0f48 100644 --- a/crates/sqlbuild-python-base/src/native_host/main/mod.rs +++ b/crates/sqlbuild-python-base/src/native_host/main/mod.rs @@ -7,6 +7,7 @@ pub mod interrupted; pub mod log_debug_message; pub mod log_warning_message; pub mod module_installed; +pub mod publish_invocation_phase; pub mod python_executable; pub mod redirect_stdout_to_stderr; pub mod run_interruptible; diff --git a/crates/sqlbuild-python-base/src/native_host/main/publish_invocation_phase.rs b/crates/sqlbuild-python-base/src/native_host/main/publish_invocation_phase.rs new file mode 100644 index 0000000000..1f09ffddb5 --- /dev/null +++ b/crates/sqlbuild-python-base/src/native_host/main/publish_invocation_phase.rs @@ -0,0 +1,48 @@ +//! `publish_invocation_phase`: one finished phase as a lifecycle event of the current invocation. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; +use pyo3::types::{PyDict, PyDictMethods, PyString}; +use sqlbuild_host::entries::models::ExecutorHost; + +use crate::boundary::main::call_with::call_with; +use crate::invocation_phases::constants::INVOCATION_PHASE_EVENT; +use crate::invocation_phases::models::InvocationPhase; +use crate::native_host::main::host_entry::host_entry; + +/// Publish `phase` to the current event dispatcher; without one, or outside an invocation, nothing is published. +pub fn publish_invocation_phase(py: Python<'_>, phase: &InvocationPhase<'_>) -> PyResult<()> { + let dispatcher: Bound<'_, PyAny> = + host_entry(py, ExecutorHost::CurrentEventDispatcher)?.call0()?; + if dispatcher.is_none() + || host_entry(py, ExecutorHost::CurrentExecutionIdentity)? + .call0()? + .is_none() + { + return Ok(()); + } + let payload: Bound<'_, PyDict> = PyDict::new(py); + payload.set_item("phase", phase.phase)?; + if let Some(duration_ms) = phase.duration_ms { + payload.set_item("duration_ms", duration_ms.max(0.0))?; + } + if let Some(count) = phase.count { + payload.set_item("count", count)?; + } + for (key, value) in [("name", &phase.name), ("detail", &phase.detail)] { + if let Some(value) = value { + payload.set_item(key, value)?; + } + } + let event: Bound<'_, PyAny> = call_with( + &host_entry(py, ExecutorHost::CreateLifecycleEvent)?, + &[ + ( + "event_type", + PyString::new(py, INVOCATION_PHASE_EVENT).into_any(), + ), + ("payload", payload.into_any()), + ], + )?; + dispatcher.call_method1("publish_lifecycle", (event,))?; + Ok(()) +} diff --git a/crates/sqlbuild-python-base/src/records/_helpers/compiler_errors/constants.rs b/crates/sqlbuild-python-base/src/records/_helpers/compiler_errors/constants.rs index 981e9522e6..83017bf948 100644 --- a/crates/sqlbuild-python-base/src/records/_helpers/compiler_errors/constants.rs +++ b/crates/sqlbuild-python-base/src/records/_helpers/compiler_errors/constants.rs @@ -62,7 +62,7 @@ pub(crate) const COMPILER_ERRORS: &[ErrorSpec] = &[ ErrorSpec { name: "SourceParseError", parent: "DiscoveryError", - doc: "Raised when a sources/*.yml file has an invalid shape.", + doc: "Raised when a sql/sources/*.yml file has an invalid shape.", class_attributes: &[("code", ClassValue::Text("D006"))], required: &[], optional: &[], @@ -149,6 +149,15 @@ pub(crate) const COMPILER_ERRORS: &[ErrorSpec] = &[ optional: &[], fixed: &[], }, + ErrorSpec { + name: "ProjectLayoutError", + parent: "DiscoveryError", + doc: "Raised when a project holds an entry outside the SQLBuild project layout.", + class_attributes: &[("code", ClassValue::Text("D018"))], + required: &[], + optional: &[], + fixed: &[], + }, ErrorSpec { name: "ProjectPythonPathError", parent: "DiscoveryError", diff --git a/crates/sqlbuild-python-base/src/records/_helpers/contract_records/constants.rs b/crates/sqlbuild-python-base/src/records/_helpers/contract_records/constants.rs index ac5ecec1a3..ed1198e22e 100644 --- a/crates/sqlbuild-python-base/src/records/_helpers/contract_records/constants.rs +++ b/crates/sqlbuild-python-base/src/records/_helpers/contract_records/constants.rs @@ -541,8 +541,12 @@ const R_PROJECT_CONFIG: RecordSpec = RecordSpec { FieldDefault::NativeCall(RecordId::ScenarioConfig), ), FieldSpec::new("dbt", FieldDefault::NativeCall(RecordId::DbtConfig)), - FieldSpec::new("sinks", FieldDefault::NativeCall(RecordId::SinksConfig)), + FieldSpec::new( + "event_sinks", + FieldDefault::NativeCall(RecordId::SinksConfig), + ), FieldSpec::new("env_file", FieldDefault::None), + FieldSpec::new("extra_paths", FieldDefault::EmptyTuple), ], }; const R_LOCAL_CONFIG: RecordSpec = RecordSpec { @@ -698,7 +702,7 @@ const R_SOURCE_FRESHNESS_CONFIG: RecordSpec = RecordSpec { }; const R_SOURCE_COLUMN_ENTRY: RecordSpec = RecordSpec { name: "SourceColumnEntry", - doc: "One source column entry from sources/*.yml.", + doc: "One source column entry from sql/sources/*.yml.", fields: &[ FieldSpec::required("name"), FieldSpec::new("type", FieldDefault::None), @@ -710,7 +714,7 @@ const R_SOURCE_COLUMN_ENTRY: RecordSpec = RecordSpec { }; const R_SOURCE_ENTRY: RecordSpec = RecordSpec { name: "SourceEntry", - doc: "One source declaration from sources/*.yml.", + doc: "One source declaration from sql/sources/*.yml.", fields: &[ FieldSpec::required("name"), FieldSpec::new("database", FieldDefault::None), diff --git a/crates/sqlbuild-python-base/src/records/_helpers/native_classes/ids.rs b/crates/sqlbuild-python-base/src/records/_helpers/native_classes/ids.rs index e195926e7c..c5be82a6b9 100644 --- a/crates/sqlbuild-python-base/src/records/_helpers/native_classes/ids.rs +++ b/crates/sqlbuild-python-base/src/records/_helpers/native_classes/ids.rs @@ -625,6 +625,7 @@ native_id_names! { ErrorId::OrchestrationDeclaration => "OrchestrationDeclarationError", ErrorId::ProjectCompile => "ProjectCompileError", ErrorId::ProjectConfig => "ProjectConfigError", + ErrorId::ProjectLayout => "ProjectLayoutError", ErrorId::ProjectPath => "ProjectPathError", ErrorId::ProjectPythonPath => "ProjectPythonPathError", ErrorId::ProviderDiscovery => "ProviderDiscoveryError", diff --git a/crates/sqlbuild-python-base/src/records/types.rs b/crates/sqlbuild-python-base/src/records/types.rs index ce28b138cf..0d379bc2b3 100644 --- a/crates/sqlbuild-python-base/src/records/types.rs +++ b/crates/sqlbuild-python-base/src/records/types.rs @@ -618,6 +618,7 @@ pub enum ErrorId { OrchestrationDeclaration, ProjectCompile, ProjectConfig, + ProjectLayout, ProjectPath, ProjectPythonPath, ProviderDiscovery, diff --git a/crates/sqlbuild-python-compile/src/compile_command/_helpers/artifacts/target_writer.rs b/crates/sqlbuild-python-compile/src/compile_command/_helpers/artifacts/target_writer.rs index c9908f9f54..1703315537 100644 --- a/crates/sqlbuild-python-compile/src/compile_command/_helpers/artifacts/target_writer.rs +++ b/crates/sqlbuild-python-compile/src/compile_command/_helpers/artifacts/target_writer.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; use pyo3::exceptions::PyValueError; use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyErr, PyResult, Python}; -use pyo3::types::{PyDict, PyDictMethods, PyTuple, PyTupleMethods}; +use pyo3::types::{PyDict, PyDictMethods, PyTuple}; use pyo3::{IntoPyObjectExt, pyclass, pyfunction}; use sqlbuild_cache::artifacts::constants::SQL_TEST_CACHE_FILE; use sqlbuild_cache::artifacts::main::new_sql_test_record::new_sql_test_record; @@ -60,9 +60,9 @@ use sqlbuild_python_project::sql_test_glue::models::PlanRow; use sqlbuild_python_project::sql_test_glue::models::SqlTestPlanOptions; const COMPILED_DIR: &str = "compiled"; -const MODELS_DIR: &str = "models"; -const FUNCTIONS_DIR: &str = "functions"; -const AUDITS_DIR: &str = "audits"; +const MODELS_DIR: &str = sqlbuild_core::constants::MODELS_PATH; +const FUNCTIONS_DIR: &str = sqlbuild_core::constants::FUNCTIONS_PATH; +const AUDITS_DIR: &str = sqlbuild_core::constants::AUDITS_PATH; const GENERIC_DIR: &str = "generic"; const SINGULAR_DIR: &str = "singular"; const TESTS_DIR: &str = "tests"; @@ -78,8 +78,6 @@ const NOT_RECORDED: &str = "not_recorded"; const LOGGED_MISSES: usize = 16; /// Leading characters of a record key that name it in a cache-miss debug line. const LOGGED_KEY_CHARS: usize = 12; -/// `functions/` path components that already lead a function's path. -const LANGUAGE_DIR_DEPTH: usize = 2; const PUBLISHED_STAGING_CHANGED: &str = "changed"; const PUBLISHED_TREE: &str = "tree"; const TARGET_OPTIONS: (&[&str], &[&str]) = (&["target_dir", "adapter", "project"], &["manifest"]); @@ -101,12 +99,18 @@ fn path_class(py: Python<'_>) -> PyResult> { imported(py, "pathlib", "Path") } -/// `relative_path` under `models/`, unless it already starts there. +/// Whether the `/`-separated `path` lies below the folder `root`. +fn is_below(path: &str, root: &str) -> bool { + path.strip_prefix(root) + .is_some_and(|rest| rest.starts_with('/')) +} + +/// `relative_path` under `sql/models/`, unless it already starts there. fn model_output_path<'py>(relative_path: &Bound<'py, PyAny>) -> PyResult> { let py: Python<'py> = relative_path.py(); - let parts: Bound<'py, PyTuple> = native_field(relative_path, "parts")?.downcast_into()?; - if !parts.is_empty() && parts.get_item(0)?.eq(MODELS_DIR)? { - return path_class(py)?.call1(parts); + let text: String = path_posix_text(relative_path)?; + if is_below(&text, MODELS_DIR) { + return path_class(py)?.call1((text,)); } path_class(py)?.call1((MODELS_DIR,))?.div(relative_path) } @@ -114,14 +118,11 @@ fn model_output_path<'py>(relative_path: &Bound<'py, PyAny>) -> PyResult PathBuf { let mut path: PathBuf = compiled.to_path_buf(); - let mut segments = relative_path - .split('/') - .filter(|segment| !segment.is_empty()) - .peekable(); - if segments.peek() != Some(&MODELS_DIR) { - path.push(MODELS_DIR); - } - for segment in segments { + let trimmed: &str = relative_path.trim_start_matches('/'); + if !is_below(trimmed, MODELS_DIR) { + path.extend(MODELS_DIR.split('/')); + } + for segment in trimmed.split('/').filter(|segment| !segment.is_empty()) { path.push(segment); } path @@ -138,13 +139,11 @@ fn function_output_path<'py>( language: &Bound<'py, PyAny>, ) -> PyResult> { let py: Python<'py> = relative_path.py(); - let parts: Bound<'py, PyTuple> = native_field(relative_path, "parts")?.downcast_into()?; + let text: String = path_posix_text(relative_path)?; let language_dir: Bound<'py, PyAny> = native_field(language, "value")?; - let path: Bound<'py, PyAny> = if parts.len() >= LANGUAGE_DIR_DEPTH - && parts.get_item(0)?.eq(FUNCTIONS_DIR)? - && parts.get_item(1)?.eq(&language_dir)? - { - path_class(py)?.call1(parts)? + let language_name: String = language_dir.extract()?; + let path: Bound<'py, PyAny> = if is_below(&text, &format!("{FUNCTIONS_DIR}/{language_name}")) { + path_class(py)?.call1((text,))? } else { path_class(py)? .call1((FUNCTIONS_DIR,))? diff --git a/crates/sqlbuild-python-compile/src/compile_delta/_helpers/driver.rs b/crates/sqlbuild-python-compile/src/compile_delta/_helpers/driver.rs index 9490c6e738..77e705da34 100644 --- a/crates/sqlbuild-python-compile/src/compile_delta/_helpers/driver.rs +++ b/crates/sqlbuild-python-compile/src/compile_delta/_helpers/driver.rs @@ -53,7 +53,7 @@ const MAX_RERUN_MODELS: usize = 500; const MAX_RERUN_PERCENT: usize = 5; /// How many times a changed relation shape may pull its dependents into the delta. const MAX_ROUNDS: usize = 4; -const MODELS_ROOT: &str = "models/"; +const MODELS_ROOT: &str = "sql/models/"; /// How a rules diagnostic's report JSON names its phase; rules run over the whole project. const RULE_PHASE: &str = "\"phase\": \"rule\""; /// What every error for a reference to an undiscovered source says. diff --git a/crates/sqlbuild-python-compile/src/compile_delta/tests/helpers.rs b/crates/sqlbuild-python-compile/src/compile_delta/tests/helpers.rs index 6ba7133e99..080ae3fc2e 100644 --- a/crates/sqlbuild-python-compile/src/compile_delta/tests/helpers.rs +++ b/crates/sqlbuild-python-compile/src/compile_delta/tests/helpers.rs @@ -45,16 +45,16 @@ pub(crate) fn image() -> ProjectImage { models: vec![ CapturedModel { name: "orders".to_owned(), - relative_path: "models/orders.sql".to_owned(), + relative_path: "sql/models/orders.sql".to_owned(), upstream: pairs(&[("source", "raw_orders"), ("model", "customers")]), }, CapturedModel { name: "customers".to_owned(), - relative_path: "models/customers.sql".to_owned(), + relative_path: "sql/models/customers.sql".to_owned(), upstream: Vec::new(), }, ], - usages: BTreeMap::from([("models/orders.sql".to_owned(), "digest-1".to_owned())]), + usages: BTreeMap::from([("sql/models/orders.sql".to_owned(), "digest-1".to_owned())]), tests: vec![CapturedTest { key: "orders_test".to_owned(), relative_path: "tests/unit/orders.sql".to_owned(), @@ -86,12 +86,12 @@ pub(crate) fn image() -> ProjectImage { fact_digests: vec![(strings(&["model", "orders"]), "fact-digest".to_owned())], model_subjects: Some(vec![ ( - "models/orders.sql".to_owned(), + "sql/models/orders.sql".to_owned(), "orders".to_owned(), Some("table".to_owned()), ), ( - "models/customers.sql".to_owned(), + "sql/models/customers.sql".to_owned(), "customers".to_owned(), None, ), @@ -99,7 +99,7 @@ pub(crate) fn image() -> ProjectImage { diagnostics: vec![CapturedDiagnostic { json: "{\"code\": \"W1\"}".to_owned(), resource_name: Some("orders".to_owned()), - paths: strings(&["models/orders.sql"]), + paths: strings(&["sql/models/orders.sql"]), error: false, }], text_models: Some(vec![("orders".to_owned(), true, 3)]), @@ -119,17 +119,20 @@ pub(crate) fn image() -> ProjectImage { blocked: true, partial: strings(&["open source: raw_orders"]), }]), - lint_model_keys: Some(pairs(&[("models/orders.sql", "lint-key")])), + lint_model_keys: Some(pairs(&[("sql/models/orders.sql", "lint-key")])), lint_file_keys: Some(vec![ - ("models/orders.sql".to_owned(), Some("file-key".to_owned())), - ("models/customers.sql".to_owned(), None), + ( + "sql/models/orders.sql".to_owned(), + Some("file-key".to_owned()), + ), + ("sql/models/customers.sql".to_owned(), None), ]), header_keys: BTreeMap::from([( - "models/orders.sql".to_owned(), + "sql/models/orders.sql".to_owned(), pairs(&[("description", "0123")]), )]), audit_references: BTreeMap::from([( - "models/orders.sql".to_owned(), + "sql/models/orders.sql".to_owned(), strings(&["order_quality"]), )]), rules: Some(ImageRules::Retained(RetainedRows { diff --git a/crates/sqlbuild-python-compile/src/compile_delta/tests/test_delta_facts.rs b/crates/sqlbuild-python-compile/src/compile_delta/tests/test_delta_facts.rs index 45839fa62a..20bcb63b37 100644 --- a/crates/sqlbuild-python-compile/src/compile_delta/tests/test_delta_facts.rs +++ b/crates/sqlbuild-python-compile/src/compile_delta/tests/test_delta_facts.rs @@ -9,31 +9,31 @@ fn given_custom_rule_fact_when_a_delta_compiles_some_models_then_only_facts_it_h let test_cases = [ DeltaFactTestCase { description: "the SQL of a compiled model", - key: &["sql.for_model", "models/orders.sql"], + key: &["sql.for_model", "sql/models/orders.sql"], all_sources: false, expected_safe: true, }, DeltaFactTestCase { description: "the inferred columns of a compiled model", - key: &["columns.inferred", "models/orders.sql"], + key: &["columns.inferred", "sql/models/orders.sql"], all_sources: false, expected_safe: true, }, DeltaFactTestCase { description: "the SQL of a model the delta does not compile", - key: &["sql.for_model", "models/customers.sql"], + key: &["sql.for_model", "sql/models/customers.sql"], all_sources: false, expected_safe: false, }, DeltaFactTestCase { description: "the dependencies of a compiled model", - key: &["graph.dependencies", "models/orders.sql"], + key: &["graph.dependencies", "sql/models/orders.sql"], all_sources: false, expected_safe: false, }, DeltaFactTestCase { description: "the text of any project file", - key: &["tree.read_text", "models/customers.sql"], + key: &["tree.read_text", "sql/models/customers.sql"], all_sources: false, expected_safe: true, }, @@ -68,7 +68,7 @@ fn given_custom_rule_fact_when_a_delta_compiles_some_models_then_only_facts_it_h expected_safe: false, }, ]; - let compiled: BTreeSet = names(&["models/orders.sql"]); + let compiled: BTreeSet = names(&["sql/models/orders.sql"]); for test_case in test_cases { let safe: bool = delta_safe_fact(&strings(test_case.key), &compiled, test_case.all_sources); diff --git a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/compiled.rs b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/compiled.rs new file mode 100644 index 0000000000..fbb20d59f2 --- /dev/null +++ b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/compiled.rs @@ -0,0 +1,28 @@ +//! The finished compile as an invocation phase, with the models it compiled. + +use pyo3::prelude::{Bound, PyAny, PyResult}; +use pyo3::types::PyTupleMethods; +use sqlbuild_python_base::invocation_phases::constants::COMPILED_PHASE; +use sqlbuild_python_base::invocation_phases::models::InvocationPhase; +use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; +use sqlbuild_python_project::compiled_views::models::NativeProjectView; + +/// Publish the compile of `project`, which took `seconds`; a project that is not a native view has no model count. +pub(crate) fn publish_compiled(project: &Bound<'_, PyAny>, seconds: f64) -> PyResult<()> { + let py = project.py(); + let count: Option = match project.cast::() { + Ok(view) => { + Some(i64::try_from(view.borrow().models(py).bind(py).len()).unwrap_or(i64::MAX)) + } + Err(_) => None, + }; + publish_invocation_phase( + py, + &InvocationPhase { + phase: COMPILED_PHASE, + duration_ms: Some(seconds * 1000.0), + count, + ..InvocationPhase::default() + }, + ) +} diff --git a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/mod.rs b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/mod.rs index 7c158b10a8..91a2e5894f 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/mod.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod compiled; pub(crate) mod dynamic; pub(crate) mod inputs; pub(crate) mod model_free_locations; diff --git a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/discovery.rs b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/discovery.rs index b49885f80b..ce5ac9cdf6 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/discovery.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/discovery.rs @@ -34,6 +34,7 @@ use sqlbuild_python_front::discovery::main::python_files::discover_materializati use sqlbuild_python_front::discovery::main::python_files::discover_provider_classes::discover_provider_classes; use sqlbuild_python_front::discovery::main::python_files::discover_python_function_files::discover_python_function_files; use sqlbuild_python_front::discovery::main::python_files::discover_python_node_functions::discover_python_node_functions; +use sqlbuild_python_front::discovery::main::python_files::reject_project_layout::reject_project_layout; use sqlbuild_python_front::discovery::main::python_files::reject_unsupported_python_paths::reject_unsupported_python_paths; use sqlbuild_python_front::discovery::main::records::discover_adapter_file::discover_adapter_file; use sqlbuild_python_front::discovery::main::records::discover_audit_files::discover_audit_files; @@ -248,6 +249,8 @@ pub(crate) fn assembled_inputs<'py>( local_config: &local_config, })?; warn_deprecated_settings(py, project_dir)?; + let extra_paths: Vec = native_field(&project_config, "extra_paths")?.extract()?; + reject_project_layout(project_dir, &extra_paths)?; reject_unsupported_python_paths(project_dir)?; let delta_settings: &Bound<'py, PyAny> = if native_field(&local_config, "setting_overrides")?.contains(DELTA_COMPILE_SETTING_KEY)? { diff --git a/crates/sqlbuild-python-compile/src/compile_driver/main/setup/compiled_phase.rs b/crates/sqlbuild-python-compile/src/compile_driver/main/setup/compiled_phase.rs index 87cab0830a..a7c9a2f041 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/main/setup/compiled_phase.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/main/setup/compiled_phase.rs @@ -1,5 +1,6 @@ //! `compile_project_phase` with resolved arguments. +use crate::compile_driver::_helpers::setup::compiled::publish_compiled; use crate::compile_driver::_helpers::setup::pipeline::reject_compile_errors; use crate::compile_driver::_helpers::setup::pipeline_entries::compile_analysis_selection; use crate::compile_driver::main::setup::build_compiled_project::build_compiled_project; @@ -85,6 +86,7 @@ pub fn compiled_phase<'py>( } let project: Bound<'py, PyAny> = compiled?; reject_compile_errors(&project, &options, on_progress)?; + publish_compiled(&project, compile_seconds)?; progress( on_progress, &format!("Compiled project. ({compile_seconds:.2}s)"), diff --git a/crates/sqlbuild-python-compile/src/compile_driver/main/stages/discover_project_inputs.rs b/crates/sqlbuild-python-compile/src/compile_driver/main/stages/discover_project_inputs.rs index 971e077989..115e566c33 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/main/stages/discover_project_inputs.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/main/stages/discover_project_inputs.rs @@ -12,7 +12,11 @@ use sqlbuild_python_base::boundary::main::within::within; use sqlbuild_python_base::boundary::models::KeywordArguments; use sqlbuild_python_base::compile_driver::constants::PROJECT_DISCOVERIES; use sqlbuild_python_base::compile_driver::main::count_stage::count_stage; +use sqlbuild_python_base::invocation_phases::constants::DISCOVERED_PHASE; +use sqlbuild_python_base::invocation_phases::main::phase_since::phase_since; +use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; use sqlbuild_python_front::discovery::models::SecretPolicy; +use std::time::Instant; /// Load all raw project inputs from disk before semantic resolution. #[pyfunction] @@ -47,11 +51,14 @@ pub fn discover_project_inputs<'py>( || arguments.flag("extract_output_column_locations")?, secret_policy, }; - within(&lifecycle(py, "project_discovery")?, |_| { + let started: Instant = Instant::now(); + let discovered: Bound<'py, PyAny> = within(&lifecycle(py, "project_discovery")?, |_| { let assembled: Bound<'py, PyAny> = within(&lifecycle(py, "discovery_project_assembly")?, |_| { assembled_inputs(py, &request) })?; produced(FrontierStage::DiscoveredProjectInputs, assembled) - }) + })?; + publish_invocation_phase(py, &phase_since(DISCOVERED_PHASE, started))?; + Ok(discovered) } diff --git a/crates/sqlbuild-python-compile/src/input_loops/_helpers/model_loop/model_loop_named.rs b/crates/sqlbuild-python-compile/src/input_loops/_helpers/model_loop/model_loop_named.rs index 503513302b..99ccf45923 100644 --- a/crates/sqlbuild-python-compile/src/input_loops/_helpers/model_loop/model_loop_named.rs +++ b/crates/sqlbuild-python-compile/src/input_loops/_helpers/model_loop/model_loop_named.rs @@ -188,7 +188,7 @@ fn report_inaccessible( "help", format!( "move '{record_path}' to a {role}/ role owned by '{folder}' or one of its parent \ - folders, or to the project-wide {role}/ when consumers span resource trees" + folders, or to the project-wide sql/{role}/ when consumers span resource trees" ), )?; let diagnostic: Bound<'_, PyAny> = context diff --git a/crates/sqlbuild-python-front/src/discovered_sets/_helpers/state.rs b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/state.rs index 41aa8ea0a2..3d34285810 100644 --- a/crates/sqlbuild-python-front/src/discovered_sets/_helpers/state.rs +++ b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/state.rs @@ -1,5 +1,6 @@ //! The process's discovery source, the sets its last compile used, and the registered runner. +use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Mutex, OnceLock}; use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; @@ -13,3 +14,7 @@ pub(crate) static SOURCE: Mutex> = Mutex::new(None); pub(crate) static USED: Mutex> = Mutex::new(None); /// The function that calls a discover function with a target's providers. pub(crate) static RUNNER: OnceLock = OnceLock::new(); +/// Sets the newest compile found an item of naming a tag no node carries, with their errors. +pub(crate) static TAG_FAILURES: Mutex> = Mutex::new(BTreeMap::new()); +/// Sets already compiled once more with their last good items in this publication. +pub(crate) static FALLEN_BACK: Mutex> = Mutex::new(BTreeSet::new()); diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/for_each_assets.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/for_each_assets.rs new file mode 100644 index 0000000000..db2b32b886 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/for_each_assets.rs @@ -0,0 +1,19 @@ +//! The `for_each` assets that read each discovered set, for the snapshot. + +use std::collections::BTreeMap; + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_python_base::records::main::fields::field::field as native_field; + +/// Each set's `for_each` assets by set name, in declaration order; empty without any. +pub fn for_each_assets(inputs: &Bound<'_, PyAny>) -> PyResult>> { + let mut assets: BTreeMap> = BTreeMap::new(); + for template in native_field(inputs, "for_each_assets")?.try_iter()? { + let template: Bound<'_, PyAny> = template?; + assets + .entry(native_field(&template, "for_each")?.extract()?) + .or_default() + .push(native_field(&template, "name")?.extract()?); + } + Ok(assets) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/mod.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/mod.rs index ce9f2872b6..5ffa5c215c 100644 --- a/crates/sqlbuild-python-front/src/discovered_sets/main/mod.rs +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/mod.rs @@ -1,8 +1,11 @@ pub mod checked_set; pub mod discover_for_publication; +pub mod for_each_assets; pub mod publish_only_placeholders; pub mod published_sets; +pub mod record_tag_failures; pub mod register_discover_runner; pub mod set_discovery_source; pub mod used_discovered_sets; pub mod with_discovered_sets; +pub mod with_set_retries; diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/record_tag_failures.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/record_tag_failures.rs new file mode 100644 index 0000000000..10331b56e4 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/record_tag_failures.rs @@ -0,0 +1,10 @@ +//! Record the discovered sets whose items depend on a tag no node carries. + +use std::sync::PoisonError; + +use crate::discovered_sets::_helpers::state::TAG_FAILURES; + +/// Replace the recorded failures with `failures`, each a set and the error naming its item and tag. +pub fn record_tag_failures(failures: Vec<(String, String)>) { + *TAG_FAILURES.lock().unwrap_or_else(PoisonError::into_inner) = failures.into_iter().collect(); +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/set_discovery_source.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/set_discovery_source.rs index 7e57eea55f..3ef39964bd 100644 --- a/crates/sqlbuild-python-front/src/discovered_sets/main/set_discovery_source.rs +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/set_discovery_source.rs @@ -2,10 +2,18 @@ use std::sync::PoisonError; -use crate::discovered_sets::_helpers::state::SOURCE; +use crate::discovered_sets::_helpers::state::{FALLEN_BACK, SOURCE, TAG_FAILURES}; use crate::discovered_sets::models::DiscoverySource; /// Expand `for_each` assets from `source` until another source is set. pub fn set_discovery_source(source: DiscoverySource) { *SOURCE.lock().unwrap_or_else(PoisonError::into_inner) = Some(source); + TAG_FAILURES + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clear(); + FALLEN_BACK + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clear(); } diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/with_set_retries.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/with_set_retries.rs new file mode 100644 index 0000000000..e651365a73 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/with_set_retries.rs @@ -0,0 +1,69 @@ +//! Compile again with each set an unknown tag failed set back to its last good items. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::PoisonError; + +use chrono::Utc; +use pyo3::PyResult; +use sqlbuild_orchestration::discovered_sets::main::record_attempt::record_attempt; +use sqlbuild_orchestration::discovered_sets::models::DiscoveredSet; +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; + +use crate::discovered_sets::_helpers::state::{FALLEN_BACK, SOURCE, TAG_FAILURES, USED}; +use crate::discovered_sets::models::{DiscoverySource, LiveDiscovery, Rediscover}; + +/// `attempt`, made again while its compile failed sets on unknown tags that can fall back. +pub fn with_set_retries(mut attempt: impl FnMut() -> PyResult) -> PyResult { + let mut outcome: PyResult = attempt(); + while outcome.is_err() && retry_without_failed_sets() { + outcome = attempt(); + } + outcome +} + +/// Whether unknown tags failed sets, which now fall back to their last good items, then placeholders. +fn retry_without_failed_sets() -> bool { + let failures: BTreeMap = + std::mem::take(&mut *TAG_FAILURES.lock().unwrap_or_else(PoisonError::into_inner)); + if failures.is_empty() { + return false; + } + let mut source = SOURCE.lock().unwrap_or_else(PoisonError::into_inner); + let Some(DiscoverySource::Live(live)) = source.as_ref() else { + return false; + }; + let Some(used) = USED.lock().unwrap_or_else(PoisonError::into_inner).clone() else { + return false; + }; + let mut fallen: std::sync::MutexGuard<'_, BTreeSet> = + FALLEN_BACK.lock().unwrap_or_else(PoisonError::into_inner); + let mut previous: DiscoveredSets = used.clone(); + for (name, error) in failures { + let Some(current) = used.get(&name) else { + continue; + }; + let earlier: Option<&DiscoveredSet> = live.previous.get(&name); + let mut failed: DiscoveredSet = record_attempt( + earlier, + Err(error), + (Utc::now(), current.check_every_seconds), + ); + let same_items: bool = + earlier.and_then(|set| set.digest.as_ref()) == current.digest.as_ref(); + if !fallen.insert(name.clone()) || same_items { + failed.result = None; + failed.digest = None; + failed.last_good_at = None; + } + previous.insert(name, failed); + } + let next: LiveDiscovery = LiveDiscovery { + target: live.target.clone(), + previous, + rediscover: Rediscover::Only(BTreeSet::new()), + keep_last_good: live.keep_last_good, + seed: None, + }; + *source = Some(DiscoverySource::Live(next)); + true +} diff --git a/crates/sqlbuild-python-front/src/discovery/_helpers/failures/raised.rs b/crates/sqlbuild-python-front/src/discovery/_helpers/failures/raised.rs index 7f03682b3f..462569113a 100644 --- a/crates/sqlbuild-python-front/src/discovery/_helpers/failures/raised.rs +++ b/crates/sqlbuild-python-front/src/discovery/_helpers/failures/raised.rs @@ -17,7 +17,7 @@ const OS_MODULE: &str = "os"; const DECODE_ENCODING: &str = "utf-8"; /// The exception class of each native failure kind. -const FAILURE_CLASSES: [(&str, ErrorId); 14] = [ +const FAILURE_CLASSES: [(&str, ErrorId); 15] = [ ("model_sql", ErrorId::ModelSqlParse), ("declaration", ErrorId::DeclarationParse), ("sql_test", ErrorId::SqlTestParse), @@ -31,6 +31,7 @@ const FAILURE_CLASSES: [(&str, ErrorId); 14] = [ ("conflict", ErrorId::DiscoveryConflict), ("seed", ErrorId::SeedDiscovery), ("python_path", ErrorId::ProjectPythonPath), + ("project_layout", ErrorId::ProjectLayout), ("orchestration", ErrorId::OrchestrationDeclaration), ]; diff --git a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs index 1b9a98dc24..1cf4b8d3cd 100644 --- a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs +++ b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs @@ -2,6 +2,7 @@ use crate::discovery::main::python_files::provider_by_name::provider_by_name; use crate::discovery::main::python_files::provider_usages::provider_usages; +use sqlbuild_core::constants::{EVENT_SINKS_PATH, PROVIDERS_PATH}; use std::collections::HashSet; use pyo3::exceptions::PyRuntimeError; @@ -204,7 +205,7 @@ pub(crate) fn discover_provider_classes<'py>( return Ok(providers); } if !project - .child("providers")? + .child(PROVIDERS_PATH)? .call_method0("is_dir")? .is_truthy()? { @@ -212,7 +213,7 @@ pub(crate) fn discover_provider_classes<'py>( } let mut providers: Vec> = Vec::new(); let mut seen: Vec<(String, Bound<'py, PyAny>)> = Vec::new(); - for file_path in project.module_files("providers", true)? { + for file_path in project.module_files(PROVIDERS_PATH, true)? { let module: Bound<'py, PyAny> = project.load(UserCodeHost::LoadProviderModule, &file_path)?; let classes: Bound<'py, PyAny> = @@ -302,19 +303,8 @@ pub(crate) fn discover_event_exporter_declarations<'py>( ) -> PyResult> { let py: Python<'py> = project_dir.py(); let project = ProjectDir { path: project_dir }; - if project - .child("event_exporters")? - .call_method0("exists")? - .is_truthy()? - { - return Err(discovery_error( - py, - SINK_ERROR, - "event_exporters/ was replaced by sinks/ and @lifecycle_event_sink".to_owned(), - )); - } if !project - .child("sinks")? + .child(EVENT_SINKS_PATH)? .call_method0("is_dir")? .is_truthy()? { @@ -323,8 +313,9 @@ pub(crate) fn discover_event_exporter_declarations<'py>( let read_definition: Bound<'py, PyAny> = host_entry(py, SINK_DEFINITION)?; let mut declarations: Vec> = Vec::new(); let mut seen: Vec<(String, Bound<'py, PyAny>)> = Vec::new(); - for file_path in project.module_files("sinks", true)? { - let module: Bound<'py, PyAny> = project.load(UserCodeHost::LoadSinkModule, &file_path)?; + for file_path in project.module_files(EVENT_SINKS_PATH, true)? { + let module: Bound<'py, PyAny> = + project.load(UserCodeHost::LoadEventSinkModule, &file_path)?; let mut seen_functions: HashSet = HashSet::new(); for function in module_functions(&module)? { if !seen_functions.insert(function.as_ptr() as usize) { diff --git a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_python_nodes.rs b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_python_nodes.rs index 45e07ed7ec..872d12d640 100644 --- a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_python_nodes.rs +++ b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_python_nodes.rs @@ -8,6 +8,8 @@ use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; use pyo3::types::{PyBytes, PyDict, PyDictMethods, PyList, PyString, PyTuple}; use pyo3::{IntoPyObjectExt, pyfunction}; use sqlbuild_core::constants::PYTHON_NODE_ROOT; +use sqlbuild_discovery::node_files::main::node_file_problems::node_file_problems; +use sqlbuild_discovery::node_files::models::NodeModule; use sqlbuild_host::entries::models::UserCodeHost; use crate::discovery::_helpers::python_files::imported_modules::{ @@ -20,6 +22,7 @@ use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::native_host::main::host_entry::host_entry; use sqlbuild_python_base::records::main::construct::new_record::new_record; use sqlbuild_python_base::records::main::fields::field::field as native_field; +use sqlbuild_python_base::records::main::fields::field_text::field_text; use sqlbuild_python_base::records::types::ErrorId; use sqlbuild_python_base::records::types::RecordId; const NODE_ERROR: ErrorId = ErrorId::PythonNodeDiscovery; @@ -34,6 +37,8 @@ const NOT_A_NODE: &str = "that is not a SQLBuild asset, loader, or check"; /// One Python-node kind: its reader, record class, bucket and copied definition fields. struct NodeKind { + /// The decorator name, as the file-name check reads it. + name: &'static str, reader: UserCodeHost, record: RecordId, bucket: usize, @@ -45,6 +50,7 @@ struct NodeKind { /// Readers in precedence order; the first matching definition decides the kind. const NODE_KINDS: [NodeKind; 3] = [ NodeKind { + name: "loader", reader: UserCodeHost::ReadLoaderDefinition, record: RecordId::DiscoveredLoaderFunction, bucket: 0, @@ -61,6 +67,7 @@ const NODE_KINDS: [NodeKind; 3] = [ ], }, NodeKind { + name: "asset", reader: UserCodeHost::ReadAssetDefinition, record: RecordId::DiscoveredAssetFunction, bucket: 1, @@ -78,6 +85,7 @@ const NODE_KINDS: [NodeKind; 3] = [ ], }, NodeKind { + name: "check", reader: UserCodeHost::ReadCheckDefinition, record: RecordId::DiscoveredCheckFunction, bucket: 2, @@ -105,6 +113,17 @@ pub(crate) const DISCOVER_BUCKET: usize = 3; /// The `Buckets::nodes` slot of assets that run once per discovered item. pub(crate) const FOR_EACH_BUCKET: usize = 4; +/// What `append_node` found in one function. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Appended { + /// A loader, asset or check: its decorator name and node name. + Node(&'static str, String), + /// A `@discover` function, which is not a node. + Discover, + /// No node definition. + Nothing, +} + /// The module and the file it was imported from. struct ImportedModule<'py> { file_path: Bound<'py, PyAny>, @@ -112,18 +131,18 @@ struct ImportedModule<'py> { } impl<'py> Buckets<'py> { - /// Append `function` to its kind's bucket; `false` when it carries no node definition. + /// Append `function` to its kind's bucket, and say what it was. fn append_node( &mut self, (project, file_path): (&ProjectDir<'py>, &Bound<'py, PyAny>), function: &Bound<'py, PyAny>, providers: &Bound<'py, PyDict>, - ) -> PyResult { + ) -> PyResult { let py: Python<'py> = project.py(); if let Some(read) = definition(function, READ_DISCOVER)? { let record = discover_function(project, (file_path, function), (&read, providers))?; self.nodes[DISCOVER_BUCKET].push(record); - return Ok(true); + return Ok(Appended::Discover); } for kind in &NODE_KINDS { let Some(read) = definition(function, kind.reader)? else { @@ -154,9 +173,9 @@ impl<'py> Buckets<'py> { } else { self.nodes[FOR_EACH_BUCKET].push(record); } - return Ok(true); + return Ok(Appended::Node(kind.name, field_text(&read, "name")?)); } - Ok(false) + Ok(Appended::Nothing) } /// Collect audit factories without routing them through Python-node discovery. @@ -217,12 +236,14 @@ impl<'py> Buckets<'py> { Ok(()) } + /// Append every factory's nodes; each factory's name with the kinds it made. fn append_factory_nodes( &mut self, (project, imported_module): (&ProjectDir<'py>, &ImportedModule<'py>), providers: &Bound<'py, PyDict>, direct: &HashMap>, - ) -> PyResult<()> { + ) -> PyResult)>> { + let mut factories: Vec<(String, Vec<&'static str>)> = Vec::new(); let py: Python<'py> = project.py(); let location: String = project.relative_to(&imported_module.file_path)?; for function in module_functions(&imported_module.module)? { @@ -231,6 +252,7 @@ impl<'py> Buckets<'py> { }; let name: String = native_field(&read, "name")?.extract()?; let result: Bound<'py, PyAny> = call_factory(&function, ("Factory", &name, &location))?; + let mut kinds: Vec<&'static str> = Vec::new(); for (index, generated) in factory_functions(&result, (&name, &location))? .into_iter() .enumerate() @@ -241,22 +263,31 @@ impl<'py> Buckets<'py> { { continue; } - if !self.append_node( + match self.append_node( (project, &imported_module.file_path), &generated, providers, )? { - return Err(discovery_error( - py, - NODE_ERROR, - format!( - "Factory '{name}' in {location} returned item {index} {NOT_A_NODE}" - ), - )); + Appended::Node(kind, _) => { + if !kinds.contains(&kind) { + kinds.push(kind); + } + } + Appended::Discover => {} + Appended::Nothing => { + return Err(discovery_error( + py, + NODE_ERROR, + format!( + "Factory '{name}' in {location} returned item {index} {NOT_A_NODE}" + ), + )); + } } } + factories.push((name, kinds)); } - Ok(()) + Ok(factories) } pub(crate) fn discover_nodes( @@ -271,16 +302,34 @@ impl<'py> Buckets<'py> { modules.push(ImportedModule { file_path, module }); } let mut direct: HashMap> = HashMap::new(); + let mut declared: Vec = Vec::new(); for imported_module in &modules { self.append_audit_factories(project, imported_module)?; + let mut module_record = NodeModule { + relative_path: project + .relative_to(&imported_module.file_path)? + .replace('\\', "/"), + ..NodeModule::default() + }; for function in module_functions(&imported_module.module)? { - if self.append_node((project, &imported_module.file_path), &function, providers)? { - direct.insert(function.as_ptr() as usize, function); + let appended: Appended = + self.append_node((project, &imported_module.file_path), &function, providers)?; + if matches!(appended, Appended::Nothing) { + continue; + } + if let Appended::Node(kind, name) = appended { + module_record.direct.push((name, kind)); } + direct.insert(function.as_ptr() as usize, function); } + declared.push(module_record); } - for imported_module in &modules { - self.append_factory_nodes((project, imported_module), providers, &direct)?; + for (imported_module, module_record) in modules.iter().zip(declared.iter_mut()) { + module_record.factories = + self.append_factory_nodes((project, imported_module), providers, &direct)?; + } + if let Some(problem) = node_file_problems(&declared) { + return Err(discovery_error(project.py(), NODE_ERROR, problem)); } Ok(()) } diff --git a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/python_paths.rs b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/python_paths.rs index 001e70123c..9e8d737a41 100644 --- a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/python_paths.rs +++ b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/python_paths.rs @@ -1,4 +1,4 @@ //! Reject project Python outside documented executable roots. pub(crate) const PYTHON_PATH_HELP: &str = "Move pipeline Python nodes and the helper modules they import under \ -python/, or move SQLBuild extensions under their documented extension path."; +python/nodes/, or move SQLBuild extensions under their documented extension path."; diff --git a/crates/sqlbuild-python-front/src/discovery/constants.rs b/crates/sqlbuild-python-front/src/discovery/constants.rs index 0f5b228000..910ccef37c 100644 --- a/crates/sqlbuild-python-front/src/discovery/constants.rs +++ b/crates/sqlbuild-python-front/src/discovery/constants.rs @@ -40,3 +40,10 @@ pub const GETTERS: &[GetterEntry] = &[ read: read_native_directory_snapshot, }, ]; +/// The extra-paths line every D018 help ends with. +pub(crate) const LAYOUT_EXTRA_PATHS_HELP: &str = + "or list it in extra_paths in sqlbuild_project.toml if it belongs here on purpose"; +/// The indent that lines a D018 help continuation up under the first help line. +pub(crate) const LAYOUT_HELP_CONTINUATION: &str = "\n "; +/// The prefix of a further D018 help line. +pub(crate) const LAYOUT_HELP_LINE: &str = "\n = help: "; diff --git a/crates/sqlbuild-python-front/src/discovery/main/python_files/discover_materialization_files.rs b/crates/sqlbuild-python-front/src/discovery/main/python_files/discover_materialization_files.rs index e370b7e2c0..94b83a2507 100644 --- a/crates/sqlbuild-python-front/src/discovery/main/python_files/discover_materialization_files.rs +++ b/crates/sqlbuild-python-front/src/discovery/main/python_files/discover_materialization_files.rs @@ -8,6 +8,7 @@ use crate::discovery::main::python_files::provider_usages::provider_usages; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; use pyo3::pyfunction; use pyo3::types::PyDict; +use sqlbuild_core::constants::MATERIALIZATIONS_PATH; use sqlbuild_host::entries::models::UserCodeHost; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::RecordId; @@ -22,7 +23,7 @@ pub fn discover_materialization_files<'py>( let py: Python<'py> = project_dir.py(); let project = ProjectDir { path: project_dir }; if !project - .child("materializations")? + .child(MATERIALIZATIONS_PATH)? .call_method0("is_dir")? .is_truthy()? { @@ -33,7 +34,7 @@ pub fn discover_materialization_files<'py>( None => PyDict::new(py), }; let mut files: Vec> = Vec::new(); - for file_path in project.module_files("materializations", false)? { + for file_path in project.module_files(MATERIALIZATIONS_PATH, false)? { let materialize: Bound<'py, PyAny> = project.load(UserCodeHost::LoadMaterializeFunction, &file_path)?; let usages: Bound<'py, PyAny> = if materialize.is_none() { diff --git a/crates/sqlbuild-python-front/src/discovery/main/python_files/mod.rs b/crates/sqlbuild-python-front/src/discovery/main/python_files/mod.rs index 4b4b592968..1ec2738bae 100644 --- a/crates/sqlbuild-python-front/src/discovery/main/python_files/mod.rs +++ b/crates/sqlbuild-python-front/src/discovery/main/python_files/mod.rs @@ -12,4 +12,5 @@ pub mod register_imported_python_nodes; pub mod register_python_function_files; pub mod register_python_hook_files; pub mod register_python_module_files; +pub mod reject_project_layout; pub mod reject_unsupported_python_paths; diff --git a/crates/sqlbuild-python-front/src/discovery/main/python_files/reject_project_layout.rs b/crates/sqlbuild-python-front/src/discovery/main/python_files/reject_project_layout.rs new file mode 100644 index 0000000000..a63bce0b9d --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovery/main/python_files/reject_project_layout.rs @@ -0,0 +1,59 @@ +//! Raise `ProjectLayoutError` (D018) naming every entry outside the project layout. + +use crate::discovery::_helpers::failures::raised::discovery_error; +use crate::discovery::constants::{ + LAYOUT_EXTRA_PATHS_HELP, LAYOUT_HELP_CONTINUATION, LAYOUT_HELP_LINE, +}; +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_discovery::project_layout::main::env_file_entries::env_file_entries; +use sqlbuild_discovery::project_layout::main::layout_problems::layout_problems; +use sqlbuild_discovery::project_layout::main::written_entries::written_entries; +use sqlbuild_discovery::project_layout::models::LayoutProblem; +use std::path::PathBuf; + +/// Raise `ProjectLayoutError` for each entry outside the layout, other than written and env files. +pub fn reject_project_layout( + project_dir: &Bound<'_, PyAny>, + extra_paths: &[String], +) -> PyResult<()> { + let root: PathBuf = project_dir.extract()?; + let mut allowed: Vec = extra_paths.to_vec(); + allowed.extend(written_entries(&root)); + allowed.extend(env_file_entries(&root)); + let problems: Vec = layout_problems(&root, &allowed); + if problems.is_empty() { + return Ok(()); + } + let quoted: Vec = problems + .iter() + .map(|problem| format!("'{}'", problem.path)) + .collect(); + let message: String = match quoted.as_slice() { + [only] => format!("{only} is not part of a SQLBuild project"), + [rest @ .., final_entry] => format!( + "{} and {final_entry} are not part of a SQLBuild project", + rest.join(", ") + ), + [] => String::new(), + }; + let mut folders: Vec> = Vec::new(); + let mut lines: Vec = Vec::new(); + for problem in &problems { + if !folders.contains(&problem.folder) { + folders.push(problem.folder); + lines.push(format!( + "move it under one of: {},", + problem.allowed.join(", ") + )); + } + } + Err(discovery_error( + project_dir.py(), + "project_layout", + message, + Some(format!( + "{}{LAYOUT_HELP_CONTINUATION}{LAYOUT_EXTRA_PATHS_HELP}", + lines.join(LAYOUT_HELP_LINE) + )), + )) +} diff --git a/crates/sqlbuild-python-front/src/discovery/main/records/discover_adapter_file.rs b/crates/sqlbuild-python-front/src/discovery/main/records/discover_adapter_file.rs index 4d5a007a95..26e7f5ddf8 100644 --- a/crates/sqlbuild-python-front/src/discovery/main/records/discover_adapter_file.rs +++ b/crates/sqlbuild-python-front/src/discovery/main/records/discover_adapter_file.rs @@ -1,17 +1,18 @@ -//! Detect a project-level adapter.py without importing it. +//! Detect a project-level python/adapter.py without importing it. use crate::discovery::_helpers::records::declaration_records::path_class; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; use pyo3::pyfunction; +use sqlbuild_core::constants::ADAPTER_FILE_PATH; use sqlbuild_python_base::records::main::construct::new_record_with::new_record_with; use sqlbuild_python_base::records::types::RecordId; -/// Detect a project-level adapter.py without importing it. +/// Detect a project-level python/adapter.py without importing it. #[pyfunction] #[pyo3(signature = (*, project_dir))] pub fn discover_adapter_file<'py>(project_dir: &Bound<'py, PyAny>) -> PyResult> { let py: Python<'py> = project_dir.py(); - let file_path: Bound<'py, PyAny> = project_dir.div("adapter.py")?; + let file_path: Bound<'py, PyAny> = project_dir.div(ADAPTER_FILE_PATH)?; if !file_path.call_method0("is_file")?.is_truthy()? { return Ok(py.None().into_bound(py)); } @@ -20,7 +21,10 @@ pub fn discover_adapter_file<'py>(project_dir: &Bound<'py, PyAny>) -> PyResult = state_table_columns( ( &columns, &types.into_any(), &PyFrozenSet::new(py, &required)?.into_any(), ), render_framework_type, - ) + )?; + Ok(create_table_sql(&table, &definitions)) } diff --git a/crates/sqlbuild-python-front/src/resource_costs/_helpers/resource_costs_state.rs b/crates/sqlbuild-python-front/src/resource_costs/_helpers/resource_costs_state.rs index 50a1ae3831..f1c907eb1a 100644 --- a/crates/sqlbuild-python-front/src/resource_costs/_helpers/resource_costs_state.rs +++ b/crates/sqlbuild-python-front/src/resource_costs/_helpers/resource_costs_state.rs @@ -11,10 +11,13 @@ use sqlbuild_core::cost_command::models::CostCoverage; use sqlbuild_core::cost_report::models::CostSummary; use sqlbuild_state::events::main::resource_cost_observation_id::resource_cost_observation_id; use sqlbuild_state::resource_costs::constants::{ - NULLABLE_RESOURCE_COST_COLUMNS, RESOURCE_COST_COLUMN_TYPES, TOTAL_RESOURCE_TYPE, + ADDED_RESOURCE_COST_COLUMNS, NULLABLE_RESOURCE_COST_COLUMNS, RESOURCE_COST_COLUMN_TYPES, + TOTAL_RESOURCE_TYPE, }; use sqlbuild_state::resource_costs::main::prune_resource_costs_sql::prune_resource_costs_sql; use sqlbuild_state::resource_costs::models::{ResourceCostKey, RunCostAttempt}; +use sqlbuild_state::state_tables::main::add_columns_sql::add_columns_sql; +use sqlbuild_state::state_tables::models::TableColumn; use crate::execution_history::main::parsed_iso::parsed_iso; use crate::execution_history::main::utc::utc; @@ -24,13 +27,25 @@ use crate::native_host::main::literal::literal; use crate::native_host::main::optional_text::optional_text; use crate::native_host::main::state_table_name::state_table_name; use crate::native_host::models::Location; +use crate::state_rows::main::tables::state_table_columns::state_table_columns; +use pyo3::types::{PyDict, PyFrozenSet, PyTuple}; use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::records::main::fields::field::field as native_field; -/// Rate source of a price the project configured, the only one shown as USD. -const CONFIGURED_RATE_SOURCE: &str = "configured"; +/// Each rate source a collection gives, as the table records it; a source not here has no price. +const RECORDED_PRICE_SOURCES: [(&str, &str); 3] = [ + ("configured", "config"), + ("rate_sheet", "rate_sheet"), + ("list_price", "list_price"), +]; /// The adapter method that marks the resource costs table as supported. pub(crate) const CREATE_TABLE_METHOD: &str = "render_create_resource_costs_table_sql"; +/// The adapter method rendering the columns an older table gains. +pub(crate) const ADD_COLUMNS_METHOD: &str = "render_add_resource_costs_columns_sql"; +/// Tables this process already gave their added columns. +pub(crate) static TABLES_WITH_ADDED_COLUMNS: std::sync::LazyLock< + std::sync::Mutex>, +> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::BTreeSet::new())); /// Create-if-missing DDL for the resource costs table, with adapter-rendered column types. #[pyfunction] @@ -52,6 +67,44 @@ pub(crate) fn build_resource_costs_create_table_sql( ) } +/// `ALTER TABLE … ADD COLUMN IF NOT EXISTS` for each column added since the table's first release. +#[pyfunction] +#[pyo3(signature = (*, database, schema, render_qualified_name, render_framework_type))] +pub(crate) fn build_resource_costs_add_columns_sql( + database: &Bound<'_, PyAny>, + schema: &Bound<'_, PyAny>, + render_qualified_name: &Bound<'_, PyAny>, + render_framework_type: &Bound<'_, PyAny>, +) -> PyResult> { + let py: Python<'_> = database.py(); + let Some(table) = state_table_name( + render_qualified_name, + (database, schema), + RESOURCE_COSTS_TABLE_NAME, + )? + else { + return Ok(Vec::new()); + }; + let added: Vec<(&str, &str)> = RESOURCE_COST_COLUMN_TYPES + .iter() + .copied() + .filter(|(column, _)| ADDED_RESOURCE_COST_COLUMNS.contains(column)) + .collect(); + let types: Bound<'_, PyDict> = PyDict::new(py); + for (column, declared) in &added { + types.set_item(column, declared)?; + } + let columns: Vec = state_table_columns( + ( + &PyTuple::new(py, added.iter().map(|(column, _)| *column))?.into_any(), + &types.into_any(), + &PyFrozenSet::empty(py)?.into_any(), + ), + render_framework_type, + )?; + Ok(add_columns_sql(&table, &columns)) +} + /// SQL deleting observations beyond the newest `retain_versions` per run, resource and warehouse. #[pyfunction] #[pyo3(signature = (*, database, schema, render_qualified_name, retain_versions))] @@ -100,8 +153,12 @@ pub(crate) fn observation_cells( summary: &CostSummary, observed_at: &str, ) -> PyResult>> { - let usd = - |value: &str| (summary.rate_source == CONFIGURED_RATE_SOURCE).then(|| value.to_owned()); + let source: Option<&str> = RECORDED_PRICE_SOURCES + .iter() + .find(|(rate_source, _)| *rate_source == summary.rate_source) + .map(|(_, recorded)| *recorded); + let usd = |value: &str| source.map(|_| value.to_owned()); + let price: Option<&str> = source.map(|_| summary.usd_per_credit.as_str()); let limitations: String = serde_json::to_string(&summary.limitations) .map_err(|error| PyValueError::new_err(error.to_string()))?; let run_row = ResourceRow { @@ -160,6 +217,8 @@ pub(crate) fn observation_cells( integer_literal(py, Some(row.bytes_scanned))?, literal(py, Some(row.estimated_credits))?, literal(py, row.estimated_usd.as_deref())?, + literal(py, price)?, + literal(py, source)?, literal(py, Some(&summary.status))?, integer_literal(py, Some(summary.expected_statement_count))?, integer_literal(py, Some(summary.observed_statement_count))?, diff --git a/crates/sqlbuild-python-front/src/resource_costs/main/register_resource_costs_state.rs b/crates/sqlbuild-python-front/src/resource_costs/main/register_resource_costs_state.rs index 502ef0673c..23d2d63455 100644 --- a/crates/sqlbuild-python-front/src/resource_costs/main/register_resource_costs_state.rs +++ b/crates/sqlbuild-python-front/src/resource_costs/main/register_resource_costs_state.rs @@ -1,5 +1,6 @@ //! Register the resource costs state functions and classes. +use crate::resource_costs::_helpers::resource_costs_state::build_resource_costs_add_columns_sql; use crate::resource_costs::_helpers::resource_costs_state::build_resource_costs_create_table_sql; use crate::resource_costs::_helpers::resource_costs_state::build_resource_costs_prune_sql; use pyo3::prelude::{Bound, PyModule, PyModuleMethods, PyResult}; @@ -11,5 +12,9 @@ pub fn register_resource_costs_state(module: &Bound<'_, PyModule>) -> PyResult<( build_resource_costs_create_table_sql, module )?)?; + module.add_function(wrap_pyfunction!( + build_resource_costs_add_columns_sql, + module + )?)?; module.add_function(wrap_pyfunction!(build_resource_costs_prune_sql, module)?) } diff --git a/crates/sqlbuild-python-front/src/resource_costs/models.rs b/crates/sqlbuild-python-front/src/resource_costs/models.rs index 5bed834d05..3f5c7aeb88 100644 --- a/crates/sqlbuild-python-front/src/resource_costs/models.rs +++ b/crates/sqlbuild-python-front/src/resource_costs/models.rs @@ -3,10 +3,12 @@ use crate::native_host::constants::ROWS_PER_STATEMENT; use crate::native_host::main::execute::execute; use crate::native_host::models::Location; -use crate::resource_costs::_helpers::resource_costs_state::CREATE_TABLE_METHOD; use crate::resource_costs::_helpers::resource_costs_state::observation_cells; use crate::resource_costs::_helpers::resource_costs_state::run_attempt; use crate::resource_costs::_helpers::resource_costs_state::table; +use crate::resource_costs::_helpers::resource_costs_state::{ + ADD_COLUMNS_METHOD, CREATE_TABLE_METHOD, TABLES_WITH_ADDED_COLUMNS, +}; use pyo3::prelude::Bound; use pyo3::prelude::PyAny; use pyo3::prelude::PyAnyMethods; @@ -94,6 +96,7 @@ impl<'py> ResourceCostStore<'py> { if !create.is_empty() { self.execute(&create)?; } + self.add_columns(&keywords)?; let observed_at: String = call_with( &native_field(&self.adapter, "render_current_utc_timestamp")?, &[], @@ -171,6 +174,26 @@ impl<'py> ResourceCostStore<'py> { ) } + /// Add the columns an older table lacks, once per table and process. + fn add_columns(&self, keywords: &[(&str, Bound<'py, PyAny>)]) -> PyResult<()> { + if !self.adapter.hasattr(ADD_COLUMNS_METHOD)? + || TABLES_WITH_ADDED_COLUMNS + .lock() + .is_ok_and(|done| done.contains(&self.table)) + { + return Ok(()); + } + for statement in + call_with(&native_field(&self.adapter, ADD_COLUMNS_METHOD)?, keywords)?.try_iter()? + { + self.execute(&statement?.extract::()?)?; + } + if let Ok(mut done) = TABLES_WITH_ADDED_COLUMNS.lock() { + done.insert(self.table.clone()); + } + Ok(()) + } + pub fn close(self) -> PyResult<()> { native_field(&self.adapter, "close")? .call1((&self.connection,)) diff --git a/crates/sqlbuild-python-front/src/scopes/_helpers/checks/scope_tolerant.rs b/crates/sqlbuild-python-front/src/scopes/_helpers/checks/scope_tolerant.rs index b6dc17d6cd..dd6d2580d7 100644 --- a/crates/sqlbuild-python-front/src/scopes/_helpers/checks/scope_tolerant.rs +++ b/crates/sqlbuild-python-front/src/scopes/_helpers/checks/scope_tolerant.rs @@ -18,11 +18,11 @@ use sqlbuild_python_base::records::types::RecordId; /// Each authored resource root, in the order a prospective path is matched against them. const PROSPECTIVE_ROOTS: [(ResourceKind, &str); 5] = [ - (ResourceKind::Model, "models"), + (ResourceKind::Model, "sql/models"), (ResourceKind::Test, "tests/unit"), (ResourceKind::Scenario, "tests/scenarios"), - (ResourceKind::Function, "functions/sql"), - (ResourceKind::Source, "sources"), + (ResourceKind::Function, "sql/functions/sql"), + (ResourceKind::Source, "sql/sources"), ]; const RESOURCE_PARSE_ERROR: &str = "S019"; const DECLARATION_PARSE_ERROR: &str = "S020"; diff --git a/crates/sqlbuild-python-front/src/scopes/_helpers/index/scope_index.rs b/crates/sqlbuild-python-front/src/scopes/_helpers/index/scope_index.rs index c771639a5b..a464c437e3 100644 --- a/crates/sqlbuild-python-front/src/scopes/_helpers/index/scope_index.rs +++ b/crates/sqlbuild-python-front/src/scopes/_helpers/index/scope_index.rs @@ -33,17 +33,17 @@ const UNINDEXABLE_SCOPE_MESSAGE: &str = "Native scope indexing could not place a const INSPECT_MODULE: &str = "inspect"; const CODE_TYPE_MODULE: &str = "types"; pub(crate) const PATHLIB_MODULE: &str = "pathlib"; -const PRIVATE_ROOT: &str = "models"; -const MACRO_FALLBACK: &str = "macros"; -const ENUM_FALLBACK: &str = "enums"; -const CONSTANT_FALLBACK: &str = "constants"; +const PRIVATE_ROOT: &str = "sql/models"; +const MACRO_FALLBACK: &str = "sql/macros"; +const ENUM_FALLBACK: &str = "sql/enums"; +const CONSTANT_FALLBACK: &str = "sql/constants"; const COLLECTION_KINDS: [&str; 3] = ["list", "set", "object"]; const NULL_KIND: &str = "null"; /// Each resource kind's own ownership root, in the order Python sorts them by path. const KIND_ROOTS: [(ResourceKind, &str); 5] = [ - (ResourceKind::Function, "functions/sql"), - (ResourceKind::Model, "models"), - (ResourceKind::Source, "sources"), + (ResourceKind::Function, "sql/functions/sql"), + (ResourceKind::Model, "sql/models"), + (ResourceKind::Source, "sql/sources"), (ResourceKind::Scenario, "tests/scenarios"), (ResourceKind::Test, "tests/unit"), ]; @@ -672,8 +672,8 @@ fn resource_root<'py>( root: ResourceRoot, ) -> PyResult> { let (path, root_kind, resource_kind): (&str, &str, ResourceKind) = match root { - ResourceRoot::Seed => ("seeds", "global", ResourceKind::Seed), - ResourceRoot::PythonFunction => ("functions/python", "global", ResourceKind::Function), + ResourceRoot::Seed => ("sql/seeds", "global", ResourceKind::Seed), + ResourceRoot::PythonFunction => ("sql/functions/python", "global", ResourceKind::Function), ResourceRoot::Kind => match KIND_ROOTS.iter().find(|(candidate, _)| *candidate == kind) { Some((_, path)) => (path, "resource", kind), None => { diff --git a/crates/sqlbuild-python-front/src/state_rows/_helpers/migrations/migration_rows.rs b/crates/sqlbuild-python-front/src/state_rows/_helpers/migrations/migration_rows.rs index 76132113ad..a8b3bae49b 100644 --- a/crates/sqlbuild-python-front/src/state_rows/_helpers/migrations/migration_rows.rs +++ b/crates/sqlbuild-python-front/src/state_rows/_helpers/migrations/migration_rows.rs @@ -18,7 +18,7 @@ use sqlbuild_state::events::main::readable_columns::readable_columns; use crate::cursor::constants::DATETIME_MODULE; use crate::state_rows::_helpers::event_rows::events::typed_insert_sql; use crate::state_rows::_helpers::migrations::migration_objects::{qualified_table, state_error}; -use crate::state_rows::_helpers::tables::state_tables::state_table_create_sql; +use crate::state_rows::_helpers::tables::state_tables::state_table_columns; use crate::state_rows::models::{EventTable, EventTableLayout}; use sqlbuild_python_base::boundary::main::imported::imported; use sqlbuild_python_base::boundary::models::Request; @@ -27,6 +27,8 @@ use sqlbuild_python_base::records::main::construct::new_record::new_record; use sqlbuild_python_base::records::main::construct::new_record_with::new_record_with; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::RecordId; +use sqlbuild_state::state_tables::main::create_table_sql::create_table_sql; +use sqlbuild_state::state_tables::models::TableColumn; /// DDL that creates one migration state table when it is missing. #[pyfunction(name = "render_migration_state_create_sql")] @@ -53,8 +55,7 @@ pub(crate) fn create_sql<'py>(request: Option<&Bound<'py, PyDict>>) -> PyResult< )?; } let columns: Bound<'py, PyAny> = PyTuple::new(py, layout.columns)?.into_any(); - let sql: String = state_table_create_sql( - &table, + let definitions: Vec = state_table_columns( ( &columns, column_types.as_any(), @@ -62,6 +63,7 @@ pub(crate) fn create_sql<'py>(request: Option<&Bound<'py, PyDict>>) -> PyResult< ), &request.get("render_framework_type")?, )?; + let sql: String = create_table_sql(&table, &definitions); Ok(PyString::new(py, &sql).into_any()) } diff --git a/crates/sqlbuild-python-front/src/state_rows/_helpers/tables/state_tables.rs b/crates/sqlbuild-python-front/src/state_rows/_helpers/tables/state_tables.rs index 933e2e3b3d..deeff2fd56 100644 --- a/crates/sqlbuild-python-front/src/state_rows/_helpers/tables/state_tables.rs +++ b/crates/sqlbuild-python-front/src/state_rows/_helpers/tables/state_tables.rs @@ -30,16 +30,15 @@ const DECLARED_TYPES: [(&str, &str); 3] = [ (TEXT_TIMESTAMP_STATE_VALUE_TYPE, "TIMESTAMP"), ]; -/// Create-if-missing DDL whose column types the adapter renders. -pub(crate) fn state_table_create_sql<'py>( - qualified_name: &str, +/// Each column with the type the adapter renders for it, and whether it is required. +pub(crate) fn state_table_columns<'py>( (columns, column_types, required_columns): ( &Bound<'py, PyAny>, &Bound<'py, PyAny>, &Bound<'py, PyAny>, ), render_framework_type: &Bound<'py, PyAny>, -) -> PyResult { +) -> PyResult> { let py: Python<'py> = render_framework_type.py(); let framework_types: Bound<'py, PyAny> = host_entry(py, AdapterHost::FrameworkType)?; let mut rendered: Vec<(&str, String)> = Vec::with_capacity(DECLARED_TYPES.len()); @@ -64,7 +63,7 @@ pub(crate) fn state_table_create_sql<'py>( required: required_columns.contains(&column)?, }); } - Ok(create_table_sql(qualified_name, &definitions)) + Ok(definitions) } /// Render create-if-missing DDL for string, integer, and text-timestamp state columns. @@ -72,15 +71,18 @@ pub(crate) fn state_table_create_sql<'py>( #[pyo3(signature = (**request))] pub(crate) fn render_create_sql(request: Option<&Bound<'_, PyDict>>) -> PyResult { let request = Request::new("render_state_table_create_sql", request)?; - state_table_create_sql( - &request.get("qualified_name")?.extract::()?, + let definitions: Vec = state_table_columns( ( &request.get("columns")?, &request.get("column_types")?, &request.get("required_columns")?, ), &request.get("render_framework_type")?, - ) + )?; + Ok(create_table_sql( + &request.get("qualified_name")?.extract::()?, + &definitions, + )) } fn adapter_user_error(py: Python<'_>, message: &str) -> PyErr { diff --git a/crates/sqlbuild-python-front/src/state_rows/main/tables/mod.rs b/crates/sqlbuild-python-front/src/state_rows/main/tables/mod.rs index cfe5add1dc..d7660e5317 100644 --- a/crates/sqlbuild-python-front/src/state_rows/main/tables/mod.rs +++ b/crates/sqlbuild-python-front/src/state_rows/main/tables/mod.rs @@ -1,2 +1,2 @@ pub mod register_state_tables; -pub mod state_table_create_sql; +pub mod state_table_columns; diff --git a/crates/sqlbuild-python-front/src/state_rows/main/tables/state_table_create_sql.rs b/crates/sqlbuild-python-front/src/state_rows/main/tables/state_table_columns.rs similarity index 55% rename from crates/sqlbuild-python-front/src/state_rows/main/tables/state_table_create_sql.rs rename to crates/sqlbuild-python-front/src/state_rows/main/tables/state_table_columns.rs index 3657bb3367..70d766bb79 100644 --- a/crates/sqlbuild-python-front/src/state_rows/main/tables/state_table_create_sql.rs +++ b/crates/sqlbuild-python-front/src/state_rows/main/tables/state_table_columns.rs @@ -1,21 +1,20 @@ -//! Create-if-missing DDL whose column types the adapter renders. +//! A state table's columns with the types the adapter renders. use crate::state_rows::_helpers::tables::state_tables; use pyo3::prelude::{Bound, PyAny, PyResult}; +use sqlbuild_state::state_tables::models::TableColumn; -/// Create-if-missing DDL whose column types the adapter renders. +/// Each column with the type the adapter renders for it, and whether it is required. #[inline] -pub fn state_table_create_sql<'py>( - qualified_name: &str, +pub fn state_table_columns<'py>( (columns, column_types, required_columns): ( &Bound<'py, PyAny>, &Bound<'py, PyAny>, &Bound<'py, PyAny>, ), render_framework_type: &Bound<'py, PyAny>, -) -> PyResult { - state_tables::state_table_create_sql( - qualified_name, +) -> PyResult> { + state_tables::state_table_columns( (columns, column_types, required_columns), render_framework_type, ) diff --git a/crates/sqlbuild-python-output/src/build_progress/models.rs b/crates/sqlbuild-python-output/src/build_progress/models.rs index 321def81b7..e8739769d3 100644 --- a/crates/sqlbuild-python-output/src/build_progress/models.rs +++ b/crates/sqlbuild-python-output/src/build_progress/models.rs @@ -95,6 +95,9 @@ use sqlbuild_python_base::build_progress::main::terminal::tty_flag::tty_flag; use sqlbuild_python_base::build_progress::main::terminal::write::write; use sqlbuild_python_base::build_progress::main::transient_status::status_reporter::status_reporter; use sqlbuild_python_base::build_progress::models::NativeProgressProjector; +use sqlbuild_python_base::invocation_phases::constants::CONNECTED_PHASE; +use sqlbuild_python_base::invocation_phases::models::InvocationPhase; +use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::main::fields::replaced_keywords::replaced_keywords; use sqlbuild_python_project::project_snapshot::models::WorkerBuild; @@ -1335,7 +1338,16 @@ impl ConnectionProgressReporter { connection_count: i64, elapsed_seconds: f64, ) -> PyResult<()> { - let _ = connection_count; + publish_invocation_phase( + py, + &InvocationPhase { + phase: CONNECTED_PHASE, + duration_ms: Some(elapsed_seconds * 1000.0), + count: Some(connection_count), + name: Some(self.adapter_name.clone()), + detail: None, + }, + )?; let line: String = connection_phase_line(self.style, true, (&self.adapter_name, elapsed_seconds)); self.write(py, &line)?; diff --git a/crates/sqlbuild-python-output/src/event_exporting/models.rs b/crates/sqlbuild-python-output/src/event_exporting/models.rs index a7de6b396a..79de178cd7 100644 --- a/crates/sqlbuild-python-output/src/event_exporting/models.rs +++ b/crates/sqlbuild-python-output/src/event_exporting/models.rs @@ -217,7 +217,7 @@ impl EventExporterDispatcher { pub(crate) fn enqueue(&self, py: Python<'_>, event: &Bound<'_, PyAny>) -> PyResult<()> { let event_type: String = native_field(event, "event_type")?.extract()?; let policy: ExportPolicy = export_policy(py, &event_type)?; - if self.withheld_kinds.contains(&policy.kind) { + if self.withheld_kinds.contains(&policy.kind) || self.withheld_kinds.contains(&event_type) { return Ok(()); } let invocation_id: Option = match native_field(event, "invocation_id") { @@ -435,10 +435,10 @@ impl EventExporterDispatcher { Ok(summary) } - /// Run `finalizer` on the calling thread, never a daemon delivery thread, once delivery is idle or the idle wait ends. + /// Run `finalizer` on the calling thread, never a daemon delivery thread, once delivery is idle or the idle wait ends; its error is raised. pub(crate) fn finalize_when_idle(&self, py: Python<'_>, finalizer: Py) -> PyResult<()> { self.shared.await_idle(py)?; - drop(finalizer.bind(py).call0()); + finalizer.bind(py).call0()?; Ok(()) } diff --git a/crates/sqlbuild-python-planner/src/freshness/_helpers/state_io.rs b/crates/sqlbuild-python-planner/src/freshness/_helpers/state_io.rs index 2fa1d3789e..06b7d05381 100644 --- a/crates/sqlbuild-python-planner/src/freshness/_helpers/state_io.rs +++ b/crates/sqlbuild-python-planner/src/freshness/_helpers/state_io.rs @@ -24,7 +24,9 @@ use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_base::warehouse_access::main::ensure_event_id_column::ensure_event_id_column; use sqlbuild_python_front::native_host::main::state_table_name::state_table_name; -use sqlbuild_python_front::state_rows::main::tables::state_table_create_sql::state_table_create_sql; +use sqlbuild_python_front::state_rows::main::tables::state_table_columns::state_table_columns; +use sqlbuild_state::state_tables::main::create_table_sql::create_table_sql as table_ddl; +use sqlbuild_state::state_tables::models::TableColumn; const MISSING_SCHEMA_MESSAGE: &str = "source freshness table requires a target schema"; @@ -97,12 +99,9 @@ fn create_table_sql<'py>( column_types.set_item(SOURCE_FRESHNESS_EVENT_ID, STRING_STATE_VALUE_TYPE)?; let column_types: Bound<'py, PyAny> = column_types.into_any(); let required: Bound<'py, PyAny> = PyFrozenSet::new(py, REQUIRED_STATE_COLUMNS)?.into_any(); - let sql: String = state_table_create_sql( - &qualified_name, - (&columns, &column_types, &required), - render_framework_type, - )?; - Ok(text(py, &sql)) + let definitions: Vec = + state_table_columns((&columns, &column_types, &required), render_framework_type)?; + Ok(text(py, &table_ddl(&qualified_name, &definitions))) } fn empty_set<'py>(schema: &Bound<'py, PyAny>) -> PyResult> { diff --git a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/execution_plan.rs b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/execution_plan.rs index 8e86841d98..fb7e182690 100644 --- a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/execution_plan.rs +++ b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/execution_plan.rs @@ -10,7 +10,12 @@ use crate::planner_phases::main::timing::record_step::record_step; use crate::planner_phases::main::timing::timed::timed; use crate::planner_warehouse::models::PlannerReads; use sqlbuild_analysis::planner_scope::constants::MODEL; +use sqlbuild_python_base::invocation_phases::constants::PLANNED_PHASE; +use sqlbuild_python_base::invocation_phases::main::phase_since::phase_since; +use sqlbuild_python_base::invocation_phases::models::InvocationPhase; +use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; use sqlbuild_python_base::native_host::models::Dialect; +use sqlbuild_python_project::planner_scope::models::RetainedScope; use crate::planner_changes::main::detect_changes::detect_changes; use crate::planner_changes::main::resolve_model_actions::resolve_model_actions; @@ -175,6 +180,7 @@ pub(crate) fn planned_output<'py>( let inspection_scope = class_field(scopes, |s: &PlannerScopeResolution| &s.inspection_scope)?; let resolved_actions = resolve_model_actions(&inspection_scope, &changes)?; record_step(DETECTING_CHANGES, changes_started.elapsed().as_secs_f64()); + let freshness_started = Instant::now(); let source_freshness = timed(SOURCE_FRESHNESS, || { build_planner_source_freshness_result( (&project, &inspection_scope), @@ -186,6 +192,7 @@ pub(crate) fn planned_output<'py>( &native_field(&snapshot, "source_freshness_state_schemas")?, ) })?; + let freshness_seconds: f64 = freshness_started.elapsed().as_secs_f64(); let entries_started = Instant::now(); let reconciliation = reconcile_execution_changes( (&inspection_scope, &snapshot), @@ -241,6 +248,24 @@ pub(crate) fn planned_output<'py>( add_deferred_origin_notes(output, (&project, scopes), (&deferral, &origin_failures))?; let plan_output = add_plan_metadata(output, &source_freshness, &policies)?.build(py)?; record_step(ASSEMBLING, assembling_started.elapsed().as_secs_f64()); + publish_invocation_phase( + py, + &InvocationPhase { + count: Some( + i64::try_from( + class_field(scopes, |s: &PlannerScopeResolution| &s.selected_scope)? + .cast::()? + .get() + .data + .selected + .len(), + ) + .unwrap_or(i64::MAX), + ), + detail: Some(format!("source freshness {freshness_seconds:.2} s")), + ..phase_since(PLANNED_PHASE, started) + }, + )?; let on_progress = args.value("on_progress")?; if !on_progress.is_none() { on_progress.call1((format!( diff --git a/crates/sqlbuild-python-planner/src/planner_phases/_helpers/inputs/warehouse_state.rs b/crates/sqlbuild-python-planner/src/planner_phases/_helpers/inputs/warehouse_state.rs index dbc53ca41c..c6c9837b8f 100644 --- a/crates/sqlbuild-python-planner/src/planner_phases/_helpers/inputs/warehouse_state.rs +++ b/crates/sqlbuild-python-planner/src/planner_phases/_helpers/inputs/warehouse_state.rs @@ -19,6 +19,9 @@ use crate::planner_warehouse::models::MigrationFingerprintCache; use crate::planner_warehouse::models::SnapshotRequest; use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyResult}; use pyo3::types::{PyDict, PyDictMethods, PyTuple}; +use sqlbuild_python_base::invocation_phases::constants::INSPECTED_PHASE; +use sqlbuild_python_base::invocation_phases::main::phase_since::phase_since; +use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_project::graph::main::project::compiled_graph_keys::compiled_graph_keys; @@ -174,6 +177,7 @@ pub(crate) fn gather_planner_warehouse_state<'py>( }, (&migration_entries, &column_entries), )?; + publish_invocation_phase(py, &phase_since(INSPECTED_PHASE, started))?; if !runtime_field(runtime, |runtime| &runtime.on_progress)?.is_none() { progress( runtime, diff --git a/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/set_dependencies.rs b/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/set_dependencies.rs index 95687625d2..75a46622b9 100644 --- a/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/set_dependencies.rs +++ b/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/set_dependencies.rs @@ -1,10 +1,15 @@ //! The discovered Python nodes declaring `job(...)` or `tag(...)` dependencies. use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_analysis::graph::models::ProjectGraph; +use sqlbuild_analysis::node_set_dependencies::main::unknown_tags::unknown_tags; use sqlbuild_analysis::node_set_dependencies::models::{DependantNode, NodeSetDependency}; +use sqlbuild_analysis::python_selection::models::PythonSelectionGraph; use sqlbuild_host::entries::models::UserCodeHost; use sqlbuild_python_base::native_host::main::host_entry::host_entry; use sqlbuild_python_base::records::main::fields::field::field as native_field; +use sqlbuild_python_base::records::main::fields::mapping_get::mapping_get; +use sqlbuild_python_front::discovered_sets::main::record_tag_failures::record_tag_failures; /// Discovered function collections and the node kind each holds. const COLLECTIONS: [(&str, &str); 3] = [ @@ -43,3 +48,46 @@ pub(crate) fn dependants(discovered: &Bound<'_, PyAny>) -> PyResult, + (graph, python): (&ProjectGraph, &PythonSelectionGraph), + found: &[DependantNode], +) -> PyResult<()> { + record_tag_failures(set_tag_failures( + discovered, + &unknown_tags(graph, python, found), + )?); + Ok(()) +} + +/// Each discovered set with an item among `unknown`, and the error naming the item and its tag. +fn set_tag_failures( + discovered: &Bound<'_, PyAny>, + unknown: &[(String, String)], +) -> PyResult> { + let mut failures: Vec<(String, String)> = Vec::new(); + if unknown.is_empty() { + return Ok(failures); + } + for function in native_field(discovered, "asset_functions")?.try_iter()? { + let function: Bound<'_, PyAny> = function?; + let item: Bound<'_, PyAny> = native_field(&function, "discovered")?; + if item.is_none() { + continue; + } + let name: String = native_field(&function, "name")?.extract()?; + for (dependant, tag) in unknown { + if *dependant == name { + let set: String = mapping_get(&item, "set")?.extract()?; + let id: String = mapping_get(&item, "item")?.extract()?; + failures.push(( + set, + format!("item '{id}' depends on tag '{tag}', which no node carries"), + )); + } + } + } + Ok(failures) +} diff --git a/crates/sqlbuild-python-project/src/graph/main/python_nodes/resolve_node_sets.rs b/crates/sqlbuild-python-project/src/graph/main/python_nodes/resolve_node_sets.rs index 9f037cc092..fa0bb1f61f 100644 --- a/crates/sqlbuild-python-project/src/graph/main/python_nodes/resolve_node_sets.rs +++ b/crates/sqlbuild-python-project/src/graph/main/python_nodes/resolve_node_sets.rs @@ -6,7 +6,7 @@ use crate::graph::_helpers::python_nodes::python_node_graph::explicit_python_nod use crate::graph::_helpers::python_nodes::python_selection::{ allows_round_trips, project_sources, selection_graph, }; -use crate::graph::_helpers::python_nodes::set_dependencies::dependants; +use crate::graph::_helpers::python_nodes::set_dependencies::{dependants, record_set_tag_failures}; use crate::graph::models::NativeProjectGraph; use crate::job_settings::main::declared_jobs::declared_jobs; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; @@ -39,6 +39,7 @@ pub fn resolve_node_sets( } else { declared_jobs(&project_dir)? }; + record_set_tag_failures(discovered, (native.get().graph(), &python), &found)?; let allow_warehouse_round_trips: bool = allows_round_trips(project)?; Some(compiler_guard(|| { Ok(resolve_node_set_dependencies( diff --git a/crates/sqlbuild-python-project/src/project_snapshot/main/saved_discovered_sets.rs b/crates/sqlbuild-python-project/src/project_snapshot/main/saved_discovered_sets.rs index 2bf9948f24..cfac95b842 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/main/saved_discovered_sets.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/main/saved_discovered_sets.rs @@ -2,12 +2,17 @@ use pyo3::exceptions::PyRuntimeError; use pyo3::prelude::{PyResult, Python}; +use serde_json::Value; +use sqlbuild_orchestration::discovered_sets::models::DiscoveredSet; use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; use sqlbuild_orchestration::worker::main::connect_worker::connect_worker; use sqlbuild_orchestration::worker::main::fetch_execution::fetch_execution; +use sqlbuild_python_base::invocation_phases::constants::DISCOVERED_SET_PHASE; +use sqlbuild_python_base::invocation_phases::models::InvocationPhase; +use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; use uuid::Uuid; -/// The sets the server saved for a claimed run, so the worker compiles the published nodes. +/// The sets the server saved for a claimed run, each published as a phase, so the worker compiles the published nodes. pub fn saved_discovered_sets( py: Python<'_>, (server_url, bearer): (&str, &str), @@ -17,7 +22,7 @@ pub fn saved_discovered_sets( Uuid::parse_str(run_id).map_err(|error| PyRuntimeError::new_err(error.to_string()))?, Uuid::parse_str(claim_id).map_err(|error| PyRuntimeError::new_err(error.to_string()))?, ); - py.detach(|| { + let sets: DiscoveredSets = py.detach(|| { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -29,5 +34,38 @@ pub fn saved_discovered_sets( }) .map(|execution| execution.discovered) .map_err(|error| PyRuntimeError::new_err(error.to_string())) - }) + })?; + for (name, set) in &sets { + publish_invocation_phase(py, &set_phase(name, set))?; + } + Ok(sets) +} + +/// One saved set as the run used it: its items, tags and when it was discovered; the worker never discovers. +fn set_phase<'a>(name: &str, set: &'a DiscoveredSet) -> InvocationPhase<'a> { + let tags: Vec = set.result.as_ref().map_or_else(Vec::new, |result| { + result + .tags + .iter() + .map(|(key, value)| match value { + Value::String(text) => format!("{key} {text}"), + other => format!("{key} {other}"), + }) + .collect() + }); + let when: Option = set + .last_good_at + .or(set.fetched_at) + .map(|at| format!("discovered {}", at.format("%Y-%m-%d %H:%M UTC"))); + let detail: Vec = tags.into_iter().chain(when).collect(); + InvocationPhase { + phase: DISCOVERED_SET_PHASE, + count: set + .result + .as_ref() + .map(|result| i64::try_from(result.items.len()).unwrap_or(i64::MAX)), + name: Some(name.to_owned()), + detail: (!detail.is_empty()).then(|| detail.join(" · ")), + ..InvocationPhase::default() + } } diff --git a/crates/sqlbuild-python-project/src/project_snapshot/models.rs b/crates/sqlbuild-python-project/src/project_snapshot/models.rs index 25bf7aab65..6acd3adda3 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/models.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/models.rs @@ -54,6 +54,9 @@ use sqlbuild_orchestration::snapshots::models::SnapshotRecord; use sqlbuild_orchestration::worker::errors::WorkerError; use sqlbuild_orchestration::worker::main::connect_worker::connect_worker; use sqlbuild_orchestration::worker::main::start_worker::start_worker; +use sqlbuild_python_base::invocation_phases::constants::MATCHED_PHASE; +use sqlbuild_python_base::invocation_phases::main::phase_since::phase_since; +use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; use sqlbuild_python_base::native_host::types::ReadResult; use sqlbuild_python_base::records::main::fields::field::field; use sqlbuild_state::runs::constants::FIRST_ATTEMPT; @@ -1181,7 +1184,8 @@ impl NativeOrchestrationWorker { Uuid::parse_str(&run_id).map_err(|error| PyValueError::new_err(error.to_string()))?, Uuid::parse_str(&claim_id).map_err(|error| PyValueError::new_err(error.to_string()))?, ); - py.detach(|| { + let started: Instant = Instant::now(); + let worker: NativeOrchestrationWorker = py.detach(|| { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -1204,7 +1208,9 @@ impl NativeOrchestrationWorker { Err(PyRuntimeError::new_err(error.to_string())) } } - }) + })?; + publish_invocation_phase(py, &phase_since(MATCHED_PHASE, started))?; + Ok(worker) } } diff --git a/crates/sqlbuild-python-project/src/resource_views/main/seed_views/paired_seeds.rs b/crates/sqlbuild-python-project/src/resource_views/main/seed_views/paired_seeds.rs index 18e88f7247..271089cd2a 100644 --- a/crates/sqlbuild-python-project/src/resource_views/main/seed_views/paired_seeds.rs +++ b/crates/sqlbuild-python-project/src/resource_views/main/seed_views/paired_seeds.rs @@ -41,7 +41,7 @@ pub fn paired_seeds( .str()? .extract()?; let message: String = format!( - "Seed declaration '{}' in {relative_path} has no matching CSV file under seeds/", + "Seed declaration '{}' in {relative_path} has no matching CSV file under sql/seeds/", names[missing] ); return Err(PyErr::from_value(compile_error.call1((message,))?)); diff --git a/crates/sqlbuild-python/src/bindings/_helpers/change_selection/definition_snapshot.rs b/crates/sqlbuild-python/src/bindings/_helpers/change_selection/definition_snapshot.rs index 476f060160..d636f24a33 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/change_selection/definition_snapshot.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/change_selection/definition_snapshot.rs @@ -46,9 +46,9 @@ const CONTRACT_KEY: &str = "contract"; /// Source declaration fields that shape a source mock's columns. const SOURCE_SHAPE_FIELDS: [&str; 3] = ["columns", "contract", "type_enforcement"]; /// Project-local adapter modules. -const ADAPTERS_DIRECTORY: &str = "adapters"; +const ADAPTERS_DIRECTORY: &str = sqlbuild_core::constants::ADAPTERS_PATH; /// Project configuration fields that other nodes fingerprint, or that do not shape compiled SQL. -const PROJECT_CONFIG_ELSEWHERE: [&str; 11] = [ +const PROJECT_CONFIG_ELSEWHERE: [&str; 12] = [ "name", "settings", "vars", @@ -58,8 +58,9 @@ const PROJECT_CONFIG_ELSEWHERE: [&str; 11] = [ "diff", "janitor", "migrations", - "sinks", + "event_sinks", "scenario", + "extra_paths", ]; const LOCAL_CONFIG_ELSEWHERE: [&str; 4] = ["settings", "setting_overrides", "vars", "scenario"]; /// Settings that tune how a run executes or validates, not what a node computes. diff --git a/crates/sqlbuild-python/src/bindings/_helpers/cli/observability.rs b/crates/sqlbuild-python/src/bindings/_helpers/cli/observability.rs index be8bef7517..dbe040187a 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/cli/observability.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/cli/observability.rs @@ -11,7 +11,8 @@ use pyo3::types::{PyBool, PyList, PyString, PyTuple, PyTupleMethods}; use pyo3::{IntoPyObjectExt, pyclass, pyfunction, pymethods, wrap_pyfunction}; use sqlbuild_cli::dispatch::main::closing_status::closing_status; use sqlbuild_cli::dispatch::main::event_export_warning::event_export_warning; -use sqlbuild_cli::dispatch::models::{ExportSummary, ExporterLoss}; +use sqlbuild_cli::dispatch::main::export_summary::export_summary; +use sqlbuild_cli::dispatch::models::ExportSummary; use sqlbuild_core::event_export::constants::DEFAULT_EVENT_EXPORT_SHUTDOWN_TIMEOUT_SECONDS; use sqlbuild_host::entries::models::{ExecutorHost, UserCodeHost}; @@ -24,7 +25,9 @@ use sqlbuild_python_base::build_progress::main::progress::machine_output_mode::m use sqlbuild_python_base::build_progress::models::NativeProgressProjector; use sqlbuild_python_base::cli::main::withhold_launch_record::withhold_launch_record; use sqlbuild_python_base::event_exporting::main::event_exporter_command_scope::event_exporter_command_scope; -use sqlbuild_python_base::event_exporting::models::EventExporterCommandScope; +use sqlbuild_python_base::event_exporting::models::{ + EventExportSummary, EventExporterCommandScope, +}; use sqlbuild_python_base::native_host::main::host_entry::host_entry; use sqlbuild_python_base::native_host::main::redirect_stdout_to_stderr::redirect_stdout_to_stderr; use sqlbuild_python_base::presentation_text::main::stdout_supports_color::stdout_supports_color; @@ -37,9 +40,9 @@ use sqlbuild_python_output::result_output::models::TerminalEventIndex; const OBSERVABILITY_LOGGER: &str = "sqlbuild.cli.observability"; const DEBUG_COMMAND: &str = "debug"; const LINEAGE_COMMAND: &str = "lineage"; -/// Compile's phase operations stay out of project lifecycle sinks; its invocation events do not. +/// Compile's phase operations and steps stay out of project lifecycle sinks; its start and outcome do not. const COMPILE_COMMAND: &str = "compile"; -const COMPILE_WITHHELD_KINDS: &[&str] = &["operation"]; +const COMPILE_WITHHELD_KINDS: &[&str] = &["operation", "invocation_phase"]; const INVOCATION_COMPLETED: &str = "invocation_completed"; const INVOCATION_FAILED: &str = "invocation_failed"; /// What an incomplete-export notice says is the only thing affected. @@ -190,32 +193,19 @@ fn run_cleanup(py: Python<'_>, result: PyResult, phase: &str) { } } -/// Native export accounting of a Python `EventExportSummary`. -fn export_summary(summary: &Bound<'_, PyAny>) -> PyResult { - let mut per_exporter: Vec = Vec::new(); - for exporter in native_field(summary, "per_exporter")?.try_iter()? { - let exporter: Bound<'_, PyAny> = exporter?; - let counts: Bound<'_, PyAny> = native_field(&exporter, "counts")?; - per_exporter.push(ExporterLoss { - exporter_name: native_field(&exporter, "exporter_name")?.extract()?, - dropped: native_field(&counts, "dropped")?.extract()?, - failed: native_field(&counts, "failed")?.extract()?, - }); - } - Ok(ExportSummary { - accepted: native_field(summary, "accepted")?.extract()?, - dropped: native_field(summary, "dropped")?.extract()?, - failed: native_field(summary, "failed")?.extract()?, - per_exporter, - }) -} - /// Print the incomplete-export warning to stderr, closed by the command's success, ignoring write failures. fn warn_incomplete_export( - summary: &Bound<'_, PyAny>, + (summary, scope): (&Bound<'_, PyAny>, &Bound<'_, PyAny>), (command, command_succeeded): (&str, bool), ) -> PyResult<()> { - let Some(message) = event_export_warning(&export_summary(summary)?, command_succeeded) else { + let accounting: ExportSummary = export_summary( + &summary.cast::()?.get().snapshot, + scope + .cast::()? + .get() + .teardown_failures()?, + ); + let Some(message) = event_export_warning(&accounting, command_succeeded) else { return Ok(()); }; let closing: String = if command_succeeded { @@ -306,11 +296,14 @@ impl Observed { projector.call_method1("restore", (&self.projector_token,)), "progress_context_restore", ); - if let Some(summary) = summary.filter(|summary| !summary.is_none()) { + if let (Some(summary), Some(scope)) = ( + summary.filter(|summary| !summary.is_none()), + self.exporter_scope.as_ref(), + ) { let succeeded: bool = self.outcome.get().succeeded.load(Ordering::SeqCst); run_cleanup( py, - warn_incomplete_export(&summary, (&self.command, succeeded)), + warn_incomplete_export((&summary, scope.bind(py)), (&self.command, succeeded)), "event_exporter_warning", ); } diff --git a/crates/sqlbuild-python/src/bindings/_helpers/exported_constants/constants.rs b/crates/sqlbuild-python/src/bindings/_helpers/exported_constants/constants.rs index 25989526f3..b4a9ea91d2 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/exported_constants/constants.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/exported_constants/constants.rs @@ -18,12 +18,12 @@ use sqlbuild_core::command_output::constants::{ INVOCATION_CONTEXT_ENV, }; use sqlbuild_core::constants::{ - AUDIT_RESULTS_TABLE_NAME, COLUMN_MIGRATION_TABLE_NAME, CONSUMPTION_TABLE_NAME, - DYNAMIC_PAUSES_TABLE_NAME, DYNAMIC_RESUME_SECONDS, FINGERPRINT_TABLE_NAME, - JANITOR_EVENTS_TABLE_NAME, MICROBATCH_TABLE_NAME, MIGRATION_TABLE_NAME, + ADAPTER_FILE_PATH, ADAPTERS_PATH, AUDIT_RESULTS_TABLE_NAME, COLUMN_MIGRATION_TABLE_NAME, + CONSUMPTION_TABLE_NAME, DYNAMIC_PAUSES_TABLE_NAME, DYNAMIC_RESUME_SECONDS, EVENT_SINKS_PATH, + FINGERPRINT_TABLE_NAME, JANITOR_EVENTS_TABLE_NAME, MICROBATCH_TABLE_NAME, MIGRATION_TABLE_NAME, NODE_RESULTS_TABLE_NAME, OBSERVATIONS_TABLE_NAME, OLD_NAME_VIEW_TABLE_NAME, - PROJECT_CONFIG_FILENAME, PYTHON_INIT_MODULE_STEM, PYTHON_NODE_ROOT, RUNS_TABLE_NAME, - SETTINGS_SECTION, SOURCE_FRESHNESS_TABLE_NAME, STAGED_PROMOTION_MODE, + PROJECT_CONFIG_FILENAME, PYTHON_DIRECTORY, PYTHON_INIT_MODULE_STEM, PYTHON_NODE_ROOT, + RUNS_TABLE_NAME, SETTINGS_SECTION, SOURCE_FRESHNESS_TABLE_NAME, STAGED_PROMOTION_MODE, TABLE_PROMOTION_MODE_SETTING_KEY, ZERO_DAY_DURATION, }; use sqlbuild_core::diagnostic_routing::constants::{ @@ -66,6 +66,10 @@ pub(crate) const EXPORTED_TEXTS: &[(&str, &str)] = &[ ("PROJECT_CONFIG_FILENAME", PROJECT_CONFIG_FILENAME), ("PYTHON_INIT_MODULE_STEM", PYTHON_INIT_MODULE_STEM), ("PYTHON_NODE_ROOT", PYTHON_NODE_ROOT), + ("PYTHON_PACKAGE_NAME", PYTHON_DIRECTORY), + ("EVENT_SINKS_PATH", EVENT_SINKS_PATH), + ("ADAPTERS_PATH", ADAPTERS_PATH), + ("ADAPTER_FILE_PATH", ADAPTER_FILE_PATH), ("SETTINGS_SECTION", SETTINGS_SECTION), ( "TABLE_PROMOTION_MODE_SETTING_KEY", diff --git a/crates/sqlbuild-python/src/bindings/_helpers/location_command/command.rs b/crates/sqlbuild-python/src/bindings/_helpers/location_command/command.rs index c77ac31612..af760f377a 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/location_command/command.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/location_command/command.rs @@ -45,6 +45,7 @@ use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_compile::compile_driver::main::setup::compiled_phase::compiled_phase; use sqlbuild_python_front::discovered_sets::main::discover_for_publication::discover_for_publication; use sqlbuild_python_front::discovered_sets::main::set_discovery_source::set_discovery_source; +use sqlbuild_python_front::discovered_sets::main::with_set_retries::with_set_retries; use sqlbuild_python_front::discovered_sets::models::DiscoverySource; use sqlbuild_python_output::recall::main::write_stderr::write_stderr; use sqlbuild_python_output::recall::models::InvocationRecall; @@ -412,7 +413,7 @@ pub(crate) fn run_location<'py>( }, )?; let (PublishedGeneration { record, .. }, _) = - publish_location(py, &arguments)?.map_err(|failure| { + with_set_retries(|| publish_location(py, &arguments))?.map_err(|failure| { PyValueError::new_err(format!( "Compile failed: {} rule findings", failure.finding_count diff --git a/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs b/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs index e7b806b26a..cd68b57b91 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs @@ -39,6 +39,7 @@ use sqlbuild_python_base::native_host::main::redirect_stdout_to_stderr::redirect use sqlbuild_python_front::discovered_sets::main::checked_set::checked_set; use sqlbuild_python_front::discovered_sets::main::discover_for_publication::discover_for_publication; use sqlbuild_python_front::discovered_sets::main::published_sets::published_sets; +use sqlbuild_python_front::discovered_sets::main::with_set_retries::with_set_retries; use sqlbuild_python_output::recall::main::write_stderr::write_stderr; pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResult { @@ -79,25 +80,26 @@ pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResul held = None; discover_for_publication(&arguments, publication)?; let mut error_text: Option = None; - let (published, rules) = match publish_location(py, &arguments) { - Ok(Ok((published, project))) => { - held = Some(project); - (Some(published), None) - } - Ok(Err(rules)) => (None, Some(rules)), - Err(error) => { - write_stderr( - py, - &format!("Location compilation/publication failed: {error}\n"), - )?; - let (message, code, help) = error_text_fields(py, &error)?; - let message = message.unwrap_or_else(|| error.to_string()); - let failed = generation_failed(generation, message, (code, help)); - py.detach(|| emit_dev_event(&failed))?; - error_text = Some(redact_error_text(&error.to_string())); - (None, None) - } - }; + let (published, rules) = + match with_set_retries(|| publish_location(py, &arguments)) { + Ok(Ok((published, project))) => { + held = Some(project); + (Some(published), None) + } + Ok(Err(rules)) => (None, Some(rules)), + Err(error) => { + write_stderr( + py, + &format!("Location compilation/publication failed: {error}\n"), + )?; + let (message, code, help) = error_text_fields(py, &error)?; + let message = message.unwrap_or_else(|| error.to_string()); + let failed = generation_failed(generation, message, (code, help)); + py.detach(|| emit_dev_event(&failed))?; + error_text = Some(redact_error_text(&error.to_string())); + (None, None) + } + }; let (discovered, discover_files) = published_sets(held.as_ref().map(|(discovered, _)| discovered))?; serde_json::to_string(&serde_json::json!({ diff --git a/crates/sqlbuild-python/src/bindings/_helpers/location_command/snapshot.rs b/crates/sqlbuild-python/src/bindings/_helpers/location_command/snapshot.rs index 94a20267ad..c5b77d353d 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/location_command/snapshot.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/location_command/snapshot.rs @@ -10,12 +10,15 @@ use sqlbuild_analysis::planner_scope::main::node_loads::node_loads; use sqlbuild_core::models::DiagnosticSeverity; use sqlbuild_discovery::orchestration_files::models::OrchestrationInventory; use sqlbuild_discovery::project_validation::main::validate_orchestration_names::validate_orchestration_names; -use sqlbuild_orchestration::discovered_sets::constants::DISCOVERED_DOCUMENT; +use sqlbuild_orchestration::discovered_sets::constants::{ + DISCOVERED_ASSETS_DOCUMENT, DISCOVERED_DOCUMENT, +}; use sqlbuild_orchestration::snapshots::models::{SnapshotInput, SnapshotNode}; use sqlbuild_python_base::boundary::models::KeywordArguments; use sqlbuild_python_base::orchestration_reads::main::environment_hash::environment_hash; use sqlbuild_python_base::records::main::fields::field::field; use sqlbuild_python_front::command_runtime::main::published_concurrency::published_concurrency; +use sqlbuild_python_front::discovered_sets::main::for_each_assets::for_each_assets; use sqlbuild_python_front::discovered_sets::main::used_discovered_sets::used_discovered_sets; use sqlbuild_python_front::discovery::main::project::named_node_rows::named_node_rows; use sqlbuild_python_front::discovery::main::project::project_facts::project_facts; @@ -114,6 +117,10 @@ pub(crate) fn orchestration_snapshot<'py>( let document = serde_json::to_value(&sets) .map_err(|error| PyValueError::new_err(error.to_string()))?; input.documents.insert(DISCOVERED_DOCUMENT.into(), document); + input.documents.insert( + DISCOVERED_ASSETS_DOCUMENT.into(), + json!(for_each_assets(&discovered_inputs)?), + ); } let graph = project.lineage_graph(py)?; let inventory = if declared { diff --git a/crates/sqlbuild-python/src/bindings/_helpers/native_host/warehouse_metadata.rs b/crates/sqlbuild-python/src/bindings/_helpers/native_host/warehouse_metadata.rs index b39e4a82a4..e128d8be0d 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/native_host/warehouse_metadata.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/native_host/warehouse_metadata.rs @@ -30,7 +30,7 @@ use sqlbuild_state::freshness::constants::{ OBSERVED_AT_COLUMN, SOURCE_FRESHNESS_COLUMN_TYPES, SQLITE_ADAPTER, }; use sqlbuild_state::observations::constants::OBSERVATION_COLUMN_TYPES; -use sqlbuild_state::resource_costs::constants::RESOURCE_COST_COLUMN_TYPES; +use sqlbuild_state::resource_costs::constants as resource_costs; use sqlbuild_state::state_tables::main::event_id_index::event_id_index; use sqlbuild_state::state_tables::main::read_history_sql::read_history_sql; use sqlbuild_state::state_tables::models::{HistoryRead, NewestVersions}; @@ -230,7 +230,7 @@ fn read_page<'py>( let freshness_columns = SOURCE_FRESHNESS_COLUMN_TYPES.map(|(name, _)| name); let consumption_columns = CONSUMPTION_COLUMN_TYPES.map(|(name, _)| name); let observation_columns = OBSERVATION_COLUMN_TYPES.map(|(name, _)| name); - let resource_cost_columns = RESOURCE_COST_COLUMN_TYPES.map(|(name, _)| name); + let resource_cost_columns = resource_costs::RESOURCE_COST_COLUMN_TYPES.map(|(name, _)| name); let event_columns: Vec = match request { WarehouseHistoryRead::AuditResults(_) => py .import("sqlbuild.executor.audit_results.constants")? @@ -447,6 +447,7 @@ fn read_page<'py>( "expires_at", "drop_reason", ], + WarehouseHistoryRead::ResourceCosts(_) => &resource_costs::ADDED_RESOURCE_COST_COLUMNS, _ => &[], }; let key_columns: Option<&[&str]> = match request { diff --git a/crates/sqlbuild-python/src/bindings/tests/helpers.rs b/crates/sqlbuild-python/src/bindings/tests/helpers.rs index b60ca65398..d3857950bd 100644 --- a/crates/sqlbuild-python/src/bindings/tests/helpers.rs +++ b/crates/sqlbuild-python/src/bindings/tests/helpers.rs @@ -30,9 +30,9 @@ pub(super) fn project_reading_environment() -> PathBuf { let root: PathBuf = std::env::temp_dir() .join(format!("sqlbuild-since-cache-{}", std::process::id())) .join("project"); - let _ = std::fs::create_dir_all(root.join("models")); + let _ = std::fs::create_dir_all(root.join("sql/models")); let _ = std::fs::write( - root.join("models/orders.sql"), + root.join("sql/models/orders.sql"), "SELECT order_id FROM orders WHERE region = '@@ENV:ORDERS_REGION'\n", ); root diff --git a/crates/sqlbuild-refactor/src/refactor_command/main/layer_move_suggestion.rs b/crates/sqlbuild-refactor/src/refactor_command/main/layer_move_suggestion.rs index fb5c6b6ea3..e92524a35a 100644 --- a/crates/sqlbuild-refactor/src/refactor_command/main/layer_move_suggestion.rs +++ b/crates/sqlbuild-refactor/src/refactor_command/main/layer_move_suggestion.rs @@ -1,13 +1,12 @@ //! Suggest the one-step `sqb mv` when a rename fails only on the layer-folder rules. -use crate::refactor_command::_helpers::layer_folders::{ - folder_of, mirrored_folder, name_layer, path_parts, -}; +use crate::refactor_command::_helpers::layer_folders::{folder_of, mirrored_folder, name_layer}; use crate::refactor_command::_helpers::quoting::command_line; use crate::refactor_command::constants::{ FOLDER_PLACEHOLDER, LAYER_FOLDER_RULE_CODES, LAYER_FOLDERS, PROJECT_DIR_OPTION, SQL_FILE_SUFFIX, }; use crate::refactor_command::models::{LayerMove, RefactorDiagnostic}; +use crate::refactoring::constants::MODELS_ROOT; use crate::refactoring::models::{FileChange, RefactorOperation, RefactorPlan}; /// The `sqb mv` that renames and moves in one step, or none for any other failure. @@ -40,13 +39,7 @@ pub fn layer_move_suggestion( }); let mut folders: Vec = match &mirrored { Some((head, tail)) => head.iter().chain(tail).cloned().collect(), - None => vec![ - path_parts(&renamed.original_path) - .first() - .map(|part| (*part).to_owned()) - .unwrap_or_default(), - FOLDER_PLACEHOLDER.to_owned(), - ], + None => vec![MODELS_ROOT.to_owned(), FOLDER_PLACEHOLDER.to_owned()], }; folders.push(format!("{new_name}{SQL_FILE_SUFFIX}")); let mut arguments: Vec = vec![ diff --git a/crates/sqlbuild-refactor/src/refactor_command/tests/test_compare_with_baseline.rs b/crates/sqlbuild-refactor/src/refactor_command/tests/test_compare_with_baseline.rs index a0c4c012d7..66ff990221 100644 --- a/crates/sqlbuild-refactor/src/refactor_command/tests/test_compare_with_baseline.rs +++ b/crates/sqlbuild-refactor/src/refactor_command/tests/test_compare_with_baseline.rs @@ -7,8 +7,8 @@ use crate::refactoring::models::FileChange; const OVER_FULL: DiagnosticRow = ( true, "XSQBRLAYOUT001", - "models/staging", - "models/staging holds 3 models; the maximum is 2", + "sql/models/staging", + "sql/models/staging holds 3 models; the maximum is 2", ); #[test] @@ -20,11 +20,11 @@ fn given_rule_failures_before_and_after_when_comparing_then_only_new_or_worse_on after: &[( true, "XSQBRLAYOUT001", - "models/staging", - "models/staging holds 2 models; the maximum is 2", + "sql/models/staging", + "sql/models/staging holds 2 models; the maximum is 2", )], - moves: &[("models/staging/a.sql", "models/finance/a.sql")], - expected_remaining: &["XSQBRLAYOUT001 models/staging"], + moves: &[("sql/models/staging/a.sql", "sql/models/finance/a.sql")], + expected_remaining: &["XSQBRLAYOUT001 sql/models/staging"], expected_resolved: &[], expected_blocking: &[], }, @@ -32,9 +32,9 @@ fn given_rule_failures_before_and_after_when_comparing_then_only_new_or_worse_on description: "a failure the moves repair is resolved", before: &[OVER_FULL], after: &[], - moves: &[("models/staging/a.sql", "models/finance/a.sql")], + moves: &[("sql/models/staging/a.sql", "sql/models/finance/a.sql")], expected_remaining: &[], - expected_resolved: &["XSQBRLAYOUT001 models/staging"], + expected_resolved: &["XSQBRLAYOUT001 sql/models/staging"], expected_blocking: &[], }, BaselineComparisonTestCase { @@ -43,13 +43,13 @@ fn given_rule_failures_before_and_after_when_comparing_then_only_new_or_worse_on after: &[( true, "XSQBRLAYOUT001", - "models/staging", - "models/staging holds 4 models; the maximum is 2", + "sql/models/staging", + "sql/models/staging holds 4 models; the maximum is 2", )], - moves: &[("models/finance/a.sql", "models/staging/a.sql")], + moves: &[("sql/models/finance/a.sql", "sql/models/staging/a.sql")], expected_remaining: &[], expected_resolved: &[], - expected_blocking: &["XSQBRLAYOUT001 models/staging"], + expected_blocking: &["XSQBRLAYOUT001 sql/models/staging"], }, BaselineComparisonTestCase { description: "a failure in a folder that had none is new and blocks", @@ -59,31 +59,31 @@ fn given_rule_failures_before_and_after_when_comparing_then_only_new_or_worse_on ( true, "XSQBRLAYOUT001", - "models/finance", - "models/finance holds 3 models; the maximum is 2", + "sql/models/finance", + "sql/models/finance holds 3 models; the maximum is 2", ), ], - moves: &[("models/marts/a.sql", "models/finance/a.sql")], - expected_remaining: &["XSQBRLAYOUT001 models/staging"], + moves: &[("sql/models/marts/a.sql", "sql/models/finance/a.sql")], + expected_remaining: &["XSQBRLAYOUT001 sql/models/staging"], expected_resolved: &[], - expected_blocking: &["XSQBRLAYOUT001 models/finance"], + expected_blocking: &["XSQBRLAYOUT001 sql/models/finance"], }, BaselineComparisonTestCase { description: "an unchanged failure on a moved file follows the file", before: &[( true, "SQBRMODEL101", - "models/staging/a.sql", + "sql/models/staging/a.sql", "a has no tests", )], after: &[( true, "SQBRMODEL101", - "models/finance/a.sql", + "sql/models/finance/a.sql", "a has no tests", )], - moves: &[("models/staging/a.sql", "models/finance/a.sql")], - expected_remaining: &["SQBRMODEL101 models/finance/a.sql"], + moves: &[("sql/models/staging/a.sql", "sql/models/finance/a.sql")], + expected_remaining: &["SQBRMODEL101 sql/models/finance/a.sql"], expected_resolved: &[], expected_blocking: &[], }, @@ -92,25 +92,25 @@ fn given_rule_failures_before_and_after_when_comparing_then_only_new_or_worse_on before: &[( true, "XSQBRSIZE001", - "models/marts/totals.sql", + "sql/models/marts/totals.sql", "totals reads 2 models", )], after: &[( true, "XSQBRSIZE001", - "models/marts/totals.sql", + "sql/models/marts/totals.sql", "totals reads 3 models", )], - moves: &[("models/marts/totals.sql", "models/marts/totals.sql")], + moves: &[("sql/models/marts/totals.sql", "sql/models/marts/totals.sql")], expected_remaining: &[], expected_resolved: &[], - expected_blocking: &["XSQBRSIZE001 models/marts/totals.sql"], + expected_blocking: &["XSQBRSIZE001 sql/models/marts/totals.sql"], }, BaselineComparisonTestCase { description: "a changed failure without a place blocks", before: &[(true, "XSQBRMART001", "", "the project has 2 marts")], after: &[(true, "XSQBRMART001", "", "the project has 3 marts")], - moves: &[("models/staging/a.sql", "models/marts/a.sql")], + moves: &[("sql/models/staging/a.sql", "sql/models/marts/a.sql")], expected_remaining: &[], expected_resolved: &[], expected_blocking: &["XSQBRMART001 "], @@ -119,7 +119,7 @@ fn given_rule_failures_before_and_after_when_comparing_then_only_new_or_worse_on description: "a reduced failure without a place is existing", before: &[(true, "XSQBRMART001", "", "the project has 3 marts")], after: &[(true, "XSQBRMART001", "", "the project has 2 marts")], - moves: &[("models/marts/a.sql", "models/staging/a.sql")], + moves: &[("sql/models/marts/a.sql", "sql/models/staging/a.sql")], expected_remaining: &["XSQBRMART001 "], expected_resolved: &[], expected_blocking: &[], @@ -129,38 +129,38 @@ fn given_rule_failures_before_and_after_when_comparing_then_only_new_or_worse_on before: &[( true, "SQBRPROJECT204", - "models/o/a.sql", + "sql/models/o/a.sql", "owner o has fin_a and fin_b", )], after: &[( true, "SQBRPROJECT204", - "models/o/a.sql", + "sql/models/o/a.sql", "owner o has fin_a and fin_c", )], - moves: &[("models/o/c/c.sql", "models/o/fin_c/c.sql")], + moves: &[("sql/models/o/c/c.sql", "sql/models/o/fin_c/c.sql")], expected_remaining: &[], expected_resolved: &[], - expected_blocking: &["SQBRPROJECT204 models/o/a.sql"], + expected_blocking: &["SQBRPROJECT204 sql/models/o/a.sql"], }, BaselineComparisonTestCase { description: "a count that grows at an untouched place blocks", before: &[( true, "SQBRPROJECT204", - "models/o/a.sql", + "sql/models/o/a.sql", "2 sibling owner directories", )], after: &[( true, "SQBRPROJECT204", - "models/o/a.sql", + "sql/models/o/a.sql", "3 sibling owner directories", )], - moves: &[("models/o/c/c.sql", "models/o/fin_c/c.sql")], + moves: &[("sql/models/o/c/c.sql", "sql/models/o/fin_c/c.sql")], expected_remaining: &[], expected_resolved: &[], - expected_blocking: &["SQBRPROJECT204 models/o/a.sql"], + expected_blocking: &["SQBRPROJECT204 sql/models/o/a.sql"], }, BaselineComparisonTestCase { description: "nothing counts as resolved when another error may have hidden rules", @@ -168,34 +168,34 @@ fn given_rule_failures_before_and_after_when_comparing_then_only_new_or_worse_on after: &[( false, "D016", - "models/staging/a.sql", + "sql/models/staging/a.sql", "invalid model identity", )], moves: &[], expected_remaining: &[], expected_resolved: &[], - expected_blocking: &["D016 models/staging/a.sql"], + expected_blocking: &["D016 sql/models/staging/a.sql"], }, BaselineComparisonTestCase { description: "errors that are not rule failures always block", before: &[OVER_FULL], after: &[ OVER_FULL, - (false, "S006", "models/staging/a.sql", "not visible"), + (false, "S006", "sql/models/staging/a.sql", "not visible"), ], moves: &[], - expected_remaining: &["XSQBRLAYOUT001 models/staging"], + expected_remaining: &["XSQBRLAYOUT001 sql/models/staging"], expected_resolved: &[], - expected_blocking: &["S006 models/staging/a.sql"], + expected_blocking: &["S006 sql/models/staging/a.sql"], }, BaselineComparisonTestCase { description: "two failures where the project had one: the second is new", before: &[OVER_FULL], after: &[OVER_FULL, OVER_FULL], moves: &[], - expected_remaining: &["XSQBRLAYOUT001 models/staging"], + expected_remaining: &["XSQBRLAYOUT001 sql/models/staging"], expected_resolved: &[], - expected_blocking: &["XSQBRLAYOUT001 models/staging"], + expected_blocking: &["XSQBRLAYOUT001 sql/models/staging"], }, ]; for test_case in test_cases { diff --git a/crates/sqlbuild-refactor/src/refactor_command/tests/test_layer_move.rs b/crates/sqlbuild-refactor/src/refactor_command/tests/test_layer_move.rs index 3785868d76..6ef191344b 100644 --- a/crates/sqlbuild-refactor/src/refactor_command/tests/test_layer_move.rs +++ b/crates/sqlbuild-refactor/src/refactor_command/tests/test_layer_move.rs @@ -11,75 +11,75 @@ use crate::refactoring::models::RefactorPlan; const LAYER_CODES: &[&str] = &["SQBRPROJECT102", "SQBRPROJECT105"]; const ENRICHED_COMMAND: &str = "sqb mv orders__int_clean__lines__web \ - models/orders/intermediate/enriched/web/orders__int_enriched__lines__web.sql"; + sql/models/orders/intermediate/enriched/web/orders__int_enriched__lines__web.sql"; #[test] fn given_rename_compile_errors_when_suggesting_layer_move_then_one_step_mv_is_exact() { let test_cases = [ LayerMoveTestCase { description: "int_clean to int_enriched keeps domain and sub-folders", - old_path: "models/orders/intermediate/clean/web/orders__int_clean__lines__web.sql", + old_path: "sql/models/orders/intermediate/clean/web/orders__int_clean__lines__web.sql", new_name: "orders__int_enriched__lines__web", codes: LAYER_CODES, project_dir: None, windows: false, expected_command: Some(ENRICHED_COMMAND), - expected_folder: Some("models/orders/intermediate/enriched"), + expected_folder: Some("sql/models/orders/intermediate/enriched"), }, LayerMoveTestCase { description: "a bare intermediate folder becomes the int_clean folder", - old_path: "models/orders/intermediate/orders__int_v__totals.sql", + old_path: "sql/models/orders/intermediate/orders__int_v__totals.sql", new_name: "orders__int_clean__totals", codes: &["SQBRPROJECT102"], project_dir: None, windows: false, expected_command: Some( "sqb mv orders__int_v__totals \ - models/orders/intermediate/clean/orders__int_clean__totals.sql", + sql/models/orders/intermediate/clean/orders__int_clean__totals.sql", ), - expected_folder: Some("models/orders/intermediate/clean"), + expected_folder: Some("sql/models/orders/intermediate/clean"), }, LayerMoveTestCase { description: "only the current layer's own folder is replaced", - old_path: "models/mart/orders/staging/orders__stg__order_lines_x.sql", + old_path: "sql/models/mart/orders/staging/orders__stg__order_lines_x.sql", new_name: "orders__int_clean__order_lines_x", codes: &["SQBRPROJECT102"], project_dir: None, windows: false, expected_command: Some( "sqb mv orders__stg__order_lines_x \ - models/mart/orders/intermediate/clean/orders__int_clean__order_lines_x.sql", + sql/models/mart/orders/intermediate/clean/orders__int_clean__order_lines_x.sql", ), - expected_folder: Some("models/mart/orders/intermediate/clean"), + expected_folder: Some("sql/models/mart/orders/intermediate/clean"), }, LayerMoveTestCase { description: "no layer folder in the current path uses a placeholder", - old_path: "models/orders/web/order_lines.sql", + old_path: "sql/models/orders/web/order_lines.sql", new_name: "orders__stg__order_lines", codes: LAYER_CODES, project_dir: None, windows: false, expected_command: Some( - "sqb mv order_lines 'models//orders__stg__order_lines.sql'", + "sqb mv order_lines 'sql/models//orders__stg__order_lines.sql'", ), expected_folder: None, }, LayerMoveTestCase { description: "a layer without a folder mapping uses a placeholder", - old_path: "models/orders/intermediate/clean/orders__int_clean__totals.sql", + old_path: "sql/models/orders/intermediate/clean/orders__int_clean__totals.sql", new_name: "orders__int_archive__totals", codes: LAYER_CODES, project_dir: None, windows: false, expected_command: Some( "sqb mv orders__int_clean__totals \ - 'models//orders__int_archive__totals.sql'", + 'sql/models//orders__int_archive__totals.sql'", ), expected_folder: None, }, LayerMoveTestCase { description: "another rule failing as well gets no suggestion", - old_path: "models/orders/intermediate/clean/orders__int_clean__totals.sql", + old_path: "sql/models/orders/intermediate/clean/orders__int_clean__totals.sql", new_name: "orders__int_enriched__totals", codes: &["SQBRPROJECT105", "SQBRMODEL103"], project_dir: None, @@ -89,31 +89,31 @@ fn given_rename_compile_errors_when_suggesting_layer_move_then_one_step_mv_is_ex }, LayerMoveTestCase { description: "posix shells get POSIX quoting", - old_path: "models/orders/intermediate/clean/web/orders__int_clean__lines__web.sql", + old_path: "sql/models/orders/intermediate/clean/web/orders__int_clean__lines__web.sql", new_name: "orders__int_enriched__lines__web", codes: LAYER_CODES, project_dir: Some("/srv/order projects/orders"), windows: false, expected_command: Some( "sqb mv orders__int_clean__lines__web \ - models/orders/intermediate/enriched/web/orders__int_enriched__lines__web.sql \ + sql/models/orders/intermediate/enriched/web/orders__int_enriched__lines__web.sql \ --project-dir '/srv/order projects/orders'", ), - expected_folder: Some("models/orders/intermediate/enriched"), + expected_folder: Some("sql/models/orders/intermediate/enriched"), }, LayerMoveTestCase { description: "windows gets cmd.exe quoting", - old_path: "models/orders/intermediate/clean/web/orders__int_clean__lines__web.sql", + old_path: "sql/models/orders/intermediate/clean/web/orders__int_clean__lines__web.sql", new_name: "orders__int_enriched__lines__web", codes: LAYER_CODES, project_dir: Some("C:\\order projects\\orders"), windows: true, expected_command: Some( "sqb mv orders__int_clean__lines__web \ - models/orders/intermediate/enriched/web/orders__int_enriched__lines__web.sql \ + sql/models/orders/intermediate/enriched/web/orders__int_enriched__lines__web.sql \ --project-dir \"C:\\order projects\\orders\"", ), - expected_folder: Some("models/orders/intermediate/enriched"), + expected_folder: Some("sql/models/orders/intermediate/enriched"), }, ]; @@ -142,18 +142,18 @@ fn given_rename_compile_errors_when_suggesting_layer_move_then_one_step_mv_is_ex fn given_layer_failure_when_rendering_text_then_suggestion_follows_errors() { let test_cases = [RenderTestCase { description: "a refused rename lists errors, the one-step move and the status", - old_path: "models/orders/staging/orders__stg__lines.sql", + old_path: "sql/models/orders/staging/orders__stg__lines.sql", new_name: "orders__mart__lines", codes: &["SQBRPROJECT105"], expected_text: "Rename model orders__stg__lines -> orders__mart__lines\n\ - \u{2514}\u{2500}\u{2500} models/orders/staging/orders__mart__lines.sql \ - (moved from models/orders/staging/orders__stg__lines.sql)\n\ + \u{2514}\u{2500}\u{2500} sql/models/orders/staging/orders__mart__lines.sql \ + (moved from sql/models/orders/staging/orders__stg__lines.sql)\n\ Compile errors in the edited project\n\ \u{2514}\u{2500}\u{2500} SQBRPROJECT105 \ - models/orders/staging/orders__mart__lines.sql:1 SQBRPROJECT105 failed\n\ - orders__mart__lines belongs under models/orders/mart/\n \ + sql/models/orders/staging/orders__mart__lines.sql:1 SQBRPROJECT105 failed\n\ + orders__mart__lines belongs under sql/models/orders/mart/\n \ Rename and move in one step:\n \ - sqb mv orders__stg__lines models/orders/mart/orders__mart__lines.sql\n \ + sqb mv orders__stg__lines sql/models/orders/mart/orders__mart__lines.sql\n \ (change the folder if you want it somewhere else)\n\ Compiled: failed; no files changed\n", }]; diff --git a/crates/sqlbuild-refactor/src/refactor_command/tests/test_refactor_pairs.rs b/crates/sqlbuild-refactor/src/refactor_command/tests/test_refactor_pairs.rs index d4ea6b989a..38e450f941 100644 --- a/crates/sqlbuild-refactor/src/refactor_command/tests/test_refactor_pairs.rs +++ b/crates/sqlbuild-refactor/src/refactor_command/tests/test_refactor_pairs.rs @@ -8,19 +8,26 @@ fn given_words_and_pair_file_when_reading_pairs_then_every_pair_is_read_in_order RefactorPairsTestCase { description: "pairs on the command line, then from the file", is_move: true, - words: &["orders", "models/finance/", "customers", "models/crm/"], - file: Some("# moves\n\nrefunds\tmodels/finance/\n totals models/marts/t.sql \n"), + words: &[ + "orders", + "sql/models/finance/", + "customers", + "sql/models/crm/", + ], + file: Some( + "# moves\n\nrefunds\tsql/models/finance/\n totals sql/models/marts/t.sql \n", + ), expected_pairs: Ok(&[ - ("orders", "models/finance/"), - ("customers", "models/crm/"), - ("refunds", "models/finance/"), - ("totals", "models/marts/t.sql"), + ("orders", "sql/models/finance/"), + ("customers", "sql/models/crm/"), + ("refunds", "sql/models/finance/"), + ("totals", "sql/models/marts/t.sql"), ]), }, RefactorPairsTestCase { description: "a target without a destination", is_move: true, - words: &["orders", "models/finance/", "customers"], + words: &["orders", "sql/models/finance/", "customers"], file: None, expected_pairs: Err("'customers' has no DESTINATION"), }, @@ -28,7 +35,7 @@ fn given_words_and_pair_file_when_reading_pairs_then_every_pair_is_read_in_order description: "a file line with three words", is_move: true, words: &[], - file: Some("orders models/finance/ extra\n"), + file: Some("orders sql/models/finance/ extra\n"), expected_pairs: Err( "pairs.tsv:1: expected TARGET and DESTINATION separated by a tab or spaces, \ found 3 words", diff --git a/crates/sqlbuild-refactor/src/refactoring/constants.rs b/crates/sqlbuild-refactor/src/refactoring/constants.rs index f209691ed6..ea533fe43c 100644 --- a/crates/sqlbuild-refactor/src/refactoring/constants.rs +++ b/crates/sqlbuild-refactor/src/refactoring/constants.rs @@ -71,9 +71,9 @@ pub const TEST_NAME_KEY: &str = "name"; pub const TEST_NAME_SEPARATOR: &str = "__"; /// The prefix of unit test file stems, as in `test___.sql`. pub const TEST_FILE_PREFIX: &str = "test_"; -/// The root that holds unit tests, mirroring model folders below `models/`. +/// The root that holds unit tests, mirroring model folders below `sql/models/`. pub const UNIT_TEST_ROOT: &str = "tests/unit"; -pub const MODELS_ROOT: &str = "models"; +pub const MODELS_ROOT: &str = "sql/models"; pub const MODEL_MANUAL_HELP: &str = "Pass the model into the macro as an argument, or edit the listed locations, then run the command again."; pub const COLUMN_MANUAL_HELP: &str = "Edit the listed locations, then run the command again."; /// `RefactorEditError`'s code: two planned edits overlap. @@ -106,7 +106,7 @@ pub const INVALID_NAME_PATTERN_PREFIX: &str = "invalid name_pattern: "; pub const JOB_FILES_DIRECTORY: &str = "orchestration/jobs"; pub const TOML_SUFFIX: &str = ".toml"; /// The folder path selectors start from. -pub const MODEL_ROOT: &str = "models"; +pub const MODEL_ROOT: &str = "sql/models"; pub const UNREADABLE_JOB_REASON: &str = "this job file cannot be read as UTF-8, so its selectors cannot be updated; fix or remove it first"; pub const PARTIAL_FOLDER_MOVE_REASON: &str = "this job selects folder '{folder}', and {models} moved out of it; check the job still selects what it should"; pub const UNWRITABLE_SELECTOR_REASON: &str = diff --git a/crates/sqlbuild-refactor/src/refactoring/tests/helpers.rs b/crates/sqlbuild-refactor/src/refactoring/tests/helpers.rs index aba5db9c50..a0a35bb2c7 100644 --- a/crates/sqlbuild-refactor/src/refactoring/tests/helpers.rs +++ b/crates/sqlbuild-refactor/src/refactoring/tests/helpers.rs @@ -205,7 +205,7 @@ pub(super) fn inserted_entry(contents: &str) -> Result, RefactorE fn yaml_file(contents: &str) -> Vec { vec![DiscoveredFile { - path: "sources/raw.yml".to_owned(), + path: "sql/sources/raw.yml".to_owned(), contents: contents.to_owned(), }] } @@ -258,7 +258,7 @@ pub(super) fn owned_span_pair(spans: (ExpectedSpans, ExpectedSpans)) -> (Spans, pub(super) fn model(name: &str, materialized: Option<&str>, schema: &str) -> ModelFacts { ModelFacts { name: name.to_owned(), - path: format!("models/{name}.sql"), + path: format!("sql/models/{name}.sql"), deps: Vec::new(), query_sql: "SELECT 1".to_owned(), authored_query_sql: "SELECT 1".to_owned(), @@ -497,7 +497,7 @@ pub(super) fn plan_consumer( }, )?; let body = BodyContext { - path: "models/consumer.sql", + path: "sql/models/consumer.sql", contents: &text, mapping: BodyMapping::Authored(0), fallback_offset: 0, @@ -633,7 +633,7 @@ pub(super) fn owner_header_parts( .into_iter() .map(|(name, body)| AuthoredFile { role: SqlFileRole::Audit, - path: format!("audits/generic/{name}.sql"), + path: format!("sql/audits/generic/{name}.sql"), contents: format!("AUDIT ();\n{body}\n"), texts: vec![body.to_owned()], }) @@ -669,7 +669,7 @@ pub(super) fn followed_unit_tests( rebound: &[&str], ) -> Result { let mut orders: ModelFacts = model("orders", Some("view"), "analytics"); - orders.path = "models/marts/orders.sql".to_owned(); + orders.path = "sql/models/marts/orders.sql".to_owned(); let mut project_facts = facts("/nonexistent/project", vec![orders]); for (path, name, targets) in tests { project_facts.authored_files.push(AuthoredFile { diff --git a/crates/sqlbuild-refactor/src/refactoring/tests/test_job_selectors.rs b/crates/sqlbuild-refactor/src/refactoring/tests/test_job_selectors.rs index 0c8a5f6c10..8d4387c5d5 100644 --- a/crates/sqlbuild-refactor/src/refactoring/tests/test_job_selectors.rs +++ b/crates/sqlbuild-refactor/src/refactoring/tests/test_job_selectors.rs @@ -9,7 +9,7 @@ use crate::refactoring::tests::test_types::JobSelectorTestCase; const JOB: &str = "orchestration/jobs/orders/refresh.toml"; /// A model the refactoring leaves alone keeps its name and path. -const STAYS: (&str, &str, &str, &str) = ("customers", "models/marts/customers.sql", "", ""); +const STAYS: (&str, &str, &str, &str) = ("customers", "sql/models/marts/customers.sql", "", ""); #[test] fn given_job_selectors_when_models_are_renamed_or_moved_then_exact_parts_follow() @@ -20,9 +20,9 @@ fn given_job_selectors_when_models_are_renamed_or_moved_then_exact_parts_follow( models: &[ ( "orders", - "models/marts/orders.sql", + "sql/models/marts/orders.sql", "sales", - "models/marts/sales.sql", + "sql/models/marts/sales.sql", ), STAYS, ], @@ -35,9 +35,9 @@ fn given_job_selectors_when_models_are_renamed_or_moved_then_exact_parts_follow( models: &[ ( "orders", - "models/marts/orders.sql", + "sql/models/marts/orders.sql", "sales", - "models/marts/sales.sql", + "sql/models/marts/sales.sql", ), STAYS, ], @@ -50,20 +50,20 @@ fn given_job_selectors_when_models_are_renamed_or_moved_then_exact_parts_follow( models: &[ ( "orders", - "models/staging/orders.sql", + "sql/models/staging/orders.sql", "orders", - "models/core/orders.sql", + "sql/models/core/orders.sql", ), ( "lines", - "models/staging/sub/lines.sql", + "sql/models/staging/sub/lines.sql", "lines", - "models/core/sub/lines.sql", + "sql/models/core/sub/lines.sql", ), STAYS, ], - job: "select = \"models/staging/ path:models/staging +models/staging/sub+ models/stagingx models\"\n", - expected_job: "select = \"models/core/ path:models/core +models/core/sub+ models/stagingx models\"\n", + job: "select = \"sql/models/staging/ path:sql/models/staging +sql/models/staging/sub+ sql/models/stagingx models\"\n", + expected_job: "select = \"sql/models/core/ path:sql/models/core +sql/models/core/sub+ sql/models/stagingx models\"\n", expected_manual: &[], }, JobSelectorTestCase { @@ -71,16 +71,16 @@ fn given_job_selectors_when_models_are_renamed_or_moved_then_exact_parts_follow( models: &[ ( "orders", - "models/staging/orders.sql", + "sql/models/staging/orders.sql", "orders", - "models/core/orders.sql", + "sql/models/core/orders.sql", ), - ("lines", "models/staging/lines.sql", "", ""), + ("lines", "sql/models/staging/lines.sql", "", ""), ], - job: "name = \"x_job\"\nselect = \"models/staging orders\"\n", - expected_job: "name = \"x_job\"\nselect = \"models/staging orders\"\n", + job: "name = \"x_job\"\nselect = \"sql/models/staging orders\"\n", + expected_job: "name = \"x_job\"\nselect = \"sql/models/staging orders\"\n", expected_manual: &[ - "2:10 this job selects folder 'models/staging', and orders moved out of it; check the job still selects what it should", + "2:10 this job selects folder 'sql/models/staging', and orders moved out of it; check the job still selects what it should", ], }, JobSelectorTestCase { @@ -88,26 +88,26 @@ fn given_job_selectors_when_models_are_renamed_or_moved_then_exact_parts_follow( models: &[ ( "orders", - "models/staging/orders.sql", + "sql/models/staging/orders.sql", "orders", - "models/marts/orders.sql", + "sql/models/marts/orders.sql", ), STAYS, ], - job: "name = \"x_job\"\nselect = \"models/staging\"\nexclude = \"models/staging\"\n", - expected_job: "name = \"x_job\"\nselect = \"models/staging\"\nexclude = \"models/staging\"\n", + job: "name = \"x_job\"\nselect = \"sql/models/staging\"\nexclude = \"sql/models/staging\"\n", + expected_job: "name = \"x_job\"\nselect = \"sql/models/staging\"\nexclude = \"sql/models/staging\"\n", expected_manual: &[ - "2:10 this job selects folder 'models/staging', and orders moved out of it; check the job still selects what it should", - "3:11 this job selects folder 'models/staging', and orders moved out of it; check the job still selects what it should", + "2:10 this job selects folder 'sql/models/staging', and orders moved out of it; check the job still selects what it should", + "3:11 this job selects folder 'sql/models/staging', and orders moved out of it; check the job still selects what it should", ], }, JobSelectorTestCase { description: "a multi-line selector is reported instead of rewritten", models: &[( "orders", - "models/marts/orders.sql", + "sql/models/marts/orders.sql", "sales", - "models/marts/sales.sql", + "sql/models/marts/sales.sql", )], job: "select = \"\"\"\norders\"\"\"\n", expected_job: "select = \"\"\"\norders\"\"\"\n", diff --git a/crates/sqlbuild-refactor/src/refactoring/tests/test_planning.rs b/crates/sqlbuild-refactor/src/refactoring/tests/test_planning.rs index 8b5da21c18..d4319341c6 100644 --- a/crates/sqlbuild-refactor/src/refactoring/tests/test_planning.rs +++ b/crates/sqlbuild-refactor/src/refactoring/tests/test_planning.rs @@ -18,7 +18,10 @@ use crate::refactoring::tests::test_types::{ fn given_taken_name_or_destination_when_planning_then_collisions_block() -> Result<(), RefactorError> { let project = tempfile::tempdir().map_err(|error| RefactorError::value(error.to_string()))?; - write_files(project.path(), &[("models/finance/orders.sql", "SELECT 1")])?; + write_files( + project.path(), + &[("sql/models/finance/orders.sql", "SELECT 1")], + )?; let project_facts = facts( &project.path().to_string_lossy(), vec![ @@ -30,12 +33,16 @@ fn given_taken_name_or_destination_when_planning_then_collisions_block() -> Resu CollisionTestCase { description: "a rename onto another model's name, ignoring case", request: request(RefactorOperation::RenameModel, "order_lines", None), - expected_reasons: &["models/Order_Lines.sql: model:order_lines already exists"], + expected_reasons: &["sql/models/Order_Lines.sql: model:order_lines already exists"], }, CollisionTestCase { description: "a move onto an existing file", - request: request(RefactorOperation::MoveModel, "", Some("models/finance/")), - expected_reasons: &["models/finance/orders.sql: destination file already exists"], + request: request( + RefactorOperation::MoveModel, + "", + Some("sql/models/finance/"), + ), + expected_reasons: &["sql/models/finance/orders.sql: destination file already exists"], }, ]; for test_case in test_cases { @@ -159,46 +166,46 @@ fn given_failing_commit_when_committing_then_project_files_are_unchanged() CommitTestCase { description: "a write failing after an earlier write restores every file", on_disk: &[ - ("models/orders.sql", "SELECT 1"), - ("models/customers.sql", "SELECT 2"), + ("sql/models/orders.sql", "SELECT 1"), + ("sql/models/customers.sql", "SELECT 2"), ], originals: &[ - ("models/orders.sql", "SELECT 1"), - ("models/customers.sql", "SELECT 2"), + ("sql/models/orders.sql", "SELECT 1"), + ("sql/models/customers.sql", "SELECT 2"), ], changes: vec![ change( - "models/orders.sql", - "models/orders.sql", + "sql/models/orders.sql", + "sql/models/orders.sql", vec![replace_all("SELECT 1", "SELECT 10")], ), change( - "models/orders.sql/customers.sql", - "models/customers.sql", + "sql/models/orders.sql/customers.sql", + "sql/models/customers.sql", Vec::new(), ), ], expected_error: (RefactorErrorKind::Io, "", ""), expected_files: &[ - ("models/orders.sql", "SELECT 1"), - ("models/customers.sql", "SELECT 2"), + ("sql/models/orders.sql", "SELECT 1"), + ("sql/models/customers.sql", "SELECT 2"), ], }, CommitTestCase { description: "a file edited since planning writes nothing", - on_disk: &[("models/orders.sql", "SELECT 3")], - originals: &[("models/orders.sql", "SELECT 1")], + on_disk: &[("sql/models/orders.sql", "SELECT 3")], + originals: &[("sql/models/orders.sql", "SELECT 1")], changes: vec![change( - "models/orders.sql", - "models/orders.sql", + "sql/models/orders.sql", + "sql/models/orders.sql", vec![replace_all("SELECT 1", "SELECT 10")], )], expected_error: ( RefactorErrorKind::Write, "C958", - "files changed while the refactoring ran: models/orders.sql", + "files changed while the refactoring ran: sql/models/orders.sql", ), - expected_files: &[("models/orders.sql", "SELECT 3")], + expected_files: &[("sql/models/orders.sql", "SELECT 3")], }, ]; for test_case in test_cases { @@ -238,7 +245,7 @@ fn given_scope_placement_when_moving_across_folders_then_declaration_files_follo DeclarationMovesTestCase { description: "a move within one folder asks no placement", on_disk: &[], - moves: &[("models/orders.sql", "models/orders_v2.sql")], + moves: &[("sql/models/orders.sql", "sql/models/orders_v2.sql")], placement: DeclarationPlacement::default(), expected_moves: &[], expected_blocking: &[], @@ -246,135 +253,161 @@ fn given_scope_placement_when_moving_across_folders_then_declaration_files_follo DeclarationMovesTestCase { description: "an unsettled placement blocks with the preview's reasons", on_disk: &[], - moves: &[("models/orders.sql", "models/marts/orders.sql")], + moves: &[("sql/models/orders.sql", "sql/models/marts/orders.sql")], placement: DeclarationPlacement { relocated: None, diagnostics: vec!["Move source model:orders is unknown".to_owned()], declarations: Vec::new(), }, expected_moves: &[], - expected_blocking: &["models/marts/orders.sql:0 Move source model:orders is unknown"], + expected_blocking: &[ + "sql/models/marts/orders.sql:0 Move source model:orders is unknown", + ], }, DeclarationMovesTestCase { description: "an unsettled placement without reasons blocks with the default reason", on_disk: &[], - moves: &[("models/orders.sql", "models/marts/orders.sql")], + moves: &[("sql/models/orders.sql", "sql/models/marts/orders.sql")], placement: DeclarationPlacement::default(), expected_moves: &[], expected_blocking: &[ - "models/marts/orders.sql:0 declaration placement at the destination could not be worked out", + "sql/models/marts/orders.sql:0 declaration placement at the destination could not be worked out", ], }, DeclarationMovesTestCase { description: "files move whole; split files, shared files, generated files and taken paths block", on_disk: &[ - ("models/_sqlbuild/_macros/cents.py", "x"), - ("models/_sqlbuild/_enums/both.sql", "x"), - ("models/marts/_sqlbuild/_enums/both.sql", "x"), + ("sql/models/_sqlbuild/_macros/cents.py", "x"), + ("sql/models/_sqlbuild/_enums/both.sql", "x"), + ("sql/models/marts/_sqlbuild/_enums/both.sql", "x"), ], - moves: &[("models/orders.sql", "models/marts/orders.sql")], + moves: &[("sql/models/orders.sql", "sql/models/marts/orders.sql")], placement: DeclarationPlacement { relocated: Some(vec![ - relocated("enum:a", "models/marts/_sqlbuild/_enums/both.sql"), - relocated("enum:b", "models/other/_sqlbuild/_enums/both.sql"), - relocated("macro:cents", "models/marts/_sqlbuild/_macros/cents.py"), - relocated("macro:generated", "models/marts/_sqlbuild/_macros/gen.py"), + relocated("enum:a", "sql/models/marts/_sqlbuild/_enums/both.sql"), + relocated("enum:b", "sql/models/other/_sqlbuild/_enums/both.sql"), + relocated("macro:cents", "sql/models/marts/_sqlbuild/_macros/cents.py"), + relocated( + "macro:generated", + "sql/models/marts/_sqlbuild/_macros/gen.py", + ), ]), diagnostics: Vec::new(), declarations: vec![ - placed("enum:a", "models/_sqlbuild/_enums/both.sql"), - placed("enum:b", "models/_sqlbuild/_enums/both.sql"), - placed("macro:cents", "models/_sqlbuild/_macros/cents.py"), - placed("macro:stays", "models/_sqlbuild/_macros/cents.py"), - placed("macro:generated", "models/_sqlbuild/_macros/gen.py"), + placed("enum:a", "sql/models/_sqlbuild/_enums/both.sql"), + placed("enum:b", "sql/models/_sqlbuild/_enums/both.sql"), + placed("macro:cents", "sql/models/_sqlbuild/_macros/cents.py"), + placed("macro:stays", "sql/models/_sqlbuild/_macros/cents.py"), + placed("macro:generated", "sql/models/_sqlbuild/_macros/gen.py"), ], }, expected_moves: &[ ( - "models/_sqlbuild/_enums/both.sql", - "models/marts/_sqlbuild/_enums/both.sql", + "sql/models/_sqlbuild/_enums/both.sql", + "sql/models/marts/_sqlbuild/_enums/both.sql", ), ( - "models/_sqlbuild/_macros/cents.py", - "models/marts/_sqlbuild/_macros/cents.py", + "sql/models/_sqlbuild/_macros/cents.py", + "sql/models/marts/_sqlbuild/_macros/cents.py", ), ], expected_blocking: &[ - "models/_sqlbuild/_enums/both.sql:1 models/_sqlbuild/_enums/both.sql holds declarations that must move to different folders (models/marts/_sqlbuild/_enums/both.sql, models/other/_sqlbuild/_enums/both.sql); split the file first", - "models/_sqlbuild/_macros/gen.py:1 macro:generated must move to models/marts/_sqlbuild/_macros/gen.py, but it is not an authored project file", - "models/_sqlbuild/_macros/cents.py:1 models/marts/_sqlbuild/_macros/cents.py would take macro:stays along, which must stay in models/_sqlbuild/_macros/cents.py; split the file first", - "models/marts/_sqlbuild/_enums/both.sql:0 a declaration must move here, but the file already exists", + "sql/models/_sqlbuild/_enums/both.sql:1 sql/models/_sqlbuild/_enums/both.sql holds declarations that must move to different folders (sql/models/marts/_sqlbuild/_enums/both.sql, sql/models/other/_sqlbuild/_enums/both.sql); split the file first", + "sql/models/_sqlbuild/_macros/gen.py:1 macro:generated must move to sql/models/marts/_sqlbuild/_macros/gen.py, but it is not an authored project file", + "sql/models/_sqlbuild/_macros/cents.py:1 sql/models/marts/_sqlbuild/_macros/cents.py would take macro:stays along, which must stay in sql/models/_sqlbuild/_macros/cents.py; split the file first", + "sql/models/marts/_sqlbuild/_enums/both.sql:0 a declaration must move here, but the file already exists", ], }, DeclarationMovesTestCase { description: "two grouped files flattened into one direct file block", on_disk: &[ - ("models/_sqlbuild/_macros/money/helpers.sql", "x"), - ("models/_sqlbuild/_macros/text/helpers.sql", "x"), + ("sql/models/_sqlbuild/_macros/money/helpers.sql", "x"), + ("sql/models/_sqlbuild/_macros/text/helpers.sql", "x"), ], - moves: &[("models/orders.sql", "models/marts/orders.sql")], + moves: &[("sql/models/orders.sql", "sql/models/marts/orders.sql")], placement: DeclarationPlacement { relocated: Some(vec![ - relocated("macro:cents", "macros/helpers.sql"), - relocated("macro:label", "macros/helpers.sql"), + relocated("macro:cents", "sql/macros/helpers.sql"), + relocated("macro:label", "sql/macros/helpers.sql"), ]), diagnostics: Vec::new(), declarations: vec![ - placed("macro:cents", "models/_sqlbuild/_macros/money/helpers.sql"), - placed("macro:label", "models/_sqlbuild/_macros/text/helpers.sql"), + placed( + "macro:cents", + "sql/models/_sqlbuild/_macros/money/helpers.sql", + ), + placed( + "macro:label", + "sql/models/_sqlbuild/_macros/text/helpers.sql", + ), ], }, expected_moves: &[ ( - "models/_sqlbuild/_macros/money/helpers.sql", - "macros/helpers.sql", + "sql/models/_sqlbuild/_macros/money/helpers.sql", + "sql/macros/helpers.sql", ), ( - "models/_sqlbuild/_macros/text/helpers.sql", - "macros/helpers.sql", + "sql/models/_sqlbuild/_macros/text/helpers.sql", + "sql/macros/helpers.sql", ), ], expected_blocking: &[ - "macros/helpers.sql:0 models/_sqlbuild/_macros/money/helpers.sql and \ - models/_sqlbuild/_macros/text/helpers.sql would both move to macros/helpers.sql; \ + "sql/macros/helpers.sql:0 sql/models/_sqlbuild/_macros/money/helpers.sql and \ + sql/models/_sqlbuild/_macros/text/helpers.sql would both move to sql/macros/helpers.sql; \ rename one of them first", ], }, DeclarationMovesTestCase { description: "two moved models' same-named local files sharing one target block", on_disk: &[ - ("models/sales/_sqlbuild/_macros/helpers.sql", "x"), - ("models/crm/_sqlbuild/_macros/helpers.sql", "x"), + ("sql/models/sales/_sqlbuild/_macros/helpers.sql", "x"), + ("sql/models/crm/_sqlbuild/_macros/helpers.sql", "x"), ], moves: &[ - ("models/sales/orders.sql", "models/marts/orders.sql"), - ("models/crm/customers.sql", "models/marts/customers.sql"), + ("sql/models/sales/orders.sql", "sql/models/marts/orders.sql"), + ( + "sql/models/crm/customers.sql", + "sql/models/marts/customers.sql", + ), ], placement: DeclarationPlacement { relocated: Some(vec![ - relocated("macro:cents", "models/marts/_sqlbuild/_macros/helpers.sql"), - relocated("macro:label", "models/marts/_sqlbuild/_macros/helpers.sql"), + relocated( + "macro:cents", + "sql/models/marts/_sqlbuild/_macros/helpers.sql", + ), + relocated( + "macro:label", + "sql/models/marts/_sqlbuild/_macros/helpers.sql", + ), ]), diagnostics: Vec::new(), declarations: vec![ - placed("macro:cents", "models/sales/_sqlbuild/_macros/helpers.sql"), - placed("macro:label", "models/crm/_sqlbuild/_macros/helpers.sql"), + placed( + "macro:cents", + "sql/models/sales/_sqlbuild/_macros/helpers.sql", + ), + placed( + "macro:label", + "sql/models/crm/_sqlbuild/_macros/helpers.sql", + ), ], }, expected_moves: &[ ( - "models/crm/_sqlbuild/_macros/helpers.sql", - "models/marts/_sqlbuild/_macros/helpers.sql", + "sql/models/crm/_sqlbuild/_macros/helpers.sql", + "sql/models/marts/_sqlbuild/_macros/helpers.sql", ), ( - "models/sales/_sqlbuild/_macros/helpers.sql", - "models/marts/_sqlbuild/_macros/helpers.sql", + "sql/models/sales/_sqlbuild/_macros/helpers.sql", + "sql/models/marts/_sqlbuild/_macros/helpers.sql", ), ], - expected_blocking: &["models/marts/_sqlbuild/_macros/helpers.sql:0 \ - models/crm/_sqlbuild/_macros/helpers.sql and \ - models/sales/_sqlbuild/_macros/helpers.sql would both move to \ - models/marts/_sqlbuild/_macros/helpers.sql; rename one of them first"], + expected_blocking: &["sql/models/marts/_sqlbuild/_macros/helpers.sql:0 \ + sql/models/crm/_sqlbuild/_macros/helpers.sql and \ + sql/models/sales/_sqlbuild/_macros/helpers.sql would both move to \ + sql/models/marts/_sqlbuild/_macros/helpers.sql; rename one of them first"], }, ]; for test_case in test_cases { @@ -437,7 +470,11 @@ fn given_unit_tests_of_model_when_renaming_or_moving_then_tests_follow() -> Resu }, FollowedUnitTestTestCase { description: "a move takes mirrored tests to the mirrored folder and leaves others", - request: request(RefactorOperation::MoveModel, "", Some("models/finance/")), + request: request( + RefactorOperation::MoveModel, + "", + Some("sql/models/finance/"), + ), rebound: &[], expected_changes: followed_test_changes(&[( "tests/unit/marts/test_orders__keeps_rows.sql -> tests/unit/finance/test_orders__keeps_rows.sql", @@ -447,7 +484,11 @@ fn given_unit_tests_of_model_when_renaming_or_moving_then_tests_follow() -> Resu }, FollowedUnitTestTestCase { description: "a move leaves a test whose declarations would rebind in its folder", - request: request(RefactorOperation::MoveModel, "", Some("models/finance/")), + request: request( + RefactorOperation::MoveModel, + "", + Some("sql/models/finance/"), + ), rebound: &["macro:mock_orders"], expected_changes: Vec::new(), expected_notes: &[ @@ -459,7 +500,7 @@ fn given_unit_tests_of_model_when_renaming_or_moving_then_tests_follow() -> Resu request: request( RefactorOperation::MoveModel, "", - Some("models/finance/order_lines.sql"), + Some("sql/models/finance/order_lines.sql"), ), rebound: &["enum:order_status", "macro:mock_orders"], expected_changes: followed_test_changes(&[ @@ -496,8 +537,8 @@ fn given_several_moves_when_planning_together_then_chains_pass_and_conflicts_blo write_files( project.path(), &[ - ("models/orders.sql", "SELECT 1"), - ("models/customers.sql", "SELECT 1"), + ("sql/models/orders.sql", "SELECT 1"), + ("sql/models/customers.sql", "SELECT 1"), ], )?; let project_facts = facts( @@ -511,57 +552,59 @@ fn given_several_moves_when_planning_together_then_chains_pass_and_conflicts_blo BatchPlanTestCase { description: "a model takes the name another move gives up", requests: vec![ - move_request("orders", "models/customers.sql"), - move_request("customers", "models/clients.sql"), + move_request("orders", "sql/models/customers.sql"), + move_request("customers", "sql/models/clients.sql"), ], - expected_blocking: &["models/customers.sql: model:orders would take the name \ + expected_blocking: &[ + "sql/models/customers.sql: model:orders would take the name \ model:customers gives up in this batch; the old name must \ - stay free for its history, so move them in separate runs"], + stay free for its history, so move them in separate runs", + ], expected_moves: &[ - "models/customers.sql -> models/clients.sql", - "models/orders.sql -> models/customers.sql", + "sql/models/customers.sql -> sql/models/clients.sql", + "sql/models/orders.sql -> sql/models/customers.sql", ], }, BatchPlanTestCase { description: "two models moved to the same file", requests: vec![ - move_request("orders", "models/finance/totals.sql"), - move_request("customers", "models/finance/totals.sql"), + move_request("orders", "sql/models/finance/totals.sql"), + move_request("customers", "sql/models/finance/totals.sql"), ], expected_blocking: &[ - "models/finance/totals.sql: model:orders and model:customers both move to \ - models/finance/totals.sql", + "sql/models/finance/totals.sql: model:orders and model:customers both move to \ + sql/models/finance/totals.sql", ], expected_moves: &[ - "models/orders.sql -> models/finance/totals.sql", - "models/customers.sql -> models/finance/totals.sql", + "sql/models/orders.sql -> sql/models/finance/totals.sql", + "sql/models/customers.sql -> sql/models/finance/totals.sql", ], }, BatchPlanTestCase { description: "one model moved twice", requests: vec![ - move_request("orders", "models/finance/"), - move_request("orders", "models/sales/"), + move_request("orders", "sql/models/finance/"), + move_request("orders", "sql/models/sales/"), ], expected_blocking: &[ - "models/orders.sql: model:orders is moved more than once in \ + "sql/models/orders.sql: model:orders is moved more than once in \ this batch", ], - expected_moves: &["models/orders.sql -> models/sales/orders.sql"], + expected_moves: &["sql/models/orders.sql -> sql/models/sales/orders.sql"], }, BatchPlanTestCase { description: "two models given one name in different folders", requests: vec![ - move_request("orders", "models/finance/totals.sql"), - move_request("customers", "models/sales/totals.sql"), + move_request("orders", "sql/models/finance/totals.sql"), + move_request("customers", "sql/models/sales/totals.sql"), ], expected_blocking: &[ - "models/sales/totals.sql: model:orders and model:customers would both be named \ + "sql/models/sales/totals.sql: model:orders and model:customers would both be named \ totals", ], expected_moves: &[ - "models/orders.sql -> models/finance/totals.sql", - "models/customers.sql -> models/sales/totals.sql", + "sql/models/orders.sql -> sql/models/finance/totals.sql", + "sql/models/customers.sql -> sql/models/sales/totals.sql", ], }, ]; @@ -596,7 +639,7 @@ fn given_pending_migration_when_moving_under_same_name_then_only_relation_moves_ write_files( project.path(), &[( - "models/orders.sql", + "sql/models/orders.sql", "MODEL (materialized table, migrate_from old_orders);\nSELECT 1", )], )?; @@ -608,12 +651,12 @@ fn given_pending_migration_when_moving_under_same_name_then_only_relation_moves_ request: request( RefactorOperation::MoveModel, "orders", - Some("models/finance/orders.sql"), + Some("sql/models/finance/orders.sql"), ), batch: Vec::new(), changes: vec![change( - "models/finance/orders.sql", - "models/orders.sql", + "sql/models/finance/orders.sql", + "sql/models/orders.sql", Vec::new(), )], manual: Vec::new(), @@ -626,7 +669,11 @@ fn given_pending_migration_when_moving_under_same_name_then_only_relation_moves_ let test_cases = [ PendingMigrationTestCase { description: "a same-name move passes the pending-migration refusal", - request: request(RefactorOperation::MoveModel, "", Some("models/finance/")), + request: request( + RefactorOperation::MoveModel, + "", + Some("sql/models/finance/"), + ), after: vec![pending.clone()], expected_refusals: vec![], expected_blocking: vec![], @@ -637,21 +684,25 @@ fn given_pending_migration_when_moving_under_same_name_then_only_relation_moves_ request: request(RefactorOperation::RenameModel, "order_lines", None), after: vec![pending.clone()], expected_refusals: vec![ - "models/orders.sql: model:orders still declares migrate_from; build it on every target and remove migrate_from before renaming it again", + "sql/models/orders.sql: model:orders still declares migrate_from; build it on every target and remove migrate_from before renaming it again", ], expected_blocking: vec![], expected_migration_count: 0, }, PendingMigrationTestCase { description: "a same-name move that changes the relation is blocked", - request: request(RefactorOperation::MoveModel, "", Some("models/finance/")), + request: request( + RefactorOperation::MoveModel, + "", + Some("sql/models/finance/"), + ), after: vec![ model("orders", Some("table"), "finance"), model("customers", Some("table"), "analytics"), ], expected_refusals: vec![], expected_blocking: vec![ - "models/finance/orders.sql: model:orders still declares migrate_from and this move changes its relation; build it on every target and remove migrate_from before moving it again", + "sql/models/finance/orders.sql: model:orders still declares migrate_from and this move changes its relation; build it on every target and remove migrate_from before moving it again", ], expected_migration_count: 0, }, diff --git a/crates/sqlbuild-refactor/src/refactoring/tests/test_text_edits.rs b/crates/sqlbuild-refactor/src/refactoring/tests/test_text_edits.rs index dd51eb9ad5..9709a0a894 100644 --- a/crates/sqlbuild-refactor/src/refactoring/tests/test_text_edits.rs +++ b/crates/sqlbuild-refactor/src/refactoring/tests/test_text_edits.rs @@ -147,11 +147,11 @@ fn given_offset_when_locating_then_line_and_column_are_one_based() { fn given_edits_and_moves_when_grouping_then_changes_follow_final_paths() { let test_cases = [FileChangesTestCase { description: "a moved file's edits follow it and paths are sorted", - edited_paths: &["models/b.sql", "models/a.sql"], - moves: &[("models/b.sql", "models/z/b.sql")], + edited_paths: &["sql/models/b.sql", "sql/models/a.sql"], + moves: &[("sql/models/b.sql", "sql/models/z/b.sql")], expected_changes: &[ - ("models/a.sql", "models/a.sql", 1), - ("models/z/b.sql", "models/b.sql", 1), + ("sql/models/a.sql", "sql/models/a.sql", 1), + ("sql/models/z/b.sql", "sql/models/b.sql", 1), ], }]; for test_case in test_cases { diff --git a/crates/sqlbuild-rules/Cargo.toml b/crates/sqlbuild-rules/Cargo.toml index 5503cadb5d..cd31ad35c2 100644 --- a/crates/sqlbuild-rules/Cargo.toml +++ b/crates/sqlbuild-rules/Cargo.toml @@ -15,6 +15,7 @@ fensu-policy.workspace = true globset.workspace = true sqlquack-parse.workspace = true sqlquack-syntax.workspace = true +sqlquack-tokenize.workspace = true rayon.workspace = true regex.workspace = true rustc-hash.workspace = true diff --git a/crates/sqlbuild-rules/src/custom_host_pool/tests/test_custom_host_pool.rs b/crates/sqlbuild-rules/src/custom_host_pool/tests/test_custom_host_pool.rs index d6a75dd132..caf270e3db 100644 --- a/crates/sqlbuild-rules/src/custom_host_pool/tests/test_custom_host_pool.rs +++ b/crates/sqlbuild-rules/src/custom_host_pool/tests/test_custom_host_pool.rs @@ -107,24 +107,24 @@ fn given_planned_invocations_when_partitioning_then_split_is_deterministic() { plan: plan(&[ ("XSQBRT101", None), ("XSQBRT102", None), - ("XSQBRT103", Some(&["models/b.sql"])), + ("XSQBRT103", Some(&["sql/models/b.sql"])), ]), invocations: invocations(&[ ("XSQBRT102", ""), - ("XSQBRT101", "models/a.sql"), - ("XSQBRT101", "models/b.sql"), - ("XSQBRT103", "models/b.sql"), - ("XSQBRT101", "models/c.sql"), + ("XSQBRT101", "sql/models/a.sql"), + ("XSQBRT101", "sql/models/b.sql"), + ("XSQBRT103", "sql/models/b.sql"), + ("XSQBRT101", "sql/models/c.sql"), ]), hosts: 2, expected_plans: vec![ plan(&[ - ("XSQBRT101", Some(&["models/b.sql"])), + ("XSQBRT101", Some(&["sql/models/b.sql"])), ("XSQBRT102", Some(&[""])), - ("XSQBRT103", Some(&["models/b.sql"])), + ("XSQBRT103", Some(&["sql/models/b.sql"])), ]), plan(&[ - ("XSQBRT101", Some(&["models/a.sql", "models/c.sql"])), + ("XSQBRT101", Some(&["sql/models/a.sql", "sql/models/c.sql"])), ("XSQBRT102", Some(&[])), ("XSQBRT103", Some(&[])), ]), @@ -133,7 +133,7 @@ fn given_planned_invocations_when_partitioning_then_split_is_deterministic() { HostPlanTestCase { description: "one subject keeps the original plan", plan: plan(&[("XSQBRT101", None)]), - invocations: invocations(&[("XSQBRT101", "models/a.sql")]), + invocations: invocations(&[("XSQBRT101", "sql/models/a.sql")]), hosts: 4, expected_plans: vec![plan(&[("XSQBRT101", None)])], }, @@ -206,7 +206,7 @@ fn given_host_response_when_decoding_then_slice_or_rules_error_is_returned() { "readsets": [[["project.models"]]], "evaluations": [ {"code": "R1", "subject": null, "findings": [{"message": "m"}], "reads": 0}, - {"code": "R2", "subject": "models/a.sql", "findings": [], "reads": 0}, + {"code": "R2", "subject": "sql/models/a.sql", "findings": [], "reads": 0}, ], "untracked": {"R2": [["tree.paths"]]}, "uncacheable": ["R3"], @@ -221,7 +221,7 @@ fn given_host_response_when_decoding_then_slice_or_rules_error_is_returned() { findings: vec![json!({"message": "m"})], ..evaluation("R1", "", Some(&[&["project.models"]])) }, - evaluation("R2", "models/a.sql", None), + evaluation("R2", "sql/models/a.sql", None), ], untracked_reads: BTreeMap::from([( "R2".to_owned(), diff --git a/crates/sqlbuild-rules/src/custom_rule_cache/tests/helpers.rs b/crates/sqlbuild-rules/src/custom_rule_cache/tests/helpers.rs index a90e902d58..80d0fb4507 100644 --- a/crates/sqlbuild-rules/src/custom_rule_cache/tests/helpers.rs +++ b/crates/sqlbuild-rules/src/custom_rule_cache/tests/helpers.rs @@ -26,12 +26,12 @@ pub(crate) fn project(model_name: &str) -> SubjectsInput { target_name: Some("dev".to_owned()), models: vec![ ModelSubjectInput { - path: "models/orders.sql".to_owned(), + path: "sql/models/orders.sql".to_owned(), name: model_name.to_owned(), materialized: None, }, ModelSubjectInput { - path: "models/customers.sql".to_owned(), + path: "sql/models/customers.sql".to_owned(), name: "customers".to_owned(), materialized: Some("table".to_owned()), }, diff --git a/crates/sqlbuild-rules/src/custom_rule_cache/tests/test_custom_rule_cache.rs b/crates/sqlbuild-rules/src/custom_rule_cache/tests/test_custom_rule_cache.rs index 8f306ff3ac..679b891289 100644 --- a/crates/sqlbuild-rules/src/custom_rule_cache/tests/test_custom_rule_cache.rs +++ b/crates/sqlbuild-rules/src/custom_rule_cache/tests/test_custom_rule_cache.rs @@ -75,7 +75,7 @@ fn given_stored_results_when_looking_up_then_unchanged_subjects_and_reads_hit() description: "a renamed model misses only that subject", current_digest: "digest-a", model_name: "orders_v2", - expected_plan: vec![("CUSTOM001", Some(vec!["models/orders.sql"]))], + expected_plan: vec![("CUSTOM001", Some(vec!["sql/models/orders.sql"]))], expected_hits: 1, }, ]; diff --git a/crates/sqlbuild-rules/src/engine/tests/helpers.rs b/crates/sqlbuild-rules/src/engine/tests/helpers.rs index 878e4ba729..592a9d3a16 100644 --- a/crates/sqlbuild-rules/src/engine/tests/helpers.rs +++ b/crates/sqlbuild-rules/src/engine/tests/helpers.rs @@ -30,7 +30,7 @@ pub(crate) fn request(project_dir: &TempDir, config: &Value) -> String { "config": config, "models": [{ "name": "commerce__mart__orders", - "relative_path": "models/mart/commerce__mart__orders.sql", + "relative_path": "sql/models/mart/commerce__mart__orders.sql", "query_sql": "SELECT * FROM orders", "authored_sql": "SELECT * FROM orders" }] @@ -77,9 +77,9 @@ pub(crate) fn scope_with_macros(paths: &[String]) -> Value { .iter() .enumerate() .map(|(index, path)| { - let relative = path.trim_start_matches("models/commerce/_macros/"); + let relative = path.trim_start_matches("sql/models/commerce/_macros/"); let relative = relative - .strip_prefix("python/") + .strip_prefix("python/nodes/") .or_else(|| relative.strip_prefix("sql/")) .unwrap_or(relative); let bucket_path = std::path::Path::new(relative) @@ -97,10 +97,10 @@ pub(crate) fn scope_with_macros(paths: &[String]) -> Value { "scope": "local", "role": "macros", "visibility": "exact_owner_private", - "role_root": "models/commerce/_macros", + "role_root": "sql/models/commerce/_macros", "bucket_path": bucket_path, - "ownership_root": "models", - "owning_path": "models/race", + "ownership_root": "sql/models", + "owning_path": "sql/models/race", "metadata": {"macro": { "parameters": [], "dependencies": [], @@ -127,7 +127,7 @@ pub(crate) fn threshold_request( "config": config, "models": [{ "name": "commerce__mart__orders", - "relative_path": "models/mart/commerce__mart__orders.sql", + "relative_path": "sql/models/mart/commerce__mart__orders.sql", "query_sql": query_sql, "authored_sql": query_sql, "references": references, @@ -146,8 +146,8 @@ pub(crate) fn scope_index() -> Value { "identity": "model:orders", "kind": "model", "name": "orders", - "path": "models/orders.sql", - "ownership_root": "models", + "path": "sql/models/orders.sql", + "ownership_root": "sql/models", "ownership_root_kind": "model" }], "declarations": [{ @@ -155,7 +155,7 @@ pub(crate) fn scope_index() -> Value { "kind": "enum", "name": "status", "owner": null, - "path": "enums/status.sql", + "path": "sql/enums/status.sql", "line": 1, "column": 1, "scope": "global", @@ -163,7 +163,7 @@ pub(crate) fn scope_index() -> Value { "visibility": "project", "role_root": "enums", "bucket_path": null, - "ownership_root": "enums", + "ownership_root": "sql/enums", "owning_path": null, "metadata": {"enum": { "members": [{"name": "OPEN"}], @@ -174,7 +174,7 @@ pub(crate) fn scope_index() -> Value { "kind": "macro", "name": "normalize_status", "owner": null, - "path": "macros/normalize_status.py", + "path": "sql/macros/normalize_status.py", "line": 1, "column": 1, "scope": "global", @@ -182,7 +182,7 @@ pub(crate) fn scope_index() -> Value { "visibility": "project", "role_root": "macros", "bucket_path": null, - "ownership_root": "macros", + "ownership_root": "sql/macros", "owning_path": null, "metadata": {"macro": { "parameters": ["status"], @@ -295,7 +295,7 @@ pub(crate) fn cached_sql_test_rules_request(project_dir: &TempDir, name: Option< "project_dir": project_dir.path(), "config": {"select": ["SQBRTEST104"], "cache": {"enabled": true}}, "models": [{ - "name": "orders", "relative_path": "models/orders.sql", + "name": "orders", "relative_path": "sql/models/orders.sql", "query_sql": "SELECT 1", "authored_sql": "SELECT 1" }], "sql_tests": [sql_test_fact( @@ -369,7 +369,7 @@ pub(crate) fn dialect_empty_input_rule_evaluation( }, "models": [{ "name": "orders", - "relative_path": "models/orders.sql", + "relative_path": "sql/models/orders.sql", "query_sql": "SELECT order_id, amount * 2 AS doubled_amount FROM raw_orders", "authored_sql": "SELECT order_id, amount * 2 AS doubled_amount FROM raw_orders", "targeting_test_count": tests.as_array().map_or(0, Vec::len) @@ -438,15 +438,15 @@ pub(crate) fn orders_model(path: &str, query: &str) -> Value { pub(crate) fn orders_models() -> Vec { vec![ orders_model( - "models/commerce/mart/commerce__mart__orders.sql", + "sql/models/commerce/mart/commerce__mart__orders.sql", "SELECT * FROM warehouse.raw.orders", ), orders_model( - "models/commerce/mart/commerce__mart__customers.sql", + "sql/models/commerce/mart/commerce__mart__customers.sql", "WITH customers AS (SELECT 1 AS customer_id) SELECT customer_id FROM customers", ), orders_model( - "models/commerce/staging/commerce__stg__products.sql", + "sql/models/commerce/staging/commerce__stg__products.sql", "SELECT product_id, 1 AS quantity FROM products WHERE status = 3", ), ] @@ -525,7 +525,7 @@ pub(crate) const SPECULATIVE_CACHE_FILE: &str = "target/rules-cache/bulk/native. pub(crate) const SPECULATIVE_PYTHON_CACHE_FILE: &str = "target/rules-cache/bulk/python.json"; /// A project Python file with an unannotated parameter, so the Python rules write their cache. const SPECULATIVE_PYTHON_FILE: (&str, &str) = ( - "hooks/python/notify.py", + "sql/hooks/python/notify.py", "def send(count) -> None:\n pass\n", ); const SPECULATIVE_MEMO_FILE: &str = "target/rules-cache/bulk/native-response.json"; @@ -699,7 +699,7 @@ pub(crate) fn restored_rows(retained: &RetainedRows) -> Result Model { let declaration: Declaration = Declaration { name: "status".to_owned(), - relative_path: "enums/status.sql".to_owned(), + relative_path: "sql/enums/status.sql".to_owned(), members: vec![DeclarationMember { name: "open".to_owned(), value: json!({"code": 1, "ratio": -0.25, "tags": ["a", null, true]}), @@ -711,7 +711,7 @@ pub(crate) fn every_field_model() -> Model { Model { sql_analysis_disabled: true, name: "orders".to_owned(), - relative_path: "models/orders.sql".to_owned(), + relative_path: "sql/models/orders.sql".to_owned(), query_sql: "SELECT 1".to_owned(), authored_sql: "SELECT 1 -- authored".to_owned(), config: BTreeMap::from([ @@ -801,7 +801,7 @@ fn published_model(name: &str, references: &[&str]) -> Value { let domain: &str = name.split("__").next().unwrap_or_default(); json!({ "name": name, - "relative_path": format!("models/{domain}/mart/{name}.sql"), + "relative_path": format!("sql/models/{domain}/mart/{name}.sql"), "query_sql": "SELECT 1", "authored_sql": "SELECT 1", "references": references @@ -848,7 +848,7 @@ pub(crate) fn published_layer_faults( } /// The model path the relation-exception cases use. -pub(crate) const CROSS_JOIN_MODEL_PATH: &str = "models/orders.sql"; +pub(crate) const CROSS_JOIN_MODEL_PATH: &str = "sql/models/orders.sql"; /// The Rule whose findings name a joined relation. pub(crate) const CROSS_JOIN_CODE: &str = "SQLCLEAN038"; @@ -867,7 +867,7 @@ fn cross_join_fault(message: &str, line: u64) -> Fault { /// Finalize a top-level `order_policy` join and a `customers` join in CTE `checks`. pub(crate) fn finalize_cross_joins(exceptions: Value) -> Result, String> { let project_dir = TempDir::new().map_err(|error| error.to_string())?; - std::fs::create_dir_all(project_dir.path().join("models")) + std::fs::create_dir_all(project_dir.path().join("sql/models")) .map_err(|error| error.to_string())?; std::fs::write(project_dir.path().join(CROSS_JOIN_MODEL_PATH), "SELECT 1") .map_err(|error| error.to_string())?; diff --git a/crates/sqlbuild-rules/src/engine/tests/test_domain_layout.rs b/crates/sqlbuild-rules/src/engine/tests/test_domain_layout.rs index 40b6061f83..4a4193f8a4 100644 --- a/crates/sqlbuild-rules/src/engine/tests/test_domain_layout.rs +++ b/crates/sqlbuild-rules/src/engine/tests/test_domain_layout.rs @@ -9,19 +9,20 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau -> Result<(), String> { install_test_identity(); let oversized_paths: Vec = (0..11) - .map(|index| format!("models/commerce/_macros/item_{index}.py")) + .map(|index| format!("sql/models/commerce/_macros/item_{index}.py")) .collect(); let repeated_paths: Vec = (0..11) - .map(|_| "models/commerce/_macros/orders.py".to_owned()) + .map(|_| "sql/models/commerce/_macros/orders.py".to_owned()) .collect(); let python_and_sql: Vec = (0..6) - .map(|index| format!("models/commerce/_macros/python/normalise/item_{index}.py")) + .map(|index| format!("sql/models/commerce/_macros/python/normalise/item_{index}.py")) .chain( - (0..7).map(|index| format!("models/commerce/_macros/sql/normalise/item_{index}.sql")), + (0..7) + .map(|index| format!("sql/models/commerce/_macros/sql/normalise/item_{index}.sql")), ) .collect(); let oversized_sql: Vec = (0..11) - .map(|index| format!("models/commerce/_macros/sql/normalise/item_{index}.sql")) + .map(|index| format!("sql/models/commerce/_macros/sql/normalise/item_{index}.sql")) .collect(); let test_cases = [ test_types::DomainLayoutTestCase { @@ -44,7 +45,7 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau scope_index: helpers::scope_with_macros(&oversized_sql), expected_codes: &["SQBRDECLARATION304"], expected_message_fragments: &[ - "declaration container \"models/commerce/_macros/sql/normalise\" has 11 files", + "declaration container \"sql/models/commerce/_macros/sql/normalise\" has 11 files", ], expected_absent_fragments: &[], }, @@ -55,8 +56,8 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau thresholds: json!({}), layout: json!({}), scope_index: helpers::scope_with_macros(&[ - "models/commerce/_macros/python/normalise_order.py".into(), - "models/commerce/_macros/sql/normalise_person.sql".into(), + "sql/models/commerce/_macros/python/normalise_order.py".into(), + "sql/models/commerce/_macros/sql/normalise_person.sql".into(), ]), expected_codes: &[], expected_message_fragments: &[], @@ -69,13 +70,13 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau thresholds: json!({}), layout: json!({}), scope_index: helpers::scope_with_macros(&[ - "models/commerce/_macros/sql/normalise_order.sql".into(), - "models/commerce/_macros/sql/normalise_person.sql".into(), + "sql/models/commerce/_macros/sql/normalise_order.sql".into(), + "sql/models/commerce/_macros/sql/normalise_person.sql".into(), ]), expected_codes: &["SQBRDECLARATION306"], expected_message_fragments: &[ "2 sibling SQL macro files", - "Move these files into models/commerce/_macros/sql/normalise/", + "Move these files into sql/models/commerce/_macros/sql/normalise/", "each macro keeps its name", ], expected_absent_fragments: &[], @@ -84,8 +85,8 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau description: "leaf and branch models fault", code: "SQBRPROJECT202", models: json!([ - helpers::model("models/commerce/mart/summary.sql"), - helpers::model("models/commerce/mart/orders/model.sql") + helpers::model("sql/models/commerce/mart/summary.sql"), + helpers::model("sql/models/commerce/mart/orders/model.sql") ]), thresholds: json!({}), layout: json!({}), @@ -98,7 +99,7 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau description: "default owner depth faults", code: "SQBRPROJECT203", models: json!([helpers::model( - "models/commerce/intermediate/enriched/order/clusters_resolved/model.sql" + "sql/models/commerce/intermediate/enriched/order/clusters_resolved/model.sql" )]), thresholds: json!({}), layout: json!({}), @@ -111,7 +112,7 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau description: "configured owner depth passes", code: "SQBRPROJECT203", models: json!([helpers::model( - "models/commerce/intermediate/enriched/order/clusters_resolved/model.sql" + "sql/models/commerce/intermediate/enriched/order/clusters_resolved/model.sql" )]), thresholds: json!({"max_subdomain_depth": 2}), layout: json!({}), @@ -124,8 +125,8 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau description: "longest unary owner prefix faults", code: "SQBRPROJECT204", models: json!([ - helpers::model("models/commerce/mart/order_status/model.sql"), - helpers::model("models/commerce/mart/order_status_history/model.sql") + helpers::model("sql/models/commerce/mart/order_status/model.sql"), + helpers::model("sql/models/commerce/mart/order_status_history/model.sql") ]), thresholds: json!({}), layout: json!({}), @@ -138,9 +139,9 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau description: "each branching owner prefix faults", code: "SQBRPROJECT204", models: json!([ - helpers::model("models/crm/mart/partner_annotation_export/model.sql"), - helpers::model("models/crm/mart/partner_annotation_validation/model.sql"), - helpers::model("models/crm/mart/partner_events/model.sql") + helpers::model("sql/models/crm/mart/partner_annotation_export/model.sql"), + helpers::model("sql/models/crm/mart/partner_annotation_validation/model.sql"), + helpers::model("sql/models/crm/mart/partner_events/model.sql") ]), thresholds: json!({}), layout: json!({}), @@ -156,8 +157,8 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau thresholds: json!({}), layout: json!({}), scope_index: helpers::scope_with_macros(&[ - "models/commerce/_macros/direct.py".into(), - "models/commerce/_macros/scoring/grouped.py".into(), + "sql/models/commerce/_macros/direct.py".into(), + "sql/models/commerce/_macros/scoring/grouped.py".into(), ]), expected_codes: &["SQBRDECLARATION302"], expected_message_fragments: &[], @@ -170,7 +171,7 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau thresholds: json!({}), layout: json!({}), scope_index: helpers::scope_with_macros(&[ - "models/commerce/_macros/scoring/candidates/item.py".into(), + "sql/models/commerce/_macros/scoring/candidates/item.py".into(), ]), expected_codes: &["SQBRDECLARATION303"], expected_message_fragments: &[], @@ -205,7 +206,7 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau thresholds: json!({}), layout: json!({}), scope_index: helpers::scope_with_macros(&[ - "models/commerce/_macros/utils/item.py".into() + "sql/models/commerce/_macros/utils/item.py".into() ]), expected_codes: &["SQBRDECLARATION305"], expected_message_fragments: &[], @@ -218,8 +219,8 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau thresholds: json!({}), layout: json!({}), scope_index: helpers::scope_with_macros(&[ - "models/commerce/_macros/normalise_order.py".into(), - "models/commerce/_macros/normalise_person.py".into(), + "sql/models/commerce/_macros/normalise_order.py".into(), + "sql/models/commerce/_macros/normalise_person.py".into(), ]), expected_codes: &["SQBRDECLARATION306"], expected_message_fragments: &["normalise"], @@ -228,7 +229,7 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau test_types::DomainLayoutTestCase { description: "model outside configured levels faults", code: "SQBRPROJECT201", - models: json!([helpers::model("models/commerce/unknown/model.sql")]), + models: json!([helpers::model("sql/models/commerce/unknown/model.sql")]), thresholds: json!({}), layout: json!({}), scope_index: helpers::scope_index(), @@ -240,8 +241,8 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau description: "implicit domain grouping prefix faults", code: "SQBRPROJECT204", models: json!([ - helpers::model("models/partner_annotation_export/mart/model.sql"), - helpers::model("models/partner_annotation_validation/mart/model.sql") + helpers::model("sql/models/partner_annotation_export/mart/model.sql"), + helpers::model("sql/models/partner_annotation_validation/mart/model.sql") ]), thresholds: json!({}), layout: json!({}), @@ -253,7 +254,7 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau test_types::DomainLayoutTestCase { description: "ambiguous inferred domain root faults", code: "SQBRPROJECT201", - models: json!([helpers::model("models/commerce/staging/mart/model.sql")]), + models: json!([helpers::model("sql/models/commerce/staging/mart/model.sql")]), thresholds: json!({}), layout: json!({}), scope_index: helpers::scope_index(), @@ -264,7 +265,9 @@ fn given_owner_and_declaration_layouts_when_evaluating_then_returns_expected_fau test_types::DomainLayoutTestCase { description: "explicit nested domain root resolves", code: "SQBRPROJECT201", - models: json!([helpers::model("models/commerce/orders/mart/core/model.sql")]), + models: json!([helpers::model( + "sql/models/commerce/orders/mart/core/model.sql" + )]), thresholds: json!({}), layout: json!({"levels": ["mart"], "domain_roots": ["commerce/orders"]}), scope_index: helpers::scope_index(), diff --git a/crates/sqlbuild-rules/src/engine/tests/test_empty_input_tests.rs b/crates/sqlbuild-rules/src/engine/tests/test_empty_input_tests.rs index 492206bde4..118716a8d1 100644 --- a/crates/sqlbuild-rules/src/engine/tests/test_empty_input_tests.rs +++ b/crates/sqlbuild-rules/src/engine/tests/test_empty_input_tests.rs @@ -340,7 +340,7 @@ fn given_empty_input_only_tests_when_evaluating_minimum_tests_then_they_do_not_c tests: json!([helpers::filler_test()]), allowed_tests: json!([]), expected_messages: &[ - "SQBRTEST202 models/orders.sql: model \"orders\" has 0 tests; 1 required (1 empty-input-only test not counted; see SQBRTEST203)", + "SQBRTEST202 sql/models/orders.sql: model \"orders\" has 0 tests; 1 required (1 empty-input-only test not counted; see SQBRTEST203)", ], }, test_types::EmptyInputMinimumTestsTestCase { @@ -394,7 +394,7 @@ fn given_cached_minimum_tests_when_filler_becomes_real_test_then_model_cache_is_ tests: json!([helpers::filler_test()]), allowed_tests: json!([]), expected_messages: &[ - "SQBRTEST202 models/orders.sql: model \"orders\" has 0 tests; 1 required (1 empty-input-only test not counted; see SQBRTEST203)", + "SQBRTEST202 sql/models/orders.sql: model \"orders\" has 0 tests; 1 required (1 empty-input-only test not counted; see SQBRTEST203)", ], }, test_types::EmptyInputMinimumTestsTestCase { diff --git a/crates/sqlbuild-rules/src/engine/tests/test_evaluation.rs b/crates/sqlbuild-rules/src/engine/tests/test_evaluation.rs index 5c1148a44d..3cf15799eb 100644 --- a/crates/sqlbuild-rules/src/engine/tests/test_evaluation.rs +++ b/crates/sqlbuild-rules/src/engine/tests/test_evaluation.rs @@ -151,7 +151,7 @@ fn given_conflicting_model_identity_when_evaluating_layer_rules_then_reports_ind .map_err(|error| error.to_string())?; request["models"][0] = json!({ "name": "commerce__mart_v__int_v_orders", - "relative_path": "models/commerce/intermediate/enriched/orders/commerce__mart_v__int_v_orders.sql", + "relative_path": "sql/models/commerce/intermediate/enriched/orders/commerce__mart_v__int_v_orders.sql", "query_sql": "SELECT 1 AS order_id", "authored_sql": "SELECT 1 AS order_id", "config": {"materialized": "table", "schema": "staging"}, @@ -183,7 +183,7 @@ fn given_internal_dependency_edges_when_evaluating_graph_rule_then_only_exact_li let models = json!([ { "name": "commerce__stg__orders", - "relative_path": "models/commerce/staging/commerce__stg__orders.sql", + "relative_path": "sql/models/commerce/staging/commerce__stg__orders.sql", "query_sql": "SELECT 1", "authored_sql": "SELECT 1", "references": [ @@ -193,14 +193,14 @@ fn given_internal_dependency_edges_when_evaluating_graph_rule_then_only_exact_li }, { "name": "commerce__int_clean__orders", - "relative_path": "models/commerce/intermediate/clean/commerce__int_clean__orders.sql", + "relative_path": "sql/models/commerce/intermediate/clean/commerce__int_clean__orders.sql", "query_sql": "SELECT 1", "authored_sql": "SELECT 1", "references": [{"ref_kind": "ref", "ref_name": "commerce__int_enriched__customers"}] }, { "name": "commerce__mart__summary", - "relative_path": "models/commerce/mart/commerce__mart__summary.sql", + "relative_path": "sql/models/commerce/mart/commerce__mart__summary.sql", "query_sql": "SELECT 1", "authored_sql": "SELECT 1", "references": [{"ref_kind": "ref", "ref_name": "commerce__int_enriched__orders"}] @@ -286,7 +286,7 @@ fn given_repeated_native_evaluation_when_faulting_then_returns_deterministic_com }), expected_faults: json!([{ "code": "SQBRCONTRACT101", - "path": "models/mart/commerce__mart__orders.sql", + "path": "sql/models/mart/commerce__mart__orders.sql", "line": 1, "column": 1, "message": "models must declare an enforced output contract", @@ -400,7 +400,7 @@ fn given_scoped_suppression_when_evaluating_native_fault_then_returns_no_faults( "cache": {"enabled": false}, "rule_ignores": [{ "rules": ["SQBRCONTRACT"], - "paths": ["models/mart/**"], + "paths": ["sql/models/mart/**"], "reason": "Tracked migration" }] }), @@ -443,12 +443,12 @@ fn given_declaration_only_project_when_evaluating_project_rule_then_rule_still_r request["public_enums"] = json!([ { "name": "order_status", - "relative_path": "enums/orders/order_status.sql", + "relative_path": "sql/enums/orders/order_status.sql", "members": [{"name": "OPEN", "value": "open"}] }, { "name": "support_status", - "relative_path": "enums/support/support_status.sql", + "relative_path": "sql/enums/support/support_status.sql", "members": [{"name": "OPEN", "value": "open"}] } ]); @@ -485,7 +485,7 @@ fn given_scoped_and_global_declarations_when_evaluating_domain_rule_then_only_gl test_types::DeclarationScopeTestCase { description: "global declaration without domain remains in policy", scope: "global", - path: "enums/status.sql", + path: "sql/enums/status.sql", expected_fault_count: 1, }, ]; @@ -1354,7 +1354,7 @@ fn given_path_threshold_overrides_when_evaluating_then_matches_in_authored_order "select": ["SQBRTEST201", "SQBRTEST202"], "thresholds": {"min_audits_per_model": 1, "min_tests_per_model": 1}, "threshold_overrides": [{ - "paths": ["models/mart/**"], + "paths": ["sql/models/mart/**"], "thresholds": {"min_audits_per_model": 2, "min_tests_per_model": 2}, "reason": "marts require stronger evidence" }], @@ -1370,7 +1370,7 @@ fn given_path_threshold_overrides_when_evaluating_then_matches_in_authored_order "select": ["SQBRTEST201", "SQBRTEST202"], "thresholds": {"min_audits_per_model": 1, "min_tests_per_model": 1}, "threshold_overrides": [{ - "paths": ["models/staging/**"], + "paths": ["sql/models/staging/**"], "thresholds": {"min_audits_per_model": 2, "min_tests_per_model": 2}, "reason": "staging requires stronger evidence" }], @@ -1387,12 +1387,12 @@ fn given_path_threshold_overrides_when_evaluating_then_matches_in_authored_order "thresholds": {"min_audits_per_model": 1, "min_tests_per_model": 1}, "threshold_overrides": [ { - "paths": ["models/**"], + "paths": ["sql/models/**"], "thresholds": {"min_audits_per_model": 2, "min_tests_per_model": 2}, "reason": "all models require stronger evidence" }, { - "paths": ["models/mart/**"], + "paths": ["sql/models/mart/**"], "thresholds": {"min_audits_per_model": 1, "min_tests_per_model": 1}, "reason": "mart migration temporarily uses global minima" } @@ -1409,7 +1409,7 @@ fn given_path_threshold_overrides_when_evaluating_then_matches_in_authored_order "select": ["SQBRTEST201", "SQBRTEST202"], "thresholds": {"min_audits_per_model": 1, "min_tests_per_model": 1}, "threshold_overrides": [{ - "paths": ["models/mart/**"], + "paths": ["sql/models/mart/**"], "thresholds": {"min_audits_per_model": 2}, "reason": "marts require an additional audit" }], @@ -1424,7 +1424,7 @@ fn given_path_threshold_overrides_when_evaluating_then_matches_in_authored_order config: json!({ "select": ["SQBRTEST201", "SQBRTEST202"], "threshold_overrides": [{ - "paths": ["models/mart/**"], + "paths": ["sql/models/mart/**"], "thresholds": {"min_audits_per_model": 10, "min_tests_per_model": 10}, "reason": "marts require strong evidence" }], @@ -1470,7 +1470,7 @@ fn given_threshold_override_change_when_evaluating_then_ruleset_fingerprint_chan overridden_config: json!({ "select": ["SQBRTEST202"], "threshold_overrides": [{ - "paths": ["models/mart/**"], + "paths": ["sql/models/mart/**"], "thresholds": {"min_tests_per_model": 2}, "reason": "marts require two focused tests" }], @@ -1535,7 +1535,7 @@ fn given_a_model_whose_analysis_was_skipped_when_building_rules_rows_then_its_ru for test_case in test_cases { let mut row: ModelRow = ModelRow { name: "orders".to_owned(), - relative_path: "models/orders.sql".to_owned(), + relative_path: "sql/models/orders.sql".to_owned(), query_sql: "SELECT 1 AS id".to_owned(), sql_analysis_skipped: test_case.sql_analysis_skipped, ..ModelRow::default() diff --git a/crates/sqlbuild-rules/src/engine/tests/test_incremental_rules.rs b/crates/sqlbuild-rules/src/engine/tests/test_incremental_rules.rs index e8ed79e46d..244b593ec6 100644 --- a/crates/sqlbuild-rules/src/engine/tests/test_incremental_rules.rs +++ b/crates/sqlbuild-rules/src/engine/tests/test_incremental_rules.rs @@ -381,7 +381,7 @@ fn given_suppression_change_when_evaluating_then_cached_models_are_reused_with_u let _ = evaluate_split(&rest, &models)?; rest["config"]["rule_ignores"] = json!([{ "rules": ["SQBRGRAPH102"], - "paths": ["models/commerce/mart/commerce__mart__orders.sql"], + "paths": ["sql/models/commerce/mart/commerce__mart__orders.sql"], "reason": "legacy warehouse table" }]); @@ -414,8 +414,8 @@ fn given_removed_model_file_when_cache_is_rewritten_then_only_its_entry_is_dropp let test_cases = [test_types::CachePruningTestCase { description: "deleted model is pruned while an unselected model is kept", expected_paths: &[ - "models/commerce/mart/commerce__mart__customers.sql", - "models/commerce/staging/commerce__stg__products.sql", + "sql/models/commerce/mart/commerce__mart__customers.sql", + "sql/models/commerce/staging/commerce__stg__products.sql", ], }]; for test_case in &test_cases { diff --git a/crates/sqlbuild-rules/src/engine/tests/test_published_layers.rs b/crates/sqlbuild-rules/src/engine/tests/test_published_layers.rs index 4fdae82d0b..22a26b62d5 100644 --- a/crates/sqlbuild-rules/src/engine/tests/test_published_layers.rs +++ b/crates/sqlbuild-rules/src/engine/tests/test_published_layers.rs @@ -18,7 +18,7 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc ], options: json!({}), expected_faults: &[( - "models/sales/mart/sales__mart__orders__finance.sql", + "sql/models/sales/mart/sales__mart__orders__finance.sql", "sales__mart__orders__finance reads sales__mart__orders; published models must not read published models of their own domain", )], }, @@ -28,8 +28,8 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc models: &[("sales__mart__orders__finance", &["sales__mart__orders"])], options: json!({}), expected_faults: &[( - "models/sales/mart/sales__mart__orders__finance.sql", - "sqb mv sales__mart__orders__finance models/sales/intermediate/enriched/sales__int_enriched__orders__finance.sql", + "sql/models/sales/mart/sales__mart__orders__finance.sql", + "sqb mv sales__mart__orders__finance sql/models/sales/intermediate/enriched/sales__int_enriched__orders__finance.sql", )], }, PublishedLayerTestCase { @@ -58,7 +58,7 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc models: &[("sales__mart_v__orders__fra", &["sales__mart__orders__deu"])], options: json!({}), expected_faults: &[( - "models/sales/mart/sales__mart_v__orders__fra.sql", + "sql/models/sales/mart/sales__mart_v__orders__fra.sql", "sales__mart_v__orders__fra reads sales__mart__orders__deu", )], }, @@ -68,7 +68,7 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc models: &[("sales__mart_v__customers", &["sales__mart__orders"])], options: json!({}), expected_faults: &[( - "models/sales/mart/sales__mart_v__customers.sql", + "sql/models/sales/mart/sales__mart_v__customers.sql", "sales__mart_v__customers reads sales__mart__orders", )], }, @@ -103,7 +103,7 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc ], options: json!({}), expected_faults: &[( - "models/sales/mart/sales__mart__orders__finance.sql", + "sql/models/sales/mart/sales__mart__orders__finance.sql", "domain sales publishes 2 models as ____ and 1 as ______; sales__mart__orders__finance does not fit the majority shape ____", )], }, @@ -117,7 +117,7 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc ], options: json!({}), expected_faults: &[( - "models/sales/mart/sales__mart__customers.sql", + "sql/models/sales/mart/sales__mart__customers.sql", "sqb rename sales__mart__customers sales__mart__customers__core", )], }, @@ -147,7 +147,7 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc {"domain": "finance", "qualifier": "fra", "reason": "Published once per country."} ]}), expected_faults: &[( - "models/sales/mart/sales__mart__orders__fra.sql", + "sql/models/sales/mart/sales__mart__orders__fra.sql", "allowed_qualifiers = [{ domain = \"sales\", qualifier = \"fra\"", )], }, @@ -183,11 +183,11 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc ]}), expected_faults: &[ ( - "models/sales/mart/sales__mart__orders__finance.sql", + "sql/models/sales/mart/sales__mart__orders__finance.sql", "domain sales publishes 2 models as ____ and 2 as", ), ( - "models/sales/mart/sales__mart__orders__fra.sql", + "sql/models/sales/mart/sales__mart__orders__fra.sql", "sales__mart__orders__fra does not fit the majority shape", ), ], @@ -201,7 +201,7 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc ("sales__mart__orders__deu", &[]), ], options: json!({"allowed_qualifiers": [ - {"paths": ["models/sales/*"], "reason": "Published once per country."} + {"paths": ["sql/models/sales/*"], "reason": "Published once per country."} ]}), expected_faults: &[], }, @@ -216,10 +216,10 @@ fn given_published_models_when_evaluating_layer_rules_then_reads_and_shapes_matc ("finance__mart__revenue__fra", &[]), ], options: json!({"allowed_qualifiers": [ - {"paths": ["models/sales/mart/*"], "reason": "Published once per country."} + {"paths": ["sql/models/sales/mart/*"], "reason": "Published once per country."} ]}), expected_faults: &[( - "models/finance/mart/finance__mart__revenue__fra.sql", + "sql/models/finance/mart/finance__mart__revenue__fra.sql", "domain finance publishes 1 model as ____ and 1 as", )], }, diff --git a/crates/sqlbuild-rules/src/engine/tests/test_relation_exceptions.rs b/crates/sqlbuild-rules/src/engine/tests/test_relation_exceptions.rs index ae855bee86..5f56519726 100644 --- a/crates/sqlbuild-rules/src/engine/tests/test_relation_exceptions.rs +++ b/crates/sqlbuild-rules/src/engine/tests/test_relation_exceptions.rs @@ -50,12 +50,12 @@ fn given_relation_level_exceptions_matching_nothing_when_finalizing_then_they_ar StaleRelationExceptionTestCase { description: "a relation exception that matches nothing is stale", exceptions: json!([{"rule": CROSS_JOIN_CODE, "path": CROSS_JOIN_MODEL_PATH, "relation": "shipments", "reason": "Gone."}]), - expected_error: "stale rule exception suppresses no finding: SQLCLEAN038 at models/orders.sql (relation shipments)", + expected_error: "stale rule exception suppresses no finding: SQLCLEAN038 at sql/models/orders.sql (relation shipments)", }, StaleRelationExceptionTestCase { description: "a CTE-scoped exception for another CTE is stale", exceptions: json!([{"rule": CROSS_JOIN_CODE, "path": CROSS_JOIN_MODEL_PATH, "relation": "customers", "cte": "other", "reason": "Gone."}]), - expected_error: "stale rule exception suppresses no finding: SQLCLEAN038 at models/orders.sql (relation customers in CTE other)", + expected_error: "stale rule exception suppresses no finding: SQLCLEAN038 at sql/models/orders.sql (relation customers in CTE other)", }, ]; diff --git a/crates/sqlbuild-rules/src/engine/tests/test_scope_facts.rs b/crates/sqlbuild-rules/src/engine/tests/test_scope_facts.rs index 06d9e58bfb..091f14b70c 100644 --- a/crates/sqlbuild-rules/src/engine/tests/test_scope_facts.rs +++ b/crates/sqlbuild-rules/src/engine/tests/test_scope_facts.rs @@ -77,7 +77,7 @@ fn given_partial_scope_facts_when_deserializing_then_completeness_is_preserved() "code": "S013", "message": "runtime usage is incomplete", "severity": "warning", - "path": "models/orders.sql", + "path": "sql/models/orders.sql", "line": 1, "column": 1, "declaration": null, diff --git a/crates/sqlbuild-rules/src/engine/tests/test_sql_test_rules.rs b/crates/sqlbuild-rules/src/engine/tests/test_sql_test_rules.rs index aa2b20dd82..ebff925350 100644 --- a/crates/sqlbuild-rules/src/engine/tests/test_sql_test_rules.rs +++ b/crates/sqlbuild-rules/src/engine/tests/test_sql_test_rules.rs @@ -19,23 +19,23 @@ fn given_sql_test_facts_when_evaluating_project_rules_then_returns_expected_faul scope["resources"] = json!([ { "identity": "model:stg_orders", "kind": "model", "name": "stg_orders", - "path": "models/commerce/staging/stg_orders.sql", "ownership_root": "models", + "path": "sql/models/commerce/staging/stg_orders.sql", "ownership_root": "sql/models", "ownership_root_kind": "model" }, { "identity": "model:fact_orders", "kind": "model", "name": "fact_orders", - "path": "models/commerce/marts/fact_orders.sql", "ownership_root": "models", + "path": "sql/models/commerce/marts/fact_orders.sql", "ownership_root": "sql/models", "ownership_root_kind": "model" }, { "identity": "model:daily_revenue", "kind": "model", "name": "daily_revenue", - "path": "models/finance/marts/daily_revenue.sql", "ownership_root": "models", + "path": "sql/models/finance/marts/daily_revenue.sql", "ownership_root": "sql/models", "ownership_root_kind": "model" }, { "identity": "model:commerce__mart_v_order", "kind": "model", "name": "commerce__mart_v_order", - "path": "models/commerce/marts/commerce__mart_v_order.sql", "ownership_root": "models", + "path": "sql/models/commerce/marts/commerce__mart_v_order.sql", "ownership_root": "sql/models", "ownership_root_kind": "model" } ]); @@ -61,16 +61,16 @@ fn given_sql_test_facts_when_evaluating_project_rules_then_returns_expected_faul "kind": "macro", "name": "order_policy", "owner": null, - "path": "models/commerce/staging/_sqlbuild/_macros/policy.py", + "path": "sql/models/commerce/staging/_sqlbuild/_macros/policy.py", "line": 1, "column": 1, "scope": "local", "role": "macros", "visibility": "exact_owner_private", - "role_root": "models/commerce/staging/_sqlbuild/_macros", + "role_root": "sql/models/commerce/staging/_sqlbuild/_macros", "bucket_path": null, - "ownership_root": "models", - "owning_path": "models/commerce/staging", + "ownership_root": "sql/models", + "owning_path": "sql/models/commerce/staging", "metadata": {"macro": { "parameters": [], "dependencies": [], diff --git a/crates/sqlbuild-rules/src/lint_text/constants.rs b/crates/sqlbuild-rules/src/lint_text/constants.rs index a5188d2bf4..8771b4cf37 100644 --- a/crates/sqlbuild-rules/src/lint_text/constants.rs +++ b/crates/sqlbuild-rules/src/lint_text/constants.rs @@ -83,11 +83,11 @@ pub(crate) const MOVED_EXPRESSION_ALIAS: &str = pub(crate) const DECLARATION_GROUP_DIRECTORY: &str = "_sqlbuild"; /// `GLOBAL_NAMED_DECLARATION_ROOTS`, in Python's dict order, with whether each holds audits. pub(crate) const GLOBAL_NAMED_ROOTS: [(&[&str], bool); 5] = [ - (&["audits", "generic"], true), - (&["audits", "singular"], true), - (&["schemas"], false), - (&["hooks", "sql"], false), - (&["hooks", "python"], false), + (&["sql", "audits", "generic"], true), + (&["sql", "audits", "singular"], true), + (&["sql", "schemas"], false), + (&["sql", "hooks", "sql"], false), + (&["sql", "hooks", "python"], false), ]; /// `GROUPED_NAMED_DECLARATION_ROLES`, in Python's dict order, with whether each holds audits. pub(crate) const GROUPED_NAMED_ROLES: [(&[&str], bool); 9] = [ @@ -178,7 +178,7 @@ pub(crate) const DEFAULT_DIALECT: &str = "generic"; /// Adapter names whose SQL dialect has another name; other adapters name their dialect. pub(crate) const ADAPTER_DIALECT_TRANSLATIONS: [(&str, &str); 2] = [("motherduck", "duckdb"), ("sqlserver", "tsql")]; -pub(crate) const MODELS_DIRECTORY: &str = "models"; +pub(crate) const MODELS_DIRECTORY: [&str; 2] = ["sql", "models"]; /// Inherited and local declaration folders, whose files declare several headers. pub(crate) const SCOPED_DECLARATION_DIRECTORIES: [&str; 6] = [ "macros", @@ -190,11 +190,11 @@ pub(crate) const SCOPED_DECLARATION_DIRECTORIES: [&str; 6] = [ ]; /// `GLOBAL_NAMED_DECLARATION_ROOTS`, in Python's dict order, with their declaration kinds. pub(crate) const GLOBAL_NAMED_ROOT_KINDS: [(&[&str], &str); 5] = [ - (&["audits", "generic"], "audit"), - (&["audits", "singular"], "singular_audit"), - (&["schemas"], "schema"), - (&["hooks", "sql"], "sql_hook"), - (&["hooks", "python"], "python_hook"), + (&["sql", "audits", "generic"], "audit"), + (&["sql", "audits", "singular"], "singular_audit"), + (&["sql", "schemas"], "schema"), + (&["sql", "hooks", "sql"], "sql_hook"), + (&["sql", "hooks", "python"], "python_hook"), ]; /// `GROUPED_NAMED_DECLARATION_ROLES`, in Python's dict order, with their declaration kinds. pub(crate) const GROUPED_NAMED_ROLE_KINDS: [(&[&str], &str); 9] = [ diff --git a/crates/sqlbuild-rules/src/lint_text/main/first_header_only.rs b/crates/sqlbuild-rules/src/lint_text/main/first_header_only.rs index 73aa6d3cf2..5f1263a582 100644 --- a/crates/sqlbuild-rules/src/lint_text/main/first_header_only.rs +++ b/crates/sqlbuild-rules/src/lint_text/main/first_header_only.rs @@ -7,13 +7,18 @@ use crate::lint_text::constants::{ /// Model files outside declaration folders hold one header; every other file may hold several. #[must_use] pub fn first_header_only(relative_parts: &[String]) -> bool { - let Some((first, rest)) = relative_parts.split_first() else { + if relative_parts.len() <= MODELS_DIRECTORY.len() + || relative_parts + .iter() + .zip(MODELS_DIRECTORY) + .any(|(part, root)| part != root) + { return false; - }; + } + let rest: &[String] = &relative_parts[MODELS_DIRECTORY.len()..]; let folders: &[String] = rest.split_last().map_or(&[], |(_, folders)| folders); - first == MODELS_DIRECTORY - && !folders.iter().any(|folder| { - folder == DECLARATION_GROUP_DIRECTORY - || SCOPED_DECLARATION_DIRECTORIES.contains(&folder.as_str()) - }) + !folders.iter().any(|folder| { + folder == DECLARATION_GROUP_DIRECTORY + || SCOPED_DECLARATION_DIRECTORIES.contains(&folder.as_str()) + }) } diff --git a/crates/sqlbuild-rules/src/lint_text/tests/test_format_settings.rs b/crates/sqlbuild-rules/src/lint_text/tests/test_format_settings.rs index bb7dd8c193..19b73936c3 100644 --- a/crates/sqlbuild-rules/src/lint_text/tests/test_format_settings.rs +++ b/crates/sqlbuild-rules/src/lint_text/tests/test_format_settings.rs @@ -63,22 +63,22 @@ fn given_relative_paths_when_classifying_headers_then_only_plain_models_scan_one let test_cases = [ crate::lint_text::tests::test_types::FirstHeaderTestCase { description: "a plain model file", - relative_parts: &["models", "staging", "orders.sql"], + relative_parts: &["sql", "models", "staging", "orders.sql"], expected_first_only: true, }, crate::lint_text::tests::test_types::FirstHeaderTestCase { description: "a scoped declaration file under models", - relative_parts: &["models", "_enums", "status.sql"], + relative_parts: &["sql", "models", "_enums", "status.sql"], expected_first_only: false, }, crate::lint_text::tests::test_types::FirstHeaderTestCase { description: "a declaration group file under models", - relative_parts: &["models", "_sqlbuild", "orders.sql"], + relative_parts: &["sql", "models", "_sqlbuild", "orders.sql"], expected_first_only: false, }, crate::lint_text::tests::test_types::FirstHeaderTestCase { description: "a file named like a folder is still a model", - relative_parts: &["models", "enums.sql"], + relative_parts: &["sql", "models", "enums.sql"], expected_first_only: true, }, crate::lint_text::tests::test_types::FirstHeaderTestCase { @@ -108,12 +108,20 @@ fn given_project_paths_when_classifying_named_roles_then_kinds_match_python() { let test_cases = [ crate::lint_text::tests::test_types::RoleKindTestCase { description: "a generic audit", - relative_parts: &["audits", "generic", "not_null.sql"], + relative_parts: &["sql", "audits", "generic", "not_null.sql"], expected_kind: Some("audit"), }, crate::lint_text::tests::test_types::RoleKindTestCase { description: "a local SQL hook in a declaration group", - relative_parts: &["models", "orders", "_sqlbuild", "_hooks", "sql", "h.sql"], + relative_parts: &[ + "sql", + "models", + "orders", + "_sqlbuild", + "_hooks", + "sql", + "h.sql", + ], expected_kind: Some("sql_hook"), }, crate::lint_text::tests::test_types::RoleKindTestCase { @@ -123,7 +131,7 @@ fn given_project_paths_when_classifying_named_roles_then_kinds_match_python() { }, crate::lint_text::tests::test_types::RoleKindTestCase { description: "a plain model", - relative_parts: &["models", "orders.sql"], + relative_parts: &["sql", "models", "orders.sql"], expected_kind: None, }, ]; diff --git a/crates/sqlbuild-rules/src/lint_text/tests/test_lint_text.rs b/crates/sqlbuild-rules/src/lint_text/tests/test_lint_text.rs index 03e318e5cd..9823b6c84a 100644 --- a/crates/sqlbuild-rules/src/lint_text/tests/test_lint_text.rs +++ b/crates/sqlbuild-rules/src/lint_text/tests/test_lint_text.rs @@ -237,9 +237,10 @@ fn given_relation_slot_reads_when_neutralizing_then_they_stand_as_their_expansio for test_case in test_cases { let source: String = format!("{header}{}\n", test_case.body); - let parameters = parse_sql_macro("weekly_rates", "macros/sql/weekly_rates.sql", &source) - .map(|definition| definition.parameters) - .unwrap_or_default(); + let parameters = + parse_sql_macro("weekly_rates", "sql/macros/sql/weekly_rates.sql", &source) + .map(|definition| definition.parameters) + .unwrap_or_default(); assert_eq!( neutralize_sql_macro_parameters(test_case.body, ¶meters).text, @@ -331,7 +332,7 @@ fn given_inline_directives_when_rejecting_then_each_prints_its_configured_except "SQLCLEAN005", &[ "rule = \"SQLCLEAN005\"", - "path = \"models/orders.sql\"", + "path = \"sql/models/orders.sql\"", "reason = \"kept\"", ], ), @@ -340,7 +341,7 @@ fn given_inline_directives_when_rejecting_then_each_prints_its_configured_except "nope", &[ "rule = \"nope\"", - "path = \"models/orders.sql\"", + "path = \"sql/models/orders.sql\"", "reason = \"\"", ], ), @@ -354,7 +355,7 @@ fn given_inline_directives_when_rejecting_then_each_prints_its_configured_except "SQLCLEAN038", &[ "rule = \"SQLCLEAN038\"", - "path = \"models/orders.sql\"", + "path = \"sql/models/orders.sql\"", "relation = \"order_policy\"", "reason = \"every order meets every policy\"", ], @@ -373,7 +374,7 @@ fn given_inline_directives_when_rejecting_then_each_prints_its_configured_except "SQLCLEAN038", &[ "rule = \"SQLCLEAN038\"", - "path = \"models/orders.sql\"", + "path = \"sql/models/orders.sql\"", "relation = \"customers\"", "reason = \"deliberate\"", ], @@ -387,7 +388,7 @@ fn given_inline_directives_when_rejecting_then_each_prints_its_configured_except "SQLCLEAN005", &[ "rule = \"SQLCLEAN005\"", - "path = \"models/orders.sql\"", + "path = \"sql/models/orders.sql\"", "reason = \"kept\"", ], )], @@ -400,7 +401,8 @@ fn given_inline_directives_when_rejecting_then_each_prints_its_configured_except ]; for test_case in test_cases { - let findings = reject_inline_suppressions(&[("models/orders.sql", test_case.contents)])?; + let findings = + reject_inline_suppressions(&[("sql/models/orders.sql", test_case.contents)])?; assert_eq!( findings, test_case.expected_findings, diff --git a/crates/sqlbuild-rules/src/orchestration_rules/tests/test_named_selector_limit.rs b/crates/sqlbuild-rules/src/orchestration_rules/tests/test_named_selector_limit.rs index fc64826b45..6718df59ad 100644 --- a/crates/sqlbuild-rules/src/orchestration_rules/tests/test_named_selector_limit.rs +++ b/crates/sqlbuild-rules/src/orchestration_rules/tests/test_named_selector_limit.rs @@ -55,7 +55,7 @@ fn given_job_and_sensor_selections_when_evaluating_then_more_named_nodes_than_th "orchestration/jobs/orders/nightly.toml", job( "orders_nightly_job", - "a b c a tag:orders models/orders python/orders +fct_orders fct_refunds+ fct_* job:orders_export_job orders_export_job", + "a b c a tag:orders sql/models/orders python/nodes/orders +fct_orders fct_refunds+ fct_* job:orders_export_job orders_export_job", ), ), ], diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/engine/contexts.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/engine/contexts.rs index 8e646e4eb1..98e6848f1e 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/engine/contexts.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/engine/contexts.rs @@ -11,7 +11,7 @@ use std::path::Path; use crate::models::{EvaluateRequest, RulesConfig}; use crate::python_rules::constants::{ - NAMING_CONTRACTS, NAMING_FAMILY, PACKAGE_ROOT, PROJECT_CONFIG_FILE, + NAMING_CONTRACTS, NAMING_FAMILY, PACKAGE_MODULE, PACKAGE_ROOT, PROJECT_CONFIG_FILE, }; use crate::python_rules::models::{PythonRuleSpec, PythonTarget}; @@ -92,7 +92,7 @@ pub(crate) fn rule_context(target: &PythonTarget, settings: &ContextSettings) -> role: target.role.clone(), is_main_module: target.is_main_module, is_entry_module: target.is_entry_module, - package_name: PACKAGE_ROOT.to_owned(), + package_name: PACKAGE_MODULE.to_owned(), ownership_root: Some(settings.ownership_root.clone()), ownership_roots: vec![settings.ownership_root.clone()], ownership_offset: Some(0), diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/engine/layout.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/engine/layout.rs index c0db10bccd..38c1c79115 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/engine/layout.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/engine/layout.rs @@ -86,11 +86,14 @@ fn generic_package_faults(sources: &[PythonSource]) -> Vec { .collect() } -/// Each `python/` file's path parts below `python/`. +/// Each `python/nodes/` file's path parts below `python/nodes/`. fn package_parts(sources: &[PythonSource]) -> impl Iterator> { sources.iter().filter_map(|source| { - let mut parts = source.relative_path.split('/'); - (parts.next() == Some(PACKAGE_ROOT)).then(|| parts.collect()) + let below: &str = source + .relative_path + .strip_prefix(PACKAGE_ROOT)? + .strip_prefix('/')?; + Some(below.split('/').collect()) }) } diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/engine/placement.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/engine/placement.rs index 750b2305c0..8422e222dc 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/engine/placement.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/engine/placement.rs @@ -25,9 +25,13 @@ pub(crate) fn test_targets(sources: &[PythonSource]) -> Vec { } fn placed((source, python): (usize, &PythonSource)) -> PythonTarget { - let parts: Vec = python.relative_path.split('/').map(str::to_owned).collect(); - if parts.len() > 1 && parts[0] == PACKAGE_ROOT { - let relative_parts: Vec = parts[1..].to_vec(); + let below: Option<&str> = python + .relative_path + .strip_prefix(PACKAGE_ROOT) + .and_then(|rest| rest.strip_prefix('/')) + .filter(|rest| !rest.is_empty()); + if let Some(below) = below { + let relative_parts: Vec = below.split('/').map(str::to_owned).collect(); let first_role: Option<&str> = first_directory_role(&relative_parts); let unit_main: bool = first_role.is_none() && relative_parts.len() > 1 diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/units/imports.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/units/imports.rs index 90569546be..5192d3be07 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/units/imports.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/units/imports.rs @@ -3,9 +3,9 @@ use sqlbuild_pysource::node_units::models::UnitImport; use crate::models::Fault; -use crate::python_rules::_helpers::units::project::{imported_module, unit_fault}; +use crate::python_rules::_helpers::units::project::{imported_module, module_below, unit_fault}; use crate::python_rules::constants::{ - NODE_IMPORT_BOUNDARIES_CODE, PACKAGE_ROOT, PROVIDER_ROLE_MODULES, PROVIDERS_ROOT, + NODE_IMPORT_BOUNDARIES_CODE, PACKAGE_MODULE, PROVIDER_ROLE_MODULES, PROVIDERS_MODULE, SHARED_ROLE_MODULES, SHARED_UTILITIES_PACKAGE, UNIT_HELPERS_FOLDER, }; use crate::python_rules::models::UnitProject; @@ -41,10 +41,10 @@ pub(crate) fn import_boundary_faults(project: &UnitProject<'_>) -> Vec { /// Whether a file of `unit` may import the project module `module` through `import`. fn allowed(module: &str, import: &UnitImport, unit: &str, project: &UnitProject<'_>) -> bool { let unit_parts: Vec<&str> = unit.split('/').collect(); - let own: String = format!("{PACKAGE_ROOT}.{}", unit_parts.join(".")); - let mut shared: Vec = vec![own, format!("{PACKAGE_ROOT}.{SHARED_UTILITIES_PACKAGE}")]; + let own: String = format!("{PACKAGE_MODULE}.{}", unit_parts.join(".")); + let mut shared: Vec = vec![own, format!("{PACKAGE_MODULE}.{SHARED_UTILITIES_PACKAGE}")]; for depth in 1..unit_parts.len() { - let ancestor: String = format!("{PACKAGE_ROOT}.{}", unit_parts[..depth].join(".")); + let ancestor: String = format!("{PACKAGE_MODULE}.{}", unit_parts[..depth].join(".")); shared.extend( SHARED_ROLE_MODULES .iter() @@ -58,12 +58,11 @@ fn allowed(module: &str, import: &UnitImport, unit: &str, project: &UnitProject< project.node_modules.contains(module) && import.only_in_depends_on } -/// Whether `module` is a public role file of a provider capability, `providers..`. +/// Whether `module` is a public role file of a provider capability, `python.providers..`. fn provider_role(module: &str) -> bool { - let parts: Vec<&str> = module.split('.').collect(); matches!( - parts.as_slice(), - [root, _, role, ..] if *root == PROVIDERS_ROOT && PROVIDER_ROLE_MODULES.contains(role) + module_below(module, PROVIDERS_MODULE).as_deref(), + Some([_, role, ..]) if PROVIDER_ROLE_MODULES.contains(role) ) } diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/units/layout.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/units/layout.rs index 797537a2d1..1fd7216977 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/units/layout.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/units/layout.rs @@ -12,7 +12,7 @@ use crate::python_rules::_helpers::units::project::{ }; use crate::python_rules::constants::{ NODE_DECLARED_IN_UNIT_CODE, NODE_UNIT_LAYOUT_CODE, PACKAGE_ROOT, UNIT_CHECKS_FILE, - UNIT_HELPERS_FOLDER, UNIT_MAIN_FILE, UNIT_NODE_FILE, UNIT_ROLE_FILES, + UNIT_DECLARATION_FILES, UNIT_HELPERS_FOLDER, UNIT_MAIN_FILE, UNIT_ROLE_FILES, }; use crate::python_rules::models::{UnitFile, UnitProject}; @@ -30,9 +30,10 @@ pub(crate) fn unit_layout_faults( .contains(format!("{PACKAGE_ROOT}/{unit}/{UNIT_MAIN_FILE}").as_str()) }) .filter_map(|unit| { + let anchor: String = unit_anchor(project, unit)?; catalogue_fault( NODE_UNIT_LAYOUT_CODE, - &format!("{PACKAGE_ROOT}/{unit}/{UNIT_NODE_FILE}"), + &anchor, (1, 1), &format!("{PACKAGE_ROOT}/{unit}/ has no {UNIT_MAIN_FILE}"), ) @@ -53,7 +54,8 @@ pub(crate) fn unit_layout_faults( let unit_path: String = format!("{PACKAGE_ROOT}/{}", parts[..depth].join("/")); let entry: &str = parts[depth]; if parts.len() == depth + 1 { - let allowed: bool = [UNIT_NODE_FILE, UNIT_MAIN_FILE].contains(&entry) + let allowed: bool = UNIT_DECLARATION_FILES.contains(&entry) + || entry == UNIT_MAIN_FILE || UNIT_ROLE_FILES.contains(&entry); if !allowed { faults.extend(catalogue_fault( @@ -78,7 +80,7 @@ pub(crate) fn unit_layout_faults( faults } -/// Each node or factory declared outside a unit's `node.py`, and each check outside its unit's files. +/// Each node or factory declared outside the unit file named for its kind, and each check outside its unit's files. pub(crate) fn declared_outside_unit_faults(project: &UnitProject<'_>) -> Vec { let mut faults: Vec = Vec::new(); for file in &project.files { @@ -108,13 +110,17 @@ fn misplaced( in_factory: bool, ) -> Option { let (what, decorator) = declared(function)?; - let at_home: bool = match what { - Declared::Node(..) => home == Some(UNIT_NODE_FILE), - Declared::Factory => matches!(home, Some(UNIT_NODE_FILE | UNIT_CHECKS_FILE)), - Declared::Check => { - home == Some(UNIT_CHECKS_FILE) || (home == Some(UNIT_NODE_FILE) && in_factory) - } + let expected: Option<&str> = match what { + Declared::Node(kind, _) => Some(kind_file(kind)), + Declared::Factory => factory_file(function), + Declared::Check => Some(UNIT_CHECKS_FILE), }; + let at_home: bool = match expected { + _ if in_factory && what != Declared::Factory => home.is_some_and(is_factory_file), + Some(expected) => home == Some(expected), + None => home.is_some_and(is_factory_file), + }; + let expected: &str = expected.unwrap_or("factory.py"); if at_home { return None; } @@ -123,7 +129,7 @@ fn misplaced( format!("the {UNIT_CHECKS_FILE} of the unit folder whose node it checks") } _ => format!( - "{PACKAGE_ROOT}/{}/{}/{UNIT_NODE_FILE}", + "{PACKAGE_ROOT}/{}/{}/{expected}", domain(file), function.name ), @@ -150,3 +156,47 @@ fn domain(file: &UnitFile<'_>) -> String { (*first).to_owned() } } + +/// The file of one direct node of `kind`. +fn kind_file(kind: &str) -> &'static str { + match kind { + "loader" => "loader.py", + _ => "asset.py", + } +} + +/// The first declaration file of `unit` the project holds, where a missing `main.py` is reported. +fn unit_anchor(project: &UnitProject<'_>, unit: &str) -> Option { + let mut candidates = UNIT_DECLARATION_FILES.iter().chain([&UNIT_CHECKS_FILE]); + candidates.find_map(|file| { + let path: String = format!("{PACKAGE_ROOT}/{unit}/{file}"); + project.paths.contains(path.as_str()).then_some(path) + }) +} + +/// A factory's file: plural for the one kind it declares, `factory.py` for several. +fn factory_file(function: &UnitFunction) -> Option<&'static str> { + let mut kinds: Vec<&str> = Vec::new(); + for inner in &function.inner { + let kind: &str = match declared(inner) { + Some((Declared::Node(kind, _), _)) => kind, + Some((Declared::Check, _)) => "check", + _ => continue, + }; + if !kinds.contains(&kind) { + kinds.push(kind); + } + } + match kinds.as_slice() { + [] => None, + ["loader"] => Some("loaders.py"), + ["asset"] => Some("assets.py"), + ["check"] => Some(UNIT_CHECKS_FILE), + _ => Some("factory.py"), + } +} + +/// Whether `file` is a factory's declaration file. +fn is_factory_file(file: &str) -> bool { + ["loaders.py", "assets.py", "factory.py", UNIT_CHECKS_FILE].contains(&file) +} diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/units/modules.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/units/modules.rs index 2f9f4de65c..bc4a43213d 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/units/modules.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/units/modules.rs @@ -1,4 +1,4 @@ -//! The statements a unit's node.py, main.py and checks.py may hold. +//! The statements a unit's declaration file, main.py and checks.py may hold. use sqlbuild_pysource::node_units::models::{UnitFunction, UnitPosition, UnitStatementKind}; @@ -8,20 +8,22 @@ use crate::python_rules::_helpers::units::project::{ unit_member, }; use crate::python_rules::constants::{ - CHECKS_MODULE_SHAPE_CODE, MAIN_MODULE_SHAPE_CODE, MAIN_NAME, MAIN_RESULTS, NODE_MODULE, - NODE_MODULE_SHAPE_CODE, UNIT_CHECKS_FILE, UNIT_MAIN_FILE, UNIT_NODE_FILE, + CHECKS_MODULE_SHAPE_CODE, MAIN_MODULE_SHAPE_CODE, MAIN_NAME, MAIN_RESULTS, + NODE_MODULE_SHAPE_CODE, NODE_MODULES, UNIT_CHECKS_FILE, UNIT_DECLARATION_FILES, UNIT_MAIN_FILE, }; use crate::python_rules::models::{UnitFile, UnitProject}; const FILE_START: UnitPosition = UnitPosition { line: 1, column: 1 }; const OTHER_STATEMENT: &str = "a statement that is not an import or a function"; -/// Statements and functions node.py, main.py and checks.py may not hold. +/// Statements and functions a declaration file, main.py and checks.py may not hold. pub(crate) fn module_shape_faults(project: &UnitProject<'_>) -> Vec { let mut faults: Vec = Vec::new(); for file in &project.files { match unit_file_name(file) { - Some(UNIT_NODE_FILE) => faults.extend(node_module_faults(file)), + Some(name) if UNIT_DECLARATION_FILES.contains(&name) => { + faults.extend(node_module_faults(file)); + } Some(UNIT_MAIN_FILE) => faults.extend(main_module_faults(file, project)), Some(UNIT_CHECKS_FILE) => faults.extend(checks_module_faults(file, project)), _ => {} @@ -30,7 +32,7 @@ pub(crate) fn module_shape_faults(project: &UnitProject<'_>) -> Vec { faults } -/// node.py: imports and exactly one node or factory declaration. +/// A declaration file: imports and exactly one node or factory declaration. fn node_module_faults(file: &UnitFile<'_>) -> Vec { let mut faults: Vec = Vec::new(); let mut declarations: usize = 0; @@ -139,9 +141,9 @@ fn main_result_detail(function: &UnitFunction, kind: Option<&str>) -> Option, unit: &str) -> Option<&'static str> { - let node: &UnitFile<'_> = unit_member(project, unit, UNIT_NODE_FILE)?; + let node: &UnitFile<'_> = declaration_member(project, unit)?; top_functions(node).find_map(|function| match declared(function)? { (Declared::Node(kind, _), _) => Some(kind), (Declared::Factory, _) => function.inner.iter().find_map(declared_node_kind), @@ -160,10 +162,10 @@ fn declared_node_kind(function: &UnitFunction) -> Option<&'static str> { /// checks.py: imports and checks of the unit's own node that return directly, or one factory. fn checks_module_faults(file: &UnitFile<'_>, project: &UnitProject<'_>) -> Vec { let unit_node: Vec = file.unit.as_deref().map_or_else(Vec::new, |unit| { - let mut names: Vec = names_from_unit_modules(file, project, unit, &[NODE_MODULE]) + let mut names: Vec = names_from_unit_modules(file, project, unit, &NODE_MODULES) .into_iter() .collect(); - if let Some(node) = unit_member(project, unit, UNIT_NODE_FILE) { + if let Some(node) = declaration_member(project, unit) { names.extend(top_functions(node).map(|function| function.name.clone())); } names @@ -224,3 +226,13 @@ fn checks_module_faults(file: &UnitFile<'_>, project: &UnitProject<'_>) -> Vec( + project: &'p UnitProject<'a>, + unit: &str, +) -> Option<&'p UnitFile<'a>> { + UNIT_DECLARATION_FILES + .iter() + .find_map(|name| unit_member(project, unit, name)) +} diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/units/nodes.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/units/nodes.rs index f125ff824c..09953f249f 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/units/nodes.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/units/nodes.rs @@ -12,7 +12,7 @@ use crate::python_rules::_helpers::units::project::{ use crate::python_rules::constants::{ CHECK_KIND, CONTEXT_PARAMETER, DESCRIPTION_KEYWORD, FACTORY_SHAPE_CODE, LOADER_DECORATOR, MAIN_NAME, NAME_KEYWORD, NODE_DELEGATES_TO_MAIN_CODE, NODE_DESCRIPTION_CODE, - NODE_SIGNATURE_CODE, SPEC_MODULES, UNIT_CHECKS_FILE, UNIT_NODE_FILE, + NODE_SIGNATURE_CODE, SPEC_MODULES, UNIT_CHECKS_FILE, UNIT_DECLARATION_FILES, }; use crate::python_rules::models::{UnitFile, UnitProject}; @@ -23,15 +23,16 @@ struct UnitNames { specs: BTreeSet, } -/// Declaration faults of every node, check and factory in a unit's node.py and checks.py. +/// Declaration faults of every node, check and factory in a unit's declaration file and checks.py. pub(crate) fn declaration_faults(project: &UnitProject<'_>) -> Vec { let mut faults: Vec = Vec::new(); for file in &project.files { - let (Some(unit), Some(UNIT_NODE_FILE | UNIT_CHECKS_FILE)) = - (file.unit.as_deref(), unit_file_name(file)) - else { + let (Some(unit), Some(name)) = (file.unit.as_deref(), unit_file_name(file)) else { continue; }; + if name != UNIT_CHECKS_FILE && !UNIT_DECLARATION_FILES.contains(&name) { + continue; + } let names = UnitNames { main: unit_imports(file, project, unit, &[MAIN_NAME]) .into_iter() diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/units/orchestration.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/units/orchestration.rs index 6a1f75d1a4..5aed69d3ce 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/units/orchestration.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/units/orchestration.rs @@ -8,15 +8,16 @@ use sqlbuild_pysource::orchestration_modules::main::orchestration_module_declara use crate::models::{Fault, PythonSource}; use crate::python_rules::_helpers::engine::faults::catalogue_fault; use crate::python_rules::_helpers::units::project::{ - files_naming, nearest_unit, project_modules, rejected_import_faults, unit_fault, unit_folders, + files_naming, module_below, nearest_unit, package_rest, project_modules, + rejected_import_faults, unit_fault, unit_folders, }; use crate::python_rules::constants::{ INIT_FILE, ORCHESTRATION_GENERIC_MODULES, ORCHESTRATION_IMPORT_DIRECTION_CODE, ORCHESTRATION_MODULE_PATHS_CODE, ORCHESTRATION_MODULE_SURFACE_CODE, ORCHESTRATION_NO_DOCSTRING_CODE, ORCHESTRATION_PRIVATE_SUPPORT_CODE, ORCHESTRATION_PYTHON_ROLES, ORCHESTRATION_ROOT, ORCHESTRATION_RULE_CODES, - ORCHESTRATION_SUPPORT_FILES, ORCHESTRATION_SUPPORT_FOLDER, PACKAGE_ROOT, PRIVATE_PREFIX, - PROVIDERS_ROOT, SHARED_UTILITIES_PACKAGE, + ORCHESTRATION_SUPPORT_FILES, ORCHESTRATION_SUPPORT_FOLDER, PACKAGE_MODULE, PACKAGE_ROOT, + PRIVATE_PREFIX, PROVIDERS_ROOT, SHARED_UTILITIES_PACKAGE, }; use crate::python_rules::models::ParsedFile; @@ -36,7 +37,11 @@ pub(crate) fn orchestration_faults( return Vec::new(); } let mut faults: Vec = sources.iter().filter_map(layout_fault).collect(); - let files: Vec> = files_naming(sources, ORCHESTRATION_ROOT, python_version); + let files: Vec> = files_naming( + sources, + (ORCHESTRATION_ROOT, ORCHESTRATION_ROOT), + python_version, + ); let modules: BTreeSet = project_modules(sources); let units: BTreeSet = unit_folders(sources); for file in &files { @@ -206,11 +211,17 @@ fn boundary_detail( units: &BTreeSet, ) -> Option<(&'static str, String)> { let imported: Vec<&str> = module.split('.').collect(); + let path: String = parts.join("/"); let Some(rest) = role_folders(parts) else { - let in_unit: bool = - parts.first() == Some(&PACKAGE_ROOT) && nearest_unit(&parts[1..], units).is_some(); + let in_unit: bool = package_rest(&path).is_some_and(|below| { + let below: Vec<&str> = below.split('/').collect(); + nearest_unit(&below, units).is_some() + }); + let in_providers: bool = path + .strip_prefix(PROVIDERS_ROOT) + .is_some_and(|below| below.starts_with('/')); let outside: bool = parts.first() != Some(&ORCHESTRATION_ROOT) - && parts.first() != Some(&PROVIDERS_ROOT) + && !in_providers && !in_unit && imported.first() == Some(&ORCHESTRATION_ROOT); return outside.then(|| { @@ -220,14 +231,17 @@ fn boundary_detail( ) }); }; + if let Some(below) = module_below(module, PACKAGE_MODULE) { + return (below.first() != Some(&SHARED_UTILITIES_PACKAGE)).then(|| { + ( + ORCHESTRATION_IMPORT_DIRECTION_CODE, + format!( + "but sensors and calendars import only {PACKAGE_ROOT}/{SHARED_UTILITIES_PACKAGE}/ from {PACKAGE_ROOT}/" + ), + ) + }); + } match imported.as_slice() { - [root, utils, ..] if *root == PACKAGE_ROOT && *utils == SHARED_UTILITIES_PACKAGE => None, - [root, ..] if *root == PACKAGE_ROOT => Some(( - ORCHESTRATION_IMPORT_DIRECTION_CODE, - format!( - "but sensors and calendars import only {PACKAGE_ROOT}/{SHARED_UTILITIES_PACKAGE}/ from {PACKAGE_ROOT}/" - ), - )), [root, role, domain, support @ ..] if *root == ORCHESTRATION_ROOT && is_private(support) diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/units/project.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/units/project.rs index 26a085421f..bbbb14984e 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/units/project.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/units/project.rs @@ -19,8 +19,8 @@ use crate::python_rules::_helpers::units::modules::module_shape_faults; use crate::python_rules::_helpers::units::nodes::declaration_faults; use crate::python_rules::constants::{ CHECK_KIND, FACTORY_DECORATORS, INIT_FILE, MIN_UNIT_DEPTH, NODE_KIND_DIRECTORIES, NODE_KINDS, - NODE_MODULE, PACKAGE_ROOT, ROLE_DIRECTORIES, SHARED_UTILITIES_PACKAGE, UNIT_NODE_FILE, - UNIT_RULE_CODES, + NODE_MODULES, PACKAGE_MODULE, PACKAGE_ROOT, ROLE_DIRECTORIES, SHARED_UTILITIES_PACKAGE, + UNIT_CHECKS_FILE, UNIT_DECLARATION_FILES, UNIT_RULE_CODES, }; use crate::python_rules::models::{ParsedFile, UnitFile, UnitProject}; @@ -43,10 +43,10 @@ pub(crate) fn unit_faults( faults } -/// The unit folder `parts` declares, when it is a `node.py` deep enough and outside every role folder. +/// The unit folder `parts` declares, when it is a declaration file deep enough and outside every role folder. fn unit_folder(parts: &[&str]) -> Option { let (last, folders) = parts.split_last()?; - let declares: bool = *last == UNIT_NODE_FILE + let declares: bool = (UNIT_DECLARATION_FILES.contains(last) || *last == UNIT_CHECKS_FILE) && folders.len() >= MIN_UNIT_DEPTH && !folders.iter().copied().any(is_role_folder); declares.then(|| folders.join("/")) @@ -56,8 +56,8 @@ fn unit_project(sources: &[PythonSource], python_version: (u8, u8)) -> UnitProje let package: Vec<(&PythonSource, Vec<&str>)> = sources .iter() .filter_map(|source| { - let (root, rest) = source.relative_path.split_once('/')?; - (root == PACKAGE_ROOT).then(|| (source, rest.split('/').collect())) + let rest: &str = package_rest(&source.relative_path)?; + Some((source, rest.split('/').collect())) }) .collect(); let units: BTreeSet = unit_folders(sources); @@ -80,7 +80,7 @@ fn unit_project(sources: &[PythonSource], python_version: (u8, u8)) -> UnitProje .collect(), node_modules: units .iter() - .map(|unit| format!("{PACKAGE_ROOT}.{}.{NODE_MODULE}", unit.replace('/', "."))) + .flat_map(|unit| unit_node_modules(unit)) .collect(), files, units, @@ -92,6 +92,15 @@ fn unit_project(sources: &[PythonSource], python_version: (u8, u8)) -> UnitProje } } +/// The dotted modules of `unit`'s declaration files. +fn unit_node_modules(unit: &str) -> Vec { + let package: String = format!("{PACKAGE_MODULE}.{}", unit.replace('/', ".")); + NODE_MODULES + .iter() + .map(|module| format!("{package}.{module}")) + .collect() +} + /// Every dotted module the project's Python files define, packages included. pub(crate) fn project_modules(sources: &[PythonSource]) -> BTreeSet { sources @@ -100,16 +109,20 @@ pub(crate) fn project_modules(sources: &[PythonSource]) -> BTreeSet { .collect() } -/// The files under `root/` or whose text names it, parsed; a file that does not parse is left out. +/// The files under the folder `root/` or whose text names its module, parsed; a file that does not parse is left out. pub(crate) fn files_naming<'a>( sources: &'a [PythonSource], - root: &str, + (root, module): (&str, &str), python_version: (u8, u8), ) -> Vec> { sources .par_iter() .filter(|source| { - source.relative_path.split('/').next() == Some(root) || source.text.contains(root) + source + .relative_path + .strip_prefix(root) + .is_some_and(|rest| rest.starts_with('/')) + || source.text.contains(module) }) .filter_map(|source| { Some(ParsedFile { @@ -148,16 +161,27 @@ pub(crate) fn rejected_import_faults( .collect() } -/// The unit folders under `python/`, each relative to it. +/// The path of a `python/nodes/` file below that folder. +pub(crate) fn package_rest(path: &str) -> Option<&str> { + path.strip_prefix(PACKAGE_ROOT)?.strip_prefix('/') +} + +/// The dotted parts of `module` below `package`, when it sits in that package. +pub(crate) fn module_below<'m>(module: &'m str, package: &str) -> Option> { + let rest: &str = module.strip_prefix(package)?; + if rest.is_empty() { + return Some(Vec::new()); + } + Some(rest.strip_prefix('.')?.split('.').collect()) +} + +/// The unit folders under `python/nodes/`, each relative to it. pub(crate) fn unit_folders(sources: &[PythonSource]) -> BTreeSet { sources .iter() .filter_map(|source| { - let (root, rest) = source.relative_path.split_once('/')?; - let parts: Vec<&str> = rest.split('/').collect(); - (root == PACKAGE_ROOT) - .then(|| unit_folder(&parts)) - .flatten() + let parts: Vec<&str> = package_rest(&source.relative_path)?.split('/').collect(); + unit_folder(&parts) }) .collect() } @@ -272,7 +296,7 @@ pub(crate) fn imported_module( file: &UnitFile<'_>, project: &UnitProject<'_>, ) -> Option { - let mut folder: Vec<&str> = vec![PACKAGE_ROOT]; + let mut folder: Vec<&str> = PACKAGE_MODULE.split('.').collect(); folder.extend(&file.parts[..file.parts.len() - 1]); absolute_module(import, &folder, &project.modules) } @@ -312,7 +336,7 @@ pub(crate) fn unit_imports<'f>( ) -> Vec<&'f UnitImport> { let targets: Vec = modules .iter() - .map(|module| format!("{PACKAGE_ROOT}.{}.{module}", unit.replace('/', "."))) + .map(|module| format!("{PACKAGE_MODULE}.{}.{module}", unit.replace('/', "."))) .collect(); file.module .imports diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/units/providers.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/units/providers.rs index b88f4e2db6..29c90239bc 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/units/providers.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/units/providers.rs @@ -8,14 +8,14 @@ use crate::models::{Fault, PythonSource}; use crate::python_rules::_helpers::engine::faults::catalogue_fault; use crate::python_rules::_helpers::engine::placement::package_anchor; use crate::python_rules::_helpers::units::project::{ - absolute_module, dotted_names, files_naming, project_modules, rejected_import_faults, - unit_fault, + absolute_module, dotted_names, files_naming, module_below, project_modules, + rejected_import_faults, unit_fault, }; use crate::python_rules::constants::{ - INIT_FILE, ORCHESTRATION_ROOT, PACKAGE_ROOT, PRIVATE_PREFIX, PROVIDER_BASE, PROVIDER_FILE, - PROVIDER_IMPORT_BOUNDARIES_CODE, PROVIDER_LAYOUT_CODE, PROVIDER_MODULE_SHAPE_CODE, - PROVIDER_PRIVATE_FOLDERS, PROVIDER_ROLE_FILES, PROVIDER_RULE_CODES, PROVIDERS_ROOT, - SHARED_UTILITIES_PACKAGE, STAR_IMPORT, + INIT_FILE, ORCHESTRATION_ROOT, PACKAGE_MODULE, PACKAGE_ROOT, PRIVATE_PREFIX, PROVIDER_BASE, + PROVIDER_FILE, PROVIDER_IMPORT_BOUNDARIES_CODE, PROVIDER_LAYOUT_CODE, + PROVIDER_MODULE_SHAPE_CODE, PROVIDER_PRIVATE_FOLDERS, PROVIDER_ROLE_FILES, PROVIDER_RULE_CODES, + PROVIDERS_MODULE, PROVIDERS_ROOT, SHARED_UTILITIES_PACKAGE, STAR_IMPORT, }; use crate::python_rules::models::ParsedFile; @@ -34,12 +34,15 @@ pub(crate) fn provider_faults( return Vec::new(); } let mut faults: Vec = provider_layout_faults(sources); - let files: Vec> = files_naming(sources, PROVIDERS_ROOT, python_version); + let files: Vec> = + files_naming(sources, (PROVIDERS_ROOT, PROVIDERS_MODULE), python_version); let modules: BTreeSet = project_modules(sources); let classes: ProviderClasses = provider_classes(&files, &modules); for file in &files { - if matches!(file.parts.as_slice(), [root, _, file_name] if *root == PROVIDERS_ROOT && *file_name == PROVIDER_FILE) - { + if matches!( + provider_parts(file.path).as_deref(), + Some([_, file_name]) if *file_name == PROVIDER_FILE + ) { faults.extend(provider_module_faults(file, &classes)); } faults.extend(import_faults(file, &modules)); @@ -321,15 +324,25 @@ fn base_target(file: &ParsedFile<'_>, base: &str, modules: &BTreeSet) -> } } -/// The dotted module of a project file, such as `providers.storefront_api.provider`. +/// The parts of a `python/providers/` file's path below that folder. +fn provider_parts(path: &str) -> Option> { + Some( + path.strip_prefix(PROVIDERS_ROOT)? + .strip_prefix('/')? + .split('/') + .collect(), + ) +} + +/// The dotted module of a project file, such as `python.providers.storefront_api.provider`. fn file_module(path: &str) -> String { dotted_names(path).pop().unwrap_or_default() } /// Imports of another provider's private code, and a provider's imports of python/ outside utils/ or of orchestration/. fn import_faults(file: &ParsedFile<'_>, modules: &BTreeSet) -> Vec { - let capability: Option<&str> = match file.parts.as_slice() { - [root, capability, _, ..] if *root == PROVIDERS_ROOT => Some(capability), + let capability: Option<&str> = match provider_parts(file.path).as_deref() { + Some([capability, _, ..]) => Some(capability), _ => None, }; rejected_import_faults(file, modules, |module| { @@ -339,22 +352,20 @@ fn import_faults(file: &ParsedFile<'_>, modules: &BTreeSet) -> Vec) -> Option { - let parts: Vec<&str> = module.split('.').collect(); - if let [root, owner, folder, ..] = parts.as_slice() { - let private: bool = *root == PROVIDERS_ROOT && PROVIDER_PRIVATE_FOLDERS.contains(folder); - if private && capability != Some(*owner) { - return Some(format!("which is private to {PROVIDERS_ROOT}/{owner}/")); - } + if let Some([owner, folder, ..]) = module_below(module, PROVIDERS_MODULE).as_deref() + && PROVIDER_PRIVATE_FOLDERS.contains(folder) + && capability != Some(*owner) + { + return Some(format!("which is private to {PROVIDERS_ROOT}/{owner}/")); } capability?; - match parts.as_slice() { - [root, utils, ..] if *root == PACKAGE_ROOT && *utils == SHARED_UTILITIES_PACKAGE => None, - [root, ..] if *root == PACKAGE_ROOT => Some(format!( - "but a provider imports only {PACKAGE_ROOT}/{SHARED_UTILITIES_PACKAGE}/ from {PACKAGE_ROOT}/" - )), - [root, ..] if *root == ORCHESTRATION_ROOT => Some(format!( - "but a provider never imports {ORCHESTRATION_ROOT}/" - )), - _ => None, + if let Some(below) = module_below(module, PACKAGE_MODULE) { + return (below.first() != Some(&SHARED_UTILITIES_PACKAGE)).then(|| { + format!( + "but a provider imports only {PACKAGE_ROOT}/{SHARED_UTILITIES_PACKAGE}/ from {PACKAGE_ROOT}/" + ) + }); } + module_below(module, ORCHESTRATION_ROOT) + .map(|_| format!("but a provider never imports {ORCHESTRATION_ROOT}/")) } diff --git a/crates/sqlbuild-rules/src/python_rules/_helpers/units/python_tests.rs b/crates/sqlbuild-rules/src/python_rules/_helpers/units/python_tests.rs index ed24478126..1c4758b6c3 100644 --- a/crates/sqlbuild-rules/src/python_rules/_helpers/units/python_tests.rs +++ b/crates/sqlbuild-rules/src/python_rules/_helpers/units/python_tests.rs @@ -1,10 +1,12 @@ -//! Where project Python tests sit: each mirrors an existing folder, and each test module a module, under `python/` or `providers/`. +//! Where project Python tests sit: each mirrors an existing folder, and each test module a module, under `python/nodes/`, `python/providers/` or `orchestration/`. use std::collections::BTreeSet; use crate::models::{Fault, PythonSource}; use crate::python_rules::_helpers::engine::faults::catalogue_fault; -use crate::python_rules::constants::{PYTHON_TEST_PLACEMENT_CODE, TEST_FILE_PREFIX}; +use crate::python_rules::constants::{ + MIRRORED_TEST_ROOTS, PYTHON_TEST_PLACEMENT_CODE, TEST_FILE_PREFIX, +}; /// A fault on each Python test whose mirrored folder, or for a test module whose module, is not in the project. pub(crate) fn python_test_faults( @@ -33,10 +35,16 @@ pub(crate) fn python_test_faults( .collect() } -/// What the test at `path`, such as `tests/python/orders/test_export.py`, mirrors that the project lacks. +/// What the test at `path`, such as `tests/python/nodes/orders/test_export.py`, mirrors that the project lacks. fn missing_counterpart(path: &str, paths: &BTreeSet<&str>) -> Option { - let parts: Vec<&str> = path.split('/').collect(); - let [_, root, folders @ .., file] = parts.as_slice() else { + let below: &str = path.strip_prefix("tests/")?; + let root: &str = MIRRORED_TEST_ROOTS.iter().find(|root| { + below + .strip_prefix(**root) + .is_some_and(|rest| rest.starts_with('/')) + })?; + let parts: Vec<&str> = below[root.len() + 1..].split('/').collect(); + let [folders @ .., file] = parts.as_slice() else { return None; }; if folders.is_empty() { diff --git a/crates/sqlbuild-rules/src/python_rules/constants.rs b/crates/sqlbuild-rules/src/python_rules/constants.rs index 4e40981814..9c86654dd5 100644 --- a/crates/sqlbuild-rules/src/python_rules/constants.rs +++ b/crates/sqlbuild-rules/src/python_rules/constants.rs @@ -15,8 +15,8 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ applies: PythonFiles::Package, enabled_by_default: true, options: &[], - message: "python/ may hold only domain packages, utils/ and __init__.py", - remediation: "Move direct modules into a domain package. Give each node its own unit folder holding node.py and main.py inside its domain, such as python/orders/partner_export/, and keep role folders such as _helpers/ inside the domain or unit.", + message: "python/nodes/ may hold only domain packages, utils/ and __init__.py", + remediation: "Move direct modules into a domain package. Give each node its own unit folder holding its declaration file and main.py inside its domain, such as python/nodes/orders/partner_export/, and keep role folders such as _helpers/ inside the domain or unit.", }, PythonRuleSpec { code: "SQBRPYTHON002", @@ -27,8 +27,8 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ applies: PythonFiles::Package, enabled_by_default: true, options: &[], - message: "packages under python/ must be named for what they own", - remediation: "Rename generic packages such as common/, shared/ or helpers/ after the domain or capability they hold; utils/ is allowed only directly under python/.", + message: "packages under python/nodes/ must be named for what they own", + remediation: "Rename generic packages such as common/, shared/ or helpers/ after the domain or capability they hold; utils/ is allowed only directly under python/nodes/.", }, PythonRuleSpec { code: "SQBRPYTHON003", @@ -39,8 +39,8 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ applies: PythonFiles::Package, enabled_by_default: true, options: &[], - message: "a unit folder holds node.py, main.py, optional role files and _helpers/ only", - remediation: "Add main.py beside node.py, and move any other module into _helpers/ or a named role file: checks.py, models.py, types.py, constants.py or exceptions.py.", + message: "a unit folder holds one declaration file, main.py, optional role files and _helpers/ only", + remediation: "Add main.py beside the declaration file (loader.py, asset.py, loaders.py, assets.py or factory.py), and move any other module into _helpers/ or a named role file: checks.py, models.py, types.py, constants.py or exceptions.py.", }, PythonRuleSpec { code: "SQBRPYTHON004", @@ -51,8 +51,8 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ applies: PythonFiles::Package, enabled_by_default: true, options: &[], - message: "node.py holds imports and exactly one node or factory declaration", - remediation: "Keep one @loader, @asset or @factory function in node.py; move helpers to _helpers/, constants to constants.py and checks to checks.py.", + message: "a declaration file holds imports and exactly one node or factory declaration", + remediation: "Keep one @loader, @asset or @factory function in the declaration file; move helpers to _helpers/, constants to constants.py and checks to checks.py.", }, PythonRuleSpec { code: "SQBRPYTHON005", @@ -64,7 +64,7 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ enabled_by_default: true, options: &[], message: "a node declaration's body is `return main(...)` from its unit's main.py, with every argument passed by keyword", - remediation: "Move the logic into main() in the unit's main.py, import it with `from .main import main` or its full python. path, and pass each argument as name=value, including ctx.", + remediation: "Move the logic into main() in the unit's main.py, import it with `from .main import main` or its full python.nodes. path, and pass each argument as name=value, including ctx.", }, PythonRuleSpec { code: "SQBRPYTHON006", @@ -99,8 +99,8 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ applies: PythonFiles::Package, enabled_by_default: true, options: &[], - message: "a unit imports only its own files, its domain's role files and _helpers/, python/utils/, provider role files, and other units' node.py for depends_on", - remediation: "Import shared code from python/utils// or the domain's role files, and name another unit's node only in depends_on; never import another unit's main.py, role files or _helpers/.", + message: "a unit imports only its own files, its domain's role files and _helpers/, python/nodes/utils/, provider role files, and other units' declaration files for depends_on", + remediation: "Import shared code from python/nodes/utils// or the domain's role files, and name another unit's node only in depends_on; never import another unit's main.py, role files or _helpers/.", }, PythonRuleSpec { code: "SQBRPYTHON009", @@ -147,8 +147,8 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ applies: PythonFiles::Package, enabled_by_default: true, options: &[], - message: "nodes are declared in a unit's node.py, and checks in a unit's checks.py", - remediation: "Move the declaration into its own unit folder under its domain, with the implementation in that folder's main.py.", + message: "nodes are declared in a unit's file named for their kind: loader.py, asset.py, loaders.py, assets.py, factory.py or checks.py", + remediation: "Move the declaration into its own unit folder under its domain, in the file named for what it declares, with the implementation in that folder's main.py.", }, PythonRuleSpec { code: "SQBRPYTHON013", @@ -159,8 +159,8 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ applies: PythonFiles::All, enabled_by_default: true, options: &[], - message: "providers/ holds capability folders, each with provider.py, optional role files, _helpers/ and _classes/ only", - remediation: "Move a module directly under providers/ into providers//provider.py, add provider.py to each capability folder, and move other modules into _helpers/, _classes/ or a role file: models.py, types.py, constants.py or exceptions.py.", + message: "python/providers/ holds capability folders, each with provider.py, optional role files, _helpers/ and _classes/ only", + remediation: "Move a module directly under python/providers/ into python/providers//provider.py, add provider.py to each capability folder, and move other modules into _helpers/, _classes/ or a role file: models.py, types.py, constants.py or exceptions.py.", }, PythonRuleSpec { code: "SQBRPYTHON014", @@ -183,8 +183,8 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ applies: PythonFiles::All, enabled_by_default: true, options: &[], - message: "a provider's _helpers/ and _classes/ are private to it, and providers import only python/utils/ from the runtime package and nothing from orchestration/", - remediation: "Import a provider through provider.py or its role files; move code a provider shares with nodes into python/utils//.", + message: "a provider's _helpers/ and _classes/ are private to it, and providers import only python/nodes/utils/ from the node package and nothing from orchestration/", + remediation: "Import a provider through provider.py or its role files; move code a provider shares with nodes into python/nodes/utils//.", }, PythonRuleSpec { code: "SQBRPYTHON016", @@ -255,8 +255,8 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ applies: PythonFiles::Tests, enabled_by_default: true, options: &[], - message: "Python tests must mirror an existing module under python/, providers/ or orchestration/", - remediation: "Move the test to tests/python/, tests/providers/ or tests/orchestration/ at the path of the module it tests: tests/python/orders/storefront_import/test_main.py tests python/orders/storefront_import/main.py.", + message: "Python tests must mirror an existing module under python/nodes/, python/providers/ or orchestration/", + remediation: "Move the test to tests/python/nodes/, tests/python/providers/ or tests/orchestration/ at the path of the module it tests: tests/python/nodes/orders/storefront_import/test_main.py tests python/nodes/orders/storefront_import/main.py.", }, PythonRuleSpec { code: "SQBRPYTHON022", @@ -1354,8 +1354,10 @@ pub(crate) const PYTHON_RULES: [PythonRuleSpec; 108] = [ }, ]; -/// The project folder that holds the runtime Python package, imported as `python`. -pub(crate) const PACKAGE_ROOT: &str = "python"; +/// The project folder that holds the node package, imported as `python.nodes`. +pub(crate) const PACKAGE_ROOT: &str = "python/nodes"; +/// The dotted module of the node package. +pub(crate) const PACKAGE_MODULE: &str = "python.nodes"; /// Fensu's scope for runtime code; every carried family applies to it. pub(crate) const ROOT_SCOPE: &str = "root"; pub(crate) const INIT_FILE: &str = "__init__.py"; @@ -1552,6 +1554,9 @@ pub(crate) const CONNECTING_FUNCTIONS: [&str; 2] = ["connect", "create_pool"]; pub(crate) const PACKAGE_INIT_MODULE: &str = "__init__"; /// Fensu's scope for test files, the only scope its test rules check. pub(crate) const TEST_SCOPE: &str = "test"; +/// The project folders Python tests mirror, each below `tests/`. +pub(crate) const MIRRORED_TEST_ROOTS: [&str; 3] = + ["python/nodes", "python/providers", "orchestration"]; /// The prefix of a test module's file name; other files in a mirrored test folder need only the folder. pub(crate) const TEST_FILE_PREFIX: &str = "test_"; /// The orchestration rules, which read sensor and calendar modules and their importers. @@ -1581,11 +1586,17 @@ pub(crate) const ORCHESTRATION_SUPPORT_FOLDER: &str = "_helpers"; pub(crate) const PRIVATE_PREFIX: &str = "_"; /// The name a `from module import *` binds. pub(crate) const STAR_IMPORT: &str = "*"; -/// The file that declares a unit's node and makes its folder a unit. -pub(crate) const UNIT_NODE_FILE: &str = "node.py"; +/// The files that declare a unit's nodes and make its folder a unit, one per unit. +pub(crate) const UNIT_DECLARATION_FILES: [&str; 5] = [ + "loader.py", + "asset.py", + "loaders.py", + "assets.py", + "factory.py", +]; /// The file holding a unit's checks. pub(crate) const UNIT_CHECKS_FILE: &str = "checks.py"; -/// The files a unit folder may hold beside `node.py` and `main.py`. +/// The files a unit folder may hold beside its declaration file and `main.py`. pub(crate) const UNIT_ROLE_FILES: [&str; 6] = [ "checks.py", "models.py", @@ -1600,15 +1611,17 @@ pub(crate) const UNIT_HELPERS_FOLDER: &str = "_helpers"; pub(crate) const SHARED_ROLE_MODULES: [&str; 4] = ["models", "types", "constants", "exceptions"]; /// The modules a factory may take its specs from. pub(crate) const SPEC_MODULES: [&str; 2] = ["constants", "models"]; -/// The project folder holding providers, imported as `providers`. -pub(crate) const PROVIDERS_ROOT: &str = "providers"; +/// The project folder holding providers, imported as `python.providers`. +pub(crate) const PROVIDERS_ROOT: &str = "python/providers"; +/// The dotted module of the providers package. +pub(crate) const PROVIDERS_MODULE: &str = "python.providers"; /// The public files of a provider capability a unit may import, as module names. pub(crate) const PROVIDER_ROLE_MODULES: [&str; 5] = ["provider", "models", "types", "constants", "exceptions"]; /// The module a node delegates to, and the function it calls. pub(crate) const MAIN_NAME: &str = "main"; -/// The module a unit declares its node in. -pub(crate) const NODE_MODULE: &str = "node"; +/// The modules a unit declares its nodes in. +pub(crate) const NODE_MODULES: [&str; 5] = ["loader", "asset", "loaders", "assets", "factory"]; /// The only positional parameter of a node or check. pub(crate) const CONTEXT_PARAMETER: &str = "ctx"; /// The decorator keywords the unit rules read. diff --git a/crates/sqlbuild-rules/src/python_rules/tests/helpers.rs b/crates/sqlbuild-rules/src/python_rules/tests/helpers.rs index 07d4bf4333..90e5de28b0 100644 --- a/crates/sqlbuild-rules/src/python_rules/tests/helpers.rs +++ b/crates/sqlbuild-rules/src/python_rules/tests/helpers.rs @@ -59,7 +59,7 @@ pub(super) fn core_rule_faults(source: &str, fensu_code: &str) -> Vec<(String, u /// The speculation keys of a request selecting `select`, before and after its one Python module changes from `original` to `edited`. pub(super) fn source_keys(select: &[&str], original: &str, edited: &str) -> (String, String) { let directory = tempfile::tempdir().expect("temporary project"); - let module = directory.path().join("python/orders/main.py"); + let module = directory.path().join("python/nodes/orders/main.py"); std::fs::create_dir_all(module.parent().expect("parent")).expect("folders"); std::fs::write(&module, original).expect("module"); let before: String = request_key(directory.path(), select); @@ -169,14 +169,14 @@ pub(super) fn scaling_project( functions: usize, ) -> Vec<(String, String)> { let helper = ( - "python/utils/text/join.py".to_owned(), + "python/nodes/utils/text/join.py".to_owned(), "\"\"\"Join text.\"\"\"\n\n\ndef joined(value: str) -> str:\n \"\"\"Return the value.\"\"\"\n return value\n".to_owned(), ); let modules = (0..units).map(|unit| { ( - format!("python/domain_{}/unit_{unit}/main.py", unit % 50), + format!("python/nodes/domain_{}/unit_{unit}/main.py", unit % 50), format!( - "\"\"\"Unit {unit}.\"\"\"\n\nfrom python.utils.text.join import joined\n\n\ndef run_{unit}(value: str) -> str:\n \"\"\"Run unit {unit}.\"\"\"\n return joined(value)\n" + "\"\"\"Unit {unit}.\"\"\"\n\nfrom python.nodes.utils.text.join import joined\n\n\ndef run_{unit}(value: str) -> str:\n \"\"\"Run unit {unit}.\"\"\"\n return joined(value)\n" ), ) }); @@ -186,7 +186,7 @@ pub(super) fn scaling_project( format!("def alert_{function}(ctx, reason):\n print(ctx, reason)\n\n\n") }) .collect(); - (format!("hooks/python/alert_{file}.py"), body) + (format!("sql/hooks/python/alert_{file}.py"), body) }); std::iter::once(helper) .chain(modules) @@ -202,7 +202,7 @@ pub(super) fn unit_scaling_project(units: usize, undescribed: usize) -> Vec<(Str unit_files( unit, &format!( - "from {}.node import node_{previous}\n", + "from {}.asset import node_{previous}\n", unit_module(previous) ), &format!("depends_on=[node_{previous}], description=\"Unit {unit}.\""), @@ -210,7 +210,7 @@ pub(super) fn unit_scaling_project(units: usize, undescribed: usize) -> Vec<(Str }); let bare = (units..units + undescribed).flat_map(|unit| unit_files(unit, "", "")); let utils = ( - "python/utils/text/join.py".to_owned(), + "python/nodes/utils/text/join.py".to_owned(), "def joined(value: str) -> str:\n return value\n".to_owned(), ); head.into_iter() @@ -221,7 +221,7 @@ pub(super) fn unit_scaling_project(units: usize, undescribed: usize) -> Vec<(Str } fn unit_module(unit: usize) -> String { - format!("python.area{}.unit_{unit}", unit % 50) + format!("python.nodes.area{}.unit_{unit}", unit % 50) } /// The node, main and checks files of `unit`, its node importing `upstream` and declared with `arguments`. @@ -230,19 +230,19 @@ fn unit_files(unit: usize, upstream: &str, arguments: &str) -> [(String, String) let dir = module.replace('.', "/"); [ ( - format!("{dir}/node.py"), + format!("{dir}/asset.py"), format!( "{upstream}from {module}.main import main\n\n\n@asset({arguments})\ndef node_{unit}(ctx: AssetContext) -> None:\n return main(ctx=ctx)\n" ), ), ( format!("{dir}/main.py"), - "from sqlbuild import PythonNodeResult\n\nfrom python.utils.text.join import joined\n\n\ndef main(ctx: AssetContext) -> PythonNodeResult:\n return ctx.result(joined(\"\"))\n".to_owned(), + "from sqlbuild import PythonNodeResult\n\nfrom python.nodes.utils.text.join import joined\n\n\ndef main(ctx: AssetContext) -> PythonNodeResult:\n return ctx.result(joined(\"\"))\n".to_owned(), ), ( format!("{dir}/checks.py"), format!( - "from {module}.node import node_{unit}\n\n\n@check(depends_on=[node_{unit}], description=\"Ran.\")\ndef ran_{unit}(ctx: CheckContext) -> bool:\n return ctx.ok()\n" + "from {module}.asset import node_{unit}\n\n\n@check(depends_on=[node_{unit}], description=\"Ran.\")\ndef ran_{unit}(ctx: CheckContext) -> bool:\n return ctx.ok()\n" ), ), ] @@ -258,15 +258,15 @@ pub(super) fn purity_chain_project( for chain in 0..chains { for step in 1..depth { files.push(( - format!("python/utils/chain_{chain}/step_{previous}.py", previous = step - 1), + format!("python/nodes/utils/chain_{chain}/step_{previous}.py", previous = step - 1), format!( - "from python.utils.chain_{chain} import step_{step}\n\n\ndef run():\n return step_{step}.run()\n" + "from python.nodes.utils.chain_{chain} import step_{step}\n\n\ndef run():\n return step_{step}.run()\n" ), )); } files.push(( format!( - "python/utils/chain_{chain}/step_{last}.py", + "python/nodes/utils/chain_{chain}/step_{last}.py", last = depth - 1 ), "import requests\n\n\ndef run():\n return requests.get(\"https://example.com\")\n" @@ -275,9 +275,9 @@ pub(super) fn purity_chain_project( } for root in 0..roots { files.push(( - format!("python/orders/export_{root}/constants.py"), + format!("python/nodes/orders/export_{root}/constants.py"), format!( - "from python.utils.chain_{chain} import step_0\n\nREGIONS = step_0.run()\n", + "from python.nodes.utils.chain_{chain} import step_0\n\nREGIONS = step_0.run()\n", chain = root % chains ), )); diff --git a/crates/sqlbuild-rules/src/python_rules/tests/test_compile_purity_rules.rs b/crates/sqlbuild-rules/src/python_rules/tests/test_compile_purity_rules.rs index 772582d4fd..4d29a63860 100644 --- a/crates/sqlbuild-rules/src/python_rules/tests/test_compile_purity_rules.rs +++ b/crates/sqlbuild-rules/src/python_rules/tests/test_compile_purity_rules.rs @@ -6,7 +6,7 @@ use crate::python_rules::tests::test_types::{PythonRunFailureTestCase, PythonRun const PURE_FACTORY: &str = r#"from sqlbuild.assets import factory, asset -from python.inventory.snapshots.constants import WAREHOUSE_SPECS +from python.nodes.inventory.snapshots.constants import WAREHOUSE_SPECS @factory @@ -70,7 +70,7 @@ const SENSOR: &str = r#"from orchestration.sensors.inventory._helpers import fee LATEST = feed.latest() "#; -const FEED: &str = r#"from python.utils.network import ping +const FEED: &str = r#"from python.nodes.utils.network import ping def latest(): @@ -82,7 +82,7 @@ def again(): "#; const NETWORK: &str = r#"import socket -from python.utils import network +from python.nodes.utils import network def ping(): @@ -105,7 +105,7 @@ SHELL = SSHClient() "#; const DEFERRED: &str = r#"import subprocess -from python.utils.shell import deferred_runner +from python.nodes.utils.shell import deferred_runner HANDLERS = {"ls": lambda: subprocess.run(["ls"])} RUNNER = deferred_runner() @@ -131,12 +131,12 @@ fn given_compile_time_python_when_evaluating_compile_time_purity_then_reports_ca PythonRunTestCase { description: "static specs, node bodies, main() and provider methods report nothing", files: &[ - ("python/inventory/snapshots/node.py", PURE_FACTORY), + ("python/nodes/inventory/snapshots/asset.py", PURE_FACTORY), ( - "python/inventory/snapshots/constants.py", + "python/nodes/inventory/snapshots/constants.py", "WAREHOUSE_SPECS = (\"north\", \"south\")\n", ), - ("python/orders/export/main.py", RUNTIME_ONLY), + ("python/nodes/orders/export/main.py", RUNTIME_ONLY), ], config: json!({ "select": ["SQBRPYTHON022"] }), expected_faults: vec![], @@ -144,16 +144,22 @@ fn given_compile_time_python_when_evaluating_compile_time_purity_then_reports_ca PythonRunTestCase { description: "module scope, factory bodies and the project functions they call are followed to each external call", files: &[ - ("python/inventory/snapshots/node.py", QUERYING_FACTORY), ( - "python/inventory/snapshots/_helpers/spec_loading.py", + "python/nodes/inventory/snapshots/asset.py", + QUERYING_FACTORY, + ), + ( + "python/nodes/inventory/snapshots/_helpers/spec_loading.py", SPEC_LOADING, ), - ("python/orders/storefront_import/constants.py", REGIONS), + ( + "python/nodes/orders/storefront_import/constants.py", + REGIONS, + ), ("orchestration/sensors/inventory/stock_feed.py", SENSOR), ("orchestration/sensors/inventory/_helpers/feed.py", FEED), - ("python/utils/network.py", NETWORK), - ("providers/carrier_api/constants.py", CLIENTS), + ("python/nodes/utils/network.py", NETWORK), + ("python/providers/carrier_api/constants.py", CLIENTS), ], config: json!({ "select": ["SQBRPYTHON022"] }), expected_faults: vec![ @@ -163,60 +169,93 @@ fn given_compile_time_python_when_evaluating_compile_time_purity_then_reports_ca 3, 10, ), - ("SQBRPYTHON022", "providers/carrier_api/constants.py", 6, 10), - ("SQBRPYTHON022", "providers/carrier_api/constants.py", 7, 11), - ("SQBRPYTHON022", "providers/carrier_api/constants.py", 8, 8), - ("SQBRPYTHON022", "providers/carrier_api/constants.py", 9, 9), ( "SQBRPYTHON022", - "python/inventory/snapshots/node.py", + "python/nodes/inventory/snapshots/asset.py", 10, 13, ), ( "SQBRPYTHON022", - "python/inventory/snapshots/node.py", + "python/nodes/inventory/snapshots/asset.py", 11, 12, ), ( "SQBRPYTHON022", - "python/orders/storefront_import/constants.py", + "python/nodes/orders/storefront_import/constants.py", 3, 22, ), + ( + "SQBRPYTHON022", + "python/providers/carrier_api/constants.py", + 6, + 10, + ), + ( + "SQBRPYTHON022", + "python/providers/carrier_api/constants.py", + 7, + 11, + ), + ( + "SQBRPYTHON022", + "python/providers/carrier_api/constants.py", + 8, + 8, + ), + ( + "SQBRPYTHON022", + "python/providers/carrier_api/constants.py", + 9, + 9, + ), ], }, PythonRunTestCase { description: "lambda bodies and the __main__ block never run on import, but a lambda default and an else branch do", files: &[ - ("python/orders/export/constants.py", DEFERRED), - ("python/utils/shell.py", SHELL), + ("python/nodes/orders/export/constants.py", DEFERRED), + ("python/nodes/utils/shell.py", SHELL), ], config: json!({ "select": ["SQBRPYTHON022"] }), expected_faults: vec![ - ("SQBRPYTHON022", "python/orders/export/constants.py", 7, 24), - ("SQBRPYTHON022", "python/orders/export/constants.py", 12, 5), + ( + "SQBRPYTHON022", + "python/nodes/orders/export/constants.py", + 7, + 24, + ), + ( + "SQBRPYTHON022", + "python/nodes/orders/export/constants.py", + 12, + 5, + ), ], }, PythonRunTestCase { description: "an approved loader boundary stops the walk at exactly that function", files: &[ - ("python/inventory/snapshots/node.py", QUERYING_FACTORY), ( - "python/inventory/snapshots/_helpers/spec_loading.py", + "python/nodes/inventory/snapshots/asset.py", + QUERYING_FACTORY, + ), + ( + "python/nodes/inventory/snapshots/_helpers/spec_loading.py", SPEC_LOADING, ), ], config: json!({ "select": ["SQBRPYTHON022"], "rule_options": { "SQBRPYTHON022": { "approved_loader_boundaries": [ - "python.inventory.snapshots._helpers.spec_loading.load_specs", + "python.nodes.inventory.snapshots._helpers.spec_loading.load_specs", ] } }, }), expected_faults: vec![( "SQBRPYTHON022", - "python/inventory/snapshots/node.py", + "python/nodes/inventory/snapshots/asset.py", 10, 13, )], @@ -224,16 +263,19 @@ fn given_compile_time_python_when_evaluating_compile_time_purity_then_reports_ca PythonRunTestCase { description: "an approved factory runs its body unchecked", files: &[ - ("python/inventory/snapshots/node.py", QUERYING_FACTORY), ( - "python/inventory/snapshots/_helpers/spec_loading.py", + "python/nodes/inventory/snapshots/asset.py", + QUERYING_FACTORY, + ), + ( + "python/nodes/inventory/snapshots/_helpers/spec_loading.py", SPEC_LOADING, ), ], config: json!({ "select": ["SQBRPYTHON022"], "rule_options": { "SQBRPYTHON022": { "approved_loader_boundaries": [ - "python.inventory.snapshots.node.warehouse_snapshots", + "python.nodes.inventory.snapshots.asset.warehouse_snapshots", ] } }, }), expected_faults: vec![], @@ -256,19 +298,22 @@ fn given_a_boundary_naming_a_module_when_evaluating_compile_time_purity_then_the let test_cases = [PythonRunFailureTestCase { description: "a module is not a loader boundary", files: &[ - ("python/inventory/snapshots/node.py", QUERYING_FACTORY), ( - "python/inventory/snapshots/_helpers/spec_loading.py", + "python/nodes/inventory/snapshots/asset.py", + QUERYING_FACTORY, + ), + ( + "python/nodes/inventory/snapshots/_helpers/spec_loading.py", SPEC_LOADING, ), ], config: json!({ "select": ["SQBRPYTHON022"], "rule_options": { "SQBRPYTHON022": { "approved_loader_boundaries": [ - "python.inventory.snapshots._helpers.spec_loading", + "python.nodes.inventory.snapshots._helpers.spec_loading", ] } }, }), - expected_error: "names the module python.inventory.snapshots._helpers.spec_loading", + expected_error: "names the module python.nodes.inventory.snapshots._helpers.spec_loading", }]; for test_case in test_cases { let faults = python_rule_faults(test_case.files, test_case.config); diff --git a/crates/sqlbuild-rules/src/python_rules/tests/test_evaluate_python_rules.rs b/crates/sqlbuild-rules/src/python_rules/tests/test_evaluate_python_rules.rs index 83398c9e41..a2f351a8f0 100644 --- a/crates/sqlbuild-rules/src/python_rules/tests/test_evaluate_python_rules.rs +++ b/crates/sqlbuild-rules/src/python_rules/tests/test_evaluate_python_rules.rs @@ -10,81 +10,87 @@ fn given_project_python_when_evaluating_python_rules_then_reports_fensu_findings install_test_identity(); let test_cases = [ PythonRunTestCase { - description: "a file outside python/ reports at a character column after non-ASCII text", + description: "a file outside python/nodes/ reports at a character column after non-ASCII text", files: &[( - "hooks/python/notify.py", + "sql/hooks/python/notify.py", "\"\"\"Notify.\"\"\"\n\n\ndef send(é: int, count) -> None:\n pass\n", )], config: json!({ "select": ["SQBRPYTHON101"] }), - expected_faults: vec![("SQBRPYTHON101", "hooks/python/notify.py", 4, 18)], + expected_faults: vec![("SQBRPYTHON101", "sql/hooks/python/notify.py", 4, 18)], }, PythonRunTestCase { - description: "python/ holds only domains, utils/ and __init__.py; folders report on their anchor", + description: "python/nodes/ holds only domains, utils/ and __init__.py; folders report on their anchor", files: &[ ("python/__init__.py", ""), - ("python/report.py", "\"\"\"Report.\"\"\"\n"), - ("python/loaders/orders.py", "\"\"\"Orders.\"\"\"\n"), - ("python/_helpers/Alpha.py", "\"\"\"Alpha.\"\"\"\n"), - ("python/_helpers/__init__.py", ""), - ("python/orders/daily/node.py", "\"\"\"Daily.\"\"\"\n"), - ("python/utils/currency/format.py", "\"\"\"Format.\"\"\"\n"), + ("python/nodes/report.py", "\"\"\"Report.\"\"\"\n"), + ("python/nodes/loaders/orders.py", "\"\"\"Orders.\"\"\"\n"), + ("python/nodes/_helpers/Alpha.py", "\"\"\"Alpha.\"\"\"\n"), + ("python/nodes/_helpers/__init__.py", ""), + ("python/nodes/orders/daily/asset.py", "\"\"\"Daily.\"\"\"\n"), + ( + "python/nodes/utils/currency/format.py", + "\"\"\"Format.\"\"\"\n", + ), ], config: json!({ "select": ["SQBRPYTHON001"] }), expected_faults: vec![ - ("SQBRPYTHON001", "python/_helpers/__init__.py", 1, 1), - ("SQBRPYTHON001", "python/loaders/orders.py", 1, 1), - ("SQBRPYTHON001", "python/report.py", 1, 1), + ("SQBRPYTHON001", "python/nodes/_helpers/__init__.py", 1, 1), + ("SQBRPYTHON001", "python/nodes/loaders/orders.py", 1, 1), + ("SQBRPYTHON001", "python/nodes/report.py", 1, 1), ], }, PythonRunTestCase { description: "generic package names report once per package, except utils/ at the root", files: &[ - ("python/orders/common/b.py", "\"\"\"B.\"\"\"\n"), - ("python/orders/common/a.py", "\"\"\"A.\"\"\"\n"), - ("python/utils/currency/format.py", "\"\"\"Format.\"\"\"\n"), - ("python/utils/shared/text.py", "\"\"\"Text.\"\"\"\n"), - ("python/helpers/rows.py", "\"\"\"Rows.\"\"\"\n"), + ("python/nodes/orders/common/b.py", "\"\"\"B.\"\"\"\n"), + ("python/nodes/orders/common/a.py", "\"\"\"A.\"\"\"\n"), + ( + "python/nodes/utils/currency/format.py", + "\"\"\"Format.\"\"\"\n", + ), + ("python/nodes/utils/shared/text.py", "\"\"\"Text.\"\"\"\n"), + ("python/nodes/helpers/rows.py", "\"\"\"Rows.\"\"\"\n"), ], config: json!({ "select": ["SQBRPYTHON002"] }), expected_faults: vec![ - ("SQBRPYTHON002", "python/helpers/rows.py", 1, 1), - ("SQBRPYTHON002", "python/orders/common/a.py", 1, 1), - ("SQBRPYTHON002", "python/utils/shared/text.py", 1, 1), + ("SQBRPYTHON002", "python/nodes/helpers/rows.py", 1, 1), + ("SQBRPYTHON002", "python/nodes/orders/common/a.py", 1, 1), + ("SQBRPYTHON002", "python/nodes/utils/shared/text.py", 1, 1), ], }, PythonRunTestCase { - description: "package-only rules skip files outside python/", + description: "package-only rules skip files outside python/nodes/", files: &[ - ("python/report.py", "\"\"\"Report.\"\"\"\n"), - ("providers/report.py", "\"\"\"Report.\"\"\"\n"), + ("python/nodes/report.py", "\"\"\"Report.\"\"\"\n"), + ("python/providers/report.py", "\"\"\"Report.\"\"\"\n"), ], config: json!({ "select": ["SQBRPYTHON614"] }), - expected_faults: vec![("SQBRPYTHON614", "python/report.py", 1, 1)], + expected_faults: vec![("SQBRPYTHON614", "python/nodes/report.py", 1, 1)], }, PythonRunTestCase { description: "a unit main.py is an entry module holding one public function", files: &[ ( - "python/orders/daily/main.py", + "python/nodes/orders/daily/main.py", "def first() -> None:\n pass\n\n\ndef second() -> None:\n pass\n", ), ( - "python/orders/weekly/main.py", + "python/nodes/orders/weekly/main.py", "def only() -> None:\n pass\n", ), ], config: json!({ "select": ["SQBRPYTHON617"] }), - expected_faults: vec![("SQBRPYTHON617", "python/orders/daily/main.py", 1, 1)], + expected_faults: vec![("SQBRPYTHON617", "python/nodes/orders/daily/main.py", 1, 1)], }, PythonRunTestCase { description: "a main-only threshold reads its option and skips helpers", files: &[ ( - "python/orders/main/build.py", + "python/nodes/orders/main/build.py", "def build() -> None:\n a: int = 1\n b: int = a\n print(b)\n", ), ( - "python/orders/_helpers/build_rows.py", + "python/nodes/orders/_helpers/build_rows.py", "def build_rows() -> None:\n a: int = 1\n b: int = a\n print(b)\n", ), ], @@ -92,17 +98,17 @@ fn given_project_python_when_evaluating_python_rules_then_reports_fensu_findings "select": ["SQBRPYTHON501"], "rule_options": { "SQBRPYTHON501": { "max_statements": 2 } }, }), - expected_faults: vec![("SQBRPYTHON501", "python/orders/main/build.py", 1, 1)], + expected_faults: vec![("SQBRPYTHON501", "python/nodes/orders/main/build.py", 1, 1)], }, PythonRunTestCase { description: "a package-wide rule reports once per package", files: &[ ( - "python/orders/_helpers/first.py", + "python/nodes/orders/_helpers/first.py", "def first() -> None:\n pass\n", ), ( - "python/orders/_helpers/second.py", + "python/nodes/orders/_helpers/second.py", "def second() -> None:\n pass\n", ), ], @@ -110,27 +116,32 @@ fn given_project_python_when_evaluating_python_rules_then_reports_fensu_findings "select": ["SQBRPYTHON610"], "rule_options": { "SQBRPYTHON610": { "max_helpers_container_modules": 1 } }, }), - expected_faults: vec![("SQBRPYTHON610", "python/orders/_helpers/first.py", 1, 1)], + expected_faults: vec![( + "SQBRPYTHON610", + "python/nodes/orders/_helpers/first.py", + 1, + 1, + )], }, PythonRunTestCase { description: "a public main entry nobody outside its domain imports", files: &[( - "python/orders/main/export.py", + "python/nodes/orders/main/export.py", "def export_orders() -> None:\n pass\n", )], config: json!({ "select": ["SQBRPYTHON305"] }), - expected_faults: vec![("SQBRPYTHON305", "python/orders/main/export.py", 1, 1)], + expected_faults: vec![("SQBRPYTHON305", "python/nodes/orders/main/export.py", 1, 1)], }, PythonRunTestCase { description: "a hook importing a public main entry counts as outside use", files: &[ ( - "python/orders/main/export.py", + "python/nodes/orders/main/export.py", "def export_orders() -> None:\n pass\n", ), ( - "hooks/python/notify.py", - "from python.orders.main.export import export_orders\n\n\ndef notify() -> None:\n export_orders()\n", + "sql/hooks/python/notify.py", + "from python.nodes.orders.main.export import export_orders\n\n\ndef notify() -> None:\n export_orders()\n", ), ], config: json!({ "select": ["SQBRPYTHON305"] }), @@ -139,69 +150,74 @@ fn given_project_python_when_evaluating_python_rules_then_reports_fensu_findings PythonRunTestCase { description: "naming contracts apply", files: &[( - "providers/flags.py", + "python/providers/flags.py", "def is_ready() -> int:\n return 1\n", )], config: json!({ "select": ["SQBRPYTHON402"] }), - expected_faults: vec![("SQBRPYTHON402", "providers/flags.py", 1, 1)], + expected_faults: vec![("SQBRPYTHON402", "python/providers/flags.py", 1, 1)], }, PythonRunTestCase { description: "imports resolve under the python package", files: &[ ( - "python/orders/main/export.py", - "from python.billing.main._totals import total\n", + "python/nodes/orders/main/export.py", + "from python.nodes.billing.main._totals import total\n", ), ( - "python/billing/main/_totals.py", + "python/nodes/billing/main/_totals.py", "def total() -> int:\n return 1\n", ), ], config: json!({ "select": ["SQBRPYTHON304"] }), - expected_faults: vec![("SQBRPYTHON304", "python/orders/main/export.py", 1, 1)], + expected_faults: vec![("SQBRPYTHON304", "python/nodes/orders/main/export.py", 1, 1)], }, PythonRunTestCase { description: "a discarded result of a project function is found through the called module", files: &[ ( - "python/orders/main/export.py", - "from python.orders._helpers.totals import order_total\n\n\ndef export_orders() -> None:\n order_total()\n", + "python/nodes/orders/main/export.py", + "from python.nodes.orders._helpers.totals import order_total\n\n\ndef export_orders() -> None:\n order_total()\n", ), ( - "python/orders/_helpers/totals.py", + "python/nodes/orders/_helpers/totals.py", "def order_total() -> int:\n return 1\n", ), ], config: json!({ "select": ["SQBRPYTHON506"] }), - expected_faults: vec![("SQBRPYTHON506", "python/orders/main/export.py", 5, 5)], + expected_faults: vec![("SQBRPYTHON506", "python/nodes/orders/main/export.py", 5, 5)], }, PythonRunTestCase { description: "node and hook functions are live, unreferenced helpers are dead, and hooks are never reported", files: &[ ( - "python/orders/daily/node.py", + "python/nodes/orders/daily/asset.py", "@loader\ndef daily() -> None:\n pass\n", ), ( - "python/orders/_helpers/unused.py", + "python/nodes/orders/_helpers/unused.py", "def unused() -> None:\n pass\n", ), ( - "python/orders/_helpers/totals.py", + "python/nodes/orders/_helpers/totals.py", "def order_total() -> int:\n return 1\n", ), ( - "hooks/python/notify.py", - "from python.orders._helpers.totals import order_total\n\n_UNUSED_LIMIT: int = 3\n\n\ndef notify() -> int:\n return order_total()\n", + "sql/hooks/python/notify.py", + "from python.nodes.orders._helpers.totals import order_total\n\n_UNUSED_LIMIT: int = 3\n\n\ndef notify() -> int:\n return order_total()\n", ), ], config: json!({ "select": ["SQBRPYTHON306"] }), - expected_faults: vec![("SQBRPYTHON306", "python/orders/_helpers/unused.py", 1, 1)], + expected_faults: vec![( + "SQBRPYTHON306", + "python/nodes/orders/_helpers/unused.py", + 1, + 1, + )], }, PythonRunTestCase { - description: "an audit factory under python/ is loaded", + description: "an audit factory under python/nodes/ is loaded", files: &[( - "python/orders/quality/factories.py", + "python/nodes/orders/quality/factories.py", "@audit_factory\ndef order_quality() -> list:\n return []\n", )], config: json!({ "select": ["SQBRPYTHON306"] }), @@ -211,16 +227,16 @@ fn given_project_python_when_evaluating_python_rules_then_reports_fensu_findings description: "a submodule imported from a folder without __init__.py is used", files: &[ ( - "python/orders/_tables.py", + "python/nodes/orders/_tables.py", "TABLES: int = 1\nUNUSED: int = 2\n", ), ( - "python/orders/node.py", - "from python.orders import _tables\n\n\n@asset\ndef count() -> int:\n return _tables.TABLES\n", + "python/nodes/orders/asset.py", + "from python.nodes.orders import _tables\n\n\n@asset\ndef count() -> int:\n return _tables.TABLES\n", ), ], config: json!({ "select": ["SQBRPYTHON306"] }), - expected_faults: vec![("SQBRPYTHON306", "python/orders/_tables.py", 2, 1)], + expected_faults: vec![("SQBRPYTHON306", "python/nodes/orders/_tables.py", 2, 1)], }, ]; for test_case in test_cases { @@ -240,8 +256,8 @@ fn given_python_the_parser_rejects_when_evaluating_python_rules_then_the_run_fai install_test_identity(); let test_cases = [PythonParseFailureTestCase { description: "a parameter list cut short", - files: &[("python/orders/main/bad.py", "def broken(:\n")], - expected_error: "python/orders/main/bad.py:1:12: cannot parse Python source", + files: &[("python/nodes/orders/main/bad.py", "def broken(:\n")], + expected_error: "python/nodes/orders/main/bad.py:1:12: cannot parse Python source", }]; for test_case in test_cases { let faults = python_rule_faults(test_case.files, json!({ "select": ["SQBRPYTHON101"] })); diff --git a/crates/sqlbuild-rules/src/python_rules/tests/test_node_units.rs b/crates/sqlbuild-rules/src/python_rules/tests/test_node_units.rs index 9e2ffee3fc..51fe6b7ba2 100644 --- a/crates/sqlbuild-rules/src/python_rules/tests/test_node_units.rs +++ b/crates/sqlbuild-rules/src/python_rules/tests/test_node_units.rs @@ -39,19 +39,22 @@ fn given_node_units_when_evaluating_unit_rules_then_reports_each_broken_conventi PythonRunTestCase { description: "a project laid out in units reports nothing", files: &[ - ("providers/store/provider.py", "class Store:\n pass\n"), ( - "python/utils/text.py", + "python/providers/store/provider.py", + "class Store:\n pass\n", + ), + ( + "python/nodes/utils/text.py", "def clean() -> str:\n return ''\n", ), - ("python/orders/constants.py", "LIMIT: int = 3\n"), + ("python/nodes/orders/constants.py", "LIMIT: int = 3\n"), ( - "python/orders/_helpers/dates.py", + "python/nodes/orders/_helpers/dates.py", "def today() -> str:\n return ''\n", ), ( - "python/orders/daily/node.py", - r#"from providers.store.provider import Store + "python/nodes/orders/daily/asset.py", + r#"from python.providers.store.provider import Store from .main import main @@ -62,14 +65,14 @@ def daily(ctx: AssetContext, *, store: Store) -> None: "#, ), ( - "python/orders/daily/main.py", + "python/nodes/orders/daily/main.py", r#""""Daily totals.""" from sqlbuild import PythonNodeResult, PythonNodeSkipResult -from providers.store.provider import Store -from python.orders._helpers.dates import today -from python.orders.constants import LIMIT -from python.utils.text import clean +from python.providers.store.provider import Store +from python.nodes.orders._helpers.dates import today +from python.nodes.orders.constants import LIMIT +from python.nodes.utils.text import clean from ._helpers.rows import rows @@ -79,12 +82,12 @@ def main(ctx: AssetContext, store: Store) -> PythonNodeResult | PythonNodeSkipRe "#, ), ( - "python/orders/daily/_helpers/rows.py", + "python/nodes/orders/daily/_helpers/rows.py", "def rows() -> list:\n return []\n", ), ( - "python/orders/daily/checks.py", - r#"from .node import daily + "python/nodes/orders/daily/checks.py", + r#"from .asset import daily @check(depends_on=[daily], description="Totals are positive.") @@ -93,9 +96,9 @@ def totals_positive(ctx: CheckContext) -> bool: "#, ), ( - "python/orders/weekly/node.py", - r#"from python.orders.daily.node import daily -from python.orders.weekly.main import main + "python/nodes/orders/weekly/asset.py", + r#"from python.nodes.orders.daily.asset import daily +from python.nodes.orders.weekly.main import main @asset(depends_on=[daily], description="Weekly.") @@ -104,11 +107,11 @@ def weekly(ctx: AssetContext) -> None: "#, ), ( - "python/orders/weekly/main.py", + "python/nodes/orders/weekly/main.py", "def main(ctx: AssetContext) -> PythonNodeResult:\n return ctx.result()\n", ), ( - "python/orders/raw/node.py", + "python/nodes/orders/raw/loader.py", r#"from .main import main @@ -118,11 +121,11 @@ def raw(ctx: LoaderContext) -> list: "#, ), ( - "python/orders/raw/main.py", + "python/nodes/orders/raw/main.py", "def main(ctx: LoaderContext) -> Optional[Iterator[dict]]:\n return None\n", ), ( - "python/orders/regions/node.py", + "python/nodes/orders/regions/factory.py", r#"from .constants import REGIONS from .main import main @@ -141,11 +144,11 @@ def region_exports(): "#, ), ( - "python/orders/regions/constants.py", + "python/nodes/orders/regions/constants.py", "REGIONS: tuple = ('eu', 'us')\n", ), ( - "python/orders/regions/main.py", + "python/nodes/orders/regions/main.py", "def main(ctx: AssetContext, region: str) -> PythonNodeResult:\n return ctx.result()\n", ), ], @@ -155,25 +158,35 @@ def region_exports(): PythonRunTestCase { description: "unit layout: a missing main.py, a stray module and a folder that is not _helpers/", files: &[ - ("python/orders/daily/node.py", DAILY_ASSET), - ("python/orders/weekly/node.py", ""), - ("python/orders/weekly/main.py", ""), - ("python/orders/weekly/report.py", ""), - ("python/orders/weekly/sql/query.py", ""), - ("python/orders/weekly/_helpers/rows.py", ""), + ("python/nodes/orders/daily/asset.py", DAILY_ASSET), + ("python/nodes/orders/weekly/asset.py", ""), + ("python/nodes/orders/weekly/main.py", ""), + ("python/nodes/orders/weekly/report.py", ""), + ("python/nodes/orders/weekly/sql/query.py", ""), + ("python/nodes/orders/weekly/_helpers/rows.py", ""), ], config: json!({ "select": ["SQBRPYTHON003"] }), expected_faults: vec![ - ("SQBRPYTHON003", "python/orders/daily/node.py", 1, 1), - ("SQBRPYTHON003", "python/orders/weekly/report.py", 1, 1), - ("SQBRPYTHON003", "python/orders/weekly/sql/query.py", 1, 1), + ("SQBRPYTHON003", "python/nodes/orders/daily/asset.py", 1, 1), + ( + "SQBRPYTHON003", + "python/nodes/orders/weekly/report.py", + 1, + 1, + ), + ( + "SQBRPYTHON003", + "python/nodes/orders/weekly/sql/query.py", + 1, + 1, + ), ], }, PythonRunTestCase { - description: "node.py: statements, helpers and a second declaration report; an empty node.py reports at its start", + description: "asset.py: statements, helpers and a second declaration report; an empty asset.py reports at its start", files: &[ ( - "python/orders/daily/node.py", + "python/nodes/orders/daily/asset.py", r#""""Daily.""" from .main import main @@ -194,23 +207,26 @@ def extra(ctx: AssetContext) -> None: return main(ctx=ctx) "#, ), - ("python/orders/weekly/node.py", "from .main import main\n"), + ( + "python/nodes/orders/weekly/asset.py", + "from .main import main\n", + ), ], config: json!({ "select": ["SQBRPYTHON004"] }), expected_faults: vec![ - ("SQBRPYTHON004", "python/orders/daily/node.py", 4, 1), - ("SQBRPYTHON004", "python/orders/daily/node.py", 7, 5), - ("SQBRPYTHON004", "python/orders/daily/node.py", 17, 5), - ("SQBRPYTHON004", "python/orders/weekly/node.py", 1, 1), + ("SQBRPYTHON004", "python/nodes/orders/daily/asset.py", 4, 1), + ("SQBRPYTHON004", "python/nodes/orders/daily/asset.py", 7, 5), + ("SQBRPYTHON004", "python/nodes/orders/daily/asset.py", 17, 5), + ("SQBRPYTHON004", "python/nodes/orders/weekly/asset.py", 1, 1), ], }, PythonRunTestCase { description: "delegation: positional arguments, extra statements, unpacking and another unit's main report", files: &[ ( - "python/orders/daily/node.py", - r#"from python.orders.daily.main import main -from python.orders.weekly.main import main as weekly_main + "python/nodes/orders/daily/asset.py", + r#"from python.nodes.orders.daily.main import main +from python.nodes.orders.weekly.main import main as weekly_main @asset(description="A.") @@ -234,10 +250,10 @@ def unpacked(ctx: AssetContext) -> None: return main(**ctx) "#, ), - ("python/orders/daily/main.py", ASSET_MAIN), + ("python/nodes/orders/daily/main.py", ASSET_MAIN), ( - "python/orders/weekly/node.py", - r#"from python.orders.daily.main import main + "python/nodes/orders/weekly/asset.py", + r#"from python.nodes.orders.daily.main import main @asset(description="W.") @@ -245,22 +261,22 @@ def weekly(ctx: AssetContext) -> None: return main(ctx=ctx) "#, ), - ("python/orders/weekly/main.py", ASSET_MAIN), + ("python/nodes/orders/weekly/main.py", ASSET_MAIN), ], config: json!({ "select": ["SQBRPYTHON005"] }), expected_faults: vec![ - ("SQBRPYTHON005", "python/orders/daily/node.py", 11, 5), - ("SQBRPYTHON005", "python/orders/daily/node.py", 16, 5), - ("SQBRPYTHON005", "python/orders/daily/node.py", 22, 5), - ("SQBRPYTHON005", "python/orders/weekly/node.py", 5, 5), + ("SQBRPYTHON005", "python/nodes/orders/daily/asset.py", 11, 5), + ("SQBRPYTHON005", "python/nodes/orders/daily/asset.py", 16, 5), + ("SQBRPYTHON005", "python/nodes/orders/daily/asset.py", 22, 5), + ("SQBRPYTHON005", "python/nodes/orders/weekly/asset.py", 5, 5), ], }, PythonRunTestCase { description: "main.py: other statements, a result that does not fit the node kind, and no main()", files: &[ - ("python/orders/daily/node.py", DAILY_ASSET), + ("python/nodes/orders/daily/asset.py", DAILY_ASSET), ( - "python/orders/daily/main.py", + "python/nodes/orders/daily/main.py", r#"from sqlbuild import PythonNodeResult LIMIT = 3 @@ -274,38 +290,41 @@ def helper() -> None: pass "#, ), - ("python/orders/weekly/node.py", ""), + ("python/nodes/orders/weekly/asset.py", ""), ( - "python/orders/weekly/main.py", + "python/nodes/orders/weekly/main.py", "def run() -> None:\n pass\n", ), - ("python/orders/stock/node.py", ""), - ("python/orders/stock/main.py", "def main(ctx):\n pass\n"), + ("python/nodes/orders/stock/asset.py", ""), + ( + "python/nodes/orders/stock/main.py", + "def main(ctx):\n pass\n", + ), ( - "python/orders/raw/node.py", + "python/nodes/orders/raw/loader.py", "from .main import main\n\n\n@loader\ndef raw(ctx: LoaderContext) -> list:\n return main(ctx=ctx)\n", ), ( - "python/orders/raw/main.py", + "python/nodes/orders/raw/main.py", "def main(ctx: LoaderContext) -> PythonNodeResult:\n return []\n", ), ], config: json!({ "select": ["SQBRPYTHON006"] }), expected_faults: vec![ - ("SQBRPYTHON006", "python/orders/daily/main.py", 3, 1), - ("SQBRPYTHON006", "python/orders/daily/main.py", 6, 5), - ("SQBRPYTHON006", "python/orders/daily/main.py", 10, 5), - ("SQBRPYTHON006", "python/orders/raw/main.py", 1, 5), - ("SQBRPYTHON006", "python/orders/stock/main.py", 1, 5), - ("SQBRPYTHON006", "python/orders/weekly/main.py", 1, 1), - ("SQBRPYTHON006", "python/orders/weekly/main.py", 1, 5), + ("SQBRPYTHON006", "python/nodes/orders/daily/main.py", 3, 1), + ("SQBRPYTHON006", "python/nodes/orders/daily/main.py", 6, 5), + ("SQBRPYTHON006", "python/nodes/orders/daily/main.py", 10, 5), + ("SQBRPYTHON006", "python/nodes/orders/raw/main.py", 1, 5), + ("SQBRPYTHON006", "python/nodes/orders/stock/main.py", 1, 5), + ("SQBRPYTHON006", "python/nodes/orders/weekly/main.py", 1, 1), + ("SQBRPYTHON006", "python/nodes/orders/weekly/main.py", 1, 5), ], }, PythonRunTestCase { description: "signature: ctx missing or mistyped, variadics and unannotated providers report; positional-only ctx does not", files: &[ ( - "python/orders/daily/node.py", + "python/nodes/orders/daily/asset.py", r#"from .main import main @@ -330,8 +349,8 @@ def positional_only(ctx: AssetContext, /) -> None: "#, ), ( - "python/orders/daily/checks.py", - r#"from .node import no_ctx + "python/nodes/orders/daily/checks.py", + r#"from .asset import no_ctx @check(depends_on=[no_ctx], description="Q.") @@ -342,42 +361,42 @@ def quality(ctx: AssetContext) -> bool: ], config: json!({ "select": ["SQBRPYTHON007"] }), expected_faults: vec![ - ("SQBRPYTHON007", "python/orders/daily/checks.py", 5, 5), - ("SQBRPYTHON007", "python/orders/daily/node.py", 5, 5), - ("SQBRPYTHON007", "python/orders/daily/node.py", 10, 5), - ("SQBRPYTHON007", "python/orders/daily/node.py", 15, 5), - ("SQBRPYTHON007", "python/orders/daily/node.py", 15, 5), + ("SQBRPYTHON007", "python/nodes/orders/daily/asset.py", 5, 5), + ("SQBRPYTHON007", "python/nodes/orders/daily/asset.py", 10, 5), + ("SQBRPYTHON007", "python/nodes/orders/daily/asset.py", 15, 5), + ("SQBRPYTHON007", "python/nodes/orders/daily/asset.py", 15, 5), + ("SQBRPYTHON007", "python/nodes/orders/daily/checks.py", 5, 5), ], }, PythonRunTestCase { description: "imports: another unit's main, role files and helpers, a domain module, and a node used outside depends_on report", files: &[ - ("providers/store/provider.py", ""), - ("providers/store/client.py", ""), - ("python/utils/text.py", ""), - ("python/orders/constants.py", ""), + ("python/providers/store/provider.py", ""), + ("python/providers/store/client.py", ""), + ("python/nodes/utils/text.py", ""), + ("python/nodes/orders/constants.py", ""), ( - "python/orders/report.py", - "from python.orders.weekly.main import main\n", + "python/nodes/orders/report.py", + "from python.nodes.orders.weekly.main import main\n", ), - ("python/orders/_helpers/dates.py", ""), - ("python/orders/daily/node.py", DAILY_ASSET), - ("python/orders/daily/_helpers/rows.py", ""), + ("python/nodes/orders/_helpers/dates.py", ""), + ("python/nodes/orders/daily/asset.py", DAILY_ASSET), + ("python/nodes/orders/daily/_helpers/rows.py", ""), ( - "python/orders/daily/main.py", + "python/nodes/orders/daily/main.py", r#"import os from sqlbuild import PythonNodeResult -from providers.store.provider import Store -from python.utils.text import clean -from python.orders.constants import LIMIT -from python.orders._helpers.dates import today +from python.providers.store.provider import Store +from python.nodes.utils.text import clean +from python.nodes.orders.constants import LIMIT +from python.nodes.orders._helpers.dates import today from ._helpers.rows import rows -from python.orders.report import summary -from python.orders.weekly.main import main as weekly -from python.orders.weekly.constants import WEEK -from python.orders.weekly._helpers.x import x -from python.billing.invoices.node import invoices -from providers.store.client import Client +from python.nodes.orders.report import summary +from python.nodes.orders.weekly.main import main as weekly +from python.nodes.orders.weekly.constants import WEEK +from python.nodes.orders.weekly._helpers.x import x +from python.nodes.billing.invoices.asset import invoices +from python.providers.store.client import Client def main(ctx: AssetContext) -> PythonNodeResult: @@ -385,8 +404,8 @@ def main(ctx: AssetContext) -> PythonNodeResult: "#, ), ( - "python/orders/weekly/node.py", - r#"from python.orders.daily.node import daily + "python/nodes/orders/weekly/asset.py", + r#"from python.nodes.orders.daily.asset import daily from .main import main @@ -395,35 +414,35 @@ def weekly(ctx: AssetContext) -> None: return main(ctx=ctx) "#, ), - ("python/orders/weekly/main.py", ASSET_MAIN), - ("python/orders/weekly/constants.py", ""), - ("python/orders/weekly/_helpers/x.py", ""), - ("python/billing/invoices/node.py", ""), - ("python/billing/invoices/main.py", ""), + ("python/nodes/orders/weekly/main.py", ASSET_MAIN), + ("python/nodes/orders/weekly/constants.py", ""), + ("python/nodes/orders/weekly/_helpers/x.py", ""), + ("python/nodes/billing/invoices/asset.py", ""), + ("python/nodes/billing/invoices/main.py", ""), ], config: json!({ "select": ["SQBRPYTHON008"] }), expected_faults: vec![ - ("SQBRPYTHON008", "python/orders/daily/main.py", 8, 34), - ("SQBRPYTHON008", "python/orders/daily/main.py", 9, 39), - ("SQBRPYTHON008", "python/orders/daily/main.py", 10, 44), - ("SQBRPYTHON008", "python/orders/daily/main.py", 11, 45), - ("SQBRPYTHON008", "python/orders/daily/main.py", 12, 42), - ("SQBRPYTHON008", "python/orders/daily/main.py", 13, 36), + ("SQBRPYTHON008", "python/nodes/orders/daily/main.py", 8, 40), + ("SQBRPYTHON008", "python/nodes/orders/daily/main.py", 9, 45), + ("SQBRPYTHON008", "python/nodes/orders/daily/main.py", 10, 50), + ("SQBRPYTHON008", "python/nodes/orders/daily/main.py", 11, 51), + ("SQBRPYTHON008", "python/nodes/orders/daily/main.py", 12, 49), + ("SQBRPYTHON008", "python/nodes/orders/daily/main.py", 13, 43), ], }, PythonRunTestCase { description: "checks.py: statements, a check of another unit's node, a check that computes, and a plain function report", files: &[ - ("python/orders/daily/node.py", DAILY_ASSET), + ("python/nodes/orders/daily/asset.py", DAILY_ASSET), ( - "python/orders/weekly/node.py", + "python/nodes/orders/weekly/asset.py", "@asset\ndef weekly(ctx):\n pass\n", ), ( - "python/orders/daily/checks.py", - r#"from python.orders.weekly.node import weekly + "python/nodes/orders/daily/checks.py", + r#"from python.nodes.orders.weekly.asset import weekly -from .node import daily +from .asset import daily LIMIT = 3 @@ -451,19 +470,34 @@ def helper() -> None: ], config: json!({ "select": ["SQBRPYTHON009"] }), expected_faults: vec![ - ("SQBRPYTHON009", "python/orders/daily/checks.py", 5, 1), - ("SQBRPYTHON009", "python/orders/daily/checks.py", 14, 5), - ("SQBRPYTHON009", "python/orders/daily/checks.py", 19, 5), - ("SQBRPYTHON009", "python/orders/daily/checks.py", 24, 5), + ("SQBRPYTHON009", "python/nodes/orders/daily/checks.py", 5, 1), + ( + "SQBRPYTHON009", + "python/nodes/orders/daily/checks.py", + 14, + 5, + ), + ( + "SQBRPYTHON009", + "python/nodes/orders/daily/checks.py", + 19, + 5, + ), + ( + "SQBRPYTHON009", + "python/nodes/orders/daily/checks.py", + 24, + 5, + ), ], }, PythonRunTestCase { description: "factories: specs from outside the unit, an unnamed generated node and no loop report", files: &[ - ("python/orders/constants.py", "MARKETS: tuple = ()\n"), + ("python/nodes/orders/constants.py", "MARKETS: tuple = ()\n"), ( - "python/orders/markets/node.py", - r#"from python.orders.constants import MARKETS + "python/nodes/orders/markets/assets.py", + r#"from python.nodes.orders.constants import MARKETS from .main import main @@ -477,7 +511,7 @@ def market_exports(): "#, ), ( - "python/orders/once/node.py", + "python/nodes/orders/once/assets.py", r#"from .main import main @@ -491,16 +525,26 @@ def once(): ], config: json!({ "select": ["SQBRPYTHON010"] }), expected_faults: vec![ - ("SQBRPYTHON010", "python/orders/markets/node.py", 6, 5), - ("SQBRPYTHON010", "python/orders/markets/node.py", 10, 13), - ("SQBRPYTHON010", "python/orders/once/node.py", 5, 5), + ( + "SQBRPYTHON010", + "python/nodes/orders/markets/assets.py", + 6, + 5, + ), + ( + "SQBRPYTHON010", + "python/nodes/orders/markets/assets.py", + 10, + 13, + ), + ("SQBRPYTHON010", "python/nodes/orders/once/assets.py", 5, 5), ], }, PythonRunTestCase { description: "descriptions: a docstring, a described loader and an undescribed check report", files: &[ ( - "python/orders/daily/node.py", + "python/nodes/orders/daily/asset.py", r#"from .main import main @@ -516,8 +560,8 @@ def bare(ctx: AssetContext) -> None: "#, ), ( - "python/orders/daily/checks.py", - r#"from .node import described + "python/nodes/orders/daily/checks.py", + r#"from .asset import described @check(depends_on=[described]) @@ -526,7 +570,7 @@ def quality(ctx: CheckContext) -> bool: "#, ), ( - "python/orders/raw/node.py", + "python/nodes/orders/raw/loader.py", r#"from .main import main @@ -538,16 +582,16 @@ def raw(ctx: LoaderContext) -> list: ], config: json!({ "select": ["SQBRPYTHON011"] }), expected_faults: vec![ - ("SQBRPYTHON011", "python/orders/daily/checks.py", 5, 5), - ("SQBRPYTHON011", "python/orders/daily/node.py", 10, 5), - ("SQBRPYTHON011", "python/orders/raw/node.py", 5, 5), + ("SQBRPYTHON011", "python/nodes/orders/daily/asset.py", 10, 5), + ("SQBRPYTHON011", "python/nodes/orders/daily/checks.py", 5, 5), + ("SQBRPYTHON011", "python/nodes/orders/raw/loader.py", 5, 5), ], }, PythonRunTestCase { - description: "declarations outside a unit's node.py or checks.py report; a factory's checks in node.py do not", + description: "declarations outside a unit's kind file or checks.py report; a factory's checks in factory.py do not", files: &[ ( - "python/orders/loaders.py", + "python/nodes/orders/loaders.py", r#"@loader def raw_orders(ctx: LoaderContext) -> list: return [] @@ -559,11 +603,11 @@ def raw_orders_present(ctx: CheckContext) -> bool: "#, ), ( - "python/orders/daily/main.py", + "python/nodes/orders/daily/main.py", "@asset(description=\"X.\")\ndef stray(ctx: AssetContext) -> None:\n return None\n", ), ( - "python/orders/daily/node.py", + "python/nodes/orders/daily/factory.py", r#"from .constants import TABLES from .main import main @@ -582,24 +626,24 @@ def tables(): "#, ), ( - "python/orders/daily/checks.py", + "python/nodes/orders/daily/checks.py", "@factory\ndef audits():\n pass\n", ), ( - "python/orders/quality/factories.py", + "python/nodes/orders/quality/factories.py", "@audit_factory\ndef audits():\n pass\n", ), ( - "python/utils/flat.py", + "python/nodes/utils/flat.py", "@asset\ndef util_asset(ctx):\n return 1\n", ), ], config: json!({ "select": ["SQBRPYTHON012"] }), expected_faults: vec![ - ("SQBRPYTHON012", "python/orders/daily/main.py", 2, 5), - ("SQBRPYTHON012", "python/orders/loaders.py", 2, 5), - ("SQBRPYTHON012", "python/orders/loaders.py", 7, 5), - ("SQBRPYTHON012", "python/utils/flat.py", 2, 5), + ("SQBRPYTHON012", "python/nodes/orders/daily/main.py", 2, 5), + ("SQBRPYTHON012", "python/nodes/orders/loaders.py", 2, 5), + ("SQBRPYTHON012", "python/nodes/orders/loaders.py", 7, 5), + ("SQBRPYTHON012", "python/nodes/utils/flat.py", 2, 5), ], }, ]; @@ -621,19 +665,25 @@ fn given_valid_shapes_and_hidden_mistakes_when_evaluating_unit_rules_then_report install_test_identity(); let test_cases = [ PythonRunTestCase { - description: "a node.py in utils/, a role folder or a unit's _helpers/ is not a unit", + description: "a asset.py in utils/, a role folder or a unit's _helpers/ is not a unit", files: &[ - ("python/utils/graph/node.py", "class Node:\n pass\n"), - ("python/orders/models/node.py", "class Node:\n pass\n"), - ("python/orders/daily/node.py", DAILY_ASSET), - ("python/orders/daily/main.py", ASSET_MAIN), ( - "python/orders/daily/_helpers/node.py", + "python/nodes/utils/graph/asset.py", + "class Node:\n pass\n", + ), + ( + "python/nodes/orders/models/asset.py", "class Node:\n pass\n", ), + ("python/nodes/orders/daily/asset.py", DAILY_ASSET), + ("python/nodes/orders/daily/main.py", ASSET_MAIN), ( - "python/orders/daily/_helpers/rows.py", - "from python.orders.daily.main import main\n", + "python/nodes/orders/daily/_helpers/asset.py", + "class Node:\n pass\n", + ), + ( + "python/nodes/orders/daily/_helpers/rows.py", + "from python.nodes.orders.daily.main import main\n", ), ], config: json!({ "select": UNIT_RULES }), @@ -643,11 +693,11 @@ fn given_valid_shapes_and_hidden_mistakes_when_evaluating_unit_rules_then_report description: "a factory may read specs through a method, a module attribute or a builtin call, and loop again inside", files: &[ ( - "python/orders/regions/constants.py", + "python/nodes/orders/regions/constants.py", "SPECS: dict = {}\nTABLES: tuple = ()\n", ), ( - "python/orders/regions/node.py", + "python/nodes/orders/regions/factory.py", r#"from . import constants from .constants import SPECS from .main import main @@ -669,10 +719,13 @@ def region_exports(): return main(ctx=ctx) "#, ), - ("python/orders/regions/main.py", ASSET_MAIN), - ("python/orders/ranked/constants.py", "SPECS: dict = {}\n"), + ("python/nodes/orders/regions/main.py", ASSET_MAIN), + ( + "python/nodes/orders/ranked/constants.py", + "SPECS: dict = {}\n", + ), ( - "python/orders/ranked/node.py", + "python/nodes/orders/ranked/assets.py", r#"from .constants import SPECS from .main import main @@ -686,7 +739,7 @@ def ranked_exports(): return main(ctx=ctx, region=region) "#, ), - ("python/orders/ranked/main.py", ASSET_MAIN), + ("python/nodes/orders/ranked/main.py", ASSET_MAIN), ], config: json!({ "select": ["SQBRPYTHON010"] }), expected_faults: vec![], @@ -694,16 +747,16 @@ def ranked_exports(): PythonRunTestCase { description: "imports under if TYPE_CHECKING: are imports, and their boundaries are checked", files: &[ - ("providers/store/provider.py", ""), + ("python/providers/store/provider.py", ""), ( - "python/orders/daily/node.py", + "python/nodes/orders/daily/asset.py", r#"from typing import TYPE_CHECKING from .main import main if TYPE_CHECKING: - from providers.store.provider import Store - from python.orders.weekly.main import main as weekly_main + from python.providers.store.provider import Store + from python.nodes.orders.weekly.main import main as weekly_main @asset(description="Daily.") @@ -711,59 +764,59 @@ def daily(ctx: AssetContext, *, store: "Store") -> None: return main(ctx=ctx, store=store) "#, ), - ("python/orders/daily/main.py", ASSET_MAIN), - ("python/orders/weekly/node.py", DAILY_ASSET), - ("python/orders/weekly/main.py", ASSET_MAIN), + ("python/nodes/orders/daily/main.py", ASSET_MAIN), + ("python/nodes/orders/weekly/asset.py", DAILY_ASSET), + ("python/nodes/orders/weekly/main.py", ASSET_MAIN), ], config: json!({ "select": ["SQBRPYTHON004", "SQBRPYTHON007", "SQBRPYTHON008"] }), - expected_faults: vec![("SQBRPYTHON008", "python/orders/daily/node.py", 7, 43)], + expected_faults: vec![("SQBRPYTHON008", "python/nodes/orders/daily/asset.py", 7, 49)], }, PythonRunTestCase { description: "a node named through import a.b in depends_on passes; an unused import of a node does not", files: &[ - ("python/orders/daily/node.py", DAILY_ASSET), - ("python/orders/daily/main.py", ASSET_MAIN), + ("python/nodes/orders/daily/asset.py", DAILY_ASSET), + ("python/nodes/orders/daily/main.py", ASSET_MAIN), ( - "python/orders/weekly/node.py", - r#"import python.orders.daily.node + "python/nodes/orders/weekly/asset.py", + r#"import python.nodes.orders.daily.node from .main import main -@asset(depends_on=[python.orders.daily.node.daily], description="W.") +@asset(depends_on=[python.nodes.orders.daily.asset.daily], description="W.") def weekly(ctx: AssetContext) -> None: return main(ctx=ctx) "#, ), - ("python/orders/weekly/main.py", ASSET_MAIN), + ("python/nodes/orders/weekly/main.py", ASSET_MAIN), ( - "python/orders/weekly/_helpers/rows.py", - "from python.orders.daily.node import daily\n", + "python/nodes/orders/weekly/_helpers/rows.py", + "from python.nodes.orders.daily.asset import daily\n", ), ], config: json!({ "select": ["SQBRPYTHON008"] }), expected_faults: vec![( "SQBRPYTHON008", - "python/orders/weekly/_helpers/rows.py", + "python/nodes/orders/weekly/_helpers/rows.py", 1, - 38, + 45, )], }, PythonRunTestCase { description: "a quoted union result and a loader's tuple of rows fit their node", files: &[ - ("python/orders/daily/node.py", DAILY_ASSET), + ("python/nodes/orders/daily/asset.py", DAILY_ASSET), ( - "python/orders/daily/main.py", + "python/nodes/orders/daily/main.py", "def main(ctx: AssetContext) -> \"PythonNodeResult | PythonNodeSkipResult\":\n return ctx.result()\n", ), ( - "python/orders/raw/node.py", + "python/nodes/orders/raw/loader.py", "from .main import main\n\n\n@loader\ndef raw(ctx: LoaderContext) -> tuple:\n return main(ctx=ctx)\n", ), ( - "python/orders/raw/main.py", - "def main(ctx: LoaderContext) -> \"tuple[python.orders.raw.types.Row, ...]\":\n return ()\n", + "python/nodes/orders/raw/main.py", + "def main(ctx: LoaderContext) -> \"tuple[python.nodes.orders.raw.types.Row, ...]\":\n return ()\n", ), ], config: json!({ "select": ["SQBRPYTHON006"] }), @@ -773,13 +826,13 @@ def weekly(ctx: AssetContext) -> None: description: "a node that calls the main.py module instead of main() reports", files: &[ ( - "python/orders/daily/node.py", + "python/nodes/orders/daily/asset.py", "from . import main\n\n\n@asset(description=\"D.\")\ndef daily(ctx: AssetContext) -> None:\n return main(ctx=ctx)\n", ), - ("python/orders/daily/main.py", ASSET_MAIN), + ("python/nodes/orders/daily/main.py", ASSET_MAIN), ], config: json!({ "select": ["SQBRPYTHON005"] }), - expected_faults: vec![("SQBRPYTHON005", "python/orders/daily/node.py", 5, 5)], + expected_faults: vec![("SQBRPYTHON005", "python/nodes/orders/daily/asset.py", 5, 5)], }, ]; for test_case in test_cases { diff --git a/crates/sqlbuild-rules/src/python_rules/tests/test_orchestration_rules.rs b/crates/sqlbuild-rules/src/python_rules/tests/test_orchestration_rules.rs index 8f53f8e5fa..85141dffc8 100644 --- a/crates/sqlbuild-rules/src/python_rules/tests/test_orchestration_rules.rs +++ b/crates/sqlbuild-rules/src/python_rules/tests/test_orchestration_rules.rs @@ -26,8 +26,8 @@ fn given_sensor_and_calendar_modules_when_evaluating_orchestration_rules_then_re r#"from sqlbuild.orchestration import sensor from orchestration.sensors.inventory._constants import STALE_AFTER -from python.utils.retries import ATTEMPTS -from providers.carrier_api.provider import CarrierApi +from python.nodes.utils.retries import ATTEMPTS +from python.providers.carrier_api.provider import CarrierApi from ._helpers.feed_age import feed_age @@ -54,8 +54,8 @@ def stock_feed_stale(ctx, carrier_api: CarrierApi): month_end = calendar("month_end_calendar", description="Month end.") "#, ), - ("python/utils/retries.py", "ATTEMPTS = 2\n"), - ("providers/carrier_api/provider.py", ""), + ("python/nodes/utils/retries.py", "ATTEMPTS = 2\n"), + ("python/providers/carrier_api/provider.py", ""), ], config: json!({ "select": ORCHESTRATION_RULES }), expected_faults: vec![], @@ -187,9 +187,9 @@ for row in []: ( "orchestration/sensors/orders/refund_spike.py", r#"from orchestration.sensors.inventory._helpers.feed_age import feed_age -from python.orders.daily.main import main -from python.utils.retries import ATTEMPTS -from providers.carrier_api.provider import CarrierApi +from python.nodes.orders.daily.main import main +from python.nodes.utils.retries import ATTEMPTS +from python.providers.carrier_api.provider import CarrierApi from ._helpers.window import window "#, ), @@ -197,30 +197,29 @@ from ._helpers.window import window ("orchestration/sensors/inventory/_helpers/feed_age.py", ""), ( "orchestration/sensors/inventory/_helpers/age.py", - "from ...orders._helpers.window import window\nfrom python.orders.daily.main import main\n", + "from ...orders._helpers.window import window\nfrom python.nodes.orders.daily.main import main\n", ), - ("python/orders/weekly/node.py", ""), + ("python/nodes/orders/weekly/asset.py", ""), ( - "python/orders/weekly/main.py", + "python/nodes/orders/weekly/main.py", "from orchestration.sensors.orders._helpers.window import window\n", ), ( - "python/orders/daily/main.py", + "python/nodes/orders/daily/main.py", "from orchestration.sensors.orders._helpers.window import window\n", ), - ("python/utils/retries.py", ""), + ("python/nodes/utils/retries.py", ""), ( - "providers/carrier_api/provider.py", + "python/providers/carrier_api/provider.py", "import orchestration.sensors.orders.refund_spike\n", ), ( - "hooks/python/notify.py", + "sql/hooks/python/notify.py", "import orchestration.sensors.orders.refund_spike\n", ), ], config: json!({ "select": ["SQBRPYTHON008", "SQBRPYTHON017", "SQBRPYTHON019"] }), expected_faults: vec![ - ("SQBRPYTHON019", "hooks/python/notify.py", 1, 8), ( "SQBRPYTHON017", "orchestration/sensors/inventory/_helpers/age.py", @@ -231,7 +230,7 @@ from ._helpers.window import window "SQBRPYTHON019", "orchestration/sensors/inventory/_helpers/age.py", 2, - 38, + 44, ), ( "SQBRPYTHON017", @@ -243,10 +242,11 @@ from ._helpers.window import window "SQBRPYTHON019", "orchestration/sensors/orders/refund_spike.py", 2, - 38, + 44, ), - ("SQBRPYTHON019", "python/orders/daily/main.py", 1, 58), - ("SQBRPYTHON008", "python/orders/weekly/main.py", 1, 58), + ("SQBRPYTHON019", "python/nodes/orders/daily/main.py", 1, 58), + ("SQBRPYTHON008", "python/nodes/orders/weekly/main.py", 1, 58), + ("SQBRPYTHON019", "sql/hooks/python/notify.py", 1, 8), ], }, ]; diff --git a/crates/sqlbuild-rules/src/python_rules/tests/test_provider_rules.rs b/crates/sqlbuild-rules/src/python_rules/tests/test_provider_rules.rs index 779d1124fe..32e1a99eb3 100644 --- a/crates/sqlbuild-rules/src/python_rules/tests/test_provider_rules.rs +++ b/crates/sqlbuild-rules/src/python_rules/tests/test_provider_rules.rs @@ -13,13 +13,13 @@ fn given_providers_when_evaluating_provider_rules_then_reports_each_broken_conve PythonRunTestCase { description: "capability folders with provider.py, role files and private folders report nothing", files: &[ - ("providers/__init__.py", ""), + ("python/providers/__init__.py", ""), ( - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", r#""""Storefront client.""" from sqlbuild.providers import Provider -from python.utils.retries import ATTEMPTS +from python.nodes.utils.retries import ATTEMPTS from ._classes.page_cursor import PageCursor @@ -32,44 +32,57 @@ class StorefrontApi(Provider): base_url: str "#, ), - ("providers/storefront_api/models.py", ""), - ("providers/storefront_api/_classes/page_cursor.py", ""), - ("providers/storefront_api/_helpers/paging.py", ""), - ("python/utils/retries.py", ""), + ("python/providers/storefront_api/models.py", ""), ( - "python/orders/daily/main.py", - "from providers.storefront_api.provider import StorefrontApi\n", + "python/providers/storefront_api/_classes/page_cursor.py", + "", + ), + ("python/providers/storefront_api/_helpers/paging.py", ""), + ("python/nodes/utils/retries.py", ""), + ( + "python/nodes/orders/daily/main.py", + "from python.providers.storefront_api.provider import StorefrontApi\n", ), ], config: json!({ "select": PROVIDER_RULES }), expected_faults: vec![], }, PythonRunTestCase { - description: "layout: a module directly in providers/, a stray module, a missing provider.py and a stray folder", + description: "layout: a module directly in python/providers/, a stray module, a missing provider.py and a stray folder", files: &[ - ("providers/storefront_api.py", ""), - ("providers/carrier_api/client.py", ""), - ("providers/partner_sftp/provider.py", ""), - ("providers/partner_sftp/sftp/connection.py", ""), + ("python/providers/storefront_api.py", ""), + ("python/providers/carrier_api/client.py", ""), + ("python/providers/partner_sftp/provider.py", ""), + ("python/providers/partner_sftp/sftp/connection.py", ""), ], config: json!({ "select": ["SQBRPYTHON013"] }), expected_faults: vec![ - ("SQBRPYTHON013", "providers/carrier_api/client.py", 1, 1), - ("SQBRPYTHON013", "providers/carrier_api/client.py", 1, 1), ( "SQBRPYTHON013", - "providers/partner_sftp/sftp/connection.py", + "python/providers/carrier_api/client.py", + 1, + 1, + ), + ( + "SQBRPYTHON013", + "python/providers/carrier_api/client.py", + 1, + 1, + ), + ( + "SQBRPYTHON013", + "python/providers/partner_sftp/sftp/connection.py", 1, 1, ), - ("SQBRPYTHON013", "providers/storefront_api.py", 1, 1), + ("SQBRPYTHON013", "python/providers/storefront_api.py", 1, 1), ], }, PythonRunTestCase { description: "provider.py: a public constant, a function, a private and a plain class, a second provider, and none at all", files: &[ ( - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", r#""""Doc.""" from sqlbuild.providers import Provider @@ -97,38 +110,38 @@ class CarrierApi(Provider): """Second.""" "#, ), - ("providers/empty/provider.py", "import os\n"), + ("python/providers/empty/provider.py", "import os\n"), ], config: json!({ "select": ["SQBRPYTHON014"] }), expected_faults: vec![ - ("SQBRPYTHON014", "providers/empty/provider.py", 1, 1), + ("SQBRPYTHON014", "python/providers/empty/provider.py", 1, 1), ( "SQBRPYTHON014", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 5, 1, ), ( "SQBRPYTHON014", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 8, 5, ), ( "SQBRPYTHON014", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 12, 7, ), ( "SQBRPYTHON014", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 16, 7, ), ( "SQBRPYTHON014", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 24, 7, ), @@ -138,7 +151,7 @@ class CarrierApi(Provider): description: "provider.py: Provider through an alias, a module attribute or _classes/ bases reached by relative imports; bases outside the parsed sources stay silent", files: &[ ( - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", r#"from ._classes.paged import PagedApi @@ -147,15 +160,15 @@ class StorefrontApi(PagedApi): "#, ), ( - "providers/storefront_api/_classes/paged.py", + "python/providers/storefront_api/_classes/paged.py", "from .base import BaseApi\n\n\nclass PagedApi(BaseApi):\n pass\n", ), ( - "providers/storefront_api/_classes/base.py", + "python/providers/storefront_api/_classes/base.py", "from sqlbuild.providers import Provider\n\n\nclass BaseApi(Provider):\n pass\n", ), ( - "providers/carrier_api/provider.py", + "python/providers/carrier_api/provider.py", r#"from sqlbuild.providers import Provider as SqbProvider @@ -164,39 +177,39 @@ class CarrierApi(SqbProvider): "#, ), ( - "providers/billing_api/provider.py", + "python/providers/billing_api/provider.py", "from ._classes import paged\n\n\nclass BillingApi(paged.PagedApi):\n \"\"\"Client.\"\"\"\n", ), ( - "providers/billing_api/_classes/paged.py", + "python/providers/billing_api/_classes/paged.py", "from sqlbuild.providers import Provider\n\n\nclass PagedApi(Provider):\n pass\n", ), ( - "providers/ledger_api/provider.py", + "python/providers/ledger_api/provider.py", "from ._classes import LedgerBase\n\n\nclass LedgerApi(LedgerBase):\n \"\"\"Client.\"\"\"\n", ), ( - "providers/ledger_api/_classes/__init__.py", + "python/providers/ledger_api/_classes/__init__.py", "from .base import LedgerBase\n", ), ( - "providers/ledger_api/_classes/base.py", + "python/providers/ledger_api/_classes/base.py", "from sqlbuild.providers import Provider\n\n\nclass LedgerBase(Provider):\n pass\n", ), ( - "providers/catalog_api/provider.py", - "from python.utils.clients import PagedClient\n\n\nclass CatalogApi(PagedClient):\n \"\"\"Client.\"\"\"\n", + "python/providers/catalog_api/provider.py", + "from python.nodes.utils.clients import PagedClient\n\n\nclass CatalogApi(PagedClient):\n \"\"\"Client.\"\"\"\n", ), ( - "python/utils/clients.py", - "from python.utils.base import BaseClient\n\n\nclass PagedClient(BaseClient):\n pass\n", + "python/nodes/utils/clients.py", + "from python.nodes.utils.base import BaseClient\n\n\nclass PagedClient(BaseClient):\n pass\n", ), ( - "python/utils/base.py", + "python/nodes/utils/base.py", "from sqlbuild.providers import Provider\n\n\nclass BaseClient(Provider):\n pass\n", ), ( - "providers/partner_api/provider.py", + "python/providers/partner_api/provider.py", "from vendor.clients import VendorProvider\n\n\nclass PartnerApi(VendorProvider):\n \"\"\"Client.\"\"\"\n", ), ], @@ -207,7 +220,7 @@ class CarrierApi(SqbProvider): description: "provider.py: tuple, subscript, mixed and chained assignments, a builtin base and a module attribute naming a plain class", files: &[ ( - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", r#"import os from sqlbuild.providers import Provider @@ -224,99 +237,119 @@ class StorefrontApi(Provider): "#, ), ( - "providers/carrier_api/provider.py", + "python/providers/carrier_api/provider.py", "from ._classes import shapes\n\n\nclass CarrierApi(shapes.Parcel):\n \"\"\"Client.\"\"\"\n", ), ( - "providers/carrier_api/_classes/shapes.py", + "python/providers/carrier_api/_classes/shapes.py", "class Parcel:\n pass\n", ), ( - "providers/returns_api/provider.py", + "python/providers/returns_api/provider.py", "class ReturnsApi(Exception):\n \"\"\"Client.\"\"\"\n", ), ], config: json!({ "select": ["SQBRPYTHON014"] }), expected_faults: vec![ - ("SQBRPYTHON014", "providers/carrier_api/provider.py", 1, 1), - ("SQBRPYTHON014", "providers/carrier_api/provider.py", 4, 7), - ("SQBRPYTHON014", "providers/returns_api/provider.py", 1, 1), - ("SQBRPYTHON014", "providers/returns_api/provider.py", 1, 7), ( "SQBRPYTHON014", - "providers/storefront_api/provider.py", + "python/providers/carrier_api/provider.py", + 1, + 1, + ), + ( + "SQBRPYTHON014", + "python/providers/carrier_api/provider.py", + 4, + 7, + ), + ( + "SQBRPYTHON014", + "python/providers/returns_api/provider.py", + 1, + 1, + ), + ( + "SQBRPYTHON014", + "python/providers/returns_api/provider.py", + 1, + 7, + ), + ( + "SQBRPYTHON014", + "python/providers/storefront_api/provider.py", 6, 1, ), ( "SQBRPYTHON014", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 7, 1, ), ( "SQBRPYTHON014", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 8, 1, ), ( "SQBRPYTHON014", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 9, 1, ), ], }, PythonRunTestCase { - description: "imports: another provider's private code from anywhere, and python/ outside utils/ or orchestration/ from a provider", + description: "imports: another provider's private code from anywhere, and python/nodes/ outside utils/ or orchestration/ from a provider", files: &[ ( - "providers/storefront_api/provider.py", - r#"from python.utils.retries import ATTEMPTS -from python.orders.daily.main import main + "python/providers/storefront_api/provider.py", + r#"from python.nodes.utils.retries import ATTEMPTS +from python.nodes.orders.daily.main import main from orchestration.sensors.orders import on_orders -from providers.carrier_api._helpers.auth import token +from python.providers.carrier_api._helpers.auth import token from ._classes.cursor import Cursor -from providers.carrier_api.provider import CarrierApi +from python.providers.carrier_api.provider import CarrierApi "#, ), - ("providers/storefront_api/_classes/cursor.py", ""), - ("providers/carrier_api/provider.py", ""), - ("providers/carrier_api/_helpers/auth.py", ""), - ("python/utils/retries.py", ""), + ("python/providers/storefront_api/_classes/cursor.py", ""), + ("python/providers/carrier_api/provider.py", ""), + ("python/providers/carrier_api/_helpers/auth.py", ""), + ("python/nodes/utils/retries.py", ""), ( - "python/orders/daily/main.py", - "from providers.storefront_api._classes.cursor import Cursor\n", + "python/nodes/orders/daily/main.py", + "from python.providers.storefront_api._classes.cursor import Cursor\n", ), ("orchestration/sensors/orders.py", ""), ( - "hooks/python/notify.py", - "import providers.carrier_api._helpers.auth\n", + "sql/hooks/python/notify.py", + "import python.providers.carrier_api._helpers.auth\n", ), ], config: json!({ "select": ["SQBRPYTHON015"] }), expected_faults: vec![ - ("SQBRPYTHON015", "hooks/python/notify.py", 1, 8), + ("SQBRPYTHON015", "python/nodes/orders/daily/main.py", 1, 61), ( "SQBRPYTHON015", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 2, - 38, + 44, ), ( "SQBRPYTHON015", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 3, 42, ), ( "SQBRPYTHON015", - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", 4, - 49, + 56, ), - ("SQBRPYTHON015", "python/orders/daily/main.py", 1, 54), + ("SQBRPYTHON015", "sql/hooks/python/notify.py", 1, 8), ], }, ]; diff --git a/crates/sqlbuild-rules/src/python_rules/tests/test_python_cache.rs b/crates/sqlbuild-rules/src/python_rules/tests/test_python_cache.rs index df9a9397fb..689c06404d 100644 --- a/crates/sqlbuild-rules/src/python_rules/tests/test_python_cache.rs +++ b/crates/sqlbuild-rules/src/python_rules/tests/test_python_cache.rs @@ -19,15 +19,15 @@ fn given_a_cached_python_run_when_running_again_then_only_changed_inputs_are_eva PythonCacheTestCase { description: "an unchanged project is answered from the cache", files: &[ - ("hooks/python/notify.py", UNANNOTATED), - ("providers/settings.py", ANNOTATED), + ("sql/hooks/python/notify.py", UNANNOTATED), + ("python/providers/settings.py", ANNOTATED), ], config: json!({ "select": ["SQBRPYTHON101"] }), changes: &[], changed_config: json!({ "select": ["SQBRPYTHON101"] }), expected_runs: CachedRuns { - first_faults: named_faults(&[("SQBRPYTHON101", "hooks/python/notify.py")]), - second_faults: named_faults(&[("SQBRPYTHON101", "hooks/python/notify.py")]), + first_faults: named_faults(&[("SQBRPYTHON101", "sql/hooks/python/notify.py")]), + second_faults: named_faults(&[("SQBRPYTHON101", "sql/hooks/python/notify.py")]), second_hits: 2, second_misses: 0, }, @@ -35,14 +35,14 @@ fn given_a_cached_python_run_when_running_again_then_only_changed_inputs_are_eva PythonCacheTestCase { description: "an edited file is evaluated again and its old finding goes", files: &[ - ("hooks/python/notify.py", UNANNOTATED), - ("providers/settings.py", ANNOTATED), + ("sql/hooks/python/notify.py", UNANNOTATED), + ("python/providers/settings.py", ANNOTATED), ], config: json!({ "select": ["SQBRPYTHON101"] }), - changes: &[("hooks/python/notify.py", ANNOTATED)], + changes: &[("sql/hooks/python/notify.py", ANNOTATED)], changed_config: json!({ "select": ["SQBRPYTHON101"] }), expected_runs: CachedRuns { - first_faults: named_faults(&[("SQBRPYTHON101", "hooks/python/notify.py")]), + first_faults: named_faults(&[("SQBRPYTHON101", "sql/hooks/python/notify.py")]), second_faults: named_faults(&[]), second_hits: 1, second_misses: 1, @@ -51,7 +51,7 @@ fn given_a_cached_python_run_when_running_again_then_only_changed_inputs_are_eva PythonCacheTestCase { description: "a changed option evaluates every file again", files: &[( - "python/orders/main/build.py", + "python/nodes/orders/main/build.py", "def build() -> None:\n a: int = 1\n b: int = a\n print(b)\n", )], config: json!({ "select": ["SQBRPYTHON501"] }), @@ -62,7 +62,10 @@ fn given_a_cached_python_run_when_running_again_then_only_changed_inputs_are_eva }), expected_runs: CachedRuns { first_faults: named_faults(&[]), - second_faults: named_faults(&[("SQBRPYTHON501", "python/orders/main/build.py")]), + second_faults: named_faults(&[( + "SQBRPYTHON501", + "python/nodes/orders/main/build.py", + )]), second_hits: 0, second_misses: 1, }, @@ -70,18 +73,21 @@ fn given_a_cached_python_run_when_running_again_then_only_changed_inputs_are_eva PythonCacheTestCase { description: "an unchanged file whose import target appears is evaluated again", files: &[( - "python/orders/main/export.py", - "from python.billing.main._totals import total\n", + "python/nodes/orders/main/export.py", + "from python.nodes.billing.main._totals import total\n", )], config: json!({ "select": ["SQBRPYTHON304"] }), changes: &[( - "python/billing/main/_totals.py", + "python/nodes/billing/main/_totals.py", "def total() -> int:\n return 1\n", )], changed_config: json!({ "select": ["SQBRPYTHON304"] }), expected_runs: CachedRuns { first_faults: named_faults(&[]), - second_faults: named_faults(&[("SQBRPYTHON304", "python/orders/main/export.py")]), + second_faults: named_faults(&[( + "SQBRPYTHON304", + "python/nodes/orders/main/export.py", + )]), second_hits: 0, second_misses: 2, }, @@ -89,22 +95,25 @@ fn given_a_cached_python_run_when_running_again_then_only_changed_inputs_are_eva PythonCacheTestCase { description: "an unchanged domain package whose folder gains a subdomain is evaluated again", files: &[ - ("python/inventory/__init__.py", ""), - ("python/inventory/main/__init__.py", ""), + ("python/nodes/inventory/__init__.py", ""), + ("python/nodes/inventory/main/__init__.py", ""), ( - "python/inventory/main/publish.py", + "python/nodes/inventory/main/publish.py", "def publish() -> None:\n pass\n", ), ], config: json!({ "select": ["SQBRPYTHON613"] }), changes: &[ - ("python/inventory/restock/__init__.py", ""), - ("python/inventory/restock/main/__init__.py", ""), + ("python/nodes/inventory/restock/__init__.py", ""), + ("python/nodes/inventory/restock/main/__init__.py", ""), ], changed_config: json!({ "select": ["SQBRPYTHON613"] }), expected_runs: CachedRuns { first_faults: named_faults(&[]), - second_faults: named_faults(&[("SQBRPYTHON613", "python/inventory/__init__.py")]), + second_faults: named_faults(&[( + "SQBRPYTHON613", + "python/nodes/inventory/__init__.py", + )]), second_hits: 0, second_misses: 1, }, diff --git a/crates/sqlbuild-rules/src/python_rules/tests/test_python_test_rules.rs b/crates/sqlbuild-rules/src/python_rules/tests/test_python_test_rules.rs index 37bfeef3b5..12186a5a36 100644 --- a/crates/sqlbuild-rules/src/python_rules/tests/test_python_test_rules.rs +++ b/crates/sqlbuild-rules/src/python_rules/tests/test_python_test_rules.rs @@ -6,10 +6,10 @@ use crate::python_rules::tests::test_types::PythonRunTestCase; const RUNTIME_FILES: [(&str, &str); 5] = [ ( - "python/orders/storefront_import/node.py", + "python/nodes/orders/storefront_import/asset.py", r#"from sqlbuild.assets import AssetContext, asset -from python.orders.storefront_import.main import main +from python.nodes.orders.storefront_import.main import main @asset(description="Import storefront orders.") @@ -18,7 +18,7 @@ def storefront_import(ctx: AssetContext) -> None: "#, ), ( - "python/orders/storefront_import/main.py", + "python/nodes/orders/storefront_import/main.py", r#"from sqlbuild.assets import PythonNodeResult, AssetContext @@ -27,13 +27,13 @@ def main(ctx: AssetContext) -> PythonNodeResult: "#, ), ( - "python/orders/storefront_import/_helpers/row_mapping.py", + "python/nodes/orders/storefront_import/_helpers/row_mapping.py", r#"def map_row(raw: dict[str, object]) -> dict[str, object]: return {"status": str(raw["state"]).lower()} "#, ), ( - "providers/storefront_api/provider.py", + "python/providers/storefront_api/provider.py", r#"from sqlbuild.providers import Provider @@ -41,7 +41,7 @@ class StorefrontApi(Provider): region: str = "eu" "#, ), - ("providers/storefront_api/__init__.py", ""), + ("python/providers/storefront_api/__init__.py", ""), ]; const CASE_TYPES: &str = r#"from dataclasses import dataclass @@ -56,8 +56,8 @@ class RowMappingCase: const ROW_MAPPING_TEST: &str = r#"import pytest -from python.orders.storefront_import._helpers.row_mapping import map_row -from tests.python.orders.storefront_import._helpers._test_types import RowMappingCase +from python.nodes.orders.storefront_import._helpers.row_mapping import map_row +from tests.python.nodes.orders.storefront_import._helpers._test_types import RowMappingCase @pytest.mark.parametrize( @@ -83,8 +83,8 @@ class RegionCase: const PROVIDER_TEST: &str = r#"import pytest -from providers.storefront_api.provider import StorefrontApi -from tests.providers.storefront_api._test_types import RegionCase +from python.providers.storefront_api.provider import StorefrontApi +from tests.python.providers.storefront_api._test_types import RegionCase @pytest.mark.parametrize( @@ -130,19 +130,19 @@ fn given_project_python_tests_when_evaluating_test_rules_then_reports_misplaced_ RUNTIME_FILES[3], RUNTIME_FILES[4], ( - "tests/python/orders/storefront_import/_helpers/_test_types.py", + "tests/python/nodes/orders/storefront_import/_helpers/_test_types.py", CASE_TYPES, ), ( - "tests/python/orders/storefront_import/_helpers/test_row_mapping.py", + "tests/python/nodes/orders/storefront_import/_helpers/test_row_mapping.py", ROW_MAPPING_TEST, ), ( - "tests/providers/storefront_api/_test_types.py", + "tests/python/providers/storefront_api/_test_types.py", PROVIDER_CASE_TYPES, ), ( - "tests/providers/storefront_api/test_provider.py", + "tests/python/providers/storefront_api/test_provider.py", PROVIDER_TEST, ), ], @@ -154,35 +154,46 @@ fn given_project_python_tests_when_evaluating_test_rules_then_reports_misplaced_ files: &[ RUNTIME_FILES[0], RUNTIME_FILES[1], - ("tests/python/orders/_test_types.py", CASE_TYPES), - ("tests/python/orders/test_storefront.py", ROW_MAPPING_TEST), - ("tests/python/inventory/_test_types.py", CASE_TYPES), - ("tests/python/inventory/test_stock.py", ROW_MAPPING_TEST), - ("tests/python/_test_types.py", CASE_TYPES), - ("tests/python/test_everything.py", ROW_MAPPING_TEST), + ("tests/python/nodes/orders/_test_types.py", CASE_TYPES), + ( + "tests/python/nodes/orders/test_storefront.py", + ROW_MAPPING_TEST, + ), + ("tests/python/nodes/inventory/_test_types.py", CASE_TYPES), + ( + "tests/python/nodes/inventory/test_stock.py", + ROW_MAPPING_TEST, + ), + ("tests/python/nodes/_test_types.py", CASE_TYPES), + ("tests/python/nodes/test_everything.py", ROW_MAPPING_TEST), ], config: json!({"select": ["SQBRPYTHON021"]}), expected_faults: vec![ - ("SQBRPYTHON021", "tests/python/_test_types.py", 1, 1), + ("SQBRPYTHON021", "tests/python/nodes/_test_types.py", 1, 1), + ( + "SQBRPYTHON021", + "tests/python/nodes/inventory/_test_types.py", + 1, + 1, + ), ( "SQBRPYTHON021", - "tests/python/inventory/_test_types.py", + "tests/python/nodes/inventory/test_stock.py", 1, 1, ), ( "SQBRPYTHON021", - "tests/python/inventory/test_stock.py", + "tests/python/nodes/orders/test_storefront.py", 1, 1, ), ( "SQBRPYTHON021", - "tests/python/orders/test_storefront.py", + "tests/python/nodes/test_everything.py", 1, 1, ), - ("SQBRPYTHON021", "tests/python/test_everything.py", 1, 1), ], }, PythonRunTestCase { @@ -216,15 +227,15 @@ fn given_project_python_tests_when_evaluating_test_rules_then_reports_misplaced_ RUNTIME_FILES[1], RUNTIME_FILES[2], ( - "tests/python/orders/storefront_import/_test_types.py", + "tests/python/nodes/orders/storefront_import/_test_types.py", CASE_TYPES, ), ( - "tests/python/orders/storefront_import/_helpers/_test_types.py", + "tests/python/nodes/orders/storefront_import/_helpers/_test_types.py", CASE_TYPES, ), ( - "tests/python/orders/storefront_import/_helpers/test_row_mapping.py", + "tests/python/nodes/orders/storefront_import/_helpers/test_row_mapping.py", BRANCHING_TEST, ), ], @@ -232,19 +243,19 @@ fn given_project_python_tests_when_evaluating_test_rules_then_reports_misplaced_ expected_faults: vec![ ( "SQBRPYTHON702", - "tests/python/orders/storefront_import/_helpers/test_row_mapping.py", + "tests/python/nodes/orders/storefront_import/_helpers/test_row_mapping.py", 3, 1, ), ( "SQBRPYTHON703", - "tests/python/orders/storefront_import/_helpers/test_row_mapping.py", + "tests/python/nodes/orders/storefront_import/_helpers/test_row_mapping.py", 6, 1, ), ( "SQBRPYTHON704", - "tests/python/orders/storefront_import/_helpers/test_row_mapping.py", + "tests/python/nodes/orders/storefront_import/_helpers/test_row_mapping.py", 16, 5, ), diff --git a/crates/sqlbuild-rules/src/query_facts/_helpers/tokens.rs b/crates/sqlbuild-rules/src/query_facts/_helpers/tokens.rs index b847237997..4d5970efc0 100644 --- a/crates/sqlbuild-rules/src/query_facts/_helpers/tokens.rs +++ b/crates/sqlbuild-rules/src/query_facts/_helpers/tokens.rs @@ -1,8 +1,8 @@ use crate::query_facts::constants::MIN_CAST_TOKENS; use crate::query_facts::models::{CodeToken, ComparisonSpan}; -use sqlquack_syntax::LosslessToken; -use sqlquack_syntax::TokenKind; use sqlquack_syntax::tokens::models::TokenType; +use sqlquack_tokenize::LosslessToken; +use sqlquack_tokenize::TokenKind; use std::cell::RefCell; use std::collections::HashSet; use std::ops::Range; diff --git a/crates/sqlbuild-rules/src/rule_catalogue/tests/helpers.rs b/crates/sqlbuild-rules/src/rule_catalogue/tests/helpers.rs index 7af1f8c6df..1ecb1578ea 100644 --- a/crates/sqlbuild-rules/src/rule_catalogue/tests/helpers.rs +++ b/crates/sqlbuild-rules/src/rule_catalogue/tests/helpers.rs @@ -58,7 +58,7 @@ pub(crate) fn overridden_config() -> RulesConfig { RulesConfig { thresholds: BTreeMap::from([("min_tests_per_model".into(), 3)]), threshold_overrides: vec![ThresholdOverride { - paths: vec!["models/a".into()], + paths: vec!["sql/models/a".into()], thresholds: BTreeMap::from([("min_audits_per_model".into(), 2)]), reason: "Critical.".into(), }], diff --git a/crates/sqlbuild-rules/src/rule_catalogue/tests/test_rule_catalogue.rs b/crates/sqlbuild-rules/src/rule_catalogue/tests/test_rule_catalogue.rs index 69a6f4e799..9b7212f46f 100644 --- a/crates/sqlbuild-rules/src/rule_catalogue/tests/test_rule_catalogue.rs +++ b/crates/sqlbuild-rules/src/rule_catalogue/tests/test_rule_catalogue.rs @@ -97,7 +97,7 @@ fn given_rule_when_formatting_then_matches_python_inspection_text() { ..RuleText::default() }, with_config: true, - expected_text: "SQBRTEST202: \nFamily: \nEnabled by default: no\nKind: built-in\n\n\n\nRemediation: \n\nEffective thresholds:\n- `max_constant_container_files` = `10`\n- `max_enum_container_files` = `10`\n- `max_macro_container_files` = `10`\n- `max_role_container_depth` = `1`\n- `max_subdomain_depth` = `1`\n- `min_audits_per_model` = `1`\n- `min_custom_rule_test_cases` = `1`\n- `min_shared_container_prefix_files` = `2`\n- `min_shared_owner_prefix_directories` = `2`\n- `min_tests_per_model` = `3`\n- Override 1 at `models/a`: `{'min_audits_per_model': 2}` (Critical.)\n- Matching overrides apply in authored order; the last match wins.\n\nEffective SQL test paths:\n- Unit tests: tests/unit/\n- Scenarios: tests/scenarios/\n- Cross-domain pipelines: tests/unit/pipelines/", + expected_text: "SQBRTEST202: \nFamily: \nEnabled by default: no\nKind: built-in\n\n\n\nRemediation: \n\nEffective thresholds:\n- `max_constant_container_files` = `10`\n- `max_enum_container_files` = `10`\n- `max_macro_container_files` = `10`\n- `max_role_container_depth` = `1`\n- `max_subdomain_depth` = `1`\n- `min_audits_per_model` = `1`\n- `min_custom_rule_test_cases` = `1`\n- `min_shared_container_prefix_files` = `2`\n- `min_shared_owner_prefix_directories` = `2`\n- `min_tests_per_model` = `3`\n- Override 1 at `sql/models/a`: `{'min_audits_per_model': 2}` (Critical.)\n- Matching overrides apply in authored order; the last match wins.\n\nEffective SQL test paths:\n- Unit tests: tests/unit/\n- Scenarios: tests/scenarios/\n- Cross-domain pipelines: tests/unit/pipelines/", }, ]; let config: RulesConfig = overridden_config(); diff --git a/crates/sqlbuild-rules/src/rule_results/_helpers/literals.rs b/crates/sqlbuild-rules/src/rule_results/_helpers/literals.rs index b9eecdf2ba..82e9445709 100644 --- a/crates/sqlbuild-rules/src/rule_results/_helpers/literals.rs +++ b/crates/sqlbuild-rules/src/rule_results/_helpers/literals.rs @@ -7,6 +7,7 @@ use crate::rule_results::constants::{ INHERITED_CONSTANTS, LISTED_PATHS, LOCAL_CONSTANTS, MIN_SCOPED_FOLDER_DEPTH, PROJECT_CONSTANTS, QUOTE, }; +use sqlbuild_core::constants::SQL_DIRECTORY; /// The single-quoted literal starting at a one-based position, quotes included. pub(crate) fn literal_at(lines: &[String], line: i64, column: i64) -> Option { @@ -47,7 +48,8 @@ pub(crate) fn hint(others: &[&Vec], every: &BTreeSet>) -> St }; let owners: BTreeSet> = every.iter().map(|path| owner(path)).collect(); let common: Vec = common_folder(&owners.iter().cloned().collect::>()); - let placement: String = if common.len() < MIN_SCOPED_FOLDER_DEPTH { + let roots: usize = usize::from(common.first().is_some_and(|part| part == SQL_DIRECTORY)); + let placement: String = if common.len() < MIN_SCOPED_FOLDER_DEPTH + roots { format!( "no folder below the project roots holds every use, so declare it once in \ top-level `{PROJECT_CONSTANTS}`" diff --git a/crates/sqlbuild-rules/src/rule_results/constants.rs b/crates/sqlbuild-rules/src/rule_results/constants.rs index b053a8e161..e48a34c2e8 100644 --- a/crates/sqlbuild-rules/src/rule_results/constants.rs +++ b/crates/sqlbuild-rules/src/rule_results/constants.rs @@ -8,7 +8,7 @@ pub(crate) const MIN_SCOPED_FOLDER_DEPTH: usize = 2; pub(crate) const DECLARATION_GROUP: &str = "_sqlbuild"; pub(crate) const LOCAL_CONSTANTS: &str = "_sqlbuild/_constants/"; pub(crate) const INHERITED_CONSTANTS: &str = "_sqlbuild/constants/"; -pub(crate) const PROJECT_CONSTANTS: &str = "constants/"; +pub(crate) const PROJECT_CONSTANTS: &str = "sql/constants/"; pub(crate) const FIX_AVAILABLE_NOTE: &str = "Fix available: `sqb format --fix` applies it after compiler verification"; pub(crate) const JSON_INDENT: usize = 2; diff --git a/crates/sqlbuild-rules/src/rule_results/tests/helpers.rs b/crates/sqlbuild-rules/src/rule_results/tests/helpers.rs index e251d603fa..aca5099903 100644 --- a/crates/sqlbuild-rules/src/rule_results/tests/helpers.rs +++ b/crates/sqlbuild-rules/src/rule_results/tests/helpers.rs @@ -1,10 +1,10 @@ use crate::rule_results::models::RuleFinding; -/// One unevaluated finding of `code` in `models/a.sql` at `line`. +/// One unevaluated finding of `code` in `sql/models/a.sql` at `line`. pub(crate) fn unevaluated(code: &str, line: i64) -> RuleFinding { RuleFinding { code: code.into(), - path: "models/a.sql".into(), + path: "sql/models/a.sql".into(), line, column: 1, message: format!("Rule {code} could not be evaluated: too deep"), diff --git a/crates/sqlbuild-rules/src/rule_results/tests/test_rule_results.rs b/crates/sqlbuild-rules/src/rule_results/tests/test_rule_results.rs index 1782bc251a..4fa5ad7afe 100644 --- a/crates/sqlbuild-rules/src/rule_results/tests/test_rule_results.rs +++ b/crates/sqlbuild-rules/src/rule_results/tests/test_rule_results.rs @@ -17,40 +17,40 @@ fn given_repeated_long_literals_when_hinting_then_matches_python_wording() { let test_cases = [ HintTestCase { description: "two files in one folder share a local constants folder", - paths: vec!["models/a/x.sql", "models/a/y.sql"], + paths: vec!["sql/models/a/x.sql", "sql/models/a/y.sql"], expected_hint: Some( - "The identical literal also appears in models/a/y.sql; their nearest common folder is `models/a`, so declare it once in `models/a/_sqlbuild/_constants/`", + "The identical literal also appears in sql/models/a/y.sql; their nearest common folder is `sql/models/a`, so declare it once in `sql/models/a/_sqlbuild/_constants/`", ), }, HintTestCase { description: "a declaration group file and subfolders inherit constants", paths: vec![ - "models/a/_sqlbuild/x.sql", - "models/a/b/y.sql", - "models/a/c/z.sql", + "sql/models/a/_sqlbuild/x.sql", + "sql/models/a/b/y.sql", + "sql/models/a/c/z.sql", ], expected_hint: Some( - "The identical literal also appears in models/a/b/y.sql, models/a/c/z.sql; their nearest common folder is `models/a`, so declare it once in `models/a/_sqlbuild/constants/`", + "The identical literal also appears in sql/models/a/b/y.sql, sql/models/a/c/z.sql; their nearest common folder is `sql/models/a`, so declare it once in `sql/models/a/_sqlbuild/constants/`", ), }, HintTestCase { description: "paths sort by parts and only five are listed", paths: vec![ - "models/a-b/x.sql", - "models/a/b/x.sql", - "models/a/y.sql", + "sql/models/a-b/x.sql", + "sql/models/a/b/x.sql", + "sql/models/a/y.sql", "m/1.sql", "m/2.sql", "m/3.sql", "m/4.sql", ], expected_hint: Some( - "The identical literal also appears in m/1.sql, m/2.sql, m/3.sql, m/4.sql, models/a/b/x.sql and 1 more; no folder below the project roots holds every use, so declare it once in top-level `constants/`", + "The identical literal also appears in m/1.sql, m/2.sql, m/3.sql, m/4.sql, sql/models/a/b/x.sql and 1 more; no folder below the project roots holds every use, so declare it once in top-level `sql/constants/`", ), }, HintTestCase { description: "a literal in one file gets no hint", - paths: vec!["models/a/x.sql"], + paths: vec!["sql/models/a/x.sql"], expected_hint: None, }, ]; @@ -89,17 +89,17 @@ fn given_rules_result_when_formatting_then_matches_python_text_and_json() { ResultTestCase { description: "text lists affected rules, the fix note and unevaluated resources", json_output: false, - expected_text: "models/o.sql:3:4 [SQLCLEAN001] bad \u{e9}\n Remediation: Fix it.\n Affected Rules: A, B\n Fix available: `sqb format --fix` applies it after compiler verification\nFound 1 Rules findings\n2 models evaluated, 1 resources could not be evaluated", + expected_text: "sql/models/o.sql:3:4 [SQLCLEAN001] bad \u{e9}\n Remediation: Fix it.\n Affected Rules: A, B\n Fix available: `sqb format --fix` applies it after compiler verification\nFound 1 Rules findings\n2 models evaluated, 1 resources could not be evaluated", }, ResultTestCase { description: "JSON is indented, key-sorted and ASCII-escaped", json_output: true, - expected_text: "{\n \"cache_hits\": 1,\n \"cache_misses\": 1,\n \"evaluated_models\": 2,\n \"finding_count\": 1,\n \"findings\": [\n {\n \"affected_rules\": [\n \"A\",\n \"B\"\n ],\n \"code\": \"SQLCLEAN001\",\n \"column\": 4,\n \"fixable\": true,\n \"line\": 3,\n \"message\": \"bad \\u00e9\",\n \"path\": \"models/o.sql\",\n \"remediation\": \"Fix it.\"\n }\n ],\n \"unevaluated_resources\": 1\n}", + expected_text: "{\n \"cache_hits\": 1,\n \"cache_misses\": 1,\n \"evaluated_models\": 2,\n \"finding_count\": 1,\n \"findings\": [\n {\n \"affected_rules\": [\n \"A\",\n \"B\"\n ],\n \"code\": \"SQLCLEAN001\",\n \"column\": 4,\n \"fixable\": true,\n \"line\": 3,\n \"message\": \"bad \\u00e9\",\n \"path\": \"sql/models/o.sql\",\n \"remediation\": \"Fix it.\"\n }\n ],\n \"unevaluated_resources\": 1\n}", }, ]; let finding = RuleFinding { code: "SQLCLEAN001".to_owned(), - path: "models/o.sql".to_owned(), + path: "sql/models/o.sql".to_owned(), line: 3, column: 4, message: "bad \u{e9}".to_owned(), @@ -177,7 +177,7 @@ fn given_unevaluated_findings_when_grouping_then_one_finding_per_path_and_reason unevaluated("SQBRB", 3), RuleFinding { code: "SQBRZ".into(), - path: "models/a.sql".into(), + path: "sql/models/a.sql".into(), line: 1, ..RuleFinding::default() }, diff --git a/crates/sqlbuild-rules/src/rules/_helpers/dispatch/catalogue.rs b/crates/sqlbuild-rules/src/rules/_helpers/dispatch/catalogue.rs index c36166b7b9..943f71a2a8 100644 --- a/crates/sqlbuild-rules/src/rules/_helpers/dispatch/catalogue.rs +++ b/crates/sqlbuild-rules/src/rules/_helpers/dispatch/catalogue.rs @@ -284,7 +284,7 @@ pub(crate) fn catalogue() -> Vec { "declarations", "declaration-domain-placement", "public enum and constant files must live under a configured domain folder", - "Move this declaration beneath enums// or constants//.", + "Move this declaration beneath sql/enums// or sql/constants//.", ), rule!( "SQBRDECLARATION302", diff --git a/crates/sqlbuild-rules/src/rules/_helpers/layers/domain_layout.rs b/crates/sqlbuild-rules/src/rules/_helpers/layers/domain_layout.rs index 9871b1b1b3..6e9e8a5964 100644 --- a/crates/sqlbuild-rules/src/rules/_helpers/layers/domain_layout.rs +++ b/crates/sqlbuild-rules/src/rules/_helpers/layers/domain_layout.rs @@ -266,7 +266,14 @@ fn resolve_model_path( levels: &[Vec<&str>], domain_roots: &[Vec<&str>], ) -> ModelPathResolution { - let parts: Vec<&str> = model.relative_path.split('/').collect(); + let Some(below_sql) = model + .relative_path + .strip_prefix(sqlbuild_core::constants::SQL_DIRECTORY) + .and_then(|rest| rest.strip_prefix('/')) + else { + return ModelPathResolution::Missing; + }; + let parts: Vec<&str> = below_sql.split('/').collect(); if parts.len() < MIN_MODEL_PATH_COMPONENTS || parts.first().copied() != Some("models") { return ModelPathResolution::Missing; } diff --git a/crates/sqlbuild-rules/src/rules/_helpers/layers/model_layers.rs b/crates/sqlbuild-rules/src/rules/_helpers/layers/model_layers.rs index 4132f1953d..25b98420e1 100644 --- a/crates/sqlbuild-rules/src/rules/_helpers/layers/model_layers.rs +++ b/crates/sqlbuild-rules/src/rules/_helpers/layers/model_layers.rs @@ -173,7 +173,7 @@ fn canonical_folder_for_layer(layer: &str) -> &'static str { fn canonical_folder_in_path(relative_path: &str) -> Option<&'static str> { let parts: Vec<&str> = relative_path.split('/').collect(); let parent = &parts[..parts.len().saturating_sub(1)]; - for (index, component) in parent.iter().enumerate().skip(1) { + for (index, component) in parent.iter().enumerate().skip(2) { if *component == STAGING_LAYER_DIRECTORY { return Some(STAGING_LAYER_DIRECTORY); } diff --git a/crates/sqlbuild-rules/src/rules/_helpers/sql_checks/sql_test_rules.rs b/crates/sqlbuild-rules/src/rules/_helpers/sql_checks/sql_test_rules.rs index 608e2ba36a..3ad64cc655 100644 --- a/crates/sqlbuild-rules/src/rules/_helpers/sql_checks/sql_test_rules.rs +++ b/crates/sqlbuild-rules/src/rules/_helpers/sql_checks/sql_test_rules.rs @@ -358,7 +358,14 @@ fn macro_parent_components( })?; parents.push(match &declaration.owning_path { Some(owner) => std::iter::once("macros".to_owned()) - .chain(owner.split('/').map(str::to_owned)) + .chain( + owner + .strip_prefix(sqlbuild_core::constants::SQL_DIRECTORY) + .and_then(|rest| rest.strip_prefix('/')) + .unwrap_or(owner) + .split('/') + .map(str::to_owned), + ) .collect(), None => direct_parent_components(&declaration.path, &declaration.ownership_root)?, }); @@ -379,17 +386,20 @@ fn function_parent_components( } fn direct_parent_components(path: &str, root: &str) -> Option> { + let path: Vec<&str> = parts_below(path, root)?; + let start: usize = usize::from(path.first() == Some(&sqlbuild_core::constants::SQL_DIRECTORY)); + Some(owned_parts(&path[start..path.len() - 1])) +} + +/// `path`'s folders and file when it lies below `root`, otherwise `None`. +fn parts_below<'a>(path: &'a str, root: &str) -> Option> { let path: Vec<&str> = path.split('/').collect(); let root: Vec<&str> = root.split('/').collect(); - if path.len() <= root.len() || path.get(..root.len()) != Some(root.as_slice()) { - return None; - } - Some( - path[..path.len() - 1] - .iter() - .map(|value| (*value).to_owned()) - .collect(), - ) + (path.len() > root.len() && path.get(..root.len()) == Some(root.as_slice())).then_some(path) +} + +fn owned_parts(parts: &[&str]) -> Vec { + parts.iter().map(|value| (*value).to_owned()).collect() } fn direct_expected_parent(parents: &[Vec]) -> Option { @@ -489,17 +499,9 @@ fn same_resource_kind(left: &ResourceKind, right: &ResourceKind) -> bool { } fn relative_parent(resource: &ScopeResource) -> Option> { - let path: Vec<&str> = resource.path.split('/').collect(); - let root: Vec<&str> = resource.ownership_root.split('/').collect(); - if path.len() <= root.len() || path.get(..root.len()) != Some(root.as_slice()) { - return None; - } - Some( - path[root.len()..path.len() - 1] - .iter() - .map(|value| (*value).to_owned()) - .collect(), - ) + let path: Vec<&str> = parts_below(&resource.path, &resource.ownership_root)?; + let depth: usize = resource.ownership_root.split('/').count(); + Some(owned_parts(&path[depth..path.len() - 1])) } fn common_components(values: &[Vec]) -> Vec { diff --git a/crates/sqlbuild-rules/tests/python_rules/helpers.rs b/crates/sqlbuild-rules/tests/python_rules/helpers.rs index 614cf74549..eef2a7b96a 100644 --- a/crates/sqlbuild-rules/tests/python_rules/helpers.rs +++ b/crates/sqlbuild-rules/tests/python_rules/helpers.rs @@ -9,13 +9,13 @@ static ALLOCATOR: &stats_alloc::StatsAlloc = &stats_alloc::I /// A shared helper, `modules` modules that import it, and one hook file of 150 functions per 100. pub(crate) fn importing_modules(modules: usize) -> Vec<(String, String)> { let helper = ( - "python/shared/text.py".to_owned(), + "python/nodes/shared/text.py".to_owned(), "\"\"\"Shared text.\"\"\"\n\n\ndef trimmed(value: str) -> str:\n \"\"\"Return the value.\"\"\"\n return value\n".to_owned(), ); std::iter::once(helper) .chain((0..modules).map(|module| { ( - format!("python/area_{}/module_{module}/entry.py", module % 40), + format!("python/nodes/area_{}/module_{module}/entry.py", module % 40), format!( "\"\"\"Module {module}.\"\"\"\n\nfrom python.shared.text import trimmed\n\n\ndef handle_{module}(value: str) -> str:\n \"\"\"Handle module {module}.\"\"\"\n return trimmed(value)\n" ), @@ -25,7 +25,7 @@ pub(crate) fn importing_modules(modules: usize) -> Vec<(String, String)> { let body: String = (0..150) .map(|function| format!("def notify_{function}(ctx, reason):\n print(ctx, reason)\n\n\n")) .collect(); - (format!("hooks/python/notify_{hook}.py"), body) + (format!("sql/hooks/python/notify_{hook}.py"), body) })) .collect() } diff --git a/crates/sqlbuild-scopes/src/compile_usages/_helpers/schema_checks.rs b/crates/sqlbuild-scopes/src/compile_usages/_helpers/schema_checks.rs index b5797c52a0..31233f3a36 100644 --- a/crates/sqlbuild-scopes/src/compile_usages/_helpers/schema_checks.rs +++ b/crates/sqlbuild-scopes/src/compile_usages/_helpers/schema_checks.rs @@ -42,20 +42,37 @@ pub(crate) fn visible_from( }) } +/// An S006 keyed by its path and the two names that identify it within the file. +fn inaccessible( + path: &str, + names: [&str; 2], + message: String, + help: String, +) -> InaccessibleDiagnostic { + let [first, second] = names; + InaccessibleDiagnostic { + key: vec![ + INACCESSIBLE_CODE.to_owned(), + path.to_owned(), + first.to_owned(), + second.to_owned(), + ], + message, + path: path.to_owned(), + help, + } +} + /// The S006 of a schema extending a schema its folder cannot see. pub(crate) fn hidden_parent( consumer: &NamedRecord, name: &str, parent: &NamedRecord, ) -> InaccessibleDiagnostic { - InaccessibleDiagnostic { - key: vec![ - INACCESSIBLE_CODE.to_owned(), - consumer.path.clone(), - SCHEMA_KIND.to_owned(), - name.to_owned(), - ], - message: format!( + inaccessible( + &consumer.path, + [SCHEMA_KIND, name], + format!( "Schema '{name}' is not visible from '{}'. It is defined at {} with {} scope owned \ by '{}'", consumer.path, @@ -63,14 +80,13 @@ pub(crate) fn hidden_parent( parent.declared.scope.as_str(), owner(parent) ), - path: consumer.path.clone(), - help: format!( + format!( "move '{}' to a schemas/ role owned by '{}' or one of its parent folders, or to the \ - project-wide schemas/ when consumers span resource trees", + project-wide sql/schemas/ when consumers span resource trees", parent.path, folder(consumer) ), - } + ) } /// The S006 of a schema column typed with an enum the schema cannot see. @@ -81,14 +97,10 @@ pub(crate) fn hidden_enum( ) -> InaccessibleDiagnostic { let (record, schema_name) = schema; let (column_name, enum_name) = column; - InaccessibleDiagnostic { - key: vec![ - INACCESSIBLE_CODE.to_owned(), - record.path.clone(), - schema_name.to_owned(), - column_name.to_owned(), - ], - message: format!( + inaccessible( + &record.path, + [schema_name, column_name], + format!( "Schema '{schema_name}' in {} column '{column_name}' uses enum '{enum_name}', which \ is not visible from the schema's location. The enum is defined at {} with {} scope \ owned by '{}'", @@ -97,9 +109,8 @@ pub(crate) fn hidden_enum( enum_record.declared.scope.as_str(), owner(enum_record) ), - path: record.path.clone(), - help: "move the enum to a role visible from the schema's owning folder, or move the \ - schema next to the enum" + "move the enum to a role visible from the schema's owning folder, or move the schema \ + next to the enum" .to_owned(), - } + ) } diff --git a/crates/sqlbuild-scopes/src/compile_usages/tests/helpers.rs b/crates/sqlbuild-scopes/src/compile_usages/tests/helpers.rs index 21aa7700ca..bd1a536b29 100644 --- a/crates/sqlbuild-scopes/src/compile_usages/tests/helpers.rs +++ b/crates/sqlbuild-scopes/src/compile_usages/tests/helpers.rs @@ -12,7 +12,7 @@ fn record(handle: usize, path: &str, scope: ScopeKind, owning_path: Option<&str> owner: None, owning_path: owning_path.map(str::to_owned), }, - ownership_root: "models".to_owned(), + ownership_root: "sql/models".to_owned(), } } @@ -41,14 +41,14 @@ pub(super) fn visible_schema_records() -> HashMap { "orders_schema".to_owned(), record( 0, - "models/sales/schemas/orders.yml", + "sql/models/sales/schemas/orders.yml", ScopeKind::Inherited, - Some("models/sales"), + Some("sql/models/sales"), ), ), ( "base_schema".to_owned(), - record(1, "schemas/base.yml", ScopeKind::Global, None), + record(1, "sql/schemas/base.yml", ScopeKind::Global, None), ), ]) } @@ -59,18 +59,18 @@ pub(super) fn hidden_schema_records() -> HashMap { "orders_schema".to_owned(), record( 0, - "models/sales/schemas/orders.yml", + "sql/models/sales/schemas/orders.yml", ScopeKind::Inherited, - Some("models/sales"), + Some("sql/models/sales"), ), ), ( "base_schema".to_owned(), record( 1, - "models/finance/schemas/base.yml", + "sql/models/finance/schemas/base.yml", ScopeKind::Inherited, - Some("models/finance"), + Some("sql/models/finance"), ), ), ]) @@ -79,7 +79,7 @@ pub(super) fn hidden_schema_records() -> HashMap { pub(super) fn visible_enum_records() -> HashMap { HashMap::from([( "order_status".to_owned(), - record(2, "enums/status.yml", ScopeKind::Global, None), + record(2, "sql/enums/status.yml", ScopeKind::Global, None), )]) } @@ -88,9 +88,9 @@ pub(super) fn hidden_enum_records() -> HashMap { "order_status".to_owned(), record( 2, - "models/finance/enums/status.yml", + "sql/models/finance/enums/status.yml", ScopeKind::Local, - Some("models/finance"), + Some("sql/models/finance"), ), )]) } diff --git a/crates/sqlbuild-scopes/src/compile_usages/tests/test_compile_usages.rs b/crates/sqlbuild-scopes/src/compile_usages/tests/test_compile_usages.rs index 9401aefd87..c729fcb8ea 100644 --- a/crates/sqlbuild-scopes/src/compile_usages/tests/test_compile_usages.rs +++ b/crates/sqlbuild-scopes/src/compile_usages/tests/test_compile_usages.rs @@ -28,8 +28,8 @@ fn given_schemas_when_collecting_scope_usages_then_python_usages_and_s006_hold() enum_records: hidden_enum_records, expected_usages: &[(0, 1), (0, 2)], expected_messages: &[ - "Schema 'base_schema' is not visible from 'models/sales/schemas/orders.yml'. It is defined at models/finance/schemas/base.yml with inherited scope owned by 'models/finance'", - "Schema 'orders_schema' in models/sales/schemas/orders.yml column 'status' uses enum 'order_status', which is not visible from the schema's location. The enum is defined at models/finance/enums/status.yml with local scope owned by 'models/finance'", + "Schema 'base_schema' is not visible from 'sql/models/sales/schemas/orders.yml'. It is defined at sql/models/finance/schemas/base.yml with inherited scope owned by 'sql/models/finance'", + "Schema 'orders_schema' in sql/models/sales/schemas/orders.yml column 'status' uses enum 'order_status', which is not visible from the schema's location. The enum is defined at sql/models/finance/enums/status.yml with local scope owned by 'sql/models/finance'", ], }, ]; diff --git a/crates/sqlbuild-scopes/src/placement/_helpers/declaration_directory.rs b/crates/sqlbuild-scopes/src/placement/_helpers/declaration_directory.rs index b1739acca5..b3b1fc747f 100644 --- a/crates/sqlbuild-scopes/src/placement/_helpers/declaration_directory.rs +++ b/crates/sqlbuild-scopes/src/placement/_helpers/declaration_directory.rs @@ -1,6 +1,7 @@ //! The project-relative folder where a declaration with a given placement lives. use crate::placement::constants::{AUTHORED_ROOT_PATHS, DECLARATION_GROUP_DIRECTORY}; +use crate::scope_index::constants::GLOBAL_ROLE_PARENT; use crate::scope_index::models::{DeclarationKind, ScopeKind}; /// Python's `declaration_directory`. @@ -12,7 +13,7 @@ pub(crate) fn declaration_directory( ) -> String { let parts: &[&str] = kind.role_parts(); let Some(path) = path.filter(|_| scope != ScopeKind::Global) else { - return parts.join("/"); + return format!("{GLOBAL_ROLE_PARENT}/{}", parts.join("/")); }; let prefix: &str = if scope == ScopeKind::Local { "_" } else { "" }; let mut role: String = format!("{prefix}{}", parts[0]); diff --git a/crates/sqlbuild-scopes/src/placement/constants.rs b/crates/sqlbuild-scopes/src/placement/constants.rs index 95f31a0a02..b807a23b17 100644 --- a/crates/sqlbuild-scopes/src/placement/constants.rs +++ b/crates/sqlbuild-scopes/src/placement/constants.rs @@ -6,9 +6,9 @@ pub(crate) const PROJECT_ROOT_PATH: &str = "."; pub(crate) const DECLARATION_GROUP_DIRECTORY: &str = "_sqlbuild"; /// Owners whose declaration roles sit directly below them. pub(crate) const AUTHORED_ROOT_PATHS: &[&str] = &[ - "models", + "sql/models", "tests/unit", "tests/scenarios", - "functions/sql", - "sources", + "sql/functions/sql", + "sql/sources", ]; diff --git a/crates/sqlbuild-scopes/src/placement/tests/helpers.rs b/crates/sqlbuild-scopes/src/placement/tests/helpers.rs index 9c89f9e811..6b07b92a52 100644 --- a/crates/sqlbuild-scopes/src/placement/tests/helpers.rs +++ b/crates/sqlbuild-scopes/src/placement/tests/helpers.rs @@ -58,23 +58,23 @@ fn runtime(consumer: &str, declaration: &str) -> PlacementUsage { } } -const SALES: (ScopeKind, Option<&str>) = (ScopeKind::Local, Some("models/sales")); +const SALES: (ScopeKind, Option<&str>) = (ScopeKind::Local, Some("sql/models/sales")); /// A model and a descendant-folder model, a local macro both use, and an unused global macro. pub(super) fn descendant_models() -> PlacementIndex { PlacementIndex { resources: vec![ - model_record("orders", "models/sales/orders.sql"), - model_record("customers", "models/sales/crm/customers.sql"), + model_record("orders", "sql/models/sales/orders.sql"), + model_record("customers", "sql/models/sales/crm/customers.sql"), ], declarations: vec![ - macro_record("cents", "models/sales/_macros/python/cents.py", SALES), + macro_record("cents", "sql/models/sales/_macros/python/cents.py", SALES), macro_record( "unused", - "macros/python/unused.py", + "sql/macros/python/unused.py", (ScopeKind::Global, None), ), - macro_record("shared", "models/sales/_macros/python/shared.py", SALES), + macro_record("shared", "sql/models/sales/_macros/python/shared.py", SALES), ], usages: vec![ runtime("orders", "cents"), @@ -87,10 +87,10 @@ pub(super) fn descendant_models() -> PlacementIndex { /// One model using a local macro, which a further macro uses in turn. pub(super) fn chained_macros() -> PlacementIndex { PlacementIndex { - resources: vec![model_record("orders", "models/sales/orders.sql")], + resources: vec![model_record("orders", "sql/models/sales/orders.sql")], declarations: vec![ - macro_record("cents", "models/sales/_macros/python/cents.py", SALES), - macro_record("round", "models/sales/_macros/python/round.py", SALES), + macro_record("cents", "sql/models/sales/_macros/python/cents.py", SALES), + macro_record("round", "sql/models/sales/_macros/python/round.py", SALES), ], usages: vec![ runtime("orders", "cents"), @@ -103,8 +103,8 @@ pub(super) fn chained_macros() -> PlacementIndex { } } -const SALES_GROUPED: (ScopeKind, Option<&str>) = (ScopeKind::Local, Some("models/sales")); -const SALES_SHARED: (ScopeKind, Option<&str>) = (ScopeKind::Inherited, Some("models/sales")); +const SALES_GROUPED: (ScopeKind, Option<&str>) = (ScopeKind::Local, Some("sql/models/sales")); +const SALES_SHARED: (ScopeKind, Option<&str>) = (ScopeKind::Inherited, Some("sql/models/sales")); /// Two sales models sharing a local `cents`, beside an optional descendant-public `labels`. fn shared_cents(cents_path: &str, labels_path: Option<&str>) -> PlacementIndex { @@ -112,9 +112,9 @@ fn shared_cents(cents_path: &str, labels_path: Option<&str>) -> PlacementIndex { declarations.extend(labels_path.map(|path| macro_record("labels", path, SALES_SHARED))); PlacementIndex { resources: vec![ - model_record("orders", "models/sales/orders.sql"), - model_record("refunds", "models/sales/refunds.sql"), - model_record("customers", "models/sales/crm/customers.sql"), + model_record("orders", "sql/models/sales/orders.sql"), + model_record("refunds", "sql/models/sales/refunds.sql"), + model_record("customers", "sql/models/sales/crm/customers.sql"), ], declarations, usages: vec![ @@ -128,30 +128,33 @@ fn shared_cents(cents_path: &str, labels_path: Option<&str>) -> PlacementIndex { /// A grouped `cents` and an empty descendant-public role. pub(super) fn grouped_cents_empty_role() -> PlacementIndex { - shared_cents("models/sales/_sqlbuild/_macros/python/money/cents.py", None) + shared_cents( + "sql/models/sales/_sqlbuild/_macros/python/money/cents.py", + None, + ) } /// A grouped `cents` and a descendant-public role keeping its files in groups. pub(super) fn grouped_cents_grouped_role() -> PlacementIndex { shared_cents( - "models/sales/_sqlbuild/_macros/python/money/cents.py", - Some("models/sales/_sqlbuild/macros/python/text/labels.py"), + "sql/models/sales/_sqlbuild/_macros/python/money/cents.py", + Some("sql/models/sales/_sqlbuild/macros/python/text/labels.py"), ) } /// A direct `cents` and a descendant-public role keeping its files in groups. pub(super) fn direct_cents_grouped_role() -> PlacementIndex { shared_cents( - "models/sales/_sqlbuild/_macros/python/cents.py", - Some("models/sales/_sqlbuild/macros/python/text/labels.py"), + "sql/models/sales/_sqlbuild/_macros/python/cents.py", + Some("sql/models/sales/_sqlbuild/macros/python/text/labels.py"), ) } /// A grouped `cents` and a descendant-public role keeping its files directly. pub(super) fn grouped_cents_direct_role() -> PlacementIndex { shared_cents( - "models/sales/_sqlbuild/_macros/python/money/cents.py", - Some("models/sales/_sqlbuild/macros/python/labels.py"), + "sql/models/sales/_sqlbuild/_macros/python/money/cents.py", + Some("sql/models/sales/_sqlbuild/macros/python/labels.py"), ) } @@ -191,11 +194,11 @@ fn order_key( /// Diagnostics without a path or line first, then by path, line, code and message. pub(super) fn mixed_diagnostics() -> Vec { vec![ - order_key(Some("models/b.sql"), Some(2), "S010", "b"), - order_key(Some("models/a.sql"), Some(9), "S010", "a"), + order_key(Some("sql/models/b.sql"), Some(2), "S010", "b"), + order_key(Some("sql/models/a.sql"), Some(9), "S010", "a"), order_key(None, None, "S019", "parse"), order_key(Some(""), Some(0), "S019", "parse"), - order_key(Some("models/a.sql"), Some(9), "S007", "z"), - order_key(Some("models/b.sql"), None, "S010", "b"), + order_key(Some("sql/models/a.sql"), Some(9), "S007", "z"), + order_key(Some("sql/models/b.sql"), None, "S010", "b"), ] } diff --git a/crates/sqlbuild-scopes/src/placement/tests/test_placement.rs b/crates/sqlbuild-scopes/src/placement/tests/test_placement.rs index e742c1dc74..becb6ae0e0 100644 --- a/crates/sqlbuild-scopes/src/placement/tests/test_placement.rs +++ b/crates/sqlbuild-scopes/src/placement/tests/test_placement.rs @@ -24,16 +24,16 @@ fn given_usages_when_validating_placement_then_unused_and_misplaced_declarations ( 1, "S010", - "Unused global declaration 'macro:unused' at macros/python/unused.py; remove it or \ + "Unused global declaration 'macro:unused' at sql/macros/python/unused.py; remove it or \ add a genuine runtime use", ), ( 2, "S007", "Declaration 'macro:shared' is currently exact-owner-private at \ - 'models/sales' (models/sales/_macros/python/shared.py); required descendant-public \ - at 'models/sales'. Consumers: model:customers, model:orders. Move it to \ - 'models/sales/_sqlbuild/macros/python/'", + 'sql/models/sales' (sql/models/sales/_macros/python/shared.py); required descendant-public \ + at 'sql/models/sales'. Consumers: model:customers, model:orders. Move it to \ + 'sql/models/sales/_sqlbuild/macros/python/'", ), ], }, @@ -69,29 +69,29 @@ fn given_placement_when_choosing_directory_then_role_folders_match_python() { description: "a global macro", kind: DeclarationKind::Macro, scope: ScopeKind::Global, - path: Some("models/sales"), - expected_directory: "macros", + path: Some("sql/models/sales"), + expected_directory: "sql/macros", }, DeclarationDirectoryTestCase { description: "a local audit below an authored root", kind: DeclarationKind::Audit, scope: ScopeKind::Local, - path: Some("models"), - expected_directory: "models/_audits/generic", + path: Some("sql/models"), + expected_directory: "sql/models/_audits/generic", }, DeclarationDirectoryTestCase { description: "an inherited hook below a nested folder", kind: DeclarationKind::SqlHook, scope: ScopeKind::Inherited, - path: Some("models/sales"), - expected_directory: "models/sales/_sqlbuild/hooks/sql", + path: Some("sql/models/sales"), + expected_directory: "sql/models/sales/_sqlbuild/hooks/sql", }, DeclarationDirectoryTestCase { description: "an inherited enum without a folder", kind: DeclarationKind::Enum, scope: ScopeKind::Inherited, path: None, - expected_directory: "enums", + expected_directory: "sql/enums", }, ]; for test_case in test_cases { @@ -110,24 +110,24 @@ fn given_resource_move_when_relocating_then_chained_local_declarations_follow() RelocationTestCase { description: "a model and the macro chain it uses move to a new folder", index: chained_macros, - destination: "models/finance/orders.sql", + destination: "sql/models/finance/orders.sql", expected_relocations: Some(&[ ( 0, - "models/finance/_sqlbuild/_macros/python/cents.py", - Some("models/finance"), + "sql/models/finance/_sqlbuild/_macros/python/cents.py", + Some("sql/models/finance"), ), ( 1, - "models/finance/_sqlbuild/_macros/python/round.py", - Some("models/finance"), + "sql/models/finance/_sqlbuild/_macros/python/round.py", + Some("sql/models/finance"), ), ]), }, RelocationTestCase { description: "a move within the same folder relocates nothing", index: chained_macros, - destination: "models/sales/renamed.sql", + destination: "sql/models/sales/renamed.sql", expected_relocations: Some(&[]), }, ]; @@ -157,45 +157,49 @@ fn given_destination_role_layout_when_carrying_declaration_then_its_shape_is_mat CarriedLayoutTestCase { description: "an empty destination role keeps the source group", index: grouped_cents_empty_role, - moves: &[("orders", "models/sales/eu/orders.sql")], + moves: &[("orders", "sql/models/sales/eu/orders.sql")], expected_relocations: &[( 0, - "models/sales/_sqlbuild/macros/python/money/cents.py", + "sql/models/sales/_sqlbuild/macros/python/money/cents.py", false, )], }, CarriedLayoutTestCase { description: "a grouped destination role keeps the source group", index: grouped_cents_grouped_role, - moves: &[("orders", "models/sales/eu/orders.sql")], + moves: &[("orders", "sql/models/sales/eu/orders.sql")], expected_relocations: &[( 0, - "models/sales/_sqlbuild/macros/python/money/cents.py", + "sql/models/sales/_sqlbuild/macros/python/money/cents.py", false, )], }, CarriedLayoutTestCase { description: "a direct source in a grouped destination role needs a group", index: direct_cents_grouped_role, - moves: &[("orders", "models/sales/eu/orders.sql")], - expected_relocations: &[(0, "models/sales/_sqlbuild/macros/python/cents.py", true)], + moves: &[("orders", "sql/models/sales/eu/orders.sql")], + expected_relocations: &[(0, "sql/models/sales/_sqlbuild/macros/python/cents.py", true)], }, CarriedLayoutTestCase { description: "a direct destination role drops the source group", index: grouped_cents_direct_role, - moves: &[("orders", "models/sales/eu/orders.sql")], - expected_relocations: &[(0, "models/sales/_sqlbuild/macros/python/cents.py", false)], + moves: &[("orders", "sql/models/sales/eu/orders.sql")], + expected_relocations: &[( + 0, + "sql/models/sales/_sqlbuild/macros/python/cents.py", + false, + )], }, CarriedLayoutTestCase { description: "moving every user together places the macro once at their new folder", index: grouped_cents_grouped_role, moves: &[ - ("orders", "models/sales/eu/orders.sql"), - ("refunds", "models/sales/eu/refunds.sql"), + ("orders", "sql/models/sales/eu/orders.sql"), + ("refunds", "sql/models/sales/eu/refunds.sql"), ], expected_relocations: &[( 0, - "models/sales/eu/_sqlbuild/_macros/python/money/cents.py", + "sql/models/sales/eu/_sqlbuild/_macros/python/money/cents.py", false, )], }, diff --git a/crates/sqlbuild-scopes/src/scope_cache/_helpers/fingerprint.rs b/crates/sqlbuild-scopes/src/scope_cache/_helpers/fingerprint.rs index 32b3e984f2..29d3c8ba7d 100644 --- a/crates/sqlbuild-scopes/src/scope_cache/_helpers/fingerprint.rs +++ b/crates/sqlbuild-scopes/src/scope_cache/_helpers/fingerprint.rs @@ -16,6 +16,7 @@ use crate::scope_cache::constants::{ RELATIONSHIP_ROOTS, SOURCE_SUFFIXES, TARGET_VARS_KEY, TARGETS_KEY, TOML_SUFFIX, }; use crate::scope_cache::models::FingerprintInputs; +use crate::scope_index::constants::GLOBAL_ROLE_PARENT; /// A config value `json.dumps` cannot serialize. pub(crate) struct Unserializable; @@ -28,9 +29,13 @@ fn suffix(path: &str) -> &str { /// `_source_role`: declaration, macro, relationship or resource. pub(crate) fn source_role(relative: &str, inputs: &FingerprintInputs) -> &'static str { let parts: Vec<&str> = relative.split('/').collect(); + let role: &str = match parts.as_slice() { + [parent, role, ..] if *parent == GLOBAL_ROLE_PARENT => role, + _ => parts[0], + }; let mut declared: bool = inputs .named_declaration_directories - .contains(&parts[0].to_owned()); + .contains(&role.to_owned()); for part in &parts { declared |= inputs.declaration_directories.contains(&(*part).to_owned()); } diff --git a/crates/sqlbuild-scopes/src/scope_cache/constants.rs b/crates/sqlbuild-scopes/src/scope_cache/constants.rs index 5f261c2754..2ac6a72eac 100644 --- a/crates/sqlbuild-scopes/src/scope_cache/constants.rs +++ b/crates/sqlbuild-scopes/src/scope_cache/constants.rs @@ -48,4 +48,4 @@ pub(crate) const FINGERPRINT_CONFIG_FILES: [&str; 4] = [ /// Project-wide named declaration folders, sorted. pub(crate) const NAMED_DECLARATION_DIRECTORIES: [&str; 3] = ["audits", "hooks", "schemas"]; /// Source roots outside the declaration layout whose files feed the fingerprint. -pub(crate) const EXTRA_SOURCE_ROOTS: [&str; 2] = ["python", "seeds"]; +pub(crate) const EXTRA_SOURCE_ROOTS: [&str; 2] = ["python", "sql/seeds"]; diff --git a/crates/sqlbuild-scopes/src/scope_cache/main/project_fingerprint_inputs.rs b/crates/sqlbuild-scopes/src/scope_cache/main/project_fingerprint_inputs.rs index 436fa9a531..0f597eea2a 100644 --- a/crates/sqlbuild-scopes/src/scope_cache/main/project_fingerprint_inputs.rs +++ b/crates/sqlbuild-scopes/src/scope_cache/main/project_fingerprint_inputs.rs @@ -6,6 +6,7 @@ use crate::scope_cache::constants::{ EXTRA_SOURCE_ROOTS, FINGERPRINT_CONFIG_FILES, NAMED_DECLARATION_DIRECTORIES, }; use crate::scope_cache::models::FingerprintInputs; +use crate::scope_index::constants::GLOBAL_ROLE_PARENT; /// The fingerprint inputs of the project layout, for the running SQLBuild version. #[must_use] @@ -16,8 +17,12 @@ pub fn project_fingerprint_inputs(sqlbuild_version: String) -> FingerprintInputs let roots: Vec = CANONICAL_AUTHORED_ROOTS .iter() .map(|parts| parts.join("/")) - .chain(declaration_directories.iter().cloned()) - .chain(named_declaration_directories.iter().cloned()) + .chain( + declaration_directories + .iter() + .chain(&named_declaration_directories) + .map(|name| format!("{GLOBAL_ROLE_PARENT}/{name}")), + ) .chain(owned(&EXTRA_SOURCE_ROOTS)) .collect(); FingerprintInputs { diff --git a/crates/sqlbuild-scopes/src/scope_cache/tests/helpers.rs b/crates/sqlbuild-scopes/src/scope_cache/tests/helpers.rs index d9a5e1e91c..0c879301a9 100644 --- a/crates/sqlbuild-scopes/src/scope_cache/tests/helpers.rs +++ b/crates/sqlbuild-scopes/src/scope_cache/tests/helpers.rs @@ -21,7 +21,7 @@ pub(super) fn orders_index() -> CachedIndex { kind: ResourceKind::Model, name: "orders".to_owned(), }, - path: "models/sales/orders.sql".to_owned(), + path: "sql/models/sales/orders.sql".to_owned(), ownership_root: models_root(), }], declarations: vec![CachedDeclaration { @@ -31,12 +31,12 @@ pub(super) fn orders_index() -> CachedIndex { name: "order_status".to_owned(), owner: None, }, - path: "models/sales/enums/status.yml".to_owned(), + path: "sql/models/sales/enums/status.yml".to_owned(), line: 1, column: 1, scope: ScopeKind::Inherited, ownership_root: models_root(), - owning_path: Some("models/sales".to_owned()), + owning_path: Some("sql/models/sales".to_owned()), dependencies: Vec::new(), }, macro_facts: None, diff --git a/crates/sqlbuild-scopes/src/scope_cache/tests/test_scope_cache.rs b/crates/sqlbuild-scopes/src/scope_cache/tests/test_scope_cache.rs index b7424a486f..317cad2890 100644 --- a/crates/sqlbuild-scopes/src/scope_cache/tests/test_scope_cache.rs +++ b/crates/sqlbuild-scopes/src/scope_cache/tests/test_scope_cache.rs @@ -60,8 +60,8 @@ fn given_config_file_when_fingerprinting_then_only_scope_relevant_keys_are_hashe ConfigBytesTestCase { description: "a non-TOML config file hashes its raw bytes", name: ".sqlbuildignore", - text: "models/tmp\n", - expected_bytes: "models/tmp\n", + text: "sql/models/tmp\n", + expected_bytes: "sql/models/tmp\n", }, ConfigBytesTestCase { description: "invalid TOML hashes its raw bytes", diff --git a/crates/sqlbuild-scopes/src/scope_index/constants.rs b/crates/sqlbuild-scopes/src/scope_index/constants.rs index 162456a17b..0f72b1d670 100644 --- a/crates/sqlbuild-scopes/src/scope_index/constants.rs +++ b/crates/sqlbuild-scopes/src/scope_index/constants.rs @@ -4,18 +4,20 @@ use crate::scope_index::models::ResourceKind; /// Python's builder `_ROOTS`, in its insertion order. pub const RESOURCE_ROOTS: [(ResourceKind, &str); 5] = [ - (ResourceKind::Model, "models"), + (ResourceKind::Model, "sql/models"), (ResourceKind::Test, "tests/unit"), (ResourceKind::Scenario, "tests/scenarios"), - (ResourceKind::Function, "functions/sql"), - (ResourceKind::Source, "sources"), + (ResourceKind::Function, "sql/functions/sql"), + (ResourceKind::Source, "sql/sources"), ]; /// The global root of seed resources. -pub const SEED_ROOT: &str = "seeds"; +pub const SEED_ROOT: &str = "sql/seeds"; /// The global root of Python function resources. -pub const PYTHON_FUNCTION_ROOT: &str = "functions/python"; +pub const PYTHON_FUNCTION_ROOT: &str = "sql/functions/python"; /// Declaration directories whose ownership root is global. -pub const GLOBAL_DECLARATION_DIRECTORIES: [&str; 3] = ["macros", "enums", "constants"]; +pub const GLOBAL_DECLARATION_DIRECTORIES: [&str; 3] = ["sql/macros", "sql/enums", "sql/constants"]; +/// The project folder holding every project-wide declaration role. +pub const GLOBAL_ROLE_PARENT: &str = "sql"; /// Python's `PATH_SEPARATOR`. pub const PATH_SEPARATOR: char = '/'; /// Python's `CURRENT_PATH_COMPONENT`. diff --git a/crates/sqlbuild-scopes/src/scope_index/tests/helpers.rs b/crates/sqlbuild-scopes/src/scope_index/tests/helpers.rs index bebc208cef..477f782e96 100644 --- a/crates/sqlbuild-scopes/src/scope_index/tests/helpers.rs +++ b/crates/sqlbuild-scopes/src/scope_index/tests/helpers.rs @@ -19,9 +19,9 @@ use crate::scope_index::tests::test_types::{ }; const GLOBAL_ROOT_FALLBACKS: [(DeclarationKind, &str); 3] = [ - (DeclarationKind::Macro, "macros"), - (DeclarationKind::Enum, "enums"), - (DeclarationKind::Constant, "constants"), + (DeclarationKind::Macro, "sql/macros"), + (DeclarationKind::Enum, "sql/enums"), + (DeclarationKind::Constant, "sql/constants"), ]; const ROOTS: [(&str, ResourceRoot); 1] = [("seed", ResourceRoot::Seed)]; @@ -207,11 +207,11 @@ fn declaration_input(row: &DeclarationRow) -> DeclarationInput { path: path.to_owned(), line, scope, - ownership_root: (scope != ScopeKind::Global).then(|| "models".to_owned()), + ownership_root: (scope != ScopeKind::Global).then(|| "sql/models".to_owned()), root_fallback: GLOBAL_ROOT_FALLBACKS .iter() .find(|(fallback_kind, _root)| *fallback_kind == kind) - .map_or("macros", |(_kind, root)| *root) + .map_or("sql/macros", |(_kind, root)| *root) .to_owned(), owning_path: owning_path.map(str::to_owned), dependencies: Vec::new(), @@ -239,15 +239,15 @@ fn owned(values: &[&str]) -> Vec { values.iter().map(|value| (*value).to_owned()).collect() } -/// Six positions: global 0 and 4, local 2 under `models/marts`, inherited 3 and 5. +/// Six positions: global 0 and 4, local 2 under `sql/models/marts`, inherited 3 and 5. fn consumer_table() -> VisibilityTable { VisibilityTable { identity_keys: vec![0, 1, 2, 3, 4, 5], global: vec![0, 4], - local: HashMap::from([("models/marts".to_owned(), vec![2])]), + local: HashMap::from([("sql/models/marts".to_owned(), vec![2])]), inherited: HashMap::from([ - ("models".to_owned(), vec![3]), - ("models/staging".to_owned(), vec![5]), + ("sql/models".to_owned(), vec![3]), + ("sql/models/staging".to_owned(), vec![5]), ]), } } diff --git a/crates/sqlbuild-scopes/src/scope_index/tests/test_build_scope_index.rs b/crates/sqlbuild-scopes/src/scope_index/tests/test_build_scope_index.rs index 85ae161e5f..0b29cf9732 100644 --- a/crates/sqlbuild-scopes/src/scope_index/tests/test_build_scope_index.rs +++ b/crates/sqlbuild-scopes/src/scope_index/tests/test_build_scope_index.rs @@ -10,15 +10,22 @@ fn given_authored_projects_when_building_then_orders_and_diagnostics_match_pytho IndexTestCase { description: "builder sorts resources by path, the lookup by identity", resources: &[ - ("model", "zeta", "models/a/zeta.sql"), - ("model", "alpha", "models/b/./alpha.sql"), + ("model", "zeta", "sql/models/a/zeta.sql"), + ("model", "alpha", "sql/models/b/./alpha.sql"), ("test", "alpha", "tests/unit/alpha.sql"), - ("seed", "lookup", "seeds/lookup.csv"), + ("seed", "lookup", "sql/seeds/lookup.csv"), ], declarations: &[ - ("macro", "pick", "macros/b.py", 10, "global", None), - ("macro", "pick_more", "macros/a.py", 9, "global", None), - ("constant", "limit", "constants/a.sql", 1, "global", None), + ("macro", "pick", "sql/macros/b.py", 10, "global", None), + ("macro", "pick_more", "sql/macros/a.py", 9, "global", None), + ( + "constant", + "limit", + "sql/constants/a.sql", + 1, + "global", + None, + ), ], expected_resource_order: &["model:zeta", "model:alpha", "seed:lookup", "test:alpha"], expected_canonical_resources: &[ @@ -27,83 +34,101 @@ fn given_authored_projects_when_building_then_orders_and_diagnostics_match_pytho "seed:lookup", "test:alpha", ], - expected_declaration_order: &["constants/a.sql:1", "macros/b.py:10", "macros/a.py:9"], + expected_declaration_order: &[ + "sql/constants/a.sql:1", + "sql/macros/b.py:10", + "sql/macros/a.py:9", + ], expected_canonical_declarations: &[ - "constants/a.sql:1", - "macros/b.py:10", - "macros/a.py:9", + "sql/constants/a.sql:1", + "sql/macros/b.py:10", + "sql/macros/a.py:9", ], expected_diagnostics: &[], }, IndexTestCase { description: "duplicates and naming problems keep Python's messages and order", resources: &[ - ("model", "orders", "models/b/orders.sql"), - ("model", "orders", "models/a/orders.sql"), + ("model", "orders", "sql/models/b/orders.sql"), + ("model", "orders", "sql/models/a/orders.sql"), ], declarations: &[ ( "constant", "rate", - "models/a/_constants/x.sql", + "sql/models/a/_constants/x.sql", 1, "local", - Some("models/a"), + Some("sql/models/a"), + ), + ( + "constant", + "rate", + "sql/constants/rates.sql", + 1, + "global", + None, + ), + ( + "enum", + "__status", + "sql/enums/status.sql", + 1, + "global", + None, ), - ("constant", "rate", "constants/rates.sql", 1, "global", None), - ("enum", "__status", "enums/status.sql", 1, "global", None), - ("enum", "_status", "enums/other.sql", 1, "global", None), + ("enum", "_status", "sql/enums/other.sql", 1, "global", None), ( "constant", "bad", - "models/a/orders.sql", + "sql/models/a/orders.sql", 1, "private", - Some("models/a"), + Some("sql/models/a"), ), ], expected_resource_order: &["model:orders", "model:orders"], expected_canonical_resources: &["model:orders", "model:orders"], expected_declaration_order: &[ - "models/a/orders.sql:1", - "constants/rates.sql:1", - "models/a/_constants/x.sql:1", - "enums/status.sql:1", - "enums/other.sql:1", + "sql/models/a/orders.sql:1", + "sql/constants/rates.sql:1", + "sql/models/a/_constants/x.sql:1", + "sql/enums/status.sql:1", + "sql/enums/other.sql:1", ], expected_canonical_declarations: &[ - "models/a/orders.sql:1", - "constants/rates.sql:1", - "models/a/_constants/x.sql:1", - "enums/status.sql:1", - "enums/other.sql:1", + "sql/models/a/orders.sql:1", + "sql/constants/rates.sql:1", + "sql/models/a/_constants/x.sql:1", + "sql/enums/status.sql:1", + "sql/enums/other.sql:1", ], expected_diagnostics: &[ - "S003 Duplicate declaration 'constant:rate' at constants/rates.sql:1:1, \ - models/a/_constants/x.sql:1:1", + "S003 Duplicate declaration 'constant:rate' at sql/constants/rates.sql:1:1, \ + sql/models/a/_constants/x.sql:1:1", "S004 Public declaration name '_status' must not start with underscore", "S005 Declaration name '__status' uses reserved '__' prefix", - "S003 Duplicate declaration 'constant:rate' at constants/rates.sql:1:1, \ - models/a/_constants/x.sql:1:1", + "S003 Duplicate declaration 'constant:rate' at sql/constants/rates.sql:1:1, \ + sql/models/a/_constants/x.sql:1:1", "S004 Private declaration name 'bad' must have exactly one leading underscore", - "S018 Duplicate resource 'model:orders' at models/a/orders.sql, models/b/orders.sql", - "S018 Duplicate resource 'model:orders' at models/a/orders.sql, models/b/orders.sql", + "S018 Duplicate resource 'model:orders' at sql/models/a/orders.sql, sql/models/b/orders.sql", + "S018 Duplicate resource 'model:orders' at sql/models/a/orders.sql, sql/models/b/orders.sql", ], }, IndexTestCase { description: "duplicate lines sort as integers in the builder and as text in the lookup", resources: &[], declarations: &[ - ("macro", "pick", "macros/a.py", 10, "global", None), - ("macro", "pick", "macros/a.py", 9, "global", None), + ("macro", "pick", "sql/macros/a.py", 10, "global", None), + ("macro", "pick", "sql/macros/a.py", 9, "global", None), ], expected_resource_order: &[], expected_canonical_resources: &[], - expected_declaration_order: &["macros/a.py:9", "macros/a.py:10"], - expected_canonical_declarations: &["macros/a.py:10", "macros/a.py:9"], + expected_declaration_order: &["sql/macros/a.py:9", "sql/macros/a.py:10"], + expected_canonical_declarations: &["sql/macros/a.py:10", "sql/macros/a.py:9"], expected_diagnostics: &[ - "S003 Duplicate declaration 'macro:pick' at macros/a.py:9:1, macros/a.py:10:1", - "S003 Duplicate declaration 'macro:pick' at macros/a.py:9:1, macros/a.py:10:1", + "S003 Duplicate declaration 'macro:pick' at sql/macros/a.py:9:1, sql/macros/a.py:10:1", + "S003 Duplicate declaration 'macro:pick' at sql/macros/a.py:9:1, sql/macros/a.py:10:1", ], }, ]; @@ -171,16 +196,16 @@ fn given_paths_python_rejects_when_building_then_the_stage_defers() { declarations: &[( "macro", "pick", - "models/_macros/a.py", + "sql/models/_macros/a.py", 1, "local", - Some("models/../.."), + Some("sql/models/../../.."), )], expected_deferral: true, }, DeferralTestCase { description: "dot segments normalize like Python", - resources: &[("model", "a", "models/./b/../a.sql")], + resources: &[("model", "a", "sql/models/./b/../a.sql")], declarations: &[], expected_deferral: false, }, @@ -201,7 +226,7 @@ fn given_declarations_when_building_then_relationship_flag_and_usages_match_pyth let test_cases = [ IndexFactsTestCase { description: "global declarations never need relationship grants", - declarations: &[("macro", "pick", "macros/a.py", 1, "global", None)], + declarations: &[("macro", "pick", "sql/macros/a.py", 1, "global", None)], dependencies: &[], expected_scoped_relationships: false, expected_usages: &[], @@ -211,10 +236,10 @@ fn given_declarations_when_building_then_relationship_flag_and_usages_match_pyth declarations: &[( "macro", "pick", - "models/a/_macros/a.py", + "sql/models/a/_macros/a.py", 1, "local", - Some("models/a"), + Some("sql/models/a"), )], dependencies: &[], expected_scoped_relationships: true, @@ -223,8 +248,8 @@ fn given_declarations_when_building_then_relationship_flag_and_usages_match_pyth IndexFactsTestCase { description: "repeated dependencies become one usage each, in order", declarations: &[ - ("macro", "outer", "macros/a.py", 1, "global", None), - ("macro", "inner", "macros/a.py", 5, "global", None), + ("macro", "outer", "sql/macros/a.py", 1, "global", None), + ("macro", "inner", "sql/macros/a.py", 5, "global", None), ], dependencies: &["inner", "first", "inner"], expected_scoped_relationships: false, diff --git a/crates/sqlbuild-scopes/src/scope_index/tests/test_classify_resource.rs b/crates/sqlbuild-scopes/src/scope_index/tests/test_classify_resource.rs index a8a479087b..c6daa6efc5 100644 --- a/crates/sqlbuild-scopes/src/scope_index/tests/test_classify_resource.rs +++ b/crates/sqlbuild-scopes/src/scope_index/tests/test_classify_resource.rs @@ -7,7 +7,7 @@ fn given_consumers_when_classifying_then_records_follow_python_order() { let test_cases = [ ClassifyTestCase { description: "global, private, local and inherited positions sort by position", - path: "models/marts/orders.sql", + path: "sql/models/marts/orders.sql", private: &[1], grants: &[], expected_classified: Some(( @@ -23,7 +23,7 @@ fn given_consumers_when_classifying_then_records_follow_python_order() { }, ClassifyTestCase { description: "grants follow the position's own reason and keep their order", - path: "models/marts/orders.sql", + path: "sql/models/marts/orders.sql", private: &[], grants: &[ (5, VisibilityReason::TestedMacro, 7), diff --git a/crates/sqlbuild-scopes/src/scope_index/tests/test_parse_identity.rs b/crates/sqlbuild-scopes/src/scope_index/tests/test_parse_identity.rs index 896b2ce495..a7c071c7be 100644 --- a/crates/sqlbuild-scopes/src/scope_index/tests/test_parse_identity.rs +++ b/crates/sqlbuild-scopes/src/scope_index/tests/test_parse_identity.rs @@ -39,8 +39,8 @@ fn given_qualified_value_when_parsing_then_python_identity_or_failure_is_returne }, ParseIdentityTestCase { description: "a path folder is an unknown kind", - value: "models/a:b/orders.sql", - expected_identity: Err(IdentityFailure::UnknownKind("models/a".to_owned())), + value: "sql/models/a:b/orders.sql", + expected_identity: Err(IdentityFailure::UnknownKind("sql/models/a".to_owned())), }, ParseIdentityTestCase { description: "an empty name", diff --git a/crates/sqlbuild-scopes/src/scope_index/tests/test_path_visible.rs b/crates/sqlbuild-scopes/src/scope_index/tests/test_path_visible.rs index ff4a487007..af9298b835 100644 --- a/crates/sqlbuild-scopes/src/scope_index/tests/test_path_visible.rs +++ b/crates/sqlbuild-scopes/src/scope_index/tests/test_path_visible.rs @@ -9,28 +9,28 @@ fn given_declared_scope_when_checking_authored_path_then_python_visibility_is_re description: "global is visible everywhere", scope: ScopeKind::Global, owning_path: None, - path: "models/marts/orders.sql", + path: "sql/models/marts/orders.sql", expected_visible: true, }, PathVisibleTestCase { description: "inherited reaches a descendant folder", scope: ScopeKind::Inherited, - owning_path: Some("models"), - path: "models/marts/orders.sql", + owning_path: Some("sql/models"), + path: "sql/models/marts/orders.sql", expected_visible: true, }, PathVisibleTestCase { description: "inherited does not reach a sibling tree", scope: ScopeKind::Inherited, - owning_path: Some("models/staging"), - path: "models/marts/orders.sql", + owning_path: Some("sql/models/staging"), + path: "sql/models/marts/orders.sql", expected_visible: false, }, PathVisibleTestCase { description: "local only reaches its own folder", scope: ScopeKind::Local, - owning_path: Some("models"), - path: "models/marts/orders.sql", + owning_path: Some("sql/models"), + path: "sql/models/marts/orders.sql", expected_visible: false, }, ]; diff --git a/crates/sqlbuild-scopes/src/scope_index/tests/test_posix_path_text.rs b/crates/sqlbuild-scopes/src/scope_index/tests/test_posix_path_text.rs index dad0d3258f..8a76cdfe5b 100644 --- a/crates/sqlbuild-scopes/src/scope_index/tests/test_posix_path_text.rs +++ b/crates/sqlbuild-scopes/src/scope_index/tests/test_posix_path_text.rs @@ -7,9 +7,9 @@ fn given_slash_separated_paths_when_printed_then_they_match_python_as_posix() { let test_cases = [ PosixPathTestCase { description: "empty and current components are dropped", - path: "models//./orders.sql", - expected_text: "models/orders.sql", - expected_parent: "models", + path: "sql/models//./orders.sql", + expected_text: "sql/models/orders.sql", + expected_parent: "sql/models", }, PosixPathTestCase { description: "an empty path prints as the current folder", diff --git a/crates/sqlbuild-scopes/src/scope_index/tests/test_relationship_grants.rs b/crates/sqlbuild-scopes/src/scope_index/tests/test_relationship_grants.rs index 9b1ba52f74..2607c77f3f 100644 --- a/crates/sqlbuild-scopes/src/scope_index/tests/test_relationship_grants.rs +++ b/crates/sqlbuild-scopes/src/scope_index/tests/test_relationship_grants.rs @@ -2,8 +2,8 @@ use crate::scope_index::tests::helpers::grant_texts; use crate::scope_index::tests::test_types::{DeclarationRow, GrantTestCase, ResourceRow}; const RESOURCES: &[ResourceRow] = &[ - ("model", "orders", "models/sales/orders.sql"), - ("model", "other", "models/other/other.sql"), + ("model", "orders", "sql/models/sales/orders.sql"), + ("model", "other", "sql/models/other/other.sql"), ("test", "t1", "tests/unit/t1.sql"), ("test", "t2", "tests/unit/t2.sql"), ]; @@ -11,35 +11,35 @@ const DECLARATIONS: &[DeclarationRow] = &[ ( "constant", "rate", - "models/sales/_sqlbuild/constants/r.sql", + "sql/models/sales/_sqlbuild/constants/r.sql", 1, "inherited", - Some("models/sales"), + Some("sql/models/sales"), ), ( "macro", "fmt", - "models/sales/_macros/m.py", + "sql/models/sales/_macros/m.py", 3, "local", - Some("models/sales"), + Some("sql/models/sales"), ), ( "macro", "unused", - "models/sales/_macros/m.py", + "sql/models/sales/_macros/m.py", 9, "local", - Some("models/sales"), + Some("sql/models/sales"), ), - ("macro", "g", "macros/g.py", 1, "global", None), + ("macro", "g", "sql/macros/g.py", 1, "global", None), ( "constant", "_own", - "models/sales/orders.sql", + "sql/models/sales/orders.sql", 1, "private", - Some("models/sales"), + Some("sql/models/sales"), ), ]; diff --git a/crates/sqlbuild-scopes/src/scope_index/tests/test_report_lookup.rs b/crates/sqlbuild-scopes/src/scope_index/tests/test_report_lookup.rs index 89ae2aca1a..ef813307e0 100644 --- a/crates/sqlbuild-scopes/src/scope_index/tests/test_report_lookup.rs +++ b/crates/sqlbuild-scopes/src/scope_index/tests/test_report_lookup.rs @@ -7,11 +7,11 @@ fn given_identity_keys_when_grouping_then_groups_follow_python_repr_order() { LookupTestCase { description: "ASCII keys order by repr, where quotes and punctuation sort first", resources: &[ - ("model", "ab", "models/ab.sql"), - ("model", "ab!", "models/ab_bang.sql"), - ("model", "it's", "models/its.sql"), - ("function", "zz", "functions/sql/zz.sql"), - ("seed", "a", "seeds/a.csv"), + ("model", "ab", "sql/models/ab.sql"), + ("model", "ab!", "sql/models/ab_bang.sql"), + ("model", "it's", "sql/models/its.sql"), + ("function", "zz", "sql/functions/sql/zz.sql"), + ("seed", "a", "sql/seeds/a.csv"), ], declarations: &[], expected_resource_groups: &[ @@ -26,12 +26,12 @@ fn given_identity_keys_when_grouping_then_groups_follow_python_repr_order() { LookupTestCase { description: "non-ASCII keys order by repr, with escapes for separators", resources: &[ - ("model", "caf\u{e9}", "models/cafe_accent.sql"), - ("model", "cafe", "models/cafe.sql"), - ("model", "\u{a0}x", "models/nbsp.sql"), - ("model", "\u{1F600}", "models/emoji.sql"), - ("model", "Zed", "models/zed.sql"), - ("model", "e\u{301}", "models/combining.sql"), + ("model", "caf\u{e9}", "sql/models/cafe_accent.sql"), + ("model", "cafe", "sql/models/cafe.sql"), + ("model", "\u{a0}x", "sql/models/nbsp.sql"), + ("model", "\u{1F600}", "sql/models/emoji.sql"), + ("model", "Zed", "sql/models/zed.sql"), + ("model", "e\u{301}", "sql/models/combining.sql"), ], declarations: &[], expected_resource_groups: &[ @@ -46,21 +46,21 @@ fn given_identity_keys_when_grouping_then_groups_follow_python_repr_order() { }, LookupTestCase { description: "visibility positions group by scope over the canonical declarations", - resources: &[("model", "orders", "models/sales/orders.sql")], + resources: &[("model", "orders", "sql/models/sales/orders.sql")], declarations: &[ - ("macro", "g", "macros/g.py", 1, "global", None), + ("macro", "g", "sql/macros/g.py", 1, "global", None), ( "macro", "l", - "models/sales/_macros/l.py", + "sql/models/sales/_macros/l.py", 1, "local", - Some("models/sales"), + Some("sql/models/sales"), ), ( "enum", "i", - "models/_sqlbuild/enums/i.sql", + "sql/models/_sqlbuild/enums/i.sql", 1, "inherited", Some("models"), @@ -68,17 +68,17 @@ fn given_identity_keys_when_grouping_then_groups_follow_python_repr_order() { ( "constant", "_p", - "models/sales/orders.sql", + "sql/models/sales/orders.sql", 1, "private", - Some("models/sales"), + Some("sql/models/sales"), ), ], expected_resource_groups: &["model:orders"], expected_visibility: &[ "global [2]", "private model:orders [0]", - "local models/sales [3]", + "local sql/models/sales [3]", "inherited models [1]", ], }, diff --git a/crates/sqlbuild-scopes/src/scope_report/_helpers/declarations.rs b/crates/sqlbuild-scopes/src/scope_report/_helpers/declarations.rs index 232ca370cd..32900b2dc2 100644 --- a/crates/sqlbuild-scopes/src/scope_report/_helpers/declarations.rs +++ b/crates/sqlbuild-scopes/src/scope_report/_helpers/declarations.rs @@ -4,6 +4,7 @@ use std::collections::BTreeSet; use sqlbuild_core::json::models::{JsonInteger, JsonValue}; +use crate::scope_index::constants::GLOBAL_ROLE_PARENT; use crate::scope_index::main::format_identity::format_identity; use crate::scope_index::models::{ DeclarationKind, DeclarationRecord, QualifiedIdentity, ScopeKind, @@ -72,7 +73,7 @@ pub(crate) fn container(record: &DeclarationRecord) -> Container { let parts: Vec<&str> = safe.split(PATH_SEPARATOR).collect(); let mut role_index: usize = match record.owning_path.as_deref() { Some(owning) if !owning.is_empty() => owning.split(PATH_SEPARATOR).count(), - _ => 0, + _ => usize::from(parts.first() == Some(&GLOBAL_ROLE_PARENT)), }; if parts.get(role_index) == Some(&GROUP_DIRECTORY) { role_index += 1; diff --git a/crates/sqlbuild-scopes/src/scope_report/_helpers/folders.rs b/crates/sqlbuild-scopes/src/scope_report/_helpers/folders.rs index c19fc6d4a3..1998abdb54 100644 --- a/crates/sqlbuild-scopes/src/scope_report/_helpers/folders.rs +++ b/crates/sqlbuild-scopes/src/scope_report/_helpers/folders.rs @@ -1,5 +1,6 @@ //! Declaration-definition folders: browsing their children and listing what lies beneath. +use crate::scope_index::constants::GLOBAL_ROLE_PARENT; use crate::scope_index::models::{ DeclarationIdentity, DeclarationRecord, QualifiedIdentity, ScopeKind, }; @@ -81,13 +82,19 @@ pub(crate) fn definition_folder(record: &DeclarationRecord) -> String { if record.scope != ScopeKind::Global { return posix_parent(&record.path); } - let source_root: &str = record - .path - .split_once('/') - .map_or(record.path.as_str(), |(root, _)| root); + let role_depth: usize = if posix_parts(&record.path).first() == Some(&GLOBAL_ROLE_PARENT) { + 2 + } else { + 1 + }; + let source_root: String = posix_parts(&record.path) + .into_iter() + .take(role_depth) + .collect::>() + .join("/"); let parent: String = posix_parent(&record.path); let relative: &str = parent - .strip_prefix(source_root) + .strip_prefix(source_root.as_str()) .unwrap_or(&parent) .trim_matches('/'); let base: String = format!("global/{}s", record.identity.kind.as_str()); diff --git a/crates/sqlbuild-scopes/src/scope_report/tests/helpers.rs b/crates/sqlbuild-scopes/src/scope_report/tests/helpers.rs index a39c88f97f..13d2809c2b 100644 --- a/crates/sqlbuild-scopes/src/scope_report/tests/helpers.rs +++ b/crates/sqlbuild-scopes/src/scope_report/tests/helpers.rs @@ -8,10 +8,10 @@ use crate::scope_report::models::{ DeclarationValues, MacroValues, QueryTarget, ReportFilters, ReportValues, }; -/// One model under `models/sales`, a global macro, an inherited constant and a local enum. +/// One model under `sql/models/sales`, a global macro, an inherited constant and a local enum. pub(super) fn orders_facts() -> (ReportRecords, ReportLookup, ReportValues) { let models: OwnershipRoot = OwnershipRoot { - path: "models".to_owned(), + path: "sql/models".to_owned(), kind: OwnershipRootKind::Resource, resource_kind: Some(ResourceKind::Model), }; @@ -45,7 +45,7 @@ pub(super) fn orders_facts() -> (ReportRecords, ReportLookup, ReportValues) { declaration( DeclarationKind::Macro, "g", - "macros/g.py", + "sql/macros/g.py", ScopeKind::Global, &project, None, @@ -53,25 +53,25 @@ pub(super) fn orders_facts() -> (ReportRecords, ReportLookup, ReportValues) { declaration( DeclarationKind::Constant, "c", - "models/constants/c.sql", + "sql/models/constants/c.sql", ScopeKind::Inherited, &models, - Some("models"), + Some("sql/models"), ), declaration( DeclarationKind::Enum, "e", - "models/finance/_enums/e.sql", + "sql/models/finance/_enums/e.sql", ScopeKind::Local, &models, - Some("models/finance"), + Some("sql/models/finance"), ), ]; let records: ReportRecords = ReportRecords { roots: vec![models.clone()], resources: vec![ResourceRecord { identity: orders.clone(), - path: "models/sales/orders.sql".to_owned(), + path: "sql/models/sales/orders.sql".to_owned(), ownership_root: models, }], usages: vec![ReportUsage { diff --git a/crates/sqlbuild-scopes/src/scope_report/tests/test_scope_report.rs b/crates/sqlbuild-scopes/src/scope_report/tests/test_scope_report.rs index 88102b678d..86377242c4 100644 --- a/crates/sqlbuild-scopes/src/scope_report/tests/test_scope_report.rs +++ b/crates/sqlbuild-scopes/src/scope_report/tests/test_scope_report.rs @@ -21,8 +21,8 @@ fn given_target_or_prospective_path_when_reporting_then_sections_follow_scope_ru expected_used: &["constant:c"], expected_nearby: &["enum:e"], expected_chain: &[ - "local models/sales 0", - "inherited models 1", + "local sql/models/sales 0", + "inherited sql/models 1", "global global 1", ], expected_complete: true, @@ -30,13 +30,13 @@ fn given_target_or_prospective_path_when_reporting_then_sections_follow_scope_ru ReportTestCase { description: "a prospective path in the enum's folder sees it but stays incomplete", target: None, - at: Some("models/finance/new.sql"), + at: Some("sql/models/finance/new.sql"), expected_available: &["constant:c", "enum:e", "macro:g"], expected_used: &[], expected_nearby: &[], expected_chain: &[ - "local models/finance 1", - "inherited models 1", + "local sql/models/finance 1", + "inherited sql/models 1", "global global 1", ], expected_complete: false, @@ -117,8 +117,8 @@ fn given_browse_result_when_serializing_then_json_is_sorted_compact_ascii() { "{\"complete\":true,\"diagnostics\":[],\"folder\":\".\",\"folders\":[", "{\"child_count\":1,\"descendant_count\":1,\"kind_counts\":{\"macro\":1},", "\"name\":\"global\",\"path\":\"global\",\"used_count\":0},", - "{\"child_count\":2,\"descendant_count\":2,\"kind_counts\":{\"constant\":1,\"enum\":1},", - "\"name\":\"models\",\"path\":\"models\",\"used_count\":1}],", + "{\"child_count\":1,\"descendant_count\":2,\"kind_counts\":{\"constant\":1,\"enum\":1},", + "\"name\":\"sql\",\"path\":\"sql\",\"used_count\":1}],", "\"schema_version\":2}\n" ), }]; @@ -152,20 +152,20 @@ fn given_paths_when_comparing_ancestry_then_whole_components_decide() { let test_cases = [ DescendantTestCase { description: "a shared name prefix is not an ancestor", - path: "models/orders", - ancestor: "models/order", + path: "sql/models/orders", + ancestor: "sql/models/order", expected_descendant: false, }, DescendantTestCase { description: "the project root contains every path", - path: "models/orders", + path: "sql/models/orders", ancestor: ".", expected_descendant: true, }, DescendantTestCase { description: "paths compare after normalization", - path: "models\\orders\\..\\sales", - ancestor: "models/./sales", + path: "sql\\models\\orders\\..\\sales", + ancestor: "sql/models/./sales", expected_descendant: true, }, ]; diff --git a/crates/sqlbuild-scopes/src/scope_text/tests/helpers.rs b/crates/sqlbuild-scopes/src/scope_text/tests/helpers.rs index 5739600401..1a9d958252 100644 --- a/crates/sqlbuild-scopes/src/scope_text/tests/helpers.rs +++ b/crates/sqlbuild-scopes/src/scope_text/tests/helpers.rs @@ -19,7 +19,7 @@ pub(super) fn browse_result(complete: bool) -> ScopeResult { ScopeResult::Browse(BrowseResult { folder: "models".to_owned(), folders: vec![ScopeFolder { - path: "models/my marts".to_owned(), + path: "sql/models/my marts".to_owned(), name: "my marts".to_owned(), descendant_count: 1, child_count: 0, diff --git a/crates/sqlbuild-scopes/src/scope_text/tests/test_scope_text.rs b/crates/sqlbuild-scopes/src/scope_text/tests/test_scope_text.rs index 75d589f51b..33de046dde 100644 --- a/crates/sqlbuild-scopes/src/scope_text/tests/test_scope_text.rs +++ b/crates/sqlbuild-scopes/src/scope_text/tests/test_scope_text.rs @@ -15,8 +15,8 @@ fn given_scope_result_when_rendering_text_then_text_and_exit_match() { request: orders_request(), expected_text: "Scope folders\n Path: models\n\n \u{2514}\u{2500} my marts/ \ 1 declaration, 1 used, 0 children; macro 1\n \ - sqb scope model:orders --browse 'models/my marts'\n \ - sqb scope model:orders --list 'models/my marts'\n\nCompleteness: partial\n", + sqb scope model:orders --browse 'sql/models/my marts'\n \ + sqb scope model:orders --list 'sql/models/my marts'\n\nCompleteness: partial\n", expected_failed: true, }, ScopeTextTestCase { diff --git a/crates/sqlbuild-sqltext/src/compiler/tests/helpers.rs b/crates/sqlbuild-sqltext/src/compiler/tests/helpers.rs index 36d9296d69..d05bbf84f2 100644 --- a/crates/sqlbuild-sqltext/src/compiler/tests/helpers.rs +++ b/crates/sqlbuild-sqltext/src/compiler/tests/helpers.rs @@ -246,9 +246,9 @@ pub(crate) fn interpolation_host(context: bool) -> MapHost { } } -/// Interpolate `sql` as `models/orders.sql`: the rendered SQL or the error message. +/// Interpolate `sql` as `sql/models/orders.sql`: the rendered SQL or the error message. pub(crate) fn interpolated(host: &MapHost, sql: &str) -> Result { - interpolate_sql(host, sql, "models/orders.sql") + interpolate_sql(host, sql, "sql/models/orders.sql") .map(|result| result.sql.unwrap_or_else(|| sql.to_owned())) .map_err(|failure| failure.message) } @@ -258,7 +258,7 @@ pub(crate) fn interpolation_facts( host: &MapHost, sql: &str, ) -> (Vec<[usize; 4]>, Vec) { - interpolate_sql(host, sql, "models/orders.sql").map_or_else( + interpolate_sql(host, sql, "sql/models/orders.sql").map_or_else( |failure| (Vec::new(), failure.reads), |result| (result.spans.iter().map(span_parts).collect(), result.reads), ) diff --git a/crates/sqlbuild-sqltext/src/compiler/tests/test_sql_interpolation.rs b/crates/sqlbuild-sqltext/src/compiler/tests/test_sql_interpolation.rs index 308d2501e4..d18e64dd55 100644 --- a/crates/sqlbuild-sqltext/src/compiler/tests/test_sql_interpolation.rs +++ b/crates/sqlbuild-sqltext/src/compiler/tests/test_sql_interpolation.rs @@ -4,7 +4,7 @@ use crate::compiler::tests::test_types::{InterpolationFactsTestCase, Interpolati #[test] fn given_sql_when_interpolating_then_text_and_errors_match_python() { - let unknown_variable = "unknown project variable '@@missing' in 'models/orders.sql'. \ + let unknown_variable = "unknown project variable '@@missing' in 'sql/models/orders.sql'. \ Available vars: größe, layout, region, revision"; let test_cases = [ InterpolationTestCase { @@ -60,39 +60,41 @@ fn given_sql_when_interpolating_then_text_and_errors_match_python() { sql: "SELECT @@ENV:SALES_REGION", context: false, expected_sql: Err( - "unknown environment variable '@@ENV:SALES_REGION' in 'models/orders.sql'", + "unknown environment variable '@@ENV:SALES_REGION' in 'sql/models/orders.sql'", ), }, InterpolationTestCase { description: "an empty environment name", sql: "SELECT @@ENV:-1", context: false, - expected_sql: Err("invalid environment interpolation token in 'models/orders.sql'"), + expected_sql: Err("invalid environment interpolation token in 'sql/models/orders.sql'"), }, InterpolationTestCase { description: "context outside hooks", sql: "SELECT @@CTX:this", context: false, - expected_sql: Err("SQL text in 'models/orders.sql' does not allow @@CTX templates"), + expected_sql: Err("SQL text in 'sql/models/orders.sql' does not allow @@CTX templates"), }, InterpolationTestCase { description: "an empty context name", sql: "SELECT @@CTX:", context: true, - expected_sql: Err("invalid CTX interpolation token in 'models/orders.sql'"), + expected_sql: Err("invalid CTX interpolation token in 'sql/models/orders.sql'"), }, InterpolationTestCase { description: "an unknown context key", sql: "SELECT @@CTX:that", context: true, - expected_sql: Err("SQL text in 'models/orders.sql' references unknown CTX key 'that'"), + expected_sql: Err( + "SQL text in 'sql/models/orders.sql' references unknown CTX key 'that'", + ), }, InterpolationTestCase { description: "a context key without a value", sql: "SELECT @@CTX:run_id", context: true, expected_sql: Err( - "SQL text in 'models/orders.sql' references CTX key 'run_id' but no value is \ + "SQL text in 'sql/models/orders.sql' references CTX key 'run_id' but no value is \ available", ), }, diff --git a/crates/sqlbuild-state/src/resource_costs/constants.rs b/crates/sqlbuild-state/src/resource_costs/constants.rs index 957ca4838b..e3cac49c1c 100644 --- a/crates/sqlbuild-state/src/resource_costs/constants.rs +++ b/crates/sqlbuild-state/src/resource_costs/constants.rs @@ -6,7 +6,7 @@ use crate::freshness::constants::{STRING_STATE_VALUE_TYPE, TEXT_TIMESTAMP_STATE_ /// The column the warehouse clock fills on insert. pub const OBSERVED_AT_COLUMN: &str = "observed_at"; /// Columns in declaration order with their state value types; `observed_at` is last. -pub const RESOURCE_COST_COLUMN_TYPES: [(&str, &str); 23] = [ +pub const RESOURCE_COST_COLUMN_TYPES: [(&str, &str); 25] = [ ("observation_id", STRING_STATE_VALUE_TYPE), ("run_id", STRING_STATE_VALUE_TYPE), ("orchestration_run_id", STRING_STATE_VALUE_TYPE), @@ -22,6 +22,8 @@ pub const RESOURCE_COST_COLUMN_TYPES: [(&str, &str); 23] = [ ("bytes_scanned", INTEGER_STATE_VALUE_TYPE), ("estimated_credits", STRING_STATE_VALUE_TYPE), ("estimated_usd", STRING_STATE_VALUE_TYPE), + ("usd_per_credit", STRING_STATE_VALUE_TYPE), + ("usd_per_credit_source", STRING_STATE_VALUE_TYPE), ("status", STRING_STATE_VALUE_TYPE), ("statements_expected", INTEGER_STATE_VALUE_TYPE), ("statements_observed", INTEGER_STATE_VALUE_TYPE), @@ -31,14 +33,18 @@ pub const RESOURCE_COST_COLUMN_TYPES: [(&str, &str); 23] = [ ("run_completed_at", TEXT_TIMESTAMP_STATE_VALUE_TYPE), (OBSERVED_AT_COLUMN, TEXT_TIMESTAMP_STATE_VALUE_TYPE), ]; -/// Columns that may be NULL: server run, optional warehouse detail, unpriced USD and target. -pub const NULLABLE_RESOURCE_COST_COLUMNS: [&str; 5] = [ +/// Columns that may be NULL: server run, optional warehouse detail, unpriced USD and its price, and target. +pub const NULLABLE_RESOURCE_COST_COLUMNS: [&str; 7] = [ "orchestration_run_id", "warehouse_type", "cluster_number", "estimated_usd", + "usd_per_credit", + "usd_per_credit_source", "target_name", ]; +/// Columns added after the table's first release; opening an older table adds them. +pub const ADDED_RESOURCE_COST_COLUMNS: [&str; 2] = ["usd_per_credit", "usd_per_credit_source"]; /// Resource type of a run's totals row; executor resource types never start with an underscore. pub const TOTAL_RESOURCE_TYPE: &str = "_total"; /// Columns a refresh reads from each run's newest run row, in this order. diff --git a/crates/sqlbuild-state/src/state_tables/main/add_columns_sql.rs b/crates/sqlbuild-state/src/state_tables/main/add_columns_sql.rs new file mode 100644 index 0000000000..69466211ed --- /dev/null +++ b/crates/sqlbuild-state/src/state_tables/main/add_columns_sql.rs @@ -0,0 +1,16 @@ +//! Statements adding columns a state table gained after it was first created, each only if missing. + +use crate::state_tables::models::TableColumn; + +/// One `ALTER TABLE … ADD COLUMN IF NOT EXISTS` per column; added columns are always nullable. +pub fn add_columns_sql(qualified_name: &str, columns: &[TableColumn]) -> Vec { + columns + .iter() + .map(|column| { + format!( + "ALTER TABLE {qualified_name} ADD COLUMN IF NOT EXISTS {} {}", + column.name, column.rendered_type + ) + }) + .collect() +} diff --git a/crates/sqlbuild-state/src/state_tables/main/mod.rs b/crates/sqlbuild-state/src/state_tables/main/mod.rs index b83c29f514..cb160b1046 100644 --- a/crates/sqlbuild-state/src/state_tables/main/mod.rs +++ b/crates/sqlbuild-state/src/state_tables/main/mod.rs @@ -1,3 +1,4 @@ +pub mod add_columns_sql; pub mod create_table_sql; pub mod event_id_index; pub mod read_history_sql; diff --git a/deploy/project/models/orders.sql b/deploy/project/sql/models/orders.sql similarity index 100% rename from deploy/project/models/orders.sql rename to deploy/project/sql/models/orders.sql diff --git a/fensu.toml b/fensu.toml index b3d2d34e49..2690f8e1b6 100644 --- a/fensu.toml +++ b/fensu.toml @@ -254,7 +254,7 @@ reason = "Native code resolves these through the sqlbuild._native_host name tabl [[targets.python.dead_code.roots]] modules = ["sqlbuild.compiler.discovery._helpers.filesystem.project_modules"] -symbols = ["import_python_root_module", "install_python_root_package", "load_materialize_function", "load_orchestration_module", "load_provider_module", "load_python_node_module", "load_sink_module", "module_functions", "module_provider_classes", "parameter_annotations", "provider_settings", "provider_usages", "requires_arguments", "restore_python_root_modules", "source_line", "validate_event_exporter_signature"] +symbols = ["import_python_root_module", "install_python_root_package", "load_event_sink_module", "load_materialize_function", "load_orchestration_module", "load_provider_module", "load_python_node_module", "module_functions", "module_provider_classes", "parameter_annotations", "provider_settings", "provider_usages", "requires_arguments", "restore_python_root_modules", "source_line", "validate_event_exporter_signature"] reason = "Native code resolves these through the sqlbuild._native_host name table." [[targets.python.dead_code.roots]] @@ -837,6 +837,11 @@ modules = ["sqlbuild.runtime.observability.main.current_execution_identity"] symbols = ["current_execution_identity"] reason = "Native code resolves these through the sqlbuild._native_host name table." +[[targets.python.dead_code.roots]] +modules = ["sqlbuild.runtime.observability.main.current_event_dispatcher"] +symbols = ["current_event_dispatcher"] +reason = "Native code resolves these through the sqlbuild._native_host name table." + [[targets.python.dead_code.roots]] modules = ["sqlbuild.runtime.observability.main.diagnostic_log_to_json"] symbols = ["diagnostic_log_to_json"] @@ -1396,7 +1401,7 @@ paths = ["crates/sqlbuild-rules/src/custom_rule_cache/main/parse_custom_rule_cac reason = "Each reads its own cache format: the SQL rule cache checks its version and the build identity and returns findings by path, the custom-rule cache checks only its version, because its identities already include the build, and returns rules by code. Only the parse-and-filter shape is alike." [[dupes.allowlist]] -paths = ["crates/sqlbuild-orchestration/src/api/_helpers/resources/administrators.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/audit.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/changed_builds.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/location_health.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/location_work.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_checks.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_location_work.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_maintenance.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_node_sql.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_operations.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_plans.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_republish.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_selection.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/service_accounts.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/trigger_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/warehouse_metadata.rs"] +paths = ["crates/sqlbuild-orchestration/src/api/_helpers/resources/administrators.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/audit.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/changed_builds.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/location_health.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/location_work.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_checks.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_cost.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_location_work.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_maintenance.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_node_sql.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_operations.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_plans.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_republish.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_selection.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/service_accounts.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/trigger_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/warehouse_metadata.rs"] reason = "Each function is one utoipa-annotated axum route: OpenAPI needs one annotated handler per operation, and each body only checks the caller's scope and calls one store operation. Scope checks and store work live in their shared owners." [[dupes.allowlist]] @@ -1427,6 +1432,14 @@ reason = "Three crates that don't depend on each other each keep the first of ev paths = ["crates/sqlbuild-orchestration/src/credentials/_helpers/locations.rs", "crates/sqlbuild-orchestration/src/credentials/main/identities/insert_principal.rs"] reason = "Locations and principals are separate identity tables with different columns and audit kinds, each created by its own operation." +[[dupes.allowlist]] +paths = ["crates/sqlbuild-orchestration/src/declarations/_helpers/job_detail.rs", "crates/sqlbuild-orchestration/src/discovered_sets/main/discovered_readback.rs"] +reason = "Job settings are shown with credentials withheld and strings redacted; a discovered item's arguments become plain text for its node. Only the map-each-JSON-value shape is alike." + +[[dupes.allowlist]] +paths = ["crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_selection.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_selection.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_series.rs"] +reason = "The period and the selection's cost rows come from the shared selection_costs_in_days; the selection read summarises them against the period before, the series read checks its group limit and builds one daily series per group. Only the forwarded store, planner, location and selector arguments are alike." + [[dupes.allowlist]] paths = ["crates/sqlbuild-orchestration/src/scheduler/main/_next_cron_time.rs", "crates/sqlbuild-orchestration/src/scheduler/main/_previous_cron_time.rs"] reason = "Forward and backward cron searches differ in search start, inclusivity and stop condition; the fold and gap rules they share live in calendar.rs." @@ -1586,8 +1599,8 @@ reason = "Bare lifecycle sink decorators are evaluated as decorator(function), r [[targets.python.rule_exceptions]] rule = "FFS120" -path = "src/sqlbuild/runtime/event_exporting/main/command_output_sink.py" -symbols = ["command_output_sink"] +path = "src/sqlbuild/runtime/event_exporting/main/command_output_event_sink.py" +symbols = ["command_output_event_sink"] reason = "Bare command-output sink decorators are evaluated as decorator(function), requiring positional function calling." [[targets.python.rule_exceptions]] @@ -1680,6 +1693,21 @@ rule = "FFT104" path = "tests/unit/src/sqlbuild/rule_engine/_helpers/host/interrupts/helpers.py" reason = "The interrupter thread polls for the event that starts the interrupt and must not interrupt once its block has ended; the tests using it remain branch-free." +[[targets.python.rule_exceptions]] +rule = "FFT104" +path = "tests/integration/src/sqlbuild/compiler/compiled_project/publication/docker/compose/helpers.py" +reason = "The Compose outage helpers poll a real server, location and webhook receiver until a fresh check-in or delivery arrives or a deadline passes, and describe what arrived on failure; the tests using them remain branch-free." + +[[targets.python.rule_exceptions]] +rule = "FFT104" +path = "tests/unit/src/sqlbuild/python_nodes/helpers.py" +reason = "node_module_files rewrites an inline node module into one kind-named file per declaration by walking its syntax tree, which needs branches by node kind; the tests that call it remain branch-free." + +[[targets.python.rule_exceptions]] +rule = "FFT106" +path = "tests/unit/src/sqlbuild/python_nodes/helpers.py" +reason = "node_module_files collects names across the declarations of an inline module with nested comprehensions over its syntax tree; the tests that call it remain branch-free." + [targets.rust] analyzer = "rust" roots = ["crates"] @@ -1706,8 +1734,8 @@ select = [ [[targets.rust.threshold_overrides]] paths = ["crates/sqlbuild-python/Cargo.toml"] -thresholds = { max_crate_code_lines = 51300 } -reason = "The Python bindings crate is above the code-line limit; this caps it near its current size until it is split into crates by area. The location and plan bindings of the large-project server work and #1560 grew it to 51,122; moving them out would need new cross-crate imports or a policy exception. The dbt event stream moved to sqlbuild-python-output, and the location sync's dynamic-model resume came in (50,945). The CHI-1589 stop handling and dev error fields plus the CHI-1595/CHI-1593 env-file merge took it to 51,210 when combined. The cap stays near its current size; lower it as code moves out." +thresholds = { max_crate_code_lines = 51311 } +reason = "The Python bindings crate is above the code-line limit; this caps it near its current size until it is split into crates by area. The location and plan bindings of the large-project server work and #1560 grew it to 51,122; moving them out would need new cross-crate imports or a policy exception. The dbt event stream moved to sqlbuild-python-output, and the location sync's dynamic-model resume came in (50,945). The CHI-1589 stop handling and dev error fields plus the CHI-1595/CHI-1593 env-file merge took it to 51,210 when combined. The CHI-1443 project layout's exported path constants and its event_sinks and extra_paths keys took it to 51,305, and CHI-1650's older-table read of the two cost price columns to 51,311. The cap stays near its current size; lower it as code moves out." [[targets.rust.threshold_overrides]] paths = ["crates/sqlbuild-python/src/bindings/_helpers"] @@ -2468,7 +2496,7 @@ pending_budgets = [ "crates/sqlbuild-python-front/src/discovery/_helpers/project/project_files.rs=3", "crates/sqlbuild-python-front/src/discovery/_helpers/project/project_validation.rs=0", "crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_modules.rs=3", - "crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs=14", + "crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs=13", "crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_python_nodes.rs=7", "crates/sqlbuild-python-front/src/discovery/_helpers/python_files/python_function_files.rs=15", "crates/sqlbuild-python-front/src/discovery/_helpers/python_files/python_hook_files.rs=1", @@ -4092,7 +4120,7 @@ paths = ["crates/sqlbuild-python-output/src/event_exporting/_helpers/getters.rs" reason = "The export summary and the per-exporter counts are separate Python classes that each expose the same delivery counters; each getter reads its own class's fields." [[dupes.allowlist]] -paths = ["crates/sqlbuild-python-base/src/boundary/_helpers/expected_errors.rs", "crates/sqlbuild-python-compile/src/compile_command/main/invocation/register_report.rs", "crates/sqlbuild-python-compile/src/compile_driver/main/setup/register_project.rs", "crates/sqlbuild-python-compile/src/compile_driver/main/setup/register_python_plan_entries.rs", "crates/sqlbuild-python-front/src/discovery/main/headers/register_header_values.rs", "crates/sqlbuild-python-front/src/macro_bridge/main/register_module_digests.rs", "crates/sqlbuild-python-output/src/event_exporting/main/register_policy.rs", "crates/sqlbuild-python-planner/src/microbatches/main/register_projection.rs", "crates/sqlbuild-python-planner/src/planner_changes/main/register_detect.rs", "crates/sqlbuild-python-planner/src/planner_changes/main/register_metadata.rs", "crates/sqlbuild-python-planner/src/planner_resolution/main/cursor/register_cursor_ranges.rs", "crates/sqlbuild-python-planner/src/planner_resolution/main/references/register_locations.rs", "crates/sqlbuild-python-planner/src/planner_resolution/main/references/register_orchestration.rs", "crates/sqlbuild-python-planner/src/planner_strategy/main/audits/register_audits.rs", "crates/sqlbuild-python-project/src/semantic_shapes/main/register_shapes.rs", "crates/sqlbuild-python/src/bindings/_helpers/command_runtime/connection.rs", "crates/sqlbuild-python/src/bindings/_helpers/cost_report/degradation.rs", "crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/pipeline.rs", "crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/plan_output.rs"] +paths = ["crates/sqlbuild-python-base/src/boundary/_helpers/expected_errors.rs", "crates/sqlbuild-python-compile/src/compile_command/main/invocation/register_report.rs", "crates/sqlbuild-python-compile/src/compile_driver/main/setup/register_project.rs", "crates/sqlbuild-python-compile/src/compile_driver/main/setup/register_python_plan_entries.rs", "crates/sqlbuild-python-front/src/discovery/main/headers/register_header_values.rs", "crates/sqlbuild-python-front/src/macro_bridge/main/register_module_digests.rs", "crates/sqlbuild-python-front/src/resource_costs/main/register_resource_costs_state.rs", "crates/sqlbuild-python-output/src/event_exporting/main/register_policy.rs", "crates/sqlbuild-python-planner/src/microbatches/main/register_projection.rs", "crates/sqlbuild-python-planner/src/planner_changes/main/register_detect.rs", "crates/sqlbuild-python-planner/src/planner_changes/main/register_metadata.rs", "crates/sqlbuild-python-planner/src/planner_resolution/main/cursor/register_cursor_ranges.rs", "crates/sqlbuild-python-planner/src/planner_resolution/main/references/register_locations.rs", "crates/sqlbuild-python-planner/src/planner_resolution/main/references/register_orchestration.rs", "crates/sqlbuild-python-planner/src/planner_strategy/main/audits/register_audits.rs", "crates/sqlbuild-python-project/src/semantic_shapes/main/register_shapes.rs", "crates/sqlbuild-python/src/bindings/_helpers/command_runtime/connection.rs", "crates/sqlbuild-python/src/bindings/_helpers/cost_report/degradation.rs", "crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/pipeline.rs", "crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/plan_output.rs"] reason = "Each registers its own module's Python functions; only the add-function calls are alike." [[dupes.allowlist]] diff --git a/python-boundary.toml b/python-boundary.toml index fa8ac7a43d..96f82acf80 100644 --- a/python-boundary.toml +++ b/python-boundary.toml @@ -305,22 +305,22 @@ note = "Package marker of the public sink decorators and the user-sink invocatio [[stays]] path = "runtime/event_exporting/main/lifecycle_event_sink.py" rule = 3 -note = "Rule 3 facade: the @lifecycle_event_sink decorator re-exported by sqlbuild.sinks, run when user sink modules are imported." +note = "Rule 3 facade: the @lifecycle_event_sink decorator re-exported by sqlbuild.event_sinks, run when user event sink modules are imported." [[stays]] -path = "runtime/event_exporting/main/command_output_sink.py" +path = "runtime/event_exporting/main/command_output_event_sink.py" rule = 3 -note = "Rule 3 facade: the @command_output_sink decorator re-exported by sqlbuild.sinks, run when user sink modules are imported." +note = "Rule 3 facade: the @command_output_event_sink decorator re-exported by sqlbuild.event_sinks, run when user event sink modules are imported." [[stays]] path = "runtime/event_exporting/main/get_lifecycle_event_sink_definition.py" rule = 3 -note = "Rule 3 facade: reads the decorator's definition off a user function; re-exported by sqlbuild.sinks." +note = "Rule 3 facade: reads the decorator's definition off a user function; re-exported by sqlbuild.event_sinks." [[stays]] -path = "runtime/event_exporting/main/get_command_output_sink_definition.py" +path = "runtime/event_exporting/main/get_command_output_event_sink_definition.py" rule = 3 -note = "Rule 3 facade: reads the decorator's definition off a user function; re-exported by sqlbuild.sinks." +note = "Rule 3 facade: reads the decorator's definition off a user function; re-exported by sqlbuild.event_sinks." [[stays]] path = "runtime/event_exporting/main/_invoke_lifecycle_event_sink.py" @@ -340,12 +340,12 @@ note = "Thin shim that calls a user Recall replacement sink with its record and [[stays]] path = "runtime/event_exporting/models.py" rule = 3 -note = "Rule 3 shape: LifecycleEventSinkDefinition re-exported by sqlbuild.sinks." +note = "Rule 3 shape: LifecycleEventSinkDefinition re-exported by sqlbuild.event_sinks." [[stays]] path = "runtime/event_exporting/types.py" rule = 3 -note = "Rule 3 shape: LifecycleEventKind re-exported by sqlbuild.sinks." +note = "Rule 3 shape: LifecycleEventKind re-exported by sqlbuild.event_sinks." [[stays]] path = "runtime/event_exporting/exceptions.py" @@ -375,17 +375,17 @@ note = "Package marker of the public command-output shapes below." [[stays]] path = "runtime/output_capture/models.py" rule = 3 -note = "Rule 3 shapes: CommandOutputRecord and sink definitions re-exported by sqlbuild.sinks; validation is native validate_command_output_record." +note = "Rule 3 shapes: CommandOutputRecord and sink definitions re-exported by sqlbuild.event_sinks; validation is native validate_command_output_record." [[stays]] path = "runtime/output_capture/types.py" rule = 3 -note = "Rule 3 shapes: CommandOutputStream re-exported by sqlbuild.sinks, priorities and the exporter protocol." +note = "Rule 3 shapes: CommandOutputStream re-exported by sqlbuild.event_sinks, priorities and the exporter protocol." [[stays]] path = "runtime/output_capture/exceptions.py" rule = 3 -note = "Rule 3 shapes: CommandOutputValidationError re-exported by sqlbuild.sinks and raised by the native records." +note = "Rule 3 shapes: CommandOutputValidationError re-exported by sqlbuild.event_sinks and raised by the native records." [[stays]] path = "runtime/output_capture/constants.py" @@ -668,7 +668,7 @@ rule = 3 note = "Public facade: re-exports only." [[stays]] -path = "sinks.py" +path = "event_sinks.py" rule = 3 note = "Public facade: re-exports only." diff --git a/scripts/build_features/constants.py b/scripts/build_features/constants.py index 19c81e0251..449bd13b15 100644 --- a/scripts/build_features/constants.py +++ b/scripts/build_features/constants.py @@ -1,8 +1,9 @@ """Stable build feature alignment constants.""" SQB_PACKAGE: str = "sqlbuild-cli" +SQB_FEATURES: str = "ui" EXTENSION_PACKAGE: str = "sqlbuild-python" -EXTENSION_FEATURES: str = "extension-module" +EXTENSION_FEATURES: str = "extension-module,sqlbuild-cli/ui" WHEEL_TARGETS: tuple[str, ...] = ( "x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", diff --git a/scripts/build_features/main/check.py b/scripts/build_features/main/check.py index 5af139afee..c8c7e78f62 100644 --- a/scripts/build_features/main/check.py +++ b/scripts/build_features/main/check.py @@ -12,6 +12,7 @@ EXTENSION_FEATURES, EXTENSION_PACKAGE, FEATURE_CRATE, + SQB_FEATURES, SQB_PACKAGE, WHEEL_TARGETS, ) @@ -30,7 +31,9 @@ def run_build_features_check(argv: list[str] | None = None) -> int: target=target, sqb=parse_cargo_tree( run_cargo_tree( - root=arguments.root, selection=("--package", SQB_PACKAGE), target=target + root=arguments.root, + selection=("--package", SQB_PACKAGE, "--features", SQB_FEATURES), + target=target, ) ), extension=parse_cargo_tree( diff --git a/scripts/cli_preview/_helpers/workflow.py b/scripts/cli_preview/_helpers/workflow.py index 47c4d61aa0..7f542c2ae2 100644 --- a/scripts/cli_preview/_helpers/workflow.py +++ b/scripts/cli_preview/_helpers/workflow.py @@ -15,7 +15,7 @@ from scripts.cli_preview.models import PreviewScene from sqlbuild._native import supports_color -_PAYMENTS_MODEL_PATH: Path = Path("models/staging/stg_payments.sql") +_PAYMENTS_MODEL_PATH: Path = Path("sql/models/staging/stg_payments.sql") _QUERY_MARKER: str = " amount_cents,\n" _CHANGED_QUERY_MARKER: str = ( " CAST(CASE WHEN payment_method = 'card' THEN 'preview'" diff --git a/scripts/cold_compile_performance/_helpers/dense_project.py b/scripts/cold_compile_performance/_helpers/dense_project.py index 1c7a08422d..91bc99b62e 100644 --- a/scripts/cold_compile_performance/_helpers/dense_project.py +++ b/scripts/cold_compile_performance/_helpers/dense_project.py @@ -32,6 +32,7 @@ def dense_model_path(*, project_dir: Path, index: int) -> Path: return ( project_dir + / "sql" / "models" / f"sales{index // 1000:03d}" / "intermediate" @@ -89,11 +90,13 @@ def write_dense_compile_project( _layered_write_seeds(project_dir=project_dir, seed_count=seed_count) _layered_write_functions(project_dir=project_dir, function_count=function_count) for cohort in range((model_count + 999) // 1000): - models: Path = project_dir / "models" / f"sales{cohort:03d}" / "intermediate" / "clean" + models: Path = ( + project_dir / "sql" / "models" / f"sales{cohort:03d}" / "intermediate" / "clean" + ) models.mkdir(parents=True) macro_count: int = max(1, min(1000, model_count - cohort * 1000) // 80) _layered_write_macros(project_dir=project_dir, macro_count=macro_count) - macro_root: Path = project_dir / "macros" / "python" + macro_root: Path = project_dir / "sql" / "macros" / "python" for macro_index, macro_path in enumerate(sorted(macro_root.glob("*.py"))): bucket: Path = ( models / "_sqlbuild" / "macros" / "python" / f"adjustment{macro_index // 8:03d}" @@ -111,7 +114,13 @@ def write_dense_compile_project( name: str = dense_model_name(index) domain: str = f"sales{index // 1000:03d}" model_owner: Path = ( - project_dir / "models" / domain / "intermediate" / "clean" / f"batch{index // 5:05d}" + project_dir + / "sql" + / "models" + / domain + / "intermediate" + / "clean" + / f"batch{index // 5:05d}" ) test_owner: Path = ( project_dir @@ -172,8 +181,8 @@ def write_dense_compile_project( def _write_sources(*, project_dir: Path, source_count: int) -> None: - sources: Path = project_dir / "sources" - sources.mkdir() + sources: Path = project_dir / "sql" / "sources" + sources.mkdir(parents=True) entries: list[str] = ["sources:"] for index in range(source_count): width: int = dense_column_count(index % 240) diff --git a/scripts/cold_compile_performance/_helpers/diagnostic_project.py b/scripts/cold_compile_performance/_helpers/diagnostic_project.py index b84cd99849..b2b518ab98 100644 --- a/scripts/cold_compile_performance/_helpers/diagnostic_project.py +++ b/scripts/cold_compile_performance/_helpers/diagnostic_project.py @@ -8,8 +8,8 @@ def write_diagnostic_project( ) -> None: """Generate large macro-backed CTE models with independent reference and conversion errors.""" project_dir.mkdir(parents=True, exist_ok=True) - models: Path = project_dir / "models" - models.mkdir(exist_ok=True) + models: Path = project_dir / "sql" / "models" + models.mkdir(parents=True, exist_ok=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "diagnostic_orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) @@ -48,8 +48,8 @@ def write_diagnostic_project( def write_cascade_project(*, project_dir: Path, depth: int, width: int = 50) -> None: """Generate a reverse-named DAG with many independently poisoned output columns.""" project_dir.mkdir(parents=True, exist_ok=True) - models: Path = project_dir / "models" - models.mkdir(exist_ok=True) + models: Path = project_dir / "sql" / "models" + models.mkdir(parents=True, exist_ok=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "cascade_orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) @@ -85,8 +85,8 @@ def write_cascade_project(*, project_dir: Path, depth: int, width: int = 50) -> def write_function_name_project(*, project_dir: Path, model_count: int, calls: int) -> None: """Generate wide Snowflake models mixing unsupported, accepted, and unknown function calls.""" project_dir.mkdir(parents=True, exist_ok=True) - models: Path = project_dir / "models" - models.mkdir(exist_ok=True) + models: Path = project_dir / "sql" / "models" + models.mkdir(parents=True, exist_ok=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "function_name_orders"\nadapter = "snowflake"\n[rules]\nselect = []\n' ) @@ -110,8 +110,8 @@ def write_function_name_project(*, project_dir: Path, model_count: int, calls: i def write_single_model_diagnostic_project(*, project_dir: Path, diagnostics: int) -> None: """Generate one wide model whose projections each raise an unknown-column or type error.""" project_dir.mkdir(parents=True, exist_ok=True) - models: Path = project_dir / "models" - models.mkdir(exist_ok=True) + models: Path = project_dir / "sql" / "models" + models.mkdir(parents=True, exist_ok=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "dense_diagnostic_orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) @@ -138,7 +138,7 @@ def write_undescribed_project(*, project_dir: Path, model_count: int, width: int """Generate models, seeds, and one large source file whose resources all lack descriptions.""" project_dir.mkdir(parents=True, exist_ok=True) for folder in ("models", "sources", "seeds"): - (project_dir / folder).mkdir(exist_ok=True) + (project_dir / "sql" / folder).mkdir(parents=True, exist_ok=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "undescribed_orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) @@ -151,15 +151,15 @@ def write_undescribed_project(*, project_dir: Path, model_count: int, width: int ) sources.append(" columns:") sources.extend(f" - name: {column}\n type: INTEGER" for column in columns) - (project_dir / "models" / f"order_totals_{index:05}.sql").write_text( + (project_dir / "sql" / "models" / f"order_totals_{index:05}.sql").write_text( "MODEL (materialized view);\n" f'SELECT {", ".join(columns)} FROM __source("orders_{index:05}")\n' ) if index % 10 == 0: seeds.append(f" - name: products_{index:05}\n columns:") seeds.extend(f" - name: {column}\n type: INTEGER" for column in columns) - (project_dir / "seeds" / f"products_{index:05}.csv").write_text( + (project_dir / "sql" / "seeds" / f"products_{index:05}.csv").write_text( ",".join(columns) + "\n" + ",".join("1" for _ in columns) + "\n" ) - (project_dir / "sources" / "orders.yml").write_text("\n".join(sources) + "\n") - (project_dir / "seeds" / "products.yml").write_text("\n".join(seeds) + "\n") + (project_dir / "sql" / "sources" / "orders.yml").write_text("\n".join(sources) + "\n") + (project_dir / "sql" / "seeds" / "products.yml").write_text("\n".join(seeds) + "\n") diff --git a/scripts/cold_compile_performance/_helpers/varied_benchmark.py b/scripts/cold_compile_performance/_helpers/varied_benchmark.py index 78c4a05c6e..d1baa6f7fd 100644 --- a/scripts/cold_compile_performance/_helpers/varied_benchmark.py +++ b/scripts/cold_compile_performance/_helpers/varied_benchmark.py @@ -38,14 +38,14 @@ def run_varied_cache_benchmark( project_dir=project_dir, label="warm", budget=test_case.expected_warm_max_seconds ) leaf: Path = next( - (project_dir / "models").rglob(f"{dense_model_name(test_case.model_count - 1)}.sql") + (project_dir / "sql" / "models").rglob(f"{dense_model_name(test_case.model_count - 1)}.sql") ) _edit_model(leaf) measurements.update(_measure_edit(project_dir=project_dir, label="leaf", test_case=test_case)) - shared: Path = next((project_dir / "models").rglob(f"{dense_model_name(0)}.sql")) + shared: Path = next((project_dir / "sql" / "models").rglob(f"{dense_model_name(0)}.sql")) _edit_model(shared) measurements.update(_measure_edit(project_dir=project_dir, label="shared", test_case=test_case)) - macro: Path = next((project_dir / "models").rglob("offset00000.py")) + macro: Path = next((project_dir / "sql" / "models").rglob("offset00000.py")) contents: str = macro.read_text(encoding="utf-8") if contents.count('return f"({expression} + 1)"') != 1: raise CompileBenchmarkFixtureError("Expected one editable macro expression") diff --git a/scripts/cold_compile_performance/_helpers/varied_project.py b/scripts/cold_compile_performance/_helpers/varied_project.py index 90be85a03a..84fef3becf 100644 --- a/scripts/cold_compile_performance/_helpers/varied_project.py +++ b/scripts/cold_compile_performance/_helpers/varied_project.py @@ -36,7 +36,7 @@ def write_varied_compile_project(*, project_dir: Path, model_count: int) -> None write_dense_compile_project( project_dir=project_dir, model_count=model_count, rule_select=DENSE_ALL_RULE_SELECT ) - for index, model in enumerate(sorted((project_dir / "models").rglob("*.sql"))): + for index, model in enumerate(sorted((project_dir / "sql" / "models").rglob("*.sql"))): contents: str = model.read_text(encoding="utf-8") replacements: dict[str, str] = _dependency_replacements( index=index, contents=contents, model_count=model_count diff --git a/scripts/compile_performance_ratio/_helpers/edit.py b/scripts/compile_performance_ratio/_helpers/edit.py index 894c2cb13a..2a7daf3f25 100644 --- a/scripts/compile_performance_ratio/_helpers/edit.py +++ b/scripts/compile_performance_ratio/_helpers/edit.py @@ -2,12 +2,13 @@ from __future__ import annotations +from itertools import chain from pathlib import Path from scripts.compile_performance_ratio.constants import ( EDIT_COMMENT, MODEL_FILE_PATTERN, - MODELS_DIRECTORY, + MODELS_DIRECTORIES, STATEMENT_START, ) from scripts.compile_performance_ratio.exceptions import BenchmarkEditError @@ -17,7 +18,9 @@ def apply_one_model_edit(*, project_dir: Path, revision: int) -> Path: """Comment the middle model's query with the revision so each revision is a new edit.""" models: list[Path] = sorted( - (project_dir / MODELS_DIRECTORY).rglob(MODEL_FILE_PATTERN), + chain.from_iterable( + (project_dir / directory).rglob(MODEL_FILE_PATTERN) for directory in MODELS_DIRECTORIES + ), key=lambda path: path.relative_to(project_dir).as_posix(), ) if not models: diff --git a/scripts/compile_performance_ratio/constants.py b/scripts/compile_performance_ratio/constants.py index 550ce619f3..33e7deb95e 100644 --- a/scripts/compile_performance_ratio/constants.py +++ b/scripts/compile_performance_ratio/constants.py @@ -26,7 +26,7 @@ ANALYSIS_CACHE_MISSES, ANALYSIS_CACHE_BYPASSES, ) -MODELS_DIRECTORY: str = "models" +MODELS_DIRECTORIES: tuple[str, ...] = ("sql/models", "models") MODEL_FILE_PATTERN: str = "*.sql" EDIT_COMMENT: str = "-- Benchmark edit {revision}.\n" STATEMENT_START: re.Pattern[str] = re.compile(r"^(WITH|SELECT)\b", re.MULTILINE) diff --git a/scripts/compiler_differential/_helpers/analysis_corpus/analysis_session.py b/scripts/compiler_differential/_helpers/analysis_corpus/analysis_session.py index a6ee164709..286604492d 100644 --- a/scripts/compiler_differential/_helpers/analysis_corpus/analysis_session.py +++ b/scripts/compiler_differential/_helpers/analysis_corpus/analysis_session.py @@ -12,13 +12,13 @@ _ORDERS: str = '__ref("stg_orders")' _MART_HEADER: str = 'MODEL (\n description "Order totals per customer",\n);\n\n' _STAGING_HEADER: str = 'MODEL (\n description "Staged orders",\n);\n\n' -_LAYERED_PATH: str = "models/marts/order_layers.sql" +_LAYERED_PATH: str = "sql/models/marts/order_layers.sql" _LAYERED_MODEL: str = ( 'MODEL (\n description "Orders layered over the staged star",\n);\n\n' f"SELECT s.*, s.amount * 2 AS doubled_amount\nFROM {_ORDERS} s\n" ) -_PIVOT_PATH: str = "models/marts/status_amounts.sql" +_PIVOT_PATH: str = "sql/models/marts/status_amounts.sql" def _pivot_model(*, pivot_column: str, body: str) -> str: diff --git a/scripts/compiler_differential/_helpers/analysis_corpus/assembly.py b/scripts/compiler_differential/_helpers/analysis_corpus/assembly.py index c9b99b759a..b6e7040148 100644 --- a/scripts/compiler_differential/_helpers/analysis_corpus/assembly.py +++ b/scripts/compiler_differential/_helpers/analysis_corpus/assembly.py @@ -8,7 +8,7 @@ ) from scripts.compiler_differential.models import FailureCase -_TRINO_ADAPTER_PATH: str = "adapters/warehouse/duckdb_trino.py" +_TRINO_ADAPTER_PATH: str = "python/adapters/warehouse/duckdb_trino.py" _TRINO_ADAPTER: str = ( "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n\n" "class DuckDbTrinoAdapter(DuckDbAdapter):\n" diff --git a/scripts/compiler_differential/_helpers/analysis_corpus/contracts.py b/scripts/compiler_differential/_helpers/analysis_corpus/contracts.py index 58e7d3d84a..06ff9fe04c 100644 --- a/scripts/compiler_differential/_helpers/analysis_corpus/contracts.py +++ b/scripts/compiler_differential/_helpers/analysis_corpus/contracts.py @@ -18,7 +18,7 @@ " columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n" " amount (type DOUBLE),\n status (type VARCHAR),\n ),\n" ) -_NAMED_SCHEMA_PATH: str = "models/staging/_sqlbuild/_schemas/staged_order.sql" +_NAMED_SCHEMA_PATH: str = "sql/models/staging/_sqlbuild/_schemas/staged_order.sql" _NAMED_SCHEMA: str = ( 'SCHEMA (\n name staged_order,\n description "Canonical staged order shape",\n' " columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n" @@ -76,7 +76,7 @@ def contracts_failure_cases() -> tuple[FailureCase, ...]: "SELECT customer_id, CAST(SUM(amount) AS VARCHAR) AS total_amount\n" 'FROM __ref("stg_orders")\nGROUP BY customer_id\n' ), - "models/marts/typed_totals.sql": ( + "sql/models/marts/typed_totals.sql": ( 'MODEL (\n description "Typed totals",\n' " columns (total_amount (type BIGINT)),\n);\n\n" "SELECT CAST(1.5 AS DOUBLE) AS total_amount\n" diff --git a/scripts/compiler_differential/_helpers/analysis_corpus/failure_cases.py b/scripts/compiler_differential/_helpers/analysis_corpus/failure_cases.py index e2e61c1072..d7174dd272 100644 --- a/scripts/compiler_differential/_helpers/analysis_corpus/failure_cases.py +++ b/scripts/compiler_differential/_helpers/analysis_corpus/failure_cases.py @@ -45,7 +45,7 @@ 'name = "failure_corpus"\nadapter = "postgres"\n\n' '[connection]\nhost = "localhost"\ndatabase = "failure"\nschema = "public"\n' ) -_FUNCTION_PATH: str = "functions/sql/scaled_amount.sql" +_FUNCTION_PATH: str = "sql/functions/sql/scaled_amount.sql" _SCALED_AMOUNT: str = ( "FUNCTION (\n" ' description "Scale an amount by an integer factor",\n' @@ -53,9 +53,9 @@ " returns DOUBLE,\n);\n\n" "p_amount * p_factor\n" ) -_HOOK_PATH: str = "hooks/sql/record_refresh.sql" +_HOOK_PATH: str = "sql/hooks/sql/record_refresh.sql" _EXPRESSION_AUDIT: str = 'AUDIT ();\n\nSELECT *\nFROM __ref("@model")\nWHERE NOT (@expression)\n' -_EXPRESSION_AUDIT_PATH: str = "models/marts/_sqlbuild/_audits/generic/expression_is_true.sql" +_EXPRESSION_AUDIT_PATH: str = "sql/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql" _TEST_PATH: str = "tests/unit/test_stg_orders.sql" @@ -350,7 +350,7 @@ def _contract_cases() -> tuple[FailureCase, ...]: "order_status" ), files={ - "models/staging/_enums/order_status.sql": ( + "sql/models/staging/_enums/order_status.sql": ( 'ENUM (name order_status, members (PLACED "placed", SHIPPED "shipped"));\n' ), **staging_files( @@ -426,14 +426,14 @@ def _target_cases() -> tuple[FailureCase, ...]: FAILURE_CONFIG_PATH: FAILURE_BASE_CONFIG + '\n[targets.dev]\nschema = "dev"\nloader_schema = "raw"\n' + '\n[targets.prod]\nschema = "prod"\nloader_schema = "raw"\n', - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n\n" "@loader\n" "def loaded_orders(ctx):\n" ' """Load raw orders."""\n' ' return [{"order_id": 1}]\n' ), - "sources/loaded.yml": ( + "sql/sources/loaded.yml": ( "sources:\n - name: loaded_orders\n description: Loaded orders.\n" " managed: true\n write_strategy: table\n" " columns:\n - name: order_id\n type: INTEGER\n" @@ -466,7 +466,7 @@ def _target_cases() -> tuple[FailureCase, ...]: 'adapter = "duckdb"\n', 'adapter = "duckdb"\ndefault_target = "dev"\n' ) + '\n[defaults]\nschema = "mart"\n\n[targets.dev]\nschema = "preserve"\n', - "python/tasks/announce.py": ( + "python/nodes/tasks/announce/asset.py": ( "from sqlbuild.assets import asset\n\n\n" "@asset\n" "def announce_orders(ctx):\n" @@ -564,7 +564,7 @@ def _ordering_cases() -> tuple[FailureCase, ...]: **staging_files( FAILURE_BASE_STAGING.replace("amount, status", "amount, discount, status") ), - "models/marts/order_counts.sql": ( + "sql/models/marts/order_counts.sql": ( 'MODEL (\n description "Order counts per customer",\n);\n\n' "SELECT customer_id, COUNT(missing_column) AS order_count\n" f"FROM {_ORDERS}\nGROUP BY customer_id\n" diff --git a/scripts/compiler_differential/_helpers/analysis_corpus/lineage.py b/scripts/compiler_differential/_helpers/analysis_corpus/lineage.py index 1508bda6de..149d322917 100644 --- a/scripts/compiler_differential/_helpers/analysis_corpus/lineage.py +++ b/scripts/compiler_differential/_helpers/analysis_corpus/lineage.py @@ -9,7 +9,7 @@ _OPTED_OUT_HEADER: str = ( 'MODEL (\n description "Order totals per customer",\n sql_analysis false,\n);\n\n' ) -_BROKEN_PATH: str = "models/marts/broken_orders.sql" +_BROKEN_PATH: str = "sql/models/marts/broken_orders.sql" _BROKEN_MODEL: str = ( 'MODEL (\n description "Orders with an unknown qualifier",\n);\n\n' f"SELECT x.order_id\nFROM {_ORDERS} o\n" diff --git a/scripts/compiler_differential/_helpers/analysis_corpus/semantic_checks.py b/scripts/compiler_differential/_helpers/analysis_corpus/semantic_checks.py index 753027e0f3..0c2b6c517b 100644 --- a/scripts/compiler_differential/_helpers/analysis_corpus/semantic_checks.py +++ b/scripts/compiler_differential/_helpers/analysis_corpus/semantic_checks.py @@ -19,14 +19,14 @@ "amount, status", "amount, status, CAST('2026-01-01' AS TIMESTAMP) AS ordered_at" ) -_INTERMEDIATE_PATH: str = "models/intermediate/int_orders.sql" +_INTERMEDIATE_PATH: str = "sql/models/intermediate/int_orders.sql" _INTERMEDIATE: str = ( 'MODEL (\n description "Doubled order amounts",\n);\n\n' "SELECT customer_id, amount * 2 AS doubled_amount\n" 'FROM __ref("stg_orders")\n' ) -_FUNCTION_PATH: str = "functions/sql/scaled_amount.sql" +_FUNCTION_PATH: str = "sql/functions/sql/scaled_amount.sql" _SCALED_AMOUNT: str = ( "FUNCTION (\n" ' description "Scale an amount by an integer factor",\n' @@ -186,7 +186,7 @@ def _metadata_cases() -> tuple[FailureCase, ...]: expected_location=(21, 20), files={ FAILURE_SOURCES_PATH: FAILURE_BASE_SOURCES + _LOADED_SOURCE, - "python/loaders/raw_events.py": _LOADER, + "python/nodes/loaders/raw_events/loader.py": _LOADER, }, ), ) diff --git a/scripts/compiler_differential/_helpers/analysis_corpus/sql_test_glue.py b/scripts/compiler_differential/_helpers/analysis_corpus/sql_test_glue.py index cc00d6d889..5dc7876a7f 100644 --- a/scripts/compiler_differential/_helpers/analysis_corpus/sql_test_glue.py +++ b/scripts/compiler_differential/_helpers/analysis_corpus/sql_test_glue.py @@ -4,7 +4,7 @@ from scripts.compiler_differential.models import FailureCase _TEST_PATH: str = "tests/unit/test_customer_totals.sql" -_WINDOWED_PATH: str = "models/marts/windowed_orders.sql" +_WINDOWED_PATH: str = "sql/models/marts/windowed_orders.sql" _WINDOWED_MODEL: str = ( "MODEL (\n description 'Orders in the cursor window',\n materialized incremental,\n" " incremental_strategy delete_insert,\n cursor order_id,\n cursor_type integer,\n" diff --git a/scripts/compiler_differential/_helpers/corpus/attachment_failure_cases.py b/scripts/compiler_differential/_helpers/corpus/attachment_failure_cases.py index 4d1e9d1be9..d6ab33c273 100644 --- a/scripts/compiler_differential/_helpers/corpus/attachment_failure_cases.py +++ b/scripts/compiler_differential/_helpers/corpus/attachment_failure_cases.py @@ -10,13 +10,13 @@ from scripts.compiler_differential.models import FailureCase _STAGING_HEADER: str = '"Staged orders",' -_FLOOR_AUDIT_PATH: str = "models/staging/_sqlbuild/_audits/generic/floor.sql" +_FLOOR_AUDIT_PATH: str = "sql/models/staging/_sqlbuild/_audits/generic/floor.sql" _FLOOR_AUDIT: str = 'AUDIT ();\n\nSELECT *\nFROM __ref("@model")\nWHERE amount < @minimum\n' _FRESH_AUDIT: str = ( 'AUDIT ();\n\nSELECT *\nFROM __ref("@model")\nWHERE ordered_at >= __cursor_start()\n' ) -_ORDER_LABEL_PATH: str = "functions/sql/order_label.sql" -_ORDER_FLAG_PATH: str = "functions/python/order_flag.py" +_ORDER_LABEL_PATH: str = "sql/functions/sql/order_label.sql" +_ORDER_FLAG_PATH: str = "sql/functions/python/order_flag.py" _SCENARIO_PATH: str = "tests/scenarios/orders.sql" _SCENARIO_HEADER: str = 'SCENARIO (\n description "Order flow"\n);\n\n' _SOURCE_FIXTURE: str = ( @@ -26,7 +26,7 @@ ) _EXPECTED_STAGING: str = "__expected__stg_orders AS (\n SELECT 1 AS order_id\n)" _TEST_PATH: str = "tests/unit/test_stg_orders.sql" -_SCHEMA_PATH: str = "schemas/orders.sql" +_SCHEMA_PATH: str = "sql/schemas/orders.sql" def _scenario(*ctes: str, tail: str = "\nSELECT 1\n") -> str: @@ -70,7 +70,7 @@ def attachment_failure_cases() -> tuple[FailureCase, ...]: name="model-schema-extends-unknown", expected_code="P001", expected_message=( - "Schema 'order_row' in schemas/orders.sql extends unknown schema 'base_row'" + "Schema 'order_row' in sql/schemas/orders.sql extends unknown schema 'base_row'" ), files={_SCHEMA_PATH: _schema(name="order_row", extends="base_row", column="id")}, ), @@ -87,8 +87,9 @@ def attachment_failure_cases() -> tuple[FailureCase, ...]: name="model-schema-redeclared-column", expected_code="P001", expected_message=( - "Schema 'order_row' in schemas/orders.sql redeclares inherited column 'ID' from " - "schemas/orders.sql:1; column overrides are not supported" + "Schema 'order_row' in sql/schemas/orders.sql redeclares inherited column " + "'ID' from " + "sql/schemas/orders.sql:1; column overrides are not supported" ), files={ _SCHEMA_PATH: _schema(name="base_row", extends=None, column="id") @@ -118,7 +119,7 @@ def attachment_failure_cases() -> tuple[FailureCase, ...]: expected_code="P001", expected_message="Audit 'fresh' uses cursor intrinsics", files={ - "models/staging/_sqlbuild/_audits/generic/fresh.sql": _FRESH_AUDIT, + "sql/models/staging/_sqlbuild/_audits/generic/fresh.sql": _FRESH_AUDIT, **_staging_audits("fresh"), }, ), @@ -145,7 +146,7 @@ def attachment_failure_cases() -> tuple[FailureCase, ...]: failure_case( name="sql-function-missing-returns", expected_code="P001", - expected_message="functions/sql/order_label.sql must declare returns", + expected_message="sql/functions/sql/order_label.sql must declare returns", files=_order_label(' description "Order label",\n arguments (p_status VARCHAR),\n'), ), failure_case( @@ -172,7 +173,7 @@ def attachment_failure_cases() -> tuple[FailureCase, ...]: failure_case( name="sql-function-arguments-not-a-map", expected_code="P001", - expected_message="functions/sql/order_label.sql arguments must be a map", + expected_message="sql/functions/sql/order_label.sql arguments must be a map", files=_order_label( ' description "Order label",\n arguments [p_status],\n returns VARCHAR\n' ), @@ -198,13 +199,13 @@ def attachment_failure_cases() -> tuple[FailureCase, ...]: failure_case( name="python-function-missing-runtime-version", expected_code="P001", - expected_message="functions/python/order_flag.py must declare runtime_version", + expected_message="sql/functions/python/order_flag.py must declare runtime_version", files=_order_flag(""), ), failure_case( name="python-function-packages-not-a-list", expected_code="P001", - expected_message="functions/python/order_flag.py packages must be a list", + expected_message="sql/functions/python/order_flag.py packages must be a list", files=_order_flag(' runtime_version="3.11",\n packages="numpy",\n'), ), failure_case( @@ -346,7 +347,7 @@ def attachment_failure_cases() -> tuple[FailureCase, ...]: "$ or non-ASCII characters are not supported" ), files={ - "macros/python/amounts.py": "def doubled(value):\n return f'{value} * 2'\n", + "sql/macros/python/amounts.py": "def doubled(value):\n return f'{value} * 2'\n", _TEST_PATH: 'TEST (mode macro, name "doubled");\n\nWITH\n' "\"__macro_actual__\" AS (\n SELECT @py.doubled('1') AS amount\n),\n" "__macro_expected__ AS (\n SELECT 2 AS amount\n)\nSELECT 1\n", diff --git a/scripts/compiler_differential/_helpers/corpus/discovery_failure_cases.py b/scripts/compiler_differential/_helpers/corpus/discovery_failure_cases.py index 74c67698f4..5f0aa4164e 100644 --- a/scripts/compiler_differential/_helpers/corpus/discovery_failure_cases.py +++ b/scripts/compiler_differential/_helpers/corpus/discovery_failure_cases.py @@ -113,13 +113,13 @@ def _sql_file_cases() -> tuple[FailureCase, ...]: failure_case( name="model-path-not-utf8", expected_code="D016", - files={os.fsdecode(b"models/staging/caf\xe9.sql"): FAILURE_BASE_STAGING}, + files={os.fsdecode(b"sql/models/staging/caf\xe9.sql"): FAILURE_BASE_STAGING}, expected_message="is not valid UTF-8; rename it so SQLBuild can read it", ), failure_case( name="model-reserved-name", expected_code="D016", - files={"models/marts/_chain_.sql": FAILURE_BASE_MART}, + files={"sql/models/marts/_chain_.sql": FAILURE_BASE_MART}, ), failure_case( name="test-case-missing-parameter", @@ -140,7 +140,7 @@ def _sql_file_cases() -> tuple[FailureCase, ...]: name="generic-audit-header", expected_code="D004", files={ - "models/marts/_sqlbuild/_audits/generic/at_least.sql": ( + "sql/models/marts/_sqlbuild/_audits/generic/at_least.sql": ( "AUDIT (unknown_option 1);\n\nSELECT * FROM @relation WHERE @column < 0\n" ) }, @@ -149,7 +149,7 @@ def _sql_file_cases() -> tuple[FailureCase, ...]: name="list-constant-mixed-types", expected_code="D013", files={ - "models/staging/_sqlbuild/_constants/statuses.sql": ( + "sql/models/staging/_sqlbuild/_constants/statuses.sql": ( 'CONSTANT (name kept_statuses, value ["placed", 3]);\n' ) }, @@ -158,7 +158,7 @@ def _sql_file_cases() -> tuple[FailureCase, ...]: name="constant-header-nested-too-deep", expected_code="D013", files={ - "models/staging/_sqlbuild/_constants/statuses.sql": ( + "sql/models/staging/_sqlbuild/_constants/statuses.sql": ( f"CONSTANT (name kept_statuses, value {_DEEP_HEADER_CALLS});\n" ) }, @@ -168,7 +168,7 @@ def _sql_file_cases() -> tuple[FailureCase, ...]: name="enum-duplicate-member", expected_code="D013", files={ - "models/staging/_sqlbuild/_enums/order_status.sql": ( + "sql/models/staging/_sqlbuild/_enums/order_status.sql": ( "ENUM (\n name order_status,\n members [PLACED, PLACED],\n);\n" ) }, @@ -177,7 +177,7 @@ def _sql_file_cases() -> tuple[FailureCase, ...]: name="sql-hook-unknown-key", expected_code="D014", files={ - "hooks/sql/record_refresh.sql": ( + "sql/hooks/sql/record_refresh.sql": ( 'HOOK (\n description "Record a refresh",\n phase post,\n);\n\nSELECT 1\n' ) }, @@ -186,7 +186,7 @@ def _sql_file_cases() -> tuple[FailureCase, ...]: name="sql-function-header", expected_code="D002", files={ - "functions/sql/is_placed.sql": ( + "sql/functions/sql/is_placed.sql": ( 'FUNCTION (\n description "Whether placed",\n returns,\n);\n\n' "order_status = 'placed'\n" ) @@ -210,18 +210,21 @@ def _layout_cases() -> tuple[FailureCase, ...]: return tuple( failure_case(name=name, expected_code="D013", files={path: contents}) for name, path, contents in ( - ("scoped-root-at-project-root", "_enums/order_status.sql", ""), ( "declaration-group-below-root", - "models/_sqlbuild/macros/python/money.py", + "sql/models/_sqlbuild/macros/python/money.py", _MACRO_MODULE, ), - ("declaration-root-nested", "models/marts/_enums/_constants/limits.sql", ""), - ("declaration-group-unsupported-entry", "models/marts/_sqlbuild/notes.txt", ""), - ("named-role-nested-declaration", "schemas/enums/order_status.sql", ""), - ("audit-role-unsupported-entry", "audits/at_least.sql", ""), - ("local-singular-audit", "models/marts/_sqlbuild/_audits/singular/at_least.sql", ""), - ("hook-role-unsupported-entry", "models/marts/_sqlbuild/hooks/notes.sql", ""), + ("declaration-root-nested", "sql/models/marts/_enums/_constants/limits.sql", ""), + ("declaration-group-unsupported-entry", "sql/models/marts/_sqlbuild/notes.txt", ""), + ("named-role-nested-declaration", "sql/schemas/enums/order_status.sql", ""), + ("audit-role-unsupported-entry", "sql/audits/at_least.sql", ""), + ( + "local-singular-audit", + "sql/models/marts/_sqlbuild/_audits/singular/at_least.sql", + "", + ), + ("hook-role-unsupported-entry", "sql/models/marts/_sqlbuild/hooks/notes.sql", ""), ) ) @@ -232,7 +235,7 @@ def _yaml_file_cases() -> tuple[FailureCase, ...]: name="schema-yml-model-metadata", expected_code="D005", files={ - "models/marts/schema.yml": ( + "sql/models/marts/schema.yml": ( "models:\n - name: customer_totals\n description: Totals.\n" ) }, @@ -241,14 +244,14 @@ def _yaml_file_cases() -> tuple[FailureCase, ...]: name="seed-yaml-extension", expected_code="D005", files={ - "seeds/order_channels.yaml": _SEED_DECLARATION, - "seeds/order_channels.csv": "id,label\n1,web\n", + "sql/seeds/order_channels.yaml": _SEED_DECLARATION, + "sql/seeds/order_channels.csv": "id,label\n1,web\n", }, ), failure_case( name="schema-yml-invalid-yaml", expected_code="D005", - files={"models/marts/schema.yml": "models: [\n"}, + files={"sql/models/marts/schema.yml": "models: [\n"}, expected_message="contains invalid YAML at line 2, column 1", ), failure_case( @@ -287,7 +290,7 @@ def _yaml_file_cases() -> tuple[FailureCase, ...]: expected_code="D006", expected_message="declares dlt_sources, a dlt integration", files={ - "sources/loaded.yml": ( + "sql/sources/loaded.yml": ( "dlt_sources:\n - type: sql_database\n resources:\n" " - name: loaded_orders\n table: orders\n" ) @@ -296,14 +299,14 @@ def _yaml_file_cases() -> tuple[FailureCase, ...]: failure_case( name="seed-declaration-without-csv", expected_code="D008", - files={"seeds/order_channels.yml": _SEED_DECLARATION}, + files={"sql/seeds/order_channels.yml": _SEED_DECLARATION}, ), failure_case( name="seed-header-mismatch", expected_code="D008", files={ - "seeds/order_channels.yml": _SEED_DECLARATION, - "seeds/order_channels.csv": "id,name\n1,web\n", + "sql/seeds/order_channels.yml": _SEED_DECLARATION, + "sql/seeds/order_channels.csv": "id,name\n1,web\n", }, ), ) @@ -314,7 +317,7 @@ def _conflict_cases() -> tuple[FailureCase, ...]: failure_case( name="duplicate-source", expected_code="D007", - files={"sources/more.yml": FAILURE_BASE_FILES[FAILURE_SOURCES_PATH]}, + files={"sql/sources/more.yml": FAILURE_BASE_FILES[FAILURE_SOURCES_PATH]}, ), failure_case( name="duplicate-scenario", @@ -334,8 +337,10 @@ def _conflict_cases() -> tuple[FailureCase, ...]: name="resource-name-collision", expected_code="D007", files={ - "seeds/stg_orders.yml": _SEED_DECLARATION.replace("order_channels", "stg_orders"), - "seeds/stg_orders.csv": "id,label\n1,web\n", + "sql/seeds/stg_orders.yml": _SEED_DECLARATION.replace( + "order_channels", "stg_orders" + ), + "sql/seeds/stg_orders.csv": "id,label\n1,web\n", }, ), failure_case( @@ -352,15 +357,15 @@ def _conflict_cases() -> tuple[FailureCase, ...]: name="duplicate-python-node", expected_code="D007", files={ - "python/tasks/first.py": _TASK_MODULE, - "python/tasks/second.py": _TASK_MODULE, + "python/nodes/tasks/first/asset.py": _TASK_MODULE, + "python/nodes/tasks/second/asset.py": _TASK_MODULE, }, ), failure_case( name="check-depends-on-check", expected_code="D007", files={ - "python/checks/orders.py": ( + "python/nodes/checks/orders/checks.py": ( "from sqlbuild.checks import check\nfrom sqlbuild.refs import model\n\n\n" '@check(depends_on=model("stg_orders"))\ndef orders_present(ctx):\n' ' """Orders present."""\n return ctx.pass_()\n\n\n' @@ -377,21 +382,24 @@ def _python_cases() -> tuple[FailureCase, ...]: failure_case( name="python-node-import-error", expected_code="D011", - files={"python/tasks/exports.py": "import missing_orders_client\n" + _TASK_MODULE}, + files={ + "python/nodes/tasks/exports/asset.py": "import missing_orders_client\n" + + _TASK_MODULE + }, ), failure_case( name="duplicate-hook", expected_code="D011", files={ - "hooks/python/first.py": _HOOK_MODULE, - "hooks/python/second.py": _HOOK_MODULE, + "sql/hooks/python/first.py": _HOOK_MODULE, + "sql/hooks/python/second.py": _HOOK_MODULE, }, ), failure_case( name="provider-invalid-settings", expected_code="D012", files={ - "providers/export_settings.py": ( + "python/providers/export_settings.py": ( "from sqlbuild.providers import Provider\n\n\n" "class ExportSettings(Provider):\n" ' """Export settings."""\n\n' @@ -403,7 +411,7 @@ def _python_cases() -> tuple[FailureCase, ...]: name="duplicate-provider", expected_code="D012", files={ - f"providers/{module}.py": ( + f"python/providers/{module}.py": ( "from sqlbuild.providers import Provider\n\n\n" "class ExportSettings(Provider):\n" ' """Export settings."""\n\n' @@ -423,17 +431,12 @@ def _python_cases() -> tuple[FailureCase, ...]: }, expected_message="files cannot sit directly in orchestration/", ), - failure_case( - name="legacy-event-exporters-directory", - expected_code="D015", - files={"event_exporters/publish.py": "VALUE = 1\n"}, - ), failure_case( name="lifecycle-sink-default-parameter", expected_code="D015", files={ - "sinks/lifecycle.py": ( - "from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink\n\n\n" + "python/event_sinks/lifecycle.py": ( + "from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink\n\n\n" "@lifecycle_event_sink()\n" "def ignore_events(event: LifecycleEvent, limit=3) -> None:\n" " return None\n" @@ -444,8 +447,8 @@ def _python_cases() -> tuple[FailureCase, ...]: name="lifecycle-sink-unknown-provider", expected_code="D015", files={ - "sinks/lifecycle.py": ( - "from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink\n\n\n" + "python/event_sinks/lifecycle.py": ( + "from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink\n\n\n" "@lifecycle_event_sink()\n" "def publish_events(event: LifecycleEvent, destination_client) -> None:\n" " return None\n" @@ -456,9 +459,11 @@ def _python_cases() -> tuple[FailureCase, ...]: name="command-output-sink-unknown-provider", expected_code="D015", files={ - "sinks/output.py": ( - "from sqlbuild.sinks import CommandOutputRecord, command_output_sink\n\n\n" - '@command_output_sink(streams={"stdout"})\n' + "python/event_sinks/output.py": ( + "from sqlbuild.event_sinks import CommandOutputRecord, " + "command_output_event_sink\n" + "\n\n" + '@command_output_event_sink(streams={"stdout"})\n' "def publish_output(record: CommandOutputRecord, destination_client) -> None:\n" " return None\n" ) @@ -468,7 +473,7 @@ def _python_cases() -> tuple[FailureCase, ...]: name="materialization-import-error", expected_code="D011", files={ - "materializations/copy_table.py": "import missing_warehouse_client\n", + "python/materializations/copy_table.py": "import missing_warehouse_client\n", FAILURE_MART_PATH: FAILURE_BASE_MART.replace( '"Order totals per customer",', '"Order totals per customer",\n materialized copy_table,', @@ -478,6 +483,15 @@ def _python_cases() -> tuple[FailureCase, ...]: failure_case( name="python-outside-extension-root", expected_code="D016", - files={"helpers/formatting.py": "VALUE = 1\n"}, + files={"sql/models/formatting.py": "VALUE = 1\n"}, + ), + *( + failure_case(name=name, expected_code="D018", files={path: contents}) + for name, path, contents in ( + ("project-layout-unknown-top-level-folder", "event_exporters/publish.py", ""), + ("project-layout-scoped-root-at-project-root", "_enums/order_status.sql", ""), + ("project-layout-unknown-sql-folder", "sql/notes/readme.md", ""), + ("project-layout-unknown-python-module", "python/helpers.py", "VALUE = 1\n"), + ) ), ) diff --git a/scripts/compiler_differential/_helpers/corpus/failure_cases.py b/scripts/compiler_differential/_helpers/corpus/failure_cases.py index 3789946a37..55fdbb4ddf 100644 --- a/scripts/compiler_differential/_helpers/corpus/failure_cases.py +++ b/scripts/compiler_differential/_helpers/corpus/failure_cases.py @@ -47,7 +47,7 @@ _RULES_CONFIG: str = '\n[rules]\nselect = ["{codes}"]\n' -_ENGINE_ERROR_MACROS: str = "macros/python/cents.py" +_ENGINE_ERROR_MACROS: str = "sql/macros/python/cents.py" _ENGINE_ERROR_CENTS: str = ( 'def cents(expression: str) -> str:\n """Convert to cents."""\n' ' return f"({expression} * 100)"\n' @@ -131,13 +131,17 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="audit-parse", expected_code="D004", files={ - "models/marts/_sqlbuild/audits/singular/broken.sql": "AUDIT (name);\n\nSELECT 1\n" + "sql/models/marts/_sqlbuild/audits/singular/broken.sql": ( + "AUDIT (name);\n\nSELECT 1\n" + ) }, ), failure_case( name="schema-unterminated-declaration", expected_code="D013", - files={"models/staging/_sqlbuild/_schemas/orders.sql": "SCHEMA (\n name orders,\n"}, + files={ + "sql/models/staging/_sqlbuild/_schemas/orders.sql": "SCHEMA (\n name orders,\n" + }, ), failure_case( name="source-parse", @@ -147,12 +151,12 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: failure_case( name="duplicate-model", expected_code="D007", - files={"models/marts/stg_orders.sql": FAILURE_BASE_STAGING}, + files={"sql/models/marts/stg_orders.sql": FAILURE_BASE_STAGING}, ), failure_case( name="seed-without-header", expected_code="D008", - files={"seeds/lookups.csv": ""}, + files={"sql/seeds/lookups.csv": ""}, ), failure_case( name="scenario-parse", @@ -163,7 +167,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="python-node-missing-description", expected_code="P010", files={ - "python/tasks/exports.py": ( + "python/nodes/tasks/exports/asset.py": ( "from sqlbuild.assets import AssetContext, asset\n\n\n" "@asset\ndef export_orders(ctx: AssetContext):\n return None\n" ) @@ -173,7 +177,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="python-node-description-too-long", expected_code="P027", files={ - "python/tasks/exports.py": ( + "python/nodes/tasks/exports/asset.py": ( "from sqlbuild.assets import AssetContext, asset\n\n\n" "@asset\ndef export_orders(ctx: AssetContext):\n" ' """' @@ -185,24 +189,26 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: failure_case( name="enum-parse", expected_code="D013", - files={"enums/order_status.sql": "ENUM (\n name order_status,\n members [,\n);\n"}, + files={ + "sql/enums/order_status.sql": "ENUM (\n name order_status,\n members [,\n);\n" + }, ), failure_case( name="hook-without-header", expected_code="D014", - files={"hooks/sql/record_refresh.sql": "SELECT 1\n"}, + files={"sql/hooks/sql/record_refresh.sql": "SELECT 1\n"}, ), failure_case( name="invalid-resource-name", expected_code="D016", - files={"models/marts/order-totals.sql": FAILURE_BASE_MART}, + files={"sql/models/marts/order-totals.sql": FAILURE_BASE_MART}, ), failure_case( name="built-in-audit-shadow", expected_code="S010", expected_warning_code="P003", files={ - "models/staging/_sqlbuild/_audits/generic/not_null.sql": ( + "sql/models/staging/_sqlbuild/_audits/generic/not_null.sql": ( 'AUDIT (name "not_null");\n\nSELECT 1 WHERE FALSE\n' ) }, @@ -211,7 +217,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="singular-audit-one-resource", expected_code="P004", files={ - "models/marts/_sqlbuild/audits/singular/positive_totals.sql": ( + "sql/models/marts/_sqlbuild/audits/singular/positive_totals.sql": ( 'AUDIT (name "positive_totals");\n\n' 'SELECT customer_id FROM __ref("customer_totals") WHERE total_amount < 0\n' ) @@ -221,7 +227,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="macro-generated-reference", expected_code="P006", files={ - "models/marts/_sqlbuild/_macros/python/orders.py": ( + "sql/models/marts/_sqlbuild/_macros/python/orders.py": ( "def staged_orders() -> str:\n" ' """Return the staged orders relation."""\n' " return '__ref(\"stg_orders\")'\n" @@ -267,7 +273,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="failing-macro", expected_code="P001", files={ - "models/staging/_sqlbuild/_macros/python/cents.py": ( + "sql/models/staging/_sqlbuild/_macros/python/cents.py": ( "def cents(expression: str) -> str:\n" ' """Refuse every input."""\n' ' raise ValueError(f"cannot convert {expression}")\n' @@ -283,7 +289,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="unknown-enum-member", expected_code="P001", files={ - "models/staging/_sqlbuild/_enums/order_status.sql": ( + "sql/models/staging/_sqlbuild/_enums/order_status.sql": ( "ENUM (\n name order_status,\n members [PLACED, SHIPPED],\n);\n" ), **staging_files( @@ -300,7 +306,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="invalid-decimal-constant", expected_code="D013", files={ - "models/staging/_sqlbuild/_constants/limits.sql": ( + "sql/models/staging/_sqlbuild/_constants/limits.sql": ( 'CONSTANT (name minimum_amount, type decimal, value "ten");\n' ), **staging_files(FAILURE_BASE_STAGING + 'WHERE amount > @const("minimum_amount")\n'), @@ -310,7 +316,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="duplicate-declaration", expected_code="P001", files={ - "models/staging/_sqlbuild/_constants/limits.sql": ( + "sql/models/staging/_sqlbuild/_constants/limits.sql": ( "CONSTANT (name minimum_amount, value 1);\n" "CONSTANT (name minimum_amount, value 2);\n" ), @@ -321,7 +327,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="inaccessible-declaration", expected_code="P001", files={ - "models/marts/_sqlbuild/_constants/limits.sql": ( + "sql/models/marts/_sqlbuild/_constants/limits.sql": ( "CONSTANT (name minimum_amount, value 1);\n" ), **staging_files(FAILURE_BASE_STAGING + 'WHERE amount > @const("minimum_amount")\n'), @@ -331,7 +337,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="over-broad-global", expected_code="S024", files={ - "constants/limits.sql": "CONSTANT (name minimum_amount, value 1);\n", + "sql/constants/limits.sql": "CONSTANT (name minimum_amount, value 1);\n", **staging_files(FAILURE_BASE_STAGING + 'WHERE amount > @const("minimum_amount")\n'), }, ), @@ -339,7 +345,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="unused-declaration", expected_code="S010", files={ - "models/staging/_sqlbuild/_constants/limits.sql": ( + "sql/models/staging/_sqlbuild/_constants/limits.sql": ( "CONSTANT (name spare, value 1);\n" ) }, @@ -348,14 +354,14 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="macro-import-cycle", expected_code="P001", files={ - "macros/python/first.py": ( - "from macros.python.second import second_value\n\n\n" + "sql/macros/python/first.py": ( + "from sql.macros.python.second import second_value\n\n\n" "def first_value() -> str:\n" ' """First value."""\n' " return second_value()\n" ), - "macros/python/second.py": ( - "from macros.python.first import first_value\n\n\n" + "sql/macros/python/second.py": ( + "from sql.macros.python.first import first_value\n\n\n" "def second_value() -> str:\n" ' """Second value."""\n' " return first_value()\n" @@ -438,7 +444,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: FAILURE_CONFIG_PATH: FAILURE_BASE_CONFIG + '\n[vars]\nfloor = "2"\n' + _RULES_CONFIG.format(codes="SQLCLEAN005"), - "models/marts/_macros/python/cents.py": _ENGINE_ERROR_CENTS, + "sql/models/marts/_macros/python/cents.py": _ENGINE_ERROR_CENTS, **mart_body_files( 'WITH totals AS (SELECT customer_id, @py.cents("amount") AS cents, ' '@@floor AS floor_cents FROM __ref("stg_orders")), spare AS (SELECT 1 AS one)\n' @@ -487,7 +493,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: FAILURE_MART_PATH: FAILURE_BASE_MART.replace( ' description "Order totals per customer",\n', "" ), - "models/marts/order_counts.sql": ( + "sql/models/marts/order_counts.sql": ( "MODEL ();\n\nSELECT customer_id, COUNT(*) AS order_count\n" 'FROM __ref("stg_orders")\nGROUP BY customer_id\n' ), @@ -590,7 +596,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: "__ref(stg_orders) is not a valid __ref() call, returned by macro staged_orders()" ), files={ - "models/marts/_sqlbuild/_macros/python/orders.py": ( + "sql/models/marts/_sqlbuild/_macros/python/orders.py": ( "def staged_orders() -> str:\n" ' """Return the staged orders relation."""\n' " return '__ref(stg_orders)'\n" @@ -605,7 +611,7 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: name="invalid-declaration-name", expected_code="D016", files={ - "models/staging/_sqlbuild/_constants/limits.sql": ( + "sql/models/staging/_sqlbuild/_constants/limits.sql": ( "CONSTANT (name MinimumAmount, value 1);\n" ), **staging_files(FAILURE_BASE_STAGING + 'WHERE amount > @const("MinimumAmount")\n'), @@ -614,13 +620,13 @@ def _compile_failure_cases() -> tuple[FailureCase, ...]: failure_case( name="python-node-syntax", expected_code="D011", - files={"python/tasks/exports.py": "def broken(:\n pass\n"}, + files={"python/nodes/tasks/exports/asset.py": "def broken(:\n pass\n"}, ), failure_case( name="hook-unknown-argument", expected_code="P001", files={ - "hooks/sql/record_refresh.sql": ( + "sql/hooks/sql/record_refresh.sql": ( "HOOK (\n description \"Record a refresh\"\n);\n\nSELECT @'label' AS label\n" ), FAILURE_MART_PATH: FAILURE_BASE_MART.replace( @@ -682,9 +688,9 @@ def engine_error_cases() -> tuple[FailureCase, ...]: failure_case( name="engine-error-non-ascii-digit-constant-value", expected_code="D013", - files={"constants/limits.sql": "CONSTANT (name minimum_amount, value \u0663);\n"}, + files={"sql/constants/limits.sql": "CONSTANT (name minimum_amount, value \u0663);\n"}, expected_message=( - "/constants/limits.sql has the bare number '\u0663', written with " + "/sql/constants/limits.sql has the bare number '\u0663', written with " "non-ASCII digits" ), expected_help=( @@ -712,7 +718,7 @@ def engine_error_cases() -> tuple[FailureCase, ...]: name="engine-error-macro-description-escaped-quote", expected_code="P015", files={ - "macros/sql/customer_label.sql": ( + "sql/macros/sql/customer_label.sql": ( "MACRO (\n" " description \"A customer's label,\n" 'quoted (\\"VIP\\").",\n' @@ -728,7 +734,7 @@ def engine_error_cases() -> tuple[FailureCase, ...]: }, expected_message=( 'a double quote ends this "..." string early; use """…""" for text ' - "containing double quotes\n --> macros/sql/customer_label.sql:3:10" + "containing double quotes\n --> sql/macros/sql/customer_label.sql:3:10" ), expected_help=_DESCRIPTION_QUOTE_HELP, ), @@ -736,12 +742,12 @@ def engine_error_cases() -> tuple[FailureCase, ...]: name="engine-error-non-ascii-digit-bare-number", expected_code="D013", files={ - "enums/order_priority.sql": ( + "sql/enums/order_priority.sql": ( "ENUM (\n name order_priority,\n members (LOW 1, HIGH \u0663),\n);\n" ) }, expected_message=( - "/enums/order_priority.sql has the bare number '\u0663', written with " + "/sql/enums/order_priority.sql has the bare number '\u0663', written with " "non-ASCII digits" ), expected_help=( diff --git a/scripts/compiler_differential/_helpers/corpus/render_failure_cases.py b/scripts/compiler_differential/_helpers/corpus/render_failure_cases.py index 05e5cd54c0..a6a096721f 100644 --- a/scripts/compiler_differential/_helpers/corpus/render_failure_cases.py +++ b/scripts/compiler_differential/_helpers/corpus/render_failure_cases.py @@ -7,8 +7,10 @@ staging_files, ) from scripts.compiler_differential.constants import ( + FAILURE_BASE_CONFIG, FAILURE_BASE_MART, FAILURE_BASE_STAGING, + FAILURE_CONFIG_PATH, FAILURE_MART_PATH, GENERATOR_MISSING_ENV_VAR, ) @@ -17,8 +19,8 @@ _STAGING_HEADER: str = '"Staged orders",' _MART_HEADER: str = '"Order totals per customer",' _STAGING_COLUMNS: str = "amount, status" -_STAGING_MACROS: str = "models/staging/_sqlbuild/_macros/python/orders.py" -_MART_MACROS: str = "models/marts/_sqlbuild/_macros/python/orders.py" +_STAGING_MACROS: str = "sql/models/staging/_sqlbuild/_macros/python/orders.py" +_MART_MACROS: str = "sql/models/marts/_sqlbuild/_macros/python/orders.py" _CENTS_MACRO: str = ( 'def cents(expression: str) -> str:\n """Convert to cents."""\n' ' return f"({expression} * 100)"\n' @@ -56,7 +58,7 @@ '__macro_actual__ AS (SELECT @py.cents("amount") AS cents FROM input_values),\n' ) -_SQL_MACRO_MACROS: str = "models/staging/_sqlbuild/_macros/sql" +_SQL_MACRO_MACROS: str = "sql/models/staging/_sqlbuild/_macros/sql" _SQL_MACRO_STAGING_COLUMNS: str = "amount, status" _SQL_MACRO_X_HEADER: str = 'MACRO (description "X", arguments ({arguments}){returns});\n\n' _SQL_MACRO_CENTS: dict[str, str] = { @@ -154,7 +156,9 @@ def _macro_cases() -> tuple[FailureCase, ...]: columns='amount, @py.explode("status") AS status', files={_STAGING_MACROS: _CENTS_MACRO + _EXPLODE_MACRO}, ), - "macros/python/explode.py": _EXPLODE_MACRO.replace("def explode", "def blow_up"), + "sql/macros/python/explode.py": _EXPLODE_MACRO.replace( + "def explode", "def blow_up" + ), FAILURE_MART_PATH: FAILURE_BASE_MART.replace( "SUM(amount)", 'SUM(@py.blow_up("total"))' ), @@ -196,12 +200,12 @@ def _macro_cases() -> tuple[FailureCase, ...]: expected_code="S007", files={ _STAGING_MACROS: _CENTS_MACRO, - "models/staging/_sqlbuild/macros/python/wrapping.py": ( - "from models.staging._sqlbuild._macros.python.orders import cents\n\n\n" + "sql/models/staging/_sqlbuild/macros/python/wrapping.py": ( + "from sql.models.staging._sqlbuild._macros.python.orders import cents\n\n\n" 'def wrapped(expression: str) -> str:\n """Wrap cents."""\n' " return cents(expression)\n" ), - "models/staging/regional/stg_regional_orders.sql": ( + "sql/models/staging/regional/stg_regional_orders.sql": ( 'MODEL (\n description "Regional orders",\n);\n\n' 'SELECT order_id, @py.wrapped("amount") AS amount_cents\n' 'FROM __ref("stg_orders")\n' @@ -243,7 +247,7 @@ def _interpolation_cases() -> tuple[FailureCase, ...]: expected_code="P001", expected_message="@@@placeholders without default values", files={ - "materializations/copy_table.py": ( + "python/materializations/copy_table.py": ( "from sqlbuild.executor.custom.models import MaterializationContext, " "MaterializationResult\n\n\n" "def materialize(ctx: MaterializationContext) -> MaterializationResult:\n" @@ -278,7 +282,7 @@ def _interpolation_cases() -> tuple[FailureCase, ...]: expected_code="P001", expected_message="is missing argument 'label'", files={ - "hooks/sql/record_refresh.sql": _RECORD_HOOK, + "sql/hooks/sql/record_refresh.sql": _RECORD_HOOK, FAILURE_MART_PATH: FAILURE_BASE_MART.replace( _MART_HEADER, f'{_MART_HEADER}\n post_hooks [sql("record_refresh")],' ), @@ -289,7 +293,7 @@ def _interpolation_cases() -> tuple[FailureCase, ...]: expected_code="P001", expected_message="is missing argument 'minimum' for generic audit 'floor'", files={ - "models/staging/_sqlbuild/_audits/generic/floor.sql": _FLOOR_AUDIT, + "sql/models/staging/_sqlbuild/_audits/generic/floor.sql": _FLOOR_AUDIT, **_staging_header(" audits [floor],"), }, ), @@ -298,7 +302,7 @@ def _interpolation_cases() -> tuple[FailureCase, ...]: expected_code="P001", expected_message="passes argument 'where_condition', which the audit's SQL in", files={ - "models/staging/_sqlbuild/_audits/generic/floor.sql": _FLOOR_AUDIT, + "sql/models/staging/_sqlbuild/_audits/generic/floor.sql": _FLOOR_AUDIT, **_staging_header( " audits [floor (minimum 0, where_condition \"status <> 'void'\")]," ), @@ -314,7 +318,7 @@ def _reference_cases() -> tuple[FailureCase, ...]: expected_code="P001", expected_message="expects 1 argument but received 2", files={ - "functions/sql/table_fn__orders_for.sql": _ORDERS_FOR, + "sql/functions/sql/table_fn__orders_for.sql": _ORDERS_FOR, **mart_body_files( "SELECT order_id AS customer_id, 1 AS total_amount\n" 'FROM __table_fn("table_fn__orders_for")(1, 2)\n' @@ -495,7 +499,9 @@ def _reference_cases() -> tuple[FailureCase, ...]: name="dbt-reference-without-manifest", expected_code="C214", files={ - **config_files('\n[dbt]\nproject_dir = "dbt"\n'), + FAILURE_CONFIG_PATH: 'extra_paths = ["dbt"]\n' + + FAILURE_BASE_CONFIG + + '\n[dbt]\nproject_dir = "dbt"\n', "dbt/dbt_project.yml": _UPSTREAM_DBT_PROJECT, **mart_body_files( "SELECT customer_id, COUNT(*) AS order_count\n" @@ -507,7 +513,7 @@ def _reference_cases() -> tuple[FailureCase, ...]: name="hard-coded-relation-in-python", expected_code="P008", files={ - "python/tasks/exports.py": ( + "python/nodes/tasks/exports/asset.py": ( "from sqlbuild.assets import asset\n\n\n" '@asset\ndef export_orders(ctx):\n """Export orders."""\n' ' return ctx.query("SELECT * FROM stg_orders")\n' @@ -523,7 +529,7 @@ def _attachment_cases() -> tuple[FailureCase, ...]: name="attached-audit-reads-dependant", expected_code="P005", files={ - "models/staging/_sqlbuild/_audits/generic/matches_totals.sql": _TOTALS_READER, + "sql/models/staging/_sqlbuild/_audits/generic/matches_totals.sql": _TOTALS_READER, **_staging_header(" audits [matches_totals],"), }, ), @@ -531,7 +537,7 @@ def _attachment_cases() -> tuple[FailureCase, ...]: name="hook-reads-dependant", expected_code="P007", files={ - "models/staging/_sqlbuild/_hooks/python/notes.py": _HOOK_READING_TOTALS, + "sql/models/staging/_sqlbuild/_hooks/python/notes.py": _HOOK_READING_TOTALS, **_staging_header(' post_hooks [python("note_refresh")],'), }, ), @@ -560,7 +566,7 @@ def _attachment_cases() -> tuple[FailureCase, ...]: name="schema-from-sibling-folder", expected_code="S006", files={ - "models/marts/_sqlbuild/_schemas/order_shape.sql": ( + "sql/models/marts/_sqlbuild/_schemas/order_shape.sql": ( 'SCHEMA (\n name order_shape,\n description "Order shape",\n' " columns (\n order_id (type INTEGER),\n ),\n);\n" ), @@ -571,7 +577,7 @@ def _attachment_cases() -> tuple[FailureCase, ...]: name="inherited-declaration-used-in-one-folder", expected_code="S008", files={ - "models/staging/_sqlbuild/constants/limits.sql": ( + "sql/models/staging/_sqlbuild/constants/limits.sql": ( "CONSTANT (name minimum_amount, value 1);\n" ), **staging_files(FAILURE_BASE_STAGING + 'WHERE amount > @const("minimum_amount")\n'), @@ -581,7 +587,7 @@ def _attachment_cases() -> tuple[FailureCase, ...]: name="singular-audit-across-trees", expected_code="S009", files={ - "models/marts/_sqlbuild/audits/singular/totals_have_orders.sql": ( + "sql/models/marts/_sqlbuild/audits/singular/totals_have_orders.sql": ( 'AUDIT (name "totals_have_orders");\n\n' 'SELECT t.customer_id\nFROM __ref("customer_totals") t\n' 'LEFT JOIN __source("raw_orders") o ON t.customer_id = o.customer_id\n' @@ -594,13 +600,13 @@ def _attachment_cases() -> tuple[FailureCase, ...]: expected_code="S024", expected_warning_code="C216", files={ - "python/audits/quality.py": ( + "python/nodes/audits/quality.py": ( "from sqlbuild.audits import AuditCase, audit_factory\n\n\n" "@audit_factory\ndef order_quality():\n" ' return [AuditCase(name="id_present", definition="not_null", ' 'arguments={"column": "order_id"})]\n' ), - "constants/limits.sql": "CONSTANT (name minimum_amount, value 1);\n", + "sql/constants/limits.sql": "CONSTANT (name minimum_amount, value 1);\n", **staging_files(FAILURE_BASE_STAGING + 'WHERE amount > @const("minimum_amount")\n'), }, ), @@ -811,12 +817,12 @@ def _sql_macro_cases() -> tuple[FailureCase, ...]: failure_case( name="sql-macro-body-declaration-not-visible", expected_code="S026", - expected_message="constant price_places is not visible from macros/sql/x.sql", + expected_message="constant price_places is not visible from sql/macros/sql/x.sql", files={ - "models/staging/_sqlbuild/_constants/places.sql": ( + "sql/models/staging/_sqlbuild/_constants/places.sql": ( "CONSTANT (name price_places, value 2);\n" ), - "macros/sql/x.sql": _SQL_MACRO_X_HEADER.format( + "sql/macros/sql/x.sql": _SQL_MACRO_X_HEADER.format( arguments="v DOUBLE", returns=", returns DOUBLE" ) + 'ROUND(@v, @const("price_places"))\n', diff --git a/scripts/compiler_differential/_helpers/corpus/scope_failure_cases.py b/scripts/compiler_differential/_helpers/corpus/scope_failure_cases.py index e0d262e461..3614bdc91b 100644 --- a/scripts/compiler_differential/_helpers/corpus/scope_failure_cases.py +++ b/scripts/compiler_differential/_helpers/corpus/scope_failure_cases.py @@ -7,9 +7,9 @@ ) from scripts.compiler_differential.models import FailureCase -_STAGING_MACRO_PATH: str = "models/staging/_macros/python/amounts.py" +_STAGING_MACRO_PATH: str = "sql/models/staging/_macros/python/amounts.py" _STAGING_MACRO: str = "def staged_amount(value):\n return f'{value} * 1'\n" -_STAGING_ENUM_PATH: str = "models/staging/_enums/status.sql" +_STAGING_ENUM_PATH: str = "sql/models/staging/_enums/status.sql" _STAGING_ENUM: str = "ENUM (name staged_status, members [PLACED]);\n" _MART_HEADER: str = 'MODEL (\n description "Order totals per customer",\n);\n\n' _STAGING_HEADER: str = 'MODEL (\n description "Staged orders",\n);\n\n' @@ -18,7 +18,7 @@ _SCENARIO_HEADER: str = 'SCENARIO (\n description "Order flow"\n);\n\n' -_GLOBAL_MACRO_PATH: str = "macros/python/amounts.py" +_GLOBAL_MACRO_PATH: str = "sql/macros/python/amounts.py" _GLOBAL_MACRO: str = "def doubled(value):\n return f'{value} * 2'\n" _MART_WITH_MACRO: str = ( _MART_HEADER + "SELECT customer_id, SUM(@py.doubled('amount')) AS total_amount\n" @@ -58,7 +58,7 @@ def scope_failure_cases() -> tuple[FailureCase, ...]: expected_code="P001", files={ _STAGING_ENUM_PATH: _STAGING_ENUM, - "enums/status.sql": "ENUM (name staged_status, members [SHIPPED]);\n", + "sql/enums/status.sql": "ENUM (name staged_status, members [SHIPPED]);\n", }, ), _case( @@ -76,7 +76,7 @@ def scope_failure_cases() -> tuple[FailureCase, ...]: expected_code="P001", files={ _STAGING_ENUM_PATH: _STAGING_ENUM, - "models/marts/_macros/python/totals.py": ( + "sql/models/marts/_macros/python/totals.py": ( "def mart_total(value):\n return value\n" ), FAILURE_STAGING_PATH: _STAGING_HEADER @@ -130,7 +130,7 @@ def scope_failure_cases() -> tuple[FailureCase, ...]: expected_message=f"SQL test '{_TEST_PATH}' CTE '__macro_actual__' must use AS (...)", files={ _STAGING_ENUM_PATH: _STAGING_ENUM, - "macros/python/amounts.py": "def doubled(value):\n return f'{value} * 2'\n", + "sql/macros/python/amounts.py": "def doubled(value):\n return f'{value} * 2'\n", _TEST_PATH: 'TEST (mode macro, name "doubled");\n\nWITH\n' "__macro_actual__ AS SELECT @py.doubled('1') AS amount\n", }, @@ -174,7 +174,9 @@ def _declaration_reference_cases() -> tuple[FailureCase, ...]: files=_staging_after_macro( where='amount > @const("order_cap")', files={ - "models/marts/_constants/limits.sql": "CONSTANT (name order_cap, value 3);\n" + "sql/models/marts/_constants/limits.sql": ( + "CONSTANT (name order_cap, value 3);\n" + ) }, ), ), diff --git a/scripts/compiler_differential/_helpers/coverage/discovery.py b/scripts/compiler_differential/_helpers/coverage/discovery.py index b6823157d5..f1d92e8c94 100644 --- a/scripts/compiler_differential/_helpers/coverage/discovery.py +++ b/scripts/compiler_differential/_helpers/coverage/discovery.py @@ -42,7 +42,9 @@ "sqlbuild.compiler.discovery.models:DiscoveredProjectInputs", frozenset() ) -_CROSS_FILE_MACRO_IMPORT: re.Pattern[str] = re.compile(r"^(?:from|import) macros\.", re.MULTILINE) +_CROSS_FILE_MACRO_IMPORT: re.Pattern[str] = re.compile( + r"^(?:from|import) sql\.macros\.", re.MULTILINE +) _NON_ASCII_COMMENT: re.Pattern[str] = re.compile(r"--[^\n]*[^\x00-\x7f]") _NON_ASCII_STRING: re.Pattern[str] = re.compile(r"'[^'\n]*[^\x00-\x7f][^'\n]*'") diff --git a/scripts/compiler_differential/_helpers/refactor_corpus/refactor_cases.py b/scripts/compiler_differential/_helpers/refactor_corpus/refactor_cases.py index 5c23babbc3..de43089b35 100644 --- a/scripts/compiler_differential/_helpers/refactor_corpus/refactor_cases.py +++ b/scripts/compiler_differential/_helpers/refactor_corpus/refactor_cases.py @@ -103,7 +103,7 @@ def refactor_cases() -> tuple[CorpusProject, ...]: name="rename-model-dry-run", refactor=_refactor("rename", "stg_orders", "stg_order_lines", "--dry-run"), ), - _case(name="mv-model", refactor=_refactor("mv", "customer_totals", "models/finance/")), + _case(name="mv-model", refactor=_refactor("mv", "customer_totals", "sql/models/finance/")), _case( name="rename-column", refactor=_refactor("rename", "stg_orders.amount", "order_amount"), diff --git a/scripts/compiler_differential/classes/analysis_features.py b/scripts/compiler_differential/classes/analysis_features.py index f56b28b908..8704fddd7c 100644 --- a/scripts/compiler_differential/classes/analysis_features.py +++ b/scripts/compiler_differential/classes/analysis_features.py @@ -94,7 +94,7 @@ def _column_shapes(self) -> None: header="", body=f'SELECT *\nFROM __ref("{base.name}")\n', ) - self._files["sources/open.yml"] = ( + self._files["sql/sources/open.yml"] = ( "sources:\n" f" - name: {GENERATOR_OPEN_SOURCE}\n" " description: Events whose columns are only known to the warehouse.\n" @@ -168,14 +168,14 @@ def _udf_signatures(self) -> None: self._features.add("udf_signatures") base: ModelPlan = self._base() factor: int = self._random.randint(2, 9) - self._files["functions/sql/scaled_amount.sql"] = ( + self._files["sql/functions/sql/scaled_amount.sql"] = ( "FUNCTION (\n" ' description "Scale an amount by an integer factor",\n' " arguments (p_amount DOUBLE, p_factor INTEGER),\n" " returns DOUBLE,\n);\n\n" "p_amount * p_factor\n" ) - self._files["functions/sql/table_fn__amount_bands.sql"] = ( + self._files["sql/functions/sql/table_fn__amount_bands.sql"] = ( "FUNCTION (\n" ' description "Band staged amounts above a floor",\n' " arguments (p_floor DOUBLE),\n" @@ -324,7 +324,7 @@ def _analysis_opt_out(self) -> None: def _python_sql(self) -> None: self._features.add("python_sql") - self._files["python/tasks/flag_exports.py"] = ( + self._files["python/nodes/tasks/flag_exports/asset.py"] = ( "from sqlbuild.assets import AssetContext, asset\n\n\n" "@asset\n" "def count_flagged_events(ctx: AssetContext):\n" diff --git a/scripts/compiler_differential/classes/discovery_features.py b/scripts/compiler_differential/classes/discovery_features.py index e53f299d5d..379bde82af 100644 --- a/scripts/compiler_differential/classes/discovery_features.py +++ b/scripts/compiler_differential/classes/discovery_features.py @@ -94,7 +94,7 @@ def write(self) -> None: "audit_factory": self._audit_factory, "provider": self._provider, "lifecycle_sink": self._lifecycle_sink, - "command_output_sink": self._command_output_sink, + "command_output_event_sink": self._command_output_sink, "custom_materialization": self._custom_materialization, "project_adapter": self._project_adapter, "model_schema": self._model_schema, @@ -194,7 +194,7 @@ def _python_hook(self) -> None: def _managed_source_loader(self) -> None: self._features.add("managed_source_loader") - self._files["sources/managed.yml"] = ( + self._files["sql/sources/managed.yml"] = ( "sources:\n" " - name: loaded_products\n" " description: Products loaded by a project loader.\n" @@ -204,7 +204,7 @@ def _managed_source_loader(self) -> None: " - name: id\n type: INTEGER\n" " - name: label\n type: VARCHAR\n" ) - self._files["python/loaders/products.py"] = ( + self._files["python/nodes/loaders/products/loader.py"] = ( "from sqlbuild.loaders import loader\n\n\n" "@loader\n" "def loaded_products(ctx):\n" @@ -221,23 +221,27 @@ def _managed_source_loader(self) -> None: def _asset_and_check(self) -> None: self._features.add("asset_and_check") base: ModelPlan = self._base() - self._files["python/assets/exports.py"] = ( + self._files["python/nodes/assets/exports/factory.py"] = ( "from sqlbuild.assets import asset\n" "from sqlbuild.checks import check\n" + "from sqlbuild.factories import factory\n" "from sqlbuild.refs import model\n\n\n" - f'@asset(depends_on=model("{base.name}"), tags=("export",))\n' - f"def export_{base.name}(ctx):\n" - ' """Export one staged model."""\n' - ' return ctx.result(metadata={"rows": 3}, materialized=True)\n\n\n' - f'@check(depends_on=export_{base.name}, severity="warn")\n' - f"def export_{base.name}_ready(ctx):\n" - ' """Check that the export ran."""\n' - " return ctx.pass_()\n" + "@factory\n" + "def export_nodes():\n" + f' @asset(depends_on=model("{base.name}"), tags=("export",))\n' + f" def export_{base.name}(ctx):\n" + ' """Export one staged model."""\n' + ' return ctx.result(metadata={"rows": 3}, materialized=True)\n\n' + f' @check(depends_on=export_{base.name}, severity="warn")\n' + f" def export_{base.name}_ready(ctx):\n" + ' """Check that the export ran."""\n' + " return ctx.pass_()\n\n" + f" return [export_{base.name}, export_{base.name}_ready]\n" ) def _discovered_set(self) -> None: self._features.add("discovered_set") - self._files["python/assets/steps.py"] = ( + self._files["python/nodes/assets/steps/asset.py"] = ( "from sqlbuild.assets import asset\n" "from sqlbuild.discovery import Discovered, Item, discover\n\n\n" '@discover(check_every="60s")\n' @@ -257,7 +261,7 @@ def _discovered_set(self) -> None: def _audit_factory(self) -> None: self._features.add("audit_factory") base: ModelPlan = self._base() - self._files["python/audits/quality.py"] = ( + self._files["python/nodes/audits/quality.py"] = ( "from sqlbuild.audits import AuditCase, audit_factory\n\n\n" "@audit_factory\n" "def event_quality():\n" @@ -275,14 +279,14 @@ def _audit_factory(self) -> None: def _provider(self) -> None: self._features.add("provider") - self._files["providers/export_settings.py"] = ( + self._files["python/providers/export_settings.py"] = ( "from sqlbuild.providers import Provider\n\n\n" "class ExportSettings(Provider):\n" ' """Settings for generated exports."""\n\n' f' region: str = "{self._random.choice(("north", "south"))}"\n' " batch_size: int = 50\n" ) - self._files["python/tasks/provided.py"] = ( + self._files["python/nodes/tasks/provided/asset.py"] = ( "from sqlbuild.assets import asset\n\n\n" "@asset\n" "def provided_export(ctx, export_settings):\n" @@ -292,8 +296,9 @@ def _provider(self) -> None: def _lifecycle_sink(self) -> None: self._features.add("lifecycle_sink") - self._files["sinks/lifecycle.py"] = ( - "from sqlbuild.sinks import LifecycleEvent, LifecycleEventKind, lifecycle_event_sink\n" + self._files["python/event_sinks/lifecycle.py"] = ( + "from sqlbuild.event_sinks import LifecycleEvent, LifecycleEventKind, " + "lifecycle_event_sink\n" "\n\n" "@lifecycle_event_sink(\n" " event_kinds={LifecycleEventKind.RUN, LifecycleEventKind.RESOURCE}\n" @@ -303,10 +308,10 @@ def _lifecycle_sink(self) -> None: ) def _command_output_sink(self) -> None: - self._features.add("command_output_sink") - self._files["sinks/output.py"] = ( - "from sqlbuild.sinks import CommandOutputRecord, command_output_sink\n\n\n" - '@command_output_sink(streams={"stderr"})\n' + self._features.add("command_output_event_sink") + self._files["python/event_sinks/output.py"] = ( + "from sqlbuild.event_sinks import CommandOutputRecord, command_output_event_sink\n\n\n" + '@command_output_event_sink(streams={"stderr"})\n' "def ignore_output(record: CommandOutputRecord) -> None:\n" " return None\n" ) @@ -314,7 +319,7 @@ def _command_output_sink(self) -> None: def _custom_materialization(self) -> None: self._features.add("custom_materialization") base: ModelPlan = self._base() - self._files["materializations/copy_table.py"] = ( + self._files["python/materializations/copy_table.py"] = ( "from sqlbuild.executor.custom.models import MaterializationContext, " "MaterializationResult\n\n\n" "def materialize(ctx: MaterializationContext) -> MaterializationResult:\n" @@ -331,12 +336,12 @@ def _custom_materialization(self) -> None: def _project_adapter(self) -> None: self._features.add("project_adapter") self.adapter = GENERATOR_PROJECT_ADAPTER - self._files["adapters/generated_duckdb.py"] = ( + self._files["python/adapters/generated_duckdb.py"] = ( "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n\n" "class GeneratedDuckDbAdapter(DuckDbAdapter):\n" f' adapter_name = "{GENERATOR_PROJECT_ADAPTER}"\n' ) - self._files["adapter.py"] = ( + self._files["python/adapter.py"] = ( "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n\n" "class ProjectOverrideAdapter(DuckDbAdapter):\n" ' """Project adapter override."""\n\n' @@ -385,13 +390,13 @@ def _list_constant(self) -> None: def _cross_file_macro_import(self) -> None: self._features.add("cross_file_macro_import") base: ModelPlan = self._base() - self._files["macros/python/rounding.py"] = ( + self._files["sql/macros/python/rounding.py"] = ( "def round_amount(expression: str, places: int = 2) -> str:\n" ' """Round an amount."""\n' ' return f"ROUND({expression}, {places})"\n' ) - self._files["macros/python/tax.py"] = ( - "from macros.python.rounding import round_amount\n\n\n" + self._files["sql/macros/python/tax.py"] = ( + "from sql.macros.python.rounding import round_amount\n\n\n" "def taxed(expression: str) -> str:\n" ' """Add tax to an amount, rounded."""\n' ' return round_amount(f"{expression} * 1.2")\n' @@ -467,14 +472,14 @@ def _generic_audit(self) -> None: def _functions(self) -> None: self._features.add("functions") - self._files["functions/sql/is_placed.sql"] = ( + self._files["sql/functions/sql/is_placed.sql"] = ( "FUNCTION (\n" ' description "Whether a status is placed.",\n' " arguments (event_status STRING),\n" " returns BOOLEAN,\n);\n\n" "event_status = 'placed'\n" ) - self._files["functions/python/is_large.py"] = ( + self._files["sql/functions/python/is_large.py"] = ( "from sqlbuild.functions import udf\n\n\n" '@udf(arguments={"amount": "DOUBLE"}, returns="BOOLEAN", runtime_version="3.11")\n' "def main(amount: float | None) -> bool:\n" @@ -533,7 +538,13 @@ def _dbt_ref(self) -> None: self.expected_error_code = GENERATOR_DBT_REF_ERROR_CODE self.succeeding_commands = (PLAN_LABEL,) self.config_lines.extend( - ["", "[dbt]", 'project_dir = "dbt"', 'target_path = "dbt/artifacts"'] + [ + 'extra_paths = ["dbt"]', + "", + "[dbt]", + 'project_dir = "dbt"', + 'target_path = "dbt/artifacts"', + ] ) self._files["dbt/dbt_project.yml"] = "name: upstream\nversion: '1.0.0'\nprofile: upstream\n" self._files["dbt/artifacts/manifest.json"] = GENERATOR_DBT_MANIFEST @@ -564,9 +575,9 @@ def _line_endings(self) -> None: ), ) self._files[path] = self._files[path].replace("\n ", "\n\t").replace("\n", GENERATOR_CRLF) - self._files["sources/raw.yml"] = GENERATOR_BOM + self._files["sources/raw.yml"].replace( - "\n", GENERATOR_CRLF - ) + self._files["sql/sources/raw.yml"] = GENERATOR_BOM + self._files[ + "sql/sources/raw.yml" + ].replace("\n", GENERATOR_CRLF) def feature_blocks_for_seed(*, seed: int, rng: random.Random) -> tuple[str, ...]: diff --git a/scripts/compiler_differential/classes/project_builder.py b/scripts/compiler_differential/classes/project_builder.py index 4b61b1b6ef..1586c24ee1 100644 --- a/scripts/compiler_differential/classes/project_builder.py +++ b/scripts/compiler_differential/classes/project_builder.py @@ -213,7 +213,9 @@ def _write_config( ] ) self._features.add("path_defaults_wildcard") - lines.extend(extra_lines) + top_level: list[str] = [line for line in extra_lines if line.startswith("extra_paths")] + lines[0:0] = top_level + lines.extend(line for line in extra_lines if not line.startswith("extra_paths")) lines.extend(GENERATOR_SQL_RULE_IGNORES) self._files["sqlbuild_project.toml"] = "\n".join(lines) + "\n" @@ -238,14 +240,14 @@ def _write_sources(self) -> None: f' expression: "({rows})"\n' f" columns:\n{columns}" ) - self._files["sources/raw.yml"] = "sources:\n" + "\n".join(entries) + "\n" + self._files["sql/sources/raw.yml"] = "sources:\n" + "\n".join(entries) + "\n" def _write_seeds(self) -> None: schemas: list[str] = [] for index in range(self._random.randint(0, 2)): name: str = f"lookup_{index}" self._seeds.append(name) - self._files[f"seeds/{name}.csv"] = f'id,label\n1,"{self._label()}"\n2,plain\n' + self._files[f"sql/seeds/{name}.csv"] = f'id,label\n1,"{self._label()}"\n2,plain\n' schemas.append( f" - name: {name}\n" f" description: Generated lookup {index}.\n" @@ -255,7 +257,7 @@ def _write_seeds(self) -> None: ) if schemas: self._features.add("seeds") - self._files["seeds/seeds.yml"] = "seeds:\n" + "\n".join(schemas) + "\n" + self._files["sql/seeds/seeds.yml"] = "seeds:\n" + "\n".join(schemas) + "\n" def _plan_models(self, *, domains: list[str]) -> None: staging: list[ModelPlan] = [] @@ -487,9 +489,9 @@ def _placement(self, declaration: DeclarationPlan) -> str: return f"{folders.pop()}/_sqlbuild/_{role}" if len(domains) == 1: self._features.add("tree_scope") - return f"models/{domains.pop()}/_sqlbuild/{role}" + return f"sql/models/{domains.pop()}/_sqlbuild/{role}" self._features.add("project_scope") - return role + return f"sql/{role}" def _write_models(self) -> None: for model in self._models: @@ -562,16 +564,20 @@ def _write_python_nodes(self) -> None: if not self._chance(GENERATOR_HALF): return self._features.add("python_nodes") - self._files["python/tasks/exports.py"] = ( - "from sqlbuild.assets import AssetContext, asset\n\n\n" - "@asset\n" - "def collect_exports(ctx: AssetContext):\n" - ' """Collect generated exports."""\n' - ' return ctx.result(payload={"rows": 3})\n\n\n' - "@asset(depends_on=collect_exports)\n" - "def publish_exports(ctx: AssetContext):\n" - ' """Publish generated exports."""\n' - ' return ctx.result(metadata={"published": True})\n' + self._files["python/nodes/tasks/exports/assets.py"] = ( + "from sqlbuild.assets import AssetContext, asset\n" + "from sqlbuild.factories import factory\n\n\n" + "@factory\n" + "def export_assets():\n" + " @asset\n" + " def collect_exports(ctx: AssetContext):\n" + ' """Collect generated exports."""\n' + ' return ctx.result(payload={"rows": 3})\n\n' + " @asset(depends_on=collect_exports)\n" + " def publish_exports(ctx: AssetContext):\n" + ' """Publish generated exports."""\n' + ' return ctx.result(metadata={"published": True})\n\n' + " return [collect_exports, publish_exports]\n" ) def _write_tests_and_scenarios(self) -> None: @@ -664,7 +670,7 @@ def _drop_description(self, model: ModelPlan) -> str: def _duplicate_macro(self, model: ModelPlan) -> str: _ = model - self._files["macros/python/duplicate_adjust_0.py"] = ( + self._files["sql/macros/python/duplicate_adjust_0.py"] = ( "def adjust_0(expression: str) -> str:\n" ' """Duplicate a macro name."""\n' " return expression\n" @@ -680,7 +686,7 @@ def _break_header(self, model: ModelPlan) -> str: def _over_broad_constant_column(self, model: ModelPlan) -> str: _ = model - self._files["constants/unused_threshold.sql"] = ( + self._files["sql/constants/unused_threshold.sql"] = ( "CONSTANT (name unused_threshold, value 3);\n" ) return '@const("unused_threshold") AS narrow' diff --git a/scripts/compiler_differential/classes/render_features.py b/scripts/compiler_differential/classes/render_features.py index 54b3ec8e36..f9cd0d6faf 100644 --- a/scripts/compiler_differential/classes/render_features.py +++ b/scripts/compiler_differential/classes/render_features.py @@ -167,7 +167,7 @@ def _macro_generated_reference(self) -> None: def _table_function(self) -> None: self._features.add("table_function") base: ModelPlan = self._base() - self._files["functions/sql/table_fn__events_above.sql"] = ( + self._files["sql/functions/sql/table_fn__events_above.sql"] = ( "FUNCTION (\n" ' description "Events above an amount",\n' " arguments (p_minimum DOUBLE),\n" @@ -222,7 +222,7 @@ def _interpolation(self) -> None: self._deferred_placeholder(base) def _deferred_placeholder(self, base: ModelPlan) -> None: - self._files["materializations/windowed_copy.py"] = ( + self._files["python/materializations/windowed_copy.py"] = ( "from sqlbuild.executor.custom.models import MaterializationContext, " "MaterializationResult\n\n\n" "def materialize(ctx: MaterializationContext) -> MaterializationResult:\n" @@ -272,7 +272,7 @@ def _macros_across_resources(self) -> None: self._features.add("macros_across_resources") base: ModelPlan = self._base() source: str = base.inputs[0].split(":", 1)[1] - self._files["macros/python/labels.py"] = ( + self._files["sql/macros/python/labels.py"] = ( "def tidy_label(expression: str) -> str:\n" ' """Trim and lower-case a label."""\n' ' return f"LOWER(TRIM({expression}))"\n' @@ -281,7 +281,7 @@ def _macros_across_resources(self) -> None: 'AUDIT ();\n\nSELECT *\nFROM __ref("@model")\nWHERE @column <> ' '@py.tidy_label("@column")\n' ) - self._files["functions/sql/tidy_status.sql"] = ( + self._files["sql/functions/sql/tidy_status.sql"] = ( "FUNCTION (\n" ' description "Normalise a status label.",\n' " arguments (raw_status STRING),\n" @@ -298,7 +298,7 @@ def _macros_across_resources(self) -> None: f'FROM __ref("{base.name}")\n' ), ) - self._files["sources/labelled.yml"] = ( + self._files["sql/sources/labelled.yml"] = ( "sources:\n" " - name: labelled_channels\n" " description: Channel labels normalised in the source expression.\n" @@ -382,7 +382,7 @@ def _enum_column_contract(self) -> None: def _resource_audits(self) -> None: self._features.add("resource_audits") - self._files["sources/audited.yml"] = ( + self._files["sql/sources/audited.yml"] = ( "sources:\n" " - name: audited_events\n" " description: Events with source audits.\n" @@ -398,8 +398,8 @@ def _resource_audits(self) -> None: " - name: amount\n" " type: DOUBLE\n" ) - self._files["seeds/channel_codes.csv"] = f'id,label\n1,"{self._label()}"\n2,web\n' - self._files["seeds/channel_codes.yml"] = ( + self._files["sql/seeds/channel_codes.csv"] = f'id,label\n1,"{self._label()}"\n2,web\n' + self._files["sql/seeds/channel_codes.yml"] = ( "seeds:\n" " - name: channel_codes\n" " description: Channel codes with seed audits.\n" @@ -456,7 +456,7 @@ def _model_config(self) -> None: ), body=f'SELECT id, amount, status\nFROM __ref("{base.name}")\n', ) - self._files["sources/configured.yml"] = ( + self._files["sql/sources/configured.yml"] = ( "sources:\n" " - name: configured_events\n" f' description: "Configured feed ${{coalesce(ENV:{GENERATOR_MISSING_ENV_VAR}, ' @@ -474,7 +474,7 @@ def _model_config(self) -> None: " - name: amount\n" " type: DOUBLE\n" ) - self._files["functions/sql/configured_label.sql"] = ( + self._files["sql/functions/sql/configured_label.sql"] = ( "FUNCTION (\n" ' description "Label a configured status.",\n' f" schema \"${{coalesce(ENV:{GENERATOR_MISSING_ENV_VAR}, 'udfs')}}\",\n" diff --git a/scripts/compiler_differential/constants.py b/scripts/compiler_differential/constants.py index 813d642d4e..0881a3c23f 100644 --- a/scripts/compiler_differential/constants.py +++ b/scripts/compiler_differential/constants.py @@ -83,6 +83,8 @@ CUSTOM_RULE_FILE: str = "rules/order_names.py" CUSTOM_RULE_SOURCE: str = """from sqlbuild.rules import Finding, Model, RuleContext, rule +MAX_MODEL_NAME_LENGTH: int = 60 + @rule( code="XSQBRDIFF001", @@ -90,7 +92,7 @@ remediation="Rename the model.", ) def short_model_names(*, model: Model, ctx: RuleContext) -> list[Finding]: - if len(model.name) < 60: + if len(model.name) < MAX_MODEL_NAME_LENGTH: return [] return [ctx.finding(subject=model)] """ @@ -191,14 +193,14 @@ def short_model_names(*, model: Model, ctx: RuleContext) -> list[Finding]: """ FAILURE_BASE_FILES: dict[str, str] = { "sqlbuild_project.toml": FAILURE_BASE_CONFIG, - "sources/raw.yml": FAILURE_BASE_SOURCES, - "models/staging/stg_orders.sql": FAILURE_BASE_STAGING, - "models/marts/customer_totals.sql": FAILURE_BASE_MART, + "sql/sources/raw.yml": FAILURE_BASE_SOURCES, + "sql/models/staging/stg_orders.sql": FAILURE_BASE_STAGING, + "sql/models/marts/customer_totals.sql": FAILURE_BASE_MART, } -FAILURE_STAGING_PATH: str = "models/staging/stg_orders.sql" -FAILURE_MART_PATH: str = "models/marts/customer_totals.sql" +FAILURE_STAGING_PATH: str = "sql/models/staging/stg_orders.sql" +FAILURE_MART_PATH: str = "sql/models/marts/customer_totals.sql" FAILURE_CONFIG_PATH: str = "sqlbuild_project.toml" -FAILURE_SOURCES_PATH: str = "sources/raw.yml" +FAILURE_SOURCES_PATH: str = "sql/sources/raw.yml" GENERATOR_ENUM_KIND: str = "enum" GENERATOR_CONSTANT_KIND: str = "constant" GENERATOR_MACRO_KIND: str = "macro" @@ -248,7 +250,7 @@ def short_model_names(*, model: Model, ctx: RuleContext) -> list[Finding]: "audit_factory", "provider", "lifecycle_sink", - "command_output_sink", + "command_output_event_sink", "custom_materialization", "project_adapter", "model_schema", @@ -271,10 +273,10 @@ def short_model_names(*, model: Model, ctx: RuleContext) -> list[Finding]: GENERATOR_RARE_FEATURE_PERIOD: int = 12 GENERATOR_RARE_FEATURE_BLOCKS: dict[str, int] = {"dbt_ref": 1} GENERATOR_DBT_REF_ERROR_CODE: str = "C214" -GENERATOR_FEATURE_FOLDER: str = "models/features" -GENERATOR_RENDER_FOLDER: str = "models/rendering" +GENERATOR_FEATURE_FOLDER: str = "sql/models/features" +GENERATOR_RENDER_FOLDER: str = "sql/models/rendering" GENERATOR_RENDER_TEST_FOLDER: str = "tests/unit/rendering" -GENERATOR_ANALYSIS_FOLDER: str = "models/analysis" +GENERATOR_ANALYSIS_FOLDER: str = "sql/models/analysis" GENERATOR_ANALYSIS_TEST_FOLDER: str = "tests/unit/analysis" GENERATOR_OPEN_SOURCE: str = "open_events" GENERATOR_DIALECT_CONNECTIONS: dict[str, tuple[str, ...]] = { @@ -451,7 +453,7 @@ def short_model_names(*, model: Model, ctx: RuleContext) -> list[Finding]: RELATIVE_PATH_FIELDS: frozenset[str] = frozenset({"relative_path"}) CONFIG_ONLY_KINDS: dict[str, str] = { "project_adapter_config": ( - "the config names a non-built-in adapter; adapters/ modules are resolved after " + "the config names a non-built-in adapter; python/adapters/ modules are resolved after " "discovery and are not in the capture" ), "dbt_target_path_config": ( diff --git a/scripts/compiler_differential/models.py b/scripts/compiler_differential/models.py index daa8870758..98764f1912 100644 --- a/scripts/compiler_differential/models.py +++ b/scripts/compiler_differential/models.py @@ -165,7 +165,7 @@ class ModelPlan: def folder(self) -> str: """Return the model's folder relative to the project root.""" - return f"models/{self.domain}/{self.layer}" + return f"sql/models/{self.domain}/{self.layer}" @dataclass(frozen=True) diff --git a/scripts/delta_compile_series/_helpers/edits.py b/scripts/delta_compile_series/_helpers/edits.py index 2f941de525..2fffd63531 100644 --- a/scripts/delta_compile_series/_helpers/edits.py +++ b/scripts/delta_compile_series/_helpers/edits.py @@ -8,6 +8,7 @@ from scripts.delta_compile_series.constants import ( EDIT_ATTEMPTS, + EDIT_ROOTS, PRIVATE_PATH_MARKER, PROJECT_CONFIG, RANDOM_VALUE_LIMIT, @@ -23,7 +24,7 @@ def project_files(*, project_dir: Path, edit: DeltaCompileEdit) -> list[Path]: if edit.target is EditTarget.PROJECT_CONFIG: return [project_dir / PROJECT_CONFIG] - root: Path = project_dir / edit.target.value + root: Path = project_dir / EDIT_ROOTS[edit.target] return sorted( path for path in root.rglob(SQL_GLOB) if PRIVATE_PATH_MARKER not in path.as_posix() ) diff --git a/scripts/delta_compile_series/constants.py b/scripts/delta_compile_series/constants.py index daada218ea..b8e3bae192 100644 --- a/scripts/delta_compile_series/constants.py +++ b/scripts/delta_compile_series/constants.py @@ -7,6 +7,8 @@ from scripts.delta_compile_series.models import DeltaCompileEdit from scripts.delta_compile_series.types import EditTarget +EDIT_ROOTS: dict[EditTarget, str] = {EditTarget.MODELS: "sql/models", EditTarget.TESTS: "tests"} + DELTA_COMPILE_LINE: str = "against the previous compile" DELTA_VERIFIED_LINE: str = "delta compile verified" DELTA_FALLBACK_PATTERN: str = r"^delta compile fell back: (.*)$" diff --git a/scripts/fensu_policy/constants.py b/scripts/fensu_policy/constants.py index be05ba1217..8ff1c5704e 100644 --- a/scripts/fensu_policy/constants.py +++ b/scripts/fensu_policy/constants.py @@ -239,8 +239,8 @@ ) EVENT_EXPORTER_RUNTIME_PREFIX: str = "src/sqlbuild/runtime/event_exporting/" -EVENT_EXPORTER_PUBLIC_PATH: str = "src/sqlbuild/sinks.py" -EVENT_EXPORTER_DIRECTORY_NAME: str = "sinks" +EVENT_EXPORTER_PUBLIC_PATH: str = "src/sqlbuild/event_sinks.py" +EVENT_EXPORTER_DIRECTORY_PARTS: tuple[str, ...] = ("python", "event_sinks") EVENT_EXPORTER_MODULE_PARTS: tuple[str, ...] = ("sqlbuild", "runtime", "event_exporting") CORE_EVENT_EXPORTER_CLASS_NAMES: frozenset[str] = frozenset( { @@ -268,7 +268,7 @@ DIAGNOSTIC_LOG_CLASS_NAME: str = "DiagnosticLog" LIFECYCLE_EVENT_FACTORY_NAME: str = "create_lifecycle_event" EVENT_EXPORTER_DECORATOR_NAMES: frozenset[str] = frozenset( - {"lifecycle_event_sink", "command_output_sink"} + {"lifecycle_event_sink", "command_output_event_sink"} ) OBSERVABILITY_LIFECYCLE_EVENT_MODULES: tuple[tuple[str, ...], ...] = ( ("sqlbuild", "observability"), @@ -282,7 +282,7 @@ OBSERVABILITY_DEFINITION_MODULES: tuple[tuple[str, ...], ...] = ( ("sqlbuild", "runtime", "observability", "models"), ) -PUBLIC_EVENT_EXPORTER_MODULE_PARTS: tuple[str, ...] = ("sqlbuild", "sinks") +PUBLIC_EVENT_EXPORTER_MODULE_PARTS: tuple[str, ...] = ("sqlbuild", "event_sinks") NATIVE_BINDINGS_ROOTS: tuple[str, ...] = ( "crates/sqlbuild-python/src/", "crates/sqlbuild-python-base/src/", diff --git a/scripts/fensu_policy/rules/execution_observability.py b/scripts/fensu_policy/rules/execution_observability.py index ccb892246d..fe12e36cfa 100644 --- a/scripts/fensu_policy/rules/execution_observability.py +++ b/scripts/fensu_policy/rules/execution_observability.py @@ -31,7 +31,7 @@ DIAGNOSTIC_CONSTRUCTION_OWNER_PATHS, DIAGNOSTIC_LOG_CLASS_NAME, EVENT_EXPORTER_DECORATOR_NAMES, - EVENT_EXPORTER_DIRECTORY_NAME, + EVENT_EXPORTER_DIRECTORY_PARTS, EVENT_EXPORTER_MODULE_PARTS, EVENT_EXPORTER_RUNTIME_PREFIX, LIFECYCLE_CATALOG_NAME_PREFIX, @@ -182,7 +182,8 @@ def event_construction_ownership(*, module: object, ctx: RuleContext) -> list[Fa slug="sink-location", message=("sink declarations and private runtime imports must stay in their owner boundary"), remediation=( - "Put project sink declarations under sinks/**/*.py and use public APIs elsewhere." + "Put project sink declarations under python/event_sinks/**/*.py and use public APIs " + "elsewhere." ), ) def event_exporter_location(*, module: object, ctx: RuleContext) -> list[Fault]: @@ -210,10 +211,7 @@ def event_exporter_location(*, module: object, ctx: RuleContext) -> list[Fault]: for decorator_name in EVENT_EXPORTER_DECORATOR_NAMES ): continue - if ( - EVENT_EXPORTER_DIRECTORY_NAME not in path_parts - or path_parts.index(EVENT_EXPORTER_DIRECTORY_NAME) != 0 - ): + if path_parts[: len(EVENT_EXPORTER_DIRECTORY_PARTS)] != EVENT_EXPORTER_DIRECTORY_PARTS: faults.append( ctx.fault_for(path=ctx.path, line=decorator.lineno, column=decorator.col_offset) ) diff --git a/scripts/format_performance/_helpers/model_project.py b/scripts/format_performance/_helpers/model_project.py index a72c86aed4..7ce764e2aa 100644 --- a/scripts/format_performance/_helpers/model_project.py +++ b/scripts/format_performance/_helpers/model_project.py @@ -18,8 +18,8 @@ def write_model_format_project( (project_dir / "sqlbuild_project.toml").write_text( 'name = "format_models"\nadapter = "duckdb"\n', encoding="utf-8" ) - models_dir: Path = project_dir / "models" - models_dir.mkdir() + models_dir: Path = project_dir / "sql" / "models" + models_dir.mkdir(parents=True) for model_index in range(model_count): models_dir.joinpath(f"orders_{model_index:05d}.sql").write_text( 'MODEL (description "Generated order model");\n\n' diff --git a/scripts/planner_differential/constants.py b/scripts/planner_differential/constants.py index 498c0b447b..b8af651d55 100644 --- a/scripts/planner_differential/constants.py +++ b/scripts/planner_differential/constants.py @@ -39,7 +39,7 @@ STATE_TABLE_PREFIX: str = "_sqlbuild" ADDED_MODEL_NAME: str = "planner_differential_added" -ADDED_MODEL_PATH: str = "models/planner_differential_added.sql" +ADDED_MODEL_PATH: str = "sql/models/planner_differential_added.sql" ADDED_COLUMN_NAME: str = "planner_differential_flag" RENAMED_SUFFIX: str = "_renamed" EDITED_DESCRIPTION: str = "Edited by the planner differential." diff --git a/scripts/rules_benchmark/_helpers/workflow.py b/scripts/rules_benchmark/_helpers/workflow.py index ac93713bdf..cd9c8b755f 100644 --- a/scripts/rules_benchmark/_helpers/workflow.py +++ b/scripts/rules_benchmark/_helpers/workflow.py @@ -292,7 +292,7 @@ def _ci_five_thousand_invalidation_results(*, project_dir: Path) -> tuple[Benchm project_dir=project_dir, iterations=1, mutate=lambda iteration: _set_macro_offset( - path=project_dir / "macros" / "python" / "macro_00000.py", + path=project_dir / "sql" / "macros" / "python" / "macro_00000.py", iteration=iteration, ), ), @@ -722,7 +722,7 @@ def _run_scenarios( project_dir=project_dir, iterations=iterations, mutate=lambda iteration: _set_macro_offset( - path=project_dir / "macros" / "python" / "macro_00000.py", + path=project_dir / "sql" / "macros" / "python" / "macro_00000.py", iteration=iteration, ), ) @@ -1156,21 +1156,22 @@ def _rules_cache_bytes(project_dir: Path) -> int: def _workload_counts(*, project_dir: Path) -> dict[str, int]: - model_paths: tuple[Path, ...] = tuple((project_dir / "models").rglob("*.sql")) + model_paths: tuple[Path, ...] = tuple((project_dir / "sql" / "models").rglob("*.sql")) test_paths: tuple[Path, ...] = tuple((project_dir / "tests").rglob("*.sql")) rule_paths: tuple[Path, ...] = tuple((project_dir / "rules").rglob("*.py")) sources_text: str = "\n".join( - path.read_text(encoding="utf-8") for path in (project_dir / "sources").rglob("*.yml") + path.read_text(encoding="utf-8") + for path in (project_dir / "sql" / "sources").rglob("*.yml") ) return { "models": len(model_paths), "sources": sources_text.count(" - name: source_"), - "seeds": sum(1 for _ in (project_dir / "seeds").rglob("*.csv")), - "functions": sum(1 for _ in (project_dir / "functions").rglob("*.sql")), - "macros": sum(1 for _ in (project_dir / "macros").rglob("*.py")), + "seeds": sum(1 for _ in (project_dir / "sql" / "seeds").rglob("*.csv")), + "functions": sum(1 for _ in (project_dir / "sql" / "functions").rglob("*.sql")), + "macros": sum(1 for _ in (project_dir / "sql" / "macros").rglob("*.py")), "tests": sum(path.read_text(encoding="utf-8").count("TEST (") for path in test_paths), "audits": sum(path.read_text(encoding="utf-8").count("audits [") for path in model_paths), - "hooks": sum(1 for _ in (project_dir / "hooks").rglob("*.sql")), + "hooks": sum(1 for _ in (project_dir / "sql" / "hooks").rglob("*.sql")), "custom_rules": sum( path.read_text(encoding="utf-8").count("@rule(") for path in rule_paths ), @@ -1182,7 +1183,9 @@ def _scaled_count(*, model_count: int, representative_count: int) -> int: def _generated_model_path(*, project_dir: Path, index: int) -> Path: - matches: tuple[Path, ...] = tuple((project_dir / "models").rglob(f"model_{index:05d}.sql")) + matches: tuple[Path, ...] = tuple( + (project_dir / "sql" / "models").rglob(f"model_{index:05d}.sql") + ) if len(matches) != 1: raise RulesBenchmarkError(f"expected one generated model path for index {index}") return matches[0] diff --git a/src/sqlbuild/.agents/skills/sqlbuild/SKILL.md b/src/sqlbuild/.agents/skills/sqlbuild/SKILL.md index 960d4d018d..366ffa9875 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/SKILL.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/SKILL.md @@ -37,7 +37,7 @@ plan, and ships tools for proving a change is correct. Use those tools; do not s flag without the user's say-so. ```sql --- models/marts/fact_orders.sql +-- sql/models/marts/fact_orders.sql MODEL ( description "One row per order with its payment total", materialized table, @@ -185,9 +185,9 @@ parameterised cases, scenarios, audits and Rules. swap for tables, and on each delta before DML for incremental models. Attach built-ins such as `not_null` and `unique` in the column schema. -**Macros, enums and constants.** SQL macros (`macros/sql/`, one per file, called `@sql.name(...)`) +**Macros, enums and constants.** SQL macros (`sql/macros/sql/`, one per file, called `@sql.name(...)`) are typed, logic-free SQL fragments; prefer them when no logic is needed. Python macros -(`macros/python/`, called `@py.name(...)`) are functions returning SQL strings; arguments are +(`sql/macros/python/`, called `@py.name(...)`) are functions returning SQL strings; arguments are Python literals, and SQL expressions are passed as quoted strings. Public functions become macros; prefix helpers with `_`. Macros work in model SQL, SQL hooks, tests, scenarios, audits and SQL functions, but not in ordinary `MODEL()` config fields. Placement decides visibility. Read diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/CONTENTS.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/CONTENTS.md index bdc3a2934d..5c8ee5e766 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/CONTENTS.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/CONTENTS.md @@ -49,7 +49,7 @@ Bundled copies of every page on the SQLBuild documentation site, matching the in - [Overview](concepts/rules.md) (`concepts/rules`) - Turn repeated SQL and project review decisions into compiler-enforced requirements. - [Configuration and selection](concepts/rules/configuration-and-selection.md) (`concepts/rules/configuration-and-selection`) - Select built-in and custom Rules by exact code or family prefix. - [Findings and exceptions](concepts/rules/findings-and-exceptions.md) (`concepts/rules/findings-and-exceptions`) - Understand Rule diagnostics and record intentional exceptions safely. -- [Python Rules](concepts/rules/python-rules.md) (`concepts/rules/python-rules`) - Check the project's Python for annotations, imports, function shape and the layout of python/. +- [Python Rules](concepts/rules/python-rules.md) (`concepts/rules/python-rules`) - Check the project's Python for annotations, imports, function shape and the layout of python/nodes/. - [Orchestration Rules](concepts/rules/orchestration-rules.md) (`concepts/rules/orchestration-rules`) - Keep job and sensor selections from listing nodes one by one. - [Performance Rules](concepts/rules/performance-rules.md) (`concepts/rules/performance-rules`) - Catch semi-structured payloads that repeat on every row and multiply storage and scan cost. - [Execution and caching](concepts/rules/execution-and-caching.md) (`concepts/rules/execution-and-caching`) - Understand Rule enforcement order, focused runs, and dependency-aware reuse. @@ -75,7 +75,7 @@ Bundled copies of every page on the SQLBuild documentation site, matching the in - [Recall](concepts/observability/recall.md) (`concepts/observability/recall`) - The local history of every command: what ran, what it executed, and what it printed. - [Sharing Recall in ClickHouse](concepts/observability/recall-clickhouse.md) (`concepts/observability/recall-clickhouse`) - Keep one Recall history for a team or CI in ClickHouse: users, grants, setup, retention and reading. - [Observability](concepts/observability.md) (`concepts/observability`) - Find out what a run did, or send its events to your own systems. -- [Typed Sinks](concepts/observability/sinks.md) (`concepts/observability/sinks`) - Export lifecycle facts and command output through project-owned providers. +- [Event Sinks](concepts/observability/event-sinks.md) (`concepts/observability/event-sinks`) - Export lifecycle facts and command output through project-owned providers. ## Advanced diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/audit.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/audit.md index e13a437384..4192716058 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/audit.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/audit.md @@ -65,7 +65,7 @@ guarantee immediate cancellation of a query already running in the warehouse. sqb audit # Run audits for marts only -sqb audit path:models/marts +sqb audit path:sql/models/marts # Run up to 8 audit queries concurrently sqb audit --concurrency 8 diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/clone.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/clone.md index fd7e912523..ca4a651ce8 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/clone.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/clone.md @@ -56,7 +56,7 @@ sqb clone --from prod --to dev sqb clone --from prod # Clone only marts to dev -sqb clone --from prod --to dev --select path:models/marts +sqb clone --from prod --to dev --select path:sql/models/marts # Force physical copies sqb clone --from prod --to dev --hard-copy diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/compile.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/compile.md index 2c4cec4884..d251ac065f 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/compile.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/compile.md @@ -114,7 +114,7 @@ A model with Rule errors starts with a header that marks it not buildable and li ```sql -- sqb: compile failed for this model; not buildable --- SQLCLEAN028 at models/open_orders.sql:6:20: Single-relation query mixes qualified and unqualified columns +-- SQLCLEAN028 at sql/models/open_orders.sql:6:20: Single-relation query mixes qualified and unqualified columns SELECT o.order_id, status FROM __ref("orders") AS o ``` @@ -143,10 +143,10 @@ argument rendered: | Path | Contents | |------|----------| -| `models/.sql` | Each model's query | -| `functions//.sql` | Each function's `CREATE FUNCTION` statements | -| `audits/generic//__.sql` | Each attached generic audit, under the model, source or seed it checks; column audits end in `__`, and an audit's `name` replaces the audit name | -| `audits/singular/.sql` | Each singular audit | +| `sql/models/.sql` | Each model's query, at its path in the project | +| `sql/functions//.sql` | Each function's `CREATE FUNCTION` statements | +| `sql/audits/generic//__.sql` | Each attached generic audit, under the model, source or seed it checks; column audits end in `__`, and an audit's `name` replaces the audit name | +| `sql/audits/singular/.sql` | Each singular audit | | `tests/...` | Each SQL unit test's comparison query | Read an audit's file to see how its arguments were spliced into the SQL, without running it. @@ -160,7 +160,7 @@ A model's declared columns are checked against the columns its SQL produces: ``` error[K001]: declared column 'total_cents' was not found in statically inferred output for model 'fact_orders' model: fact_orders - --> models/marts/fact_orders.sql:6:5 + --> sql/models/marts/fact_orders.sql:6:5 6 | total_cents (), | ^^^^^^^^^^^ = help: add total_cents to the SELECT list or correct/remove MODEL(columns (...)); MODEL(columns (...)) is validated using static SQL analysis because settings.check_declared_columns is true (the default). If this project intentionally uses columns only for metadata and audits, set [settings] check_declared_columns = false; models with contract enforced remain validated diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dag.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dag.md index 3b1f83954c..7f71053b6f 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dag.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dag.md @@ -83,7 +83,7 @@ Each node represents a source, seed, model, or function: "name": "fact_orders", "qualified_name": "dev.fact_orders" }, - "path": "models/marts/fact_orders.sql", + "path": "sql/models/marts/fact_orders.sql", "description": "Order fact table with waffle and payment details.", "tags": ["marts"], "columns": [ @@ -131,7 +131,7 @@ Each check represents a test, audit, or scenario: "kind": "audit", "name": "not_null", "checked_asset_ids": ["model:fact_orders"], - "path": "audits/generic/not_null.sql", + "path": "sql/audits/generic/not_null.sql", "severity": "error", "attached_target_name": "fact_orders", "attached_column_name": "order_id" diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dev.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dev.md index 6c914c3f6b..af91883f1d 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dev.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dev.md @@ -13,6 +13,7 @@ Online: https://sqlbuild.com/docs/cli/dev/ - Set provider secrets - Sign in to the warehouse - Keys +- Republish from a script - Stop - Plain output - Run scheduled jobs locally @@ -119,8 +120,8 @@ nodes that need the provider (the first five, then a count) and the fix, never a ```text ⚠ warn 1 provider has missing secrets missing secret - at providers/region.py:9 region_token ← REGION_TOKEN - providers/region.py:10 region_code ← REGION_CODE + at python/providers/region.py:9 region_token ← REGION_TOKEN + python/providers/region.py:10 region_code ← REGION_CODE why runs that use it stop at the provider check, before the warehouse; 2 nodes need it (raw_regions, stg_regions) fix set them in .env and press r, or set them in the environment you @@ -163,6 +164,20 @@ location reads warehouse history once the connection succeeds. Ctrl+Z is not supported: `sqb dev` does not suspend. Stop it with `q` or Ctrl+C instead. +## Republish from a script + +[`sqb location republish`](location.md#republish) asks the location `sqb dev` serves to +compile and publish again, the same as pressing `r`: every discover function runs. Use the +address and the location ID from the ready box. `sqb dev` has no sign-in, so `SQLBUILD_API_KEY` +can be any value; the command needs one to call over `http://`: + +```bash +SQLBUILD_API_KEY=local sqb location republish --server http://127.0.0.1:8000 \ + --location-id 01a1d7ff-0b3a-7631-ba35-e44d44d072f2 --target dev --wait +``` + +A `curl` request to the [republish endpoint](location.md#republish) needs no key either. + ## Stop `q`, Ctrl+C, SIGINT, SIGTERM and SIGHUP stop `sqb dev` at any point, including while it reads the diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/diff.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/diff.md index 79bb52fae3..ac9be60597 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/diff.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/diff.md @@ -123,7 +123,7 @@ sqb diff prod --select customer_status_snapshot sqb diff prod:dev --full --select customer_status_snapshot # Schema-only diff of all marts -sqb diff prod:dev --schema-only --select path:models/marts +sqb diff prod:dev --schema-only --select path:sql/models/marts # Bounded diff of last 14 days sqb diff prod:dev --bounded 14d --select hourly_order_activity diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/init.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/init.md index 7929be2bf4..ec39a821be 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/init.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/init.md @@ -49,12 +49,12 @@ my-project/ ``` Empty directories contain `.gitkeep` files so the scaffold can be committed. Reusable attached -audit definitions belong in `audits/generic/`; cross-resource singular audits belong in -`audits/singular/`. Add reusable SQL lifecycle hooks to `hooks/sql/` and decorated Python lifecycle -hooks to `hooks/python/`; see [Hooks](../concepts/models/hooks.md). +audit definitions belong in `sql/audits/generic/`; cross-resource singular audits belong in +`sql/audits/singular/`. Add reusable SQL lifecycle hooks to `sql/hooks/sql/` and decorated Python lifecycle +hooks to `sql/hooks/python/`; see [Hooks](../concepts/models/hooks.md). These top-level roles are project-wide. Once an audit, schema, hook, or macro is used only under -one folder, such as `models/marts/`, SQLBuild requires it to move into that folder's `_sqlbuild/` +one folder, such as `sql/models/marts/`, SQLBuild requires it to move into that folder's `_sqlbuild/` directory; see [Where to Put Declarations](../concepts/declaration-scopes/placement.md). The generated project uses DuckDB, creates a named `developer` connection shared by `dev` and diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/lineage.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/lineage.md index 8762e344dd..048a16f81b 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/lineage.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/lineage.md @@ -45,7 +45,7 @@ Exactly one of a positional target or `--select` is required. | `--mode` | Column lineage analysis mode: `rich` (default) or `fast`. | | `--no-sql-analysis` | Disable compile-time SQL analysis (`--no-sql-validation` is an alias). | | `--allow-missing-secrets` | Run without provider secrets; see [Secrets](../concepts/python-nodes/providers.md#secrets) | -| `--select`, `-s` | Select resources using the same selector syntax as `sqb compile`, `sqb plan` and `sqb build`, for example `path:models/marts`, `tag:finance` or `stg_*`. | +| `--select`, `-s` | Select resources using the same selector syntax as `sqb compile`, `sqb plan` and `sqb build`, for example `path:sql/models/marts`, `tag:finance` or `stg_*`. | | `--exclude` | Exclude resources from the selection. | ## Model lineage @@ -61,7 +61,7 @@ sqb lineage fact_orders --direction both ``` ``` -Lineage model fact_orders models/marts/fact_orders.sql both +Lineage model fact_orders sql/models/marts/fact_orders.sql both upstream ├── model stg_orders models/staging/stg_orders.sql │ └── source raw__orders sources/raw.yml @@ -113,14 +113,14 @@ sqb lineage fact_orders --json "id": "model:fact_orders", "name": "fact_orders", "resource_type": "model", - "relative_path": "models/marts/fact_orders.sql", + "relative_path": "sql/models/marts/fact_orders.sql", "qualified_name": "dev.fact_orders" }, { "id": "source:raw__orders", "name": "raw__orders", "resource_type": "source", - "relative_path": "sources/raw.yml" + "relative_path": "sql/sources/raw.yml" } ], "edges": [ @@ -233,7 +233,7 @@ sqb lineage fact_orders.order_id --direction downstream sqb lineage fact_orders.total_cents --depth 1 # Lineage for all models in a path -sqb lineage --select path:models/marts +sqb lineage --select path:sql/models/marts # Lineage between two models (path-between) sqb lineage --select "stg_orders~daily_activity_rollup" diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/location.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/location.md index 5d4bb65934..fcc739f30b 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/location.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/location.md @@ -72,7 +72,7 @@ error: nothing is published, and the location's output and its page in the UI sh ```text Compile failed: 1 rule finding -models/orders.sql:2:8 [SQBRMODEL102] SELECT * is allowed only inside dependency import CTEs +sql/models/orders.sql:2:8 [SQBRMODEL102] SELECT * is allowed only inside dependency import CTEs ``` Runs and plan previews on a published snapshot don't evaluate the Rules again; they passed when it @@ -154,3 +154,5 @@ curl --fail "$BASE/discovered" -H "Authorization: Bearer $SQLBUILD_API_KEY" - A failed discover function doesn't fail the publish, as its set keeps its last good items. Check the set's `status` and `tags` in `discovered` to confirm a deploy. - The audit log records who asked and why, and the location prints both. +- A location that [`sqb dev`](dev.md#republish-from-a-script) serves takes the same + request at its UI address, with any `SQLBUILD_API_KEY`, as it has no sign-in. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/playground.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/playground.md index 7d8b01c212..a1db509035 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/playground.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/playground.md @@ -31,7 +31,7 @@ A complete DuckDB-backed project with: - Staging views, fact/dimension tables, and incremental models - Sources with inline expression data (no external setup) -- Python source loaders in `python/loaders/` +- Python source loaders in `python/nodes/loaders/` - Seeds, SQL functions, and a custom materialization - Built-in and custom audits - SQL unit tests and multi-model tests @@ -52,7 +52,7 @@ The Dagster `definitions.py` uses `sqlbuild_assets`, `sqlbuild_scenario_checks`, The `python_nodes` template instead creates a focused Python-nodes project: -- `python/assets/orders_inputs.py`, `python/loaders/orders.py`, `python/assets/orders_export.py`, `python/checks/orders_export.py` +- `python/nodes/assets/orders_inputs.py`, `python/nodes/loaders/orders.py`, `python/nodes/assets/orders_export.py`, `python/nodes/checks/orders_export.py` - A `fact_orders` SQL model over a managed `raw_orders` source - Examples of the SQL boundary, `ctx.relation(model(...))`, soft-skip fan-in, and a Python check diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/rename.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/rename.md index b936b25b55..1949fe5f7d 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/rename.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/rename.md @@ -37,8 +37,8 @@ sqb rename . [--cascade] [flags] ```bash sqb rename stg_orders stg_order_lines -sqb mv fact_orders models/reporting/ # keeps the name -sqb mv fact_orders models/reporting/order_facts.sql # moves and renames +sqb mv fact_orders sql/models/reporting/ # keeps the name +sqb mv fact_orders sql/models/reporting/order_facts.sql # moves and renames sqb rename stg_orders.amount revenue sqb rename stg_orders.amount revenue --cascade ``` @@ -50,14 +50,14 @@ Targets are written the way [`sqb lineage`](lineage.md) reads them: a bare name `sqb rename` changes names and never moves files: a model rename keeps the file in its folder and renames it to `.sql`. `sqb mv` changes where a model lives and always takes a path: a new `.sql` file path, which also sets the model name, or a folder ending in `/`, which keeps it. Neither command picks a folder for you, because a folder can change the schema, materialization, tags, and declaration visibility the model gets from path defaults. ```bash -# Name only: the file stays in models/orders/intermediate/clean/ +# Name only: the file stays in sql/models/orders/intermediate/clean/ sqb rename orders__int_clean__order_lines orders__int_clean__order_items # Name and a specific folder, in one verified step -sqb mv orders__int_clean__order_lines models/orders/intermediate/enriched/orders__int_enriched__order_lines.sql +sqb mv orders__int_clean__order_lines sql/models/orders/intermediate/enriched/orders__int_enriched__order_lines.sql # Folder only: the name stays -sqb mv orders__int_clean__order_lines models/orders/intermediate/clean/web/ +sqb mv orders__int_clean__order_lines sql/models/orders/intermediate/clean/web/ ``` ## Move several models at once @@ -65,14 +65,14 @@ sqb mv orders__int_clean__order_lines models/orders/intermediate/clean/web/ `sqb mv` takes several ` ` pairs, or `--from-file` with one pair per line, separated by a tab or spaces. Blank lines and lines starting with `#` are ignored. ```bash -sqb mv stg_order_cents models/finance/ stg_order_refunds models/finance/ +sqb mv stg_order_cents sql/models/finance/ stg_order_refunds sql/models/finance/ sqb mv --from-file moves.tsv --dry-run ``` ```text # moves.tsv -stg_order_cents models/finance/ -stg_order_refunds models/finance/ +stg_order_cents sql/models/finance/ +stg_order_refunds sql/models/finance/ ``` The moves are checked together, as one change: nothing is written unless the project compiles after all of them. Declarations and unit tests go where the final state needs them, so a macro whose users all move goes straight to their new folder. @@ -104,7 +104,7 @@ The model's own unit tests, the test files whose every `TEST` block targets only - a file named `test_.sql` or `test___.sql` is renamed to the new name; - `TEST (name "__")` takes the new name as its subject; -- a test file in the folder that mirrors the model, `tests/unit//` for `models//`, moves to the folder that mirrors the destination. Test files kept elsewhere stay where they are. +- a test file in the folder that mirrors the model, `tests/unit//` for `sql/models//`, moves to the folder that mirrors the destination. Test files kept elsewhere stay where they are. - a test file stays in its folder, still renamed, when a macro, enum, or constant it uses would resolve to a different declaration, or to none, from the destination folder, such as a test macro in `tests/unit//_sqlbuild/_macros/`. The output's notes name the file and the declaration. Tests that also target other models keep their file and name; only their fixtures and references change. @@ -112,8 +112,8 @@ Tests that also target other models keep their file and name; only their fixture Moving a model to another folder also moves the macros, enums, constants, reusable schemas, generic audits, and named hooks it uses when their [placement](../concepts/declaration-scopes/placement.md) must change, following the same rules `sqb compile` enforces: - a declaration only the moved model uses moves with it, into the destination folder's matching role; -- a declaration other resources still use moves to the lowest folder they share, for example `models/staging/_sqlbuild/macros/`; -- when that folder would be an authored root such as `models/`, or the users span resource trees such as models and tests, it moves to the top-level role (`macros/`, `enums/`, `constants/`, `schemas/`, ...). +- a declaration other resources still use moves to the lowest folder they share, for example `sql/models/staging/_sqlbuild/macros/`; +- when that folder would be an authored root such as `sql/models/`, or the users span resource trees such as models and tests, it moves to the top-level role (`sql/macros/`, `sql/enums/`, `sql/constants/`, `sql/schemas/`, ...). A moved declaration file takes the shape of the role folder it lands in. In an empty role it keeps its group folder, such as `money/` in `_macros/money/cents.py`, or stays direct if it had none. In a role whose files all sit in group folders it keeps its group, and a file without a group is refused: move it into a group folder of its current role first. In a role whose files sit directly in it, the group folder is dropped. @@ -154,7 +154,7 @@ A project that already fails some project rules, such as a folder holding more m A rule failure that the project already had, at the same place and with the same message, doesn't block the change. Neither does one whose numbers only went down, such as a folder that now holds 41 models instead of 44. A new or worse failure blocks the write. Rules stay enabled throughout. -The output, including `--dry-run`, lists them under `Existing rule failures`, with how many the change resolved. Some rules report a failure at one sample file of a group, so moving part of the group can block the move even when it helps. Move the whole group in one batch instead: moving the direct models of a folder into a sub-folder at once, so that it turns from a leaf into a branch, is `sqb mv a models/entry/records/ b models/entry/records/ c models/entry/records/`. +The output, including `--dry-run`, lists them under `Existing rule failures`, with how many the change resolved. Some rules report a failure at one sample file of a group, so moving part of the group can block the move even when it helps. Move the whole group in one batch instead: moving the direct models of a folder into a sub-folder at once, so that it turns from a leaf into a branch, is `sqb mv a sql/models/entry/records/ b sql/models/entry/records/ c sql/models/entry/records/`. ## Refusals @@ -174,13 +174,13 @@ The command refuses, and writes nothing, when: A rename whose new name belongs to another layer's folder, under the layer-folder rules `SQBRPROJECT102` and `SQBRPROJECT105`, fails verification because `sqb rename` keeps the file where it is. When those rules are the only failures, the output says where the model belongs and prints the one-step [`sqb mv`](#rename-or-move) command, with that layer's folder and the current sub-folders filled in: ```text -orders__int_enriched__order_lines__web belongs under models/orders/intermediate/enriched/ +orders__int_enriched__order_lines__web belongs under sql/models/orders/intermediate/enriched/ Rename and move in one step: - sqb mv orders__int_clean__order_lines__web models/orders/intermediate/enriched/web/orders__int_enriched__order_lines__web.sql + sqb mv orders__int_clean__order_lines__web sql/models/orders/intermediate/enriched/web/orders__int_enriched__order_lines__web.sql (change the folder if you want it somewhere else) ``` -When the current path has no folder for the model's current layer to swap, or the new layer has no canonical folder, the destination is `models//.sql`, with a `` placeholder for you to fill in. +When the current path has no folder for the model's current layer to swap, or the new layer has no canonical folder, the destination is `sql/models//.sql`, with a `` placeholder for you to fill in. Each location is listed with its file, line, and column, with the fix. Edit those locations, or pass the model or column to the macro as an argument, and run the command again. The command never applies part of a rename. @@ -199,9 +199,9 @@ References produced by a macro are only possible when a project turns off explic ```text Rename model stg_orders -> stg_order_lines -├── models/marts/fact_orders.sql +├── sql/models/marts/fact_orders.sql │ └── 24:13 reference __ref("stg_orders") -> __ref("stg_order_lines") -├── models/staging/stg_order_lines.sql (moved from models/staging/stg_orders.sql) +├── sql/models/staging/stg_order_lines.sql (moved from sql/models/staging/stg_orders.sql) │ └── 1:8 migration + migrate_from stg_orders └── tests/unit/test_fact_orders.sql └── 4:1 fixture __ref__stg_orders -> __ref__stg_order_lines diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scenario.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scenario.md index c3f598dc52..1818c13c2b 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scenario.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scenario.md @@ -195,7 +195,7 @@ target/run/scenarios/daily_revenue_minimal/ fixtures/ ref__stg_orders.sql ref__stg_payments.sql - models/ + sql/models/ marts/daily_revenue.sql expectations/ expected__daily_revenue.sql diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scope.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scope.md index 98c66c22f1..ea84326e42 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scope.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scope.md @@ -59,7 +59,7 @@ sqb scope macro:normalize_order_status sqb scope enum:order_status sqb scope constant:minimum_order_value -sqb scope models/staging/orders/stg_orders.sql +sqb scope sql/models/staging/orders/stg_orders.sql ``` Models, sources, seeds, and functions share one project-wide namespace, so their bare names, such as `stg_orders`, are accepted and resolve to the qualified identity. Macros, enums, constants, tests, and audits can share names with each other and with resources, so they always need their prefix: a bare name such as `order_status` that names one of them fails with `C960` and shows the qualified form to use, and a bare name that matches both a resource and one of these declarations fails and lists every match. Public declaration identities are `macro:`, `enum:`, and `constant:`. @@ -131,34 +131,35 @@ that macro composes two project-wide macros: ```text project/ -├── macros/ -│ └── currency.py add_tax, round_money -└── models/ - └── commerce/ - ├── macros/ - │ └── orders.py formatted_order_total - ├── orders.sql - └── returns/ - └── returns.sql +└── sql/ + ├── macros/ + │ └── currency.py add_tax, round_money + └── models/ + └── commerce/ + ├── macros/ + │ └── orders.py formatted_order_total + ├── orders.sql + └── returns/ + └── returns.sql ``` ```python -# models/commerce/macros/python/orders.py -from macros.python.currency import add_tax, round_money +# sql/models/commerce/macros/python/orders.py +from sql.macros.python.currency import add_tax, round_money def formatted_order_total(expression: str) -> str: return round_money(add_tax(expression)) ``` ```sql --- models/commerce/orders.sql +-- sql/models/commerce/orders.sql MODEL(description "Orders"); SELECT @py.formatted_order_total("subtotal") AS total ``` `returns/returns.sql` calls the same macro, so the declaration must remain available throughout -`models/commerce/` and its descendants. +`sql/models/commerce/` and its descendants. The default report puts actual usage next to the complete directory-derived scope. Unused globals stay collapsed, so the useful facts remain visible even in a large project: @@ -168,18 +169,18 @@ $ sqb scope model:orders Scope Target: model:orders Resource: model:orders - Path: models/commerce/orders.sql + Path: sql/models/commerce/orders.sql Used (1) - └─ ● macro:formatted_order_total models/commerce/macros/python/orders.py:5 + └─ ● macro:formatted_order_total sql/models/commerce/macros/python/orders.py:5 Scope chain - ├─ exact-owner-private models/commerce (1) + ├─ exact-owner-private sql/models/commerce (1) ├─ descendant-public models (0) └─ project global (2) Available (1 of 3, 2 collapsed) - └─ ● macro:formatted_order_total models/commerce/macros/python/orders.py:5 + └─ ● macro:formatted_order_total sql/models/commerce/macros/python/orders.py:5 … 2 globals collapsed; run sqb scope model:orders --globals all ● used by this resource ○ not used by this resource --verbose for scope details @@ -192,13 +193,13 @@ With `--verbose`, the same `Used` section shows why each declaration is visible: ```console $ sqb scope model:orders --verbose Used (1) - └─ ● macro:formatted_order_total [macro; descendant-public; inherited_ancestor; params 1; role models/commerce/macros] models/commerce/macros/python/orders.py:5:1 + └─ ● macro:formatted_order_total [macro; descendant-public; inherited_ancestor; params 1; role sql/models/commerce/macros] sql/models/commerce/macros/python/orders.py:5:1 ``` This answers several questions without opening declaration files: what the model actually uses, where that declaration came from, which owner and parent folders SQLBuild checks, how many project-wide declarations are available, and whether the result is complete. The scope-chain count -at `models/commerce` includes declarations owned there; the `exact-owner-private` chain label does +at `sql/models/commerce` includes declarations owned there; the `exact-owner-private` chain label does not mean every declaration in that count is private. ### Follow composed macro dependencies @@ -212,12 +213,12 @@ $ sqb scope model:orders --used-only --dependency-depth 1 Scope Target: model:orders Resource: model:orders - Path: models/commerce/orders.sql + Path: sql/models/commerce/orders.sql Used (3) - ├─ ● macro:add_tax macros/python/currency.py:1 - ├─ ● macro:formatted_order_total models/commerce/macros/python/orders.py:5 - └─ ● macro:round_money macros/python/currency.py:5 + ├─ ● macro:add_tax sql/macros/python/currency.py:1 + ├─ ● macro:formatted_order_total sql/models/commerce/macros/python/orders.py:5 + └─ ● macro:round_money sql/macros/python/currency.py:5 ``` The remaining report sections follow the `Used` section as usual. The dependency graph comes from @@ -229,14 +230,14 @@ Explain the composed macro to inspect its direct graph and placement facts: ```console $ sqb scope model:orders --explain macro:formatted_order_total Explanation - └─ ● macro:formatted_order_total [macro; descendant-public; inherited_ancestor; params 1; role models/commerce/macros] models/commerce/macros/python/orders.py:5:1 + └─ ● macro:formatted_order_total [macro; descendant-public; inherited_ancestor; params 1; role sql/models/commerce/macros] sql/models/commerce/macros/python/orders.py:5:1 Owner: (none) - Owning path: models/commerce + Owning path: sql/models/commerce Consumers: model:orders, model:returns Dependencies: macro:add_tax, macro:round_money Grants: (none) Required scope: descendant-public - Required path: models/commerce + Required path: sql/models/commerce Promotion impact: (none) ``` @@ -253,7 +254,7 @@ sqb scope model:stg_orders --globals all sqb scope model:stg_orders \ --kind constant \ --kind enum \ - --defined-under models/finance + --defined-under sql/models/finance # Find visible or used settlement declarations sqb scope model:stg_orders --match '*settlement*' @@ -317,7 +318,7 @@ sqb scope model:stg_orders --used-only --dependency-depth 2 Use `--at` before creating a resource. A prospective file receives the declarations implied by that exact authored path. A prospective directory describes what a direct child resource would receive. ```bash -sqb scope --at models/staging/orders/new_model.sql +sqb scope --at sql/models/staging/orders/new_model.sql sqb scope --at tests/unit/staging/orders/ ``` @@ -336,7 +337,7 @@ independently of folder visibility. ```bash sqb scope model:stg_orders \ - --as-path models/marts/orders/stg_orders.sql + --as-path sql/models/marts/orders/stg_orders.sql ``` The destination must be a valid project-relative file path for that resource kind. This is a pure preview: `sqb scope` never moves files, edits declarations, or changes configuration. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md index 1a4fd97c9a..bad1fef717 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md @@ -344,7 +344,7 @@ receive the URL. "node_key": "model:fct_orders", "error_code": "E100", "message": "Conversion Error: Could not convert string 'n/a' to INT32", - "path": "models/marts/fct_orders.sql" + "path": "sql/models/marts/fct_orders.sql" } ], "failed_node_count": 1 @@ -652,8 +652,9 @@ forwards and backwards, read the last lines, fold runs of similar lines, search jump to error and warning lines, or download a node's output whole. No read loads a whole log at once. -A worker sends what it prints in batches of about 4 MB, or every 2 seconds. When a node prints -faster than the worker can send, the node waits for the worker. If the server stops accepting +A worker sends what it prints in batches of about 4 MB, or every 2 seconds. Each line keeps the +time the worker read it, to the millisecond. When a node prints faster than the worker can send, +the node waits for the worker. If the server stops accepting output for 30 seconds, the worker drops what it cannot send. It prints `Run output: N bytes of run output were not stored` to its log, with the reason, and adds the same warning to the run. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/test.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/test.md index 25362b1c78..0bcf57ad9d 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/test.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/test.md @@ -92,9 +92,9 @@ Details: ## Python tests -Python tests are pytest modules named `test_*.py` under `tests/python/`, `tests/providers/` and +Python tests are pytest modules named `test_*.py` under `tests/python/nodes/`, `tests/python/providers/` and `tests/orchestration/`. Each sits in the folder that mirrors the code it tests, so the tests of -`python/orders/storefront_import/node.py` live in `tests/python/orders/storefront_import/`, and +`python/nodes/orders/storefront_import/asset.py` live in `tests/python/nodes/orders/storefront_import/`, and the tests of the sensor `orchestration/sensors/orders/restock.py` in `tests/orchestration/sensors/orders/test_restock.py`. @@ -107,7 +107,7 @@ the tests of the sensor `orchestration/sensors/orders/restock.py` in | `sqb build` | Yes | Never | pytest runs from the project directory with the same Python as SQLBuild and with -`--import-mode=importlib`, so tests import project code as `python.orders...`, `providers...` or +`--import-mode=importlib`, so tests import project code as `python.nodes.orders...`, `providers...` or `orchestration.sensors...`. Its output appears after the SQL test summary, followed by `Python tests passed` or `Python tests failed`. `sqb test` exits non-zero when either kind fails. @@ -155,7 +155,7 @@ the node uses, resolved through [scopes](../concepts/declaration-scopes.md). A c count; `meta` does. A macro counts as changed when the Python file that defines it changes, or any project module it -imports, such as a helper under `python/`; when that code reads `ctx.vars`, a change to any project +imports, such as a helper under `python/nodes/`; when that code reads `ctx.vars`, a change to any project variable counts too. A [SQL macro](../concepts/macros/sql-macros.md) counts as changed when its arguments, result type or body change, or a project variable it reads; formatting, comments and its description do not count. A node that calls a SQL macro also uses every SQL macro that macro calls. An enum, constant or audit counts as changed when its declaration file @@ -171,7 +171,7 @@ Some inputs reach every test, so a change to any of them selects every test: - the `[settings]` that shape compiled models; - the adapter, `[connection]` and `[connections]` (including connection settings and adapter extensions), `[targets]` and the target in use, and project-local adapter modules under - `adapters/`. Their values are compared by digest and never printed; + `python/adapters/`. Their values are compared by digest and never printed; - the Python environment as the project records it: the git-tracked `pyproject.toml`, `uv.lock`, `poetry.lock`, `pdm.lock`, `Pipfile.lock` and `requirements*.txt` in the project directory or at the repository root, compared with line endings normalised. Untracked and ignored copies do not diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/custom.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/custom.md index 9cdc4ca2ac..c04ae611a5 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/custom.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/custom.md @@ -6,14 +6,14 @@ Online: https://sqlbuild.com/docs/concepts/adapters/custom/ -You can write your own adapter for any database engine by placing Python files under `adapters/` in your project directory. +You can write your own adapter for any database engine by placing Python files under `python/adapters/` in your project directory. ## Extending a built-in adapter The most common case is extending an existing adapter with custom behavior. Subclass the built-in adapter, set a new `adapter_name`, and override what you need: ```python -# adapters/duckdb_plus.py +# python/adapters/duckdb_plus.py from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter class DuckDbPlusAdapter(DuckDbAdapter): @@ -41,7 +41,7 @@ warehouse as the connection's `warehouse` key. For a database engine with no built-in support, subclass `BaseAdapter`. It provides ANSI SQL defaults for most methods - you only need to implement `connect`, `execute`, `close`, and any methods where your engine differs from standard SQL: ```python -# adapters/my_database.py +# python/adapters/my_database.py from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter class MyDatabaseAdapter(BaseAdapter): @@ -66,7 +66,7 @@ A few `StrictAdapter` methods are optional and have a documented default. `creat ## Discovery rules -- SQLBuild discovers all `.py` files under `adapters/` recursively (excluding `__init__.py` and files starting with `_`) +- SQLBuild discovers all `.py` files under `python/adapters/` recursively (excluding `__init__.py` and files starting with `_`) - Each file is scanned for classes that define a string `adapter_name` and subclass `StrictAdapter` (or any of its subclasses like `BaseAdapter` or a built-in adapter) - Adapter names must be unique across all adapter files - duplicates raise an error - Custom adapter names cannot shadow built-in names (`duckdb`, `motherduck`, `snowflake`, `bigquery`, `databricks`, `postgres`, `sqlite`, `sqlserver`, `clickhouse`) diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/snowflake.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/snowflake.md index 3c424b1006..26fa946341 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/snowflake.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/snowflake.md @@ -254,15 +254,26 @@ schema = "dev" Snowflake builds show a compact per-run busy-compute estimate. SQLBuild attributes visible overlapping query intervals fairly across active queries, converts attributed seconds using the -warehouse-size credit rate, and estimates USD from the configured rate: - -```toml -[cost] -usd_per_credit = 3.00 -``` - -The default is `3.00` USD per credit and is visibly marked as a default. Set it to your Snowflake -contract rate. Use `sqb cost`, `sqb cost latest`, `sqb cost `, or +warehouse-size credit rate, and estimates USD from a price per credit. The price is the first of: + +1. `usd_per_credit` under `[cost]`, your contract rate: + + ```toml + [cost] + usd_per_credit = 2.73 + ``` + +2. The account's rate sheet, `SNOWFLAKE.ORGANIZATION_USAGE.RATE_SHEET_DAILY`, when the connection's + role can read it (an organisation role). Without that permission SQLBuild moves on quietly. +3. Snowflake's public on-demand list price for the account's region at Enterprise edition, from the + Snowflake Service Consumption Table effective 2026-11-20. This is an estimate and shows as + "est."; a region not in SQLBuild's table is priced as AWS US East. + +The rate sheet or list price is looked up once per account per UTC day and kept in +`target/cost/credit_price.json`. Each row of `_sqlbuild_resource_costs` records the price it used +in `usd_per_credit` and where it came from in `usd_per_credit_source` (`config`, `rate_sheet` or +`list_price`). SQLBuild adds both columns to an existing table the first time it writes to it; rows +recorded before then leave them empty. Use `sqb cost`, `sqb cost latest`, `sqb cost `, or `sqb cost history --since 7d` to inspect persisted records. `--json` and `--json-output PATH` provide a versioned, decimal-safe output contract. Pending detail records are refreshed from Snowflake when inspected again. @@ -273,10 +284,18 @@ Under [`sqb server`](../../cli/server.md), the UI labels the same figures "estim | --- | --- | | Run | The run's total, then each model and each warehouse, most expensive first | | Model, Runs tab | The model's cost and query time in each build over the last 30 days | -| Overview | The last 7 or 30 days by job, folder and warehouse size | - -Figures are in dollars when `usd_per_credit` is set, and in credits with the default rate. A run -whose cost isn't final shows "Cost pending" or "Partial", never $0. +| Cost | A selection's cost over 7 or 30 days, by job and folder down to each model, against the period before, with a trend per day | +| Overview | The last 7 days' total, linking to the Cost page | + +Figures are in dollars, marked "est." when priced at the list price; their tooltips give the +credits, the price per credit and its source. A run whose cost isn't final shows "Cost pending" or +"Partial", never $0. + +The Cost page takes a selection as `sqb build --select` does, and the server resolves it against +the current deploy. The same reads are in the control API: `readCostSelection` returns each job's +cost on each selected model for the period and the one before, with daily series by job and +top-level folder, and `readCostSeries` returns daily series for up to 200 groups by job, folder +and model. The estimate is read from `INFORMATION_SCHEMA.QUERY_HISTORY` when the run finishes. If it can't be read within 30 seconds, the build is unaffected and its cost is recorded as `pending`; diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/audits.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/audits.md index 0535db467e..6f09161236 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/audits.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/audits.md @@ -46,7 +46,7 @@ For `warn` severity audits, the build continues and the failure is reported in t A reusable measurement audit separates the aggregate query from optional bounded evidence: ```sql --- audits/generic/valid_order_rate.sql +-- sql/audits/generic/valid_order_rate.sql AUDIT ( evaluation measurement, value valid_rate, @@ -162,7 +162,7 @@ is published as each audit finishes. ## Built-in audits -SQLBuild includes four generic audits out of the box. You do not need to define these in `audits/generic/` - they are available automatically: +SQLBuild includes four generic audits out of the box. You do not need to define these in `sql/audits/generic/` - they are available automatically: | Audit | Description | Parameters | |-------|-------------|------------| @@ -199,7 +199,7 @@ MODEL ( ### Overriding built-in audits -If you define a generic audit with the same name as a built-in (e.g. `audits/generic/not_null.sql`), your definition takes precedence. SQLBuild emits a warning so you're aware of the override: +If you define a generic audit with the same name as a built-in (e.g. `sql/audits/generic/not_null.sql`), your definition takes precedence. SQLBuild emits a warning so you're aware of the override: ``` warning[P003]: project audit 'not_null' overrides built-in audit 'not_null' @@ -211,18 +211,18 @@ Beyond the built-ins, you can define reusable SQL templates in a generic audit r | Location | Who can attach it | |----------|-------------------| -| `audits/generic/` | Resources anywhere in the project | +| `sql/audits/generic/` | Resources anywhere in the project | | `/_sqlbuild/audits/generic/` | Resources in `` and below | | `/_sqlbuild/_audits/generic/` | Resources directly in `` only | A generic audit must live under the nearest folder that contains every model, source, seed, or audit factory that attaches it. A top-level generic audit used only by models under -`models/marts/` fails to compile and names the folder it belongs in: +`sql/models/marts/` fails to compile and names the folder it belongs in: ``` -error[S024]: Declaration 'audit:non_negative' is currently project at 'audits/generic' (audits/generic/non_negative.sql); required exact-owner-private at 'models/marts'. Consumers: model:daily_revenue. Move it to 'models/marts/_sqlbuild/_audits/generic/' +error[S024]: Declaration 'audit:non_negative' is currently project at 'sql/audits/generic' (sql/audits/generic/non_negative.sql); required exact-owner-private at 'sql/models/marts'. Consumers: model:daily_revenue. Move it to 'sql/models/marts/_sqlbuild/_audits/generic/' audit: non_negative - --> audits/generic/non_negative.sql:1:1 + --> sql/audits/generic/non_negative.sql:1:1 ``` Attaching a scoped generic audit from a folder that cannot see it fails with `S006`. Built-in @@ -230,7 +230,7 @@ audits are available everywhere and are unaffected. See [Where to Put Declarations](declaration-scopes/placement.md). ```sql --- audits/generic/expression_is_true.sql +-- sql/audits/generic/expression_is_true.sql AUDIT (); SELECT * @@ -252,8 +252,8 @@ Generic audit SQL uses `@name` for parameter placeholders. These are resolved by Generic and singular audit SQL uses macros, constants, and enums available from the folder that owns the audit, not from a model or source that uses the audit. An audit in -`models/marts/_sqlbuild/_audits/generic/` sees the declarations a model in `models/marts/` sees; an -audit in the top-level `audits/` roles sees only project-wide declarations. Using a declaration +`sql/models/marts/_sqlbuild/_audits/generic/` sees the declarations a model in `sql/models/marts/` sees; an +audit in the top-level `sql/audits/` roles sees only project-wide declarations. Using a declaration that is not visible from there is a compile error. See [How Visibility Works](declaration-scopes/visibility.md). @@ -277,7 +277,7 @@ Every argument an attachment passes must be read by the audit's SQL or evidence the argument to remove, so a check is never silently broader or narrower than its attachment says: ```text -models/marts/fct_orders.sql audit 'expression_is_true' passes argument 'where_condition', which the audit's SQL in audits/generic/expression_is_true.sql never uses; remove 'where_condition' from the attachment +sql/models/marts/fct_orders.sql audit 'expression_is_true' passes argument 'where_condition', which the audit's SQL in sql/audits/generic/expression_is_true.sql never uses; remove 'where_condition' from the attachment ``` An argument that repeats one the attached resource supplies, such as `column`, is not checked. @@ -288,7 +288,7 @@ An attached audit can read other models, sources, seeds, and table functions bes for example to check that every value appears in a lookup table: ```sql --- audits/generic/known_status.sql +-- sql/audits/generic/known_status.sql AUDIT (); SELECT o.* @@ -325,7 +325,7 @@ to wait for its own dependants. That fails to compile with `P005`: error[P005]: Audit 'known_status' on model 'orders' reads model 'order_summary', which depends on 'orders'; an attached audit gates its target, so it cannot wait for a resource built from that target - = help: write a singular audit under audits/singular/ that references both 'orders' and + = help: write a singular audit under sql/audits/singular/ that references both 'orders' and 'order_summary'; it runs once both are built ``` @@ -336,7 +336,7 @@ cross-resource: a singular audit references two or more models, or at least one source, seed, or table function, through `__ref()`, `__source()`, `__seed()`, or `__table_fn()`. ```sql --- models/marts/_sqlbuild/audits/singular/orders_have_payments.sql +-- sql/models/marts/_sqlbuild/audits/singular/orders_have_payments.sql AUDIT ( name "completed_orders_have_payments", severity error @@ -361,12 +361,12 @@ Singular audits live only in a `singular/` role: | Location | What it may reference | |----------|-----------------------| -| `audits/singular/` | Resources whose nearest shared folder is the project root, such as models in sibling folders or a model and a source | +| `sql/audits/singular/` | Resources whose nearest shared folder is the project root, such as models in sibling folders or a model and a source | | `/_sqlbuild/audits/singular/` | Resources in `` and below | There is no `_audits/singular/` role, because singular audits are never attached by name. A singular audit must live under the nearest folder containing everything it references. Audit files -directly under `audits/` or in any other `audits/` child are compile errors. +directly under `sql/audits/` or in any other `sql/audits/` child are compile errors. SQLBuild infers where a singular audit runs from its references. When one referenced model is downstream of every other referenced model, the audit attaches to that model. Otherwise it runs at diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/column-lineage.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/column-lineage.md index f2f73c41bc..69ac4d6059 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/column-lineage.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/column-lineage.md @@ -116,7 +116,7 @@ sqb lineage fact_orders ``` ``` -Lineage model fact_orders models/marts/fact_orders.sql upstream +Lineage model fact_orders sql/models/marts/fact_orders.sql upstream ├── model stg_orders models/staging/stg_orders.sql │ └── source raw__orders sources/raw.yml @@ -133,7 +133,7 @@ sqb lineage daily_revenue --direction both ``` ``` -Lineage model daily_revenue models/marts/daily_revenue.sql both +Lineage model daily_revenue sql/models/marts/daily_revenue.sql both upstream ├── model stg_orders models/staging/stg_orders.sql diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/constants.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/constants.md index 7a89f9f1c9..4125e5e426 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/constants.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/constants.md @@ -12,21 +12,22 @@ SQL snippets. ## Create a constant -Put project-wide constants under the top-level `constants/` directory. Files are discovered +Put project-wide constants under the top-level `sql/constants/` directory. Files are discovered recursively, and one file may contain more than one declaration. ```text my_project/ -├── constants/ -│ ├── commerce/ -│ │ └── thresholds.sql -│ └── reporting_day.sql -├── models/ +├── sql/ +│ ├── constants/ +│ │ ├── commerce/ +│ │ │ └── thresholds.sql +│ │ └── reporting_day.sql +│ └── models/ └── sqlbuild_project.toml ``` ```sql --- constants/commerce/thresholds.sql +-- sql/constants/commerce/thresholds.sql CONSTANT (name min_items, value 7); CONSTANT (name fallback_source, value "web"); CONSTANT (name enabled, value true); @@ -34,7 +35,7 @@ CONSTANT (name ratio, value 0.75); CONSTANT (name missing_value, value null); ``` -Folders below `constants/` are organizational. They do not change where project-wide constants are +Folders below `sql/constants/` are organizational. They do not change where project-wide constants are available. ## Use a constant diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes.md index 7f3596a780..858bfa89d3 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes.md @@ -23,7 +23,7 @@ decide which files can access it. No TOML configuration is required. | Where the declaration lives | Who can use it | |-------------------------------------|--------------------| -| Top-level `macros/`, `constants/`, or `enums/` | The whole project | +| Top-level `sql/macros/`, `sql/constants/`, or `sql/enums/` | The whole project | | Nested `_sqlbuild/macros/`, `_sqlbuild/constants/`, or `_sqlbuild/enums/` | Files in the owner folder and folders below it | | Nested `_sqlbuild/_macros/`, `_sqlbuild/_constants/`, or `_sqlbuild/_enums/` | Files directly in the owner folder only | | An underscored constant or enum inside `MODEL()` | That model and its inline SQL hooks only | @@ -32,20 +32,20 @@ The same three placements apply to every kind of reusable declaration used by na | Kind | Project-wide role | Owner and below | Owner folder only | |------|-------------------|-----------------|-------------------| -| Macros | `macros/python/`, `macros/sql/` | `_sqlbuild/macros/python/`, `_sqlbuild/macros/sql/` | `_sqlbuild/_macros/python/`, `_sqlbuild/_macros/sql/` | -| Enums | `enums/` | `_sqlbuild/enums/` | `_sqlbuild/_enums/` | -| Constants | `constants/` | `_sqlbuild/constants/` | `_sqlbuild/_constants/` | -| Generic audits | `audits/generic/` | `_sqlbuild/audits/generic/` | `_sqlbuild/_audits/generic/` | -| Singular audits | `audits/singular/` | `_sqlbuild/audits/singular/` | Not supported | -| Reusable schemas | `schemas/` | `_sqlbuild/schemas/` | `_sqlbuild/_schemas/` | -| Named SQL hooks | `hooks/sql/` | `_sqlbuild/hooks/sql/` | `_sqlbuild/_hooks/sql/` | -| Python hooks | `hooks/python/` | `_sqlbuild/hooks/python/` | `_sqlbuild/_hooks/python/` | +| Macros | `sql/macros/python/`, `sql/macros/sql/` | `_sqlbuild/macros/python/`, `_sqlbuild/macros/sql/` | `_sqlbuild/_macros/python/`, `_sqlbuild/_macros/sql/` | +| Enums | `sql/enums/` | `_sqlbuild/enums/` | `_sqlbuild/_enums/` | +| Constants | `sql/constants/` | `_sqlbuild/constants/` | `_sqlbuild/_constants/` | +| Generic audits | `sql/audits/generic/` | `_sqlbuild/audits/generic/` | `_sqlbuild/_audits/generic/` | +| Singular audits | `sql/audits/singular/` | `_sqlbuild/audits/singular/` | Not supported | +| Reusable schemas | `sql/schemas/` | `_sqlbuild/schemas/` | `_sqlbuild/_schemas/` | +| Named SQL hooks | `sql/hooks/sql/` | `_sqlbuild/hooks/sql/` | `_sqlbuild/_hooks/sql/` | +| Python hooks | `sql/hooks/python/` | `_sqlbuild/hooks/python/` | `_sqlbuild/_hooks/python/` | Macro and Python hook declarations are Python files (`.py`). All other declarations are SQL files (`.sql`). Singular audits are never used by name, so they have no folder-only role; a scoped singular audit may reference only resources at or below its owner. -Functions (`functions/sql/`, `functions/python/`) stay project-wide. They are deployed warehouse +Functions (`sql/functions/sql/`, `sql/functions/python/`) stay project-wide. They are deployed warehouse objects and graph nodes, so a compile-time folder restriction would not match what the warehouse allows. @@ -54,7 +54,7 @@ allows. The annotation beside each directory shows where its contents are available: ```text -models/ +sql/models/ ├── constants/ published throughout models/ │ └── warehouse.sql └── commerce/ @@ -79,13 +79,13 @@ Legacy macro, enum, and constant roles directly below an owner remain supported; and hooks are scoped only through `_sqlbuild/`. `_sqlbuild/` is reserved for the declaration-role directories in the table above. Other direct -files or folders are rejected, as are unknown entries inside an `audits/` or `hooks/` role. It must +files or folders are rejected, as are unknown entries inside an `sql/audits/` or `sql/hooks/` role. It must also sit below a concrete owner directory. A project-root `_sqlbuild/` or authored-root path such as -`models/_sqlbuild/` is invalid; declarations at that boundary belong in the project-wide roots. +`sql/models/_sqlbuild/` is invalid; declarations at that boundary belong in the project-wide roots. A declaration file resolves the macros, enums, and constants it uses from its owner folder, not -from the role directory that contains it. A generic audit in `models/marts/_sqlbuild/_audits/generic/` -therefore sees the same declarations as a model in `models/marts/`. Those uses must be visible from +from the role directory that contains it. A generic audit in `sql/models/marts/_sqlbuild/_audits/generic/` +therefore sees the same declarations as a model in `sql/models/marts/`. Those uses must be visible from the owner folder, or compilation fails; they never change where the declaration itself must live. | Resource | Visible from the example tree | Not visible | diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/explorer.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/explorer.md index 1fc3f76411..b5d9a5e79d 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/explorer.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/explorer.md @@ -30,20 +30,21 @@ The examples below use two domains with project-wide currency helpers: ```text project/ -├── macros/ -│ └── currency.py add_tax, round_money -├── models/ -│ ├── commerce/ -│ │ ├── constants/limits.sql minimum_order_value -│ │ ├── enums/status.sql order_status -│ │ ├── macros/python/orders.py formatted_order_total -│ │ ├── orders.sql -│ │ └── returns/returns.sql -│ └── finance/ -│ ├── enums/status.sql finance_status -│ ├── macros/python/margin.py calculate_margin -│ ├── finance_summary.sql -│ └── reports/margin_report.sql +├── sql/ +│ ├── macros/ +│ │ └── currency.py add_tax, round_money +│ └── models/ +│ ├── commerce/ +│ │ ├── constants/limits.sql minimum_order_value +│ │ ├── enums/status.sql order_status +│ │ ├── macros/python/orders.py formatted_order_total +│ │ ├── orders.sql +│ │ └── returns/returns.sql +│ └── finance/ +│ ├── enums/status.sql finance_status +│ ├── macros/python/margin.py calculate_margin +│ ├── finance_summary.sql +│ └── reports/margin_report.sql └── tests/ └── unit/orders__completed_only.sql ``` @@ -51,7 +52,7 @@ project/ `formatted_order_total` composes the project-wide functions through ordinary Python calls: ```python -from macros.python.currency import add_tax, round_money +from sql.macros.python.currency import add_tax, round_money def formatted_order_total(expression: str) -> str: return round_money(add_tax(expression)) @@ -72,21 +73,21 @@ $ sqb scope model:orders Scope Target: model:orders Resource: model:orders - Path: models/commerce/orders.sql + Path: sql/models/commerce/orders.sql Used (2) - ├─ ● constant:minimum_order_value models/commerce/constants/limits.sql:1 - └─ ● macro:formatted_order_total models/commerce/macros/python/orders.py:4 + ├─ ● constant:minimum_order_value sql/models/commerce/constants/limits.sql:1 + └─ ● macro:formatted_order_total sql/models/commerce/macros/python/orders.py:4 Scope chain - ├─ exact-owner-private models/commerce (3) + ├─ exact-owner-private sql/models/commerce (3) ├─ descendant-public models (0) └─ project global (2) Available (3 of 5, 2 collapsed) - ├─ ● constant:minimum_order_value models/commerce/constants/limits.sql:1 - ├─ ○ enum:order_status models/commerce/enums/status.sql:1 - └─ ● macro:formatted_order_total models/commerce/macros/python/orders.py:4 + ├─ ● constant:minimum_order_value sql/models/commerce/constants/limits.sql:1 + ├─ ○ enum:order_status sql/models/commerce/enums/status.sql:1 + └─ ● macro:formatted_order_total sql/models/commerce/macros/python/orders.py:4 … 2 globals collapsed; run sqb scope model:orders --globals all ● used by this resource ○ not used by this resource --verbose for scope details @@ -99,7 +100,7 @@ dependency when `--dependency-depth` is nonzero. `○` marks a declaration prese not in `Used`. Add `--verbose` to see each declaration's access details, for example -`[enum; descendant-public; inherited_ancestor; members 4; type VARCHAR; role models/commerce/enums]`. +`[enum; descendant-public; inherited_ancestor; members 4; type VARCHAR; role sql/models/commerce/enums]`. Those labels translate to ordinary folder rules: | Output label | Meaning in this report | @@ -108,7 +109,7 @@ Those labels translate to ordinary folder rules: | `descendant-public` | Available from a folder at or above this resource | | `exact-owner-private` | Available directly in this resource's owner folder only | | `inherited_ancestor` | Visible because an unprefixed role publishes it down the folder tree | -| `role models/commerce/macros` | The declaration role begins at this path | +| `role sql/models/commerce/macros` | The declaration role begins at this path | In the scope chain, the first path is the resource's owner folder, followed by parent folders and the project declaration roles. The counts show declarations defined at each path; the chain label @@ -124,10 +125,10 @@ declarations. The expanded `Used` section is: ```console $ sqb scope model:orders --used-only --dependency-depth 1 Used (4) - ├─ ● constant:minimum_order_value models/commerce/constants/limits.sql:1 - ├─ ● macro:add_tax macros/python/currency.py:1 - ├─ ● macro:formatted_order_total models/commerce/macros/python/orders.py:4 - └─ ● macro:round_money macros/python/currency.py:5 + ├─ ● constant:minimum_order_value sql/models/commerce/constants/limits.sql:1 + ├─ ● macro:add_tax sql/macros/python/currency.py:1 + ├─ ● macro:formatted_order_total sql/models/commerce/macros/python/orders.py:4 + └─ ● macro:round_money sql/macros/python/currency.py:5 ``` SQLBuild derives these edges from actual Python calls, including nested calls and calls reached @@ -140,14 +141,14 @@ ordinary report appears first; its `Explanation` section is: ```console $ sqb scope model:orders --explain macro:formatted_order_total Explanation - └─ ● macro:formatted_order_total [macro; descendant-public; inherited_ancestor; params 1; role models/commerce/macros] models/commerce/macros/python/orders.py:4:1 + └─ ● macro:formatted_order_total [macro; descendant-public; inherited_ancestor; params 1; role sql/models/commerce/macros] sql/models/commerce/macros/python/orders.py:4:1 Owner: (none) - Owning path: models/commerce + Owning path: sql/models/commerce Consumers: model:orders, model:returns Dependencies: macro:add_tax, macro:round_money Grants: (none) Required scope: descendant-public - Required path: models/commerce + Required path: sql/models/commerce Promotion impact: (none) ``` @@ -158,20 +159,20 @@ explanation would then show that descendant-public placement is broader than nec ```console Explanation - └─ ● macro:formatted_order_total [macro; descendant-public; inherited_ancestor; params 1; role models/commerce/macros] models/commerce/macros/python/orders.py:4:1 + └─ ● macro:formatted_order_total [macro; descendant-public; inherited_ancestor; params 1; role sql/models/commerce/macros] sql/models/commerce/macros/python/orders.py:4:1 Owner: (none) - Owning path: models/commerce + Owning path: sql/models/commerce Consumers: model:orders Dependencies: macro:add_tax, macro:round_money Grants: (none) Required scope: exact-owner-private - Required path: models/commerce + Required path: sql/models/commerce Promotion impact: model:orders ● used by this resource ○ not used by this resource --verbose for scope details Diagnostics (1) - ERROR S008 models/commerce/macros/python/orders.py: Declaration 'macro:formatted_order_total' is currently descendant-public at 'models/commerce' (models/commerce/macros/python/orders.py); required exact-owner-private at 'models/commerce'. Consumers: model:orders. Move it to 'models/commerce/_sqlbuild/_macros/' + ERROR S008 sql/models/commerce/macros/python/orders.py: Declaration 'macro:formatted_order_total' is currently descendant-public at 'sql/models/commerce' (sql/models/commerce/macros/python/orders.py); required exact-owner-private at 'sql/models/commerce'. Consumers: model:orders. Move it to 'sql/models/commerce/_sqlbuild/_macros/' Completeness: complete ``` @@ -185,26 +186,26 @@ cannot use it. The relevant section is: ```console $ sqb scope model:orders --include-nearby Nearby unavailable (2 of 2) - ├─ ○ enum:finance_status models/finance/enums/status.sql:1 - └─ ○ macro:calculate_margin models/finance/macros/python/margin.py:4 + ├─ ○ enum:finance_status sql/models/finance/enums/status.sql:1 + └─ ○ macro:calculate_margin sql/models/finance/macros/python/margin.py:4 ``` The declarations are known, but they belong to a different folder branch. Here, the inspected -resource belongs to `models/commerce`, while the declarations belong to `models/finance`. +resource belongs to `sql/models/commerce`, while the declarations belong to `sql/models/finance`. `sibling_scope` is the compact output label for that situation. Ask for one complete explanation when you know a declaration's identity. After the ordinary report, the command adds: ```console $ sqb scope model:orders --explain macro:calculate_margin Explanation - └─ ○ macro:calculate_margin [macro; descendant-public; sibling_scope; params 2; role models/finance/macros] models/finance/macros/python/margin.py:4:1 + └─ ○ macro:calculate_margin [macro; descendant-public; sibling_scope; params 2; role sql/models/finance/macros] sql/models/finance/macros/python/margin.py:4:1 Owner: (none) - Owning path: models/finance + Owning path: sql/models/finance Consumers: model:finance_summary, model:margin_report Dependencies: (none) Grants: (none) Required scope: descendant-public - Required path: models/finance + Required path: sql/models/finance Promotion impact: (none) ``` @@ -222,10 +223,10 @@ report sections are: ```console $ sqb scope test:orders__completed_only --used-only Used (1) - └─ ● enum:order_status models/commerce/enums/status.sql:1 + └─ ● enum:order_status sql/models/commerce/enums/status.sql:1 Relationship grants (1 of 1) - └─ ● enum:order_status models/commerce/enums/status.sql:1 + └─ ● enum:order_status sql/models/commerce/enums/status.sql:1 ``` With `--verbose`, these rows show the reason `expected_model through model:orders`, which means **available through expected output @@ -242,21 +243,21 @@ Use `--as-path` to see the scope delta before moving an existing model, test, ho ordinary report is followed by: ```console -$ sqb scope model:orders --as-path models/finance/orders.sql +$ sqb scope model:orders --as-path sql/models/finance/orders.sql Move preview Resource: model:orders - Destination: models/finance/orders.sql + Destination: sql/models/finance/orders.sql Ownership root: models Retained (2) - ├─ ○ macro:add_tax macros/python/currency.py:1 - └─ ○ macro:round_money macros/python/currency.py:5 + ├─ ○ macro:add_tax sql/macros/python/currency.py:1 + └─ ○ macro:round_money sql/macros/python/currency.py:5 Gained (2) - ├─ ○ enum:finance_status models/finance/enums/status.sql:1 - └─ ○ macro:calculate_margin models/finance/macros/python/margin.py:4 + ├─ ○ enum:finance_status sql/models/finance/enums/status.sql:1 + └─ ○ macro:calculate_margin sql/models/finance/macros/python/margin.py:4 Lost (3) - ├─ ● constant:minimum_order_value models/commerce/constants/limits.sql:1 - ├─ ○ enum:order_status models/commerce/enums/status.sql:1 - └─ ● macro:formatted_order_total models/commerce/macros/python/orders.py:4 + ├─ ● constant:minimum_order_value sql/models/commerce/constants/limits.sql:1 + ├─ ○ enum:order_status sql/models/commerce/enums/status.sql:1 + └─ ● macro:formatted_order_total sql/models/commerce/macros/python/orders.py:4 Invalidated usages (2) - constant:minimum_order_value - macro:formatted_order_total @@ -271,31 +272,31 @@ be available but were never used. The preview does not move or rewrite any file. Inspect visibility before a resource exists: ```console -$ sqb scope --at models/commerce/returns/new_return.sql +$ sqb scope --at sql/models/commerce/returns/new_return.sql Scope - Target: models/commerce/returns/new_return.sql - Path: models/commerce/returns/new_return.sql + Target: sql/models/commerce/returns/new_return.sql + Path: sql/models/commerce/returns/new_return.sql Status: prospective Used (0) (none) Scope chain - ├─ exact-owner-private models/commerce/returns (0) - ├─ descendant-public models/commerce (3) + ├─ exact-owner-private sql/models/commerce/returns (0) + ├─ descendant-public sql/models/commerce (3) ├─ descendant-public models (0) └─ project global (2) Available (3 of 5, 2 collapsed) - ├─ ○ constant:minimum_order_value models/commerce/constants/limits.sql:1 - ├─ ○ enum:order_status models/commerce/enums/status.sql:1 - └─ ○ macro:formatted_order_total models/commerce/macros/python/orders.py:4 - … 2 globals collapsed; run sqb scope --at models/commerce/returns/new_return.sql --globals all + ├─ ○ constant:minimum_order_value sql/models/commerce/constants/limits.sql:1 + ├─ ○ enum:order_status sql/models/commerce/enums/status.sql:1 + └─ ○ macro:formatted_order_total sql/models/commerce/macros/python/orders.py:4 + … 2 globals collapsed; run sqb scope --at sql/models/commerce/returns/new_return.sql --globals all ● used by this resource ○ not used by this resource --verbose for scope details Diagnostics (1) - ERROR S013 models/commerce/returns/new_return.sql: Runtime usage and relationship facts are unavailable for a prospective path + ERROR S013 sql/models/commerce/returns/new_return.sql: Runtime usage and relationship facts are unavailable for a prospective path Completeness: partial ``` @@ -313,13 +314,13 @@ $ sqb scope model:orders --browse global Scope folders Path: global - ├─ constants/ 146 declarations, 18 used, 4 children; constant 146 + ├─ sql/constants/ 146 declarations, 18 used, 4 children; constant 146 sqb scope model:orders --browse global/constants sqb scope model:orders --list global/constants - ├─ enums/ 84 declarations, 11 used, 3 children; enum 84 + ├─ sql/enums/ 84 declarations, 11 used, 3 children; enum 84 sqb scope model:orders --browse global/enums sqb scope model:orders --list global/enums - └─ macros/ 231 declarations, 27 used, 8 children; macro 231 + └─ sql/macros/ 231 declarations, 27 used, 8 children; macro 231 sqb scope model:orders --browse global/macros sqb scope model:orders --list global/macros diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/placement.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/placement.md index d0f2d8643c..59ca0d6c95 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/placement.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/placement.md @@ -19,14 +19,14 @@ Online: https://sqlbuild.com/docs/concepts/declaration-scopes/placement/ Start with the ordinary project-wide directories unless you have a reason to limit access: ```text -macros/ -enums/ -constants/ -audits/generic/ -audits/singular/ -schemas/ -hooks/sql/ -hooks/python/ +sql/macros/ +sql/enums/ +sql/constants/ +sql/audits/generic/ +sql/audits/singular/ +sql/schemas/ +sql/hooks/sql/ +sql/hooks/python/ ``` Move a declaration closer to its users when it should be available only in one folder or one folder @@ -39,19 +39,19 @@ tree. | One model only | Inside that model's `MODEL()` header, for enums and constants | | SQL files directly in one directory | The underscored role under that directory's `_sqlbuild/`, such as `_sqlbuild/_macros/`, `_sqlbuild/_audits/generic/`, `_sqlbuild/_schemas/`, or `_sqlbuild/_hooks/sql/` | | A directory and its descendants | The unprefixed role under the nearest shared directory's `_sqlbuild/`, such as `_sqlbuild/constants/`, `_sqlbuild/audits/generic/`, `_sqlbuild/schemas/`, or `_sqlbuild/hooks/python/` | -| Sibling folders of one resource tree, such as `models/marts/` and `models/staging/` | The top-level role, such as `macros/`, `audits/generic/`, or `schemas/` | +| Sibling folders of one resource tree, such as `sql/models/marts/` and `sql/models/staging/` | The top-level role, such as `sql/macros/`, `sql/audits/generic/`, or `sql/schemas/` | | Different trees, such as models and tests, or models and sources | The top-level role | Singular audits have no folder-only role. A singular audit that references resources under one directory tree lives in that directory's `_sqlbuild/audits/singular/`; one that references a source, -a seed, or models in sibling top-level folders lives in `audits/singular/`. +a seed, or models in sibling top-level folders lives in `sql/audits/singular/`. ## One directory These two models use the same constant and both sit directly in `commerce/`: ```text -models/ +sql/models/ └── commerce/ ├── _sqlbuild/ │ └── _constants/ @@ -67,7 +67,7 @@ Use `_sqlbuild/_constants/` because no descendant directory needs the value. These models use the same constant across two child directories: ```text -models/ +sql/models/ └── commerce/ ├── _sqlbuild/ │ └── constants/ @@ -86,10 +86,11 @@ When a declaration is used directly from unrelated trees, make it project-wide: ```text my_project/ -├── constants/ -│ └── order_status.sql -├── models/ -│ └── commerce/orders.sql +├── sql/ +│ ├── constants/ +│ │ └── order_status.sql +│ └── models/ +│ └── commerce/orders.sql └── tests/ └── scenarios/order_lifecycle.sql ``` @@ -106,7 +107,7 @@ the audit cases returned by an audit factory. A child schema's `extends` counts child schema's owner folder. ```text -models/ +sql/models/ └── marts/ ├── _sqlbuild/ │ ├── _audits/generic/ diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/visibility.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/visibility.md index 0749dcbb8e..a19926cb5f 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/visibility.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/declaration-scopes/visibility.md @@ -27,7 +27,7 @@ SQLBuild starts from the file containing the SQL and walks up that file's direct directly containing the file is its **owner folder**. ```text -models/ +sql/models/ ├── constants/ available throughout models/ │ └── warehouse.sql └── commerce/ @@ -57,18 +57,18 @@ Grouped declaration directories can be placed below these SQL resource roots: | Root | Contents | |------|----------| -| `models/` | Models, inline model hooks, and scoped audits, schemas, and hooks | +| `sql/models/` | Models, inline model hooks, and scoped audits, schemas, and hooks | | `tests/unit/` | Unit tests | | `tests/scenarios/` | Scenarios | -| `functions/sql/` | SQL functions | -| `sources/` | Inline source expressions | +| `sql/functions/sql/` | SQL functions | +| `sql/sources/` | Inline source expressions | -Project-wide `audits/`, `schemas/`, and `hooks/` are declaration roles, not resource trees: they +Project-wide `sql/audits/`, `sql/schemas/`, and `sql/hooks/` are declaration roles, not resource trees: they cannot contain `_sqlbuild/` or other declaration directories. Scope an audit, schema, or hook by moving it under the `_sqlbuild/` folder of the models that use it. -Each root is a separate tree. For example, `models/constants/` does not make declarations available -under `tests/`. Put a declaration in the top-level `constants/`, `enums/`, or `macros/` directory +Each root is a separate tree. For example, `sql/models/constants/` does not make declarations available +under `tests/`. Put a declaration in the top-level `sql/constants/`, `sql/enums/`, or `sql/macros/` directory when it must be available across different resource trees. Project-root `_constants/`, `_enums/`, and `_macros/` directories are invalid because there is no owner folder at the project root for them to be private to. @@ -78,7 +78,7 @@ preferred layout because it keeps all declarations together without changing the Only the declaration-role directories listed on the [overview](../declaration-scopes.md) are valid directly under `_sqlbuild/`; other entries are rejected. `_sqlbuild/` must sit below a concrete owner directory. A project-root -`_sqlbuild/` or authored-root path such as `models/_sqlbuild/` is invalid; use the project-wide +`_sqlbuild/` or authored-root path such as `sql/models/_sqlbuild/` is invalid; use the project-wide roots at that boundary. ## Which file controls visibility? @@ -89,16 +89,16 @@ roots at that boundary. | Inline SQL hook in a model | The model file | | Unit test SQL | The test file, plus inferred tested-resource relationships | | Scenario SQL | The scenario file, plus expected-model enum and constant relationships | -| Named SQL hook | The owner folder of the hook's role, or the project root for `hooks/sql/` | -| SQL function | The function file under `functions/sql/` | -| Audit | The owner folder of the audit's role, or the project root for `audits/` | +| Named SQL hook | The owner folder of the hook's role, or the project root for `sql/hooks/sql/` | +| SQL function | The function file under `sql/functions/sql/` | +| Audit | The owner folder of the audit's role, or the project root for `sql/audits/` | | Reusable schema | The owner folder of the schema's role, for `extends` and enum column types | | Inline source expression | The source definition | This means a reusable named hook or audit does not change meaning depending on which model uses it. It uses declarations available from the folder that owns it: a hook in -`models/marts/_sqlbuild/hooks/sql/` sees the same macros, enums, and constants as a model directly -in `models/marts/`. +`sql/models/marts/_sqlbuild/hooks/sql/` sees the same macros, enums, and constants as a model directly +in `sql/models/marts/`. A model can name an audit, schema, or hook only when that declaration is visible from the model's folder, using the same rules as macros. Naming one from a sibling or parent folder fails with @@ -140,11 +140,11 @@ macro's production owner. SQLBuild infers tested macros from calls in `__macro_a filename or directory does not grant production visibility. ```text -models/orders/_sqlbuild/_macros/python/order_policy.py +sql/models/orders/_sqlbuild/_macros/python/order_policy.py tests/unit/macros/models/orders/test_order_policy__returns_quantity.sql ``` -The macro test can call `order_policy` without promoting it to the project-wide `macros/` root. A +The macro test can call `order_policy` without promoting it to the project-wide `sql/macros/` root. A test can also use helper macros scoped to its own test directory: ```text @@ -164,8 +164,8 @@ A macro file may import another project macro file when the imported macro is av importing file's location. The same directory rules apply as they do to SQL. ```python -# models/commerce/macros/python/orders.py -from macros.python.currency import round_money +# sql/models/commerce/macros/python/orders.py +from sql.macros.python.currency import round_money def formatted_total(expression: str) -> str: return round_money(expression) diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/diff.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/diff.md index 8f6d19b5ea..b4e59a7776 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/diff.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/diff.md @@ -246,7 +246,7 @@ Use `--max-models` and `--max-columns` to put explicit hard limits around a broa fails visibly instead of truncating the selected models or compared columns: ```bash -sqb diff prod:dev --bounded 14d --sample-rows 50000 --max-models 10 --max-columns 80 --select path:models/intermediate +sqb diff prod:dev --bounded 14d --sample-rows 50000 --max-models 10 --max-columns 80 --select path:sql/models/intermediate ``` These limits are optional and apply to the complete invocation. `--max-columns` checks the larger @@ -261,7 +261,7 @@ Diff requires `--select` in the current version. You can use any selector syntax sqb diff prod:dev --full --select customer_status_snapshot # Diff all models in a path -sqb diff prod:dev --schema-only --select path:models/marts +sqb diff prod:dev --schema-only --select path:sql/models/marts # Diff models with a specific tag sqb diff prod:dev --full --select tag:acceptance diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/enums.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/enums.md index 2aa4dd7789..d322c8e62e 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/enums.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/enums.md @@ -11,21 +11,22 @@ reference during compilation, then renders the selected value as a safe SQL lite ## Create an enum -Put project-wide enums under the top-level `enums/` directory. Files are discovered recursively, so +Put project-wide enums under the top-level `sql/enums/` directory. Files are discovered recursively, so subdirectories can organize a large enum library without changing where the enums are available. ```text my_project/ -├── enums/ -│ ├── fulfillment/ -│ │ └── fulfillment_method.sql -│ └── order_status.sql -├── models/ +├── sql/ +│ ├── enums/ +│ │ ├── fulfillment/ +│ │ │ └── fulfillment_method.sql +│ │ └── order_status.sql +│ └── models/ └── sqlbuild_project.toml ``` ```sql --- enums/fulfillment/fulfillment_method.sql +-- sql/enums/fulfillment/fulfillment_method.sql ENUM ( name fulfillment_method, members [DELIVERY, PICKUP, SHIPPING], diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/functions.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/functions.md index 8b44ef114e..e6ef1f5fe1 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/functions.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/functions.md @@ -16,7 +16,7 @@ Online: https://sqlbuild.com/docs/concepts/functions/ - Python function options - Adapter support -Functions are SQL or Python definitions under `functions/` that SQLBuild compiles and deploys to the warehouse alongside your models. They participate in the DAG: if a function definition changes, SQLBuild redeploys it, and every model that calls it directly treats the change as a change to its own query. +Functions are SQL or Python definitions under `sql/functions/` that SQLBuild compiles and deploys to the warehouse alongside your models. They participate in the DAG: if a function definition changes, SQLBuild redeploys it, and every model that calls it directly treats the change as a change to its own query. ## Scalar UDFs @@ -24,10 +24,10 @@ Scalar UDFs return a single value per row. They can be written in SQL or Python. ### SQL UDFs -Place SQL function files under `functions/sql/`. Each file has a `FUNCTION()` header declaring arguments and return type, followed by a SQL expression body. The header accepts `description`, `arguments`, `returns`, `database`, `schema`, and `tags`; any other key fails compilation with `D002`, naming the key and its file and line. `description` is required: a function without one fails compilation with `P010` (see [Descriptions](models/configuration.md#descriptions)): +Place SQL function files under `sql/functions/sql/`. Each file has a `FUNCTION()` header declaring arguments and return type, followed by a SQL expression body. The header accepts `description`, `arguments`, `returns`, `database`, `schema`, and `tags`; any other key fails compilation with `D002`, naming the key and its file and line. `description` is required: a function without one fails compilation with `P010` (see [Descriptions](models/configuration.md#descriptions)): ```sql --- functions/sql/udf__is_completed_order.sql +-- sql/functions/sql/udf__is_completed_order.sql FUNCTION ( description "Whether an order status counts as completed", arguments (order_status STRING), @@ -39,10 +39,10 @@ order_status = 'completed' ### Python UDFs -Place Python function files under `functions/python/`. Each file has exactly one function decorated with `@udf(...)`: +Place Python function files under `sql/functions/python/`. Each file has exactly one function decorated with `@udf(...)`: ```python -# functions/python/is_completed_order_py.py +# sql/functions/python/is_completed_order_py.py from sqlbuild.functions import udf @udf( @@ -74,14 +74,14 @@ The function name is the file stem (filename without extension). `__udf()` resol ## Table functions -Table functions return multiple rows and columns. Write them in SQL under `functions/sql/` with a `returns table(...)` declaration, or in Python under `functions/python/` with `@table_fn(...)`. +Table functions return multiple rows and columns. Write them in SQL under `sql/functions/sql/` with a `returns table(...)` declaration, or in Python under `sql/functions/python/` with `@table_fn(...)`. ### SQL table functions A SQL table function's body is a query: ```sql --- functions/sql/table_fn__customer_orders.sql +-- sql/functions/sql/table_fn__customer_orders.sql FUNCTION ( description "Customer orders", arguments (p_customer_id INTEGER), @@ -108,10 +108,10 @@ WHERE customer_id = p_customer_id ### Python table functions -A Python table function receives one whole partition of its input rows as a data frame and returns a data frame of rows. Use it for per-group numerics that SQL expresses badly, such as smoothing a series or fitting a curve per customer. Place it under `functions/python/`, with exactly one function decorated with `@table_fn(...)`: +A Python table function receives one whole partition of its input rows as a data frame and returns a data frame of rows. Use it for per-group numerics that SQL expresses badly, such as smoothing a series or fitting a curve per customer. Place it under `sql/functions/python/`, with exactly one function decorated with `@table_fn(...)`: ```python -# functions/python/smooth_payments.py +# sql/functions/python/smooth_payments.py import polars as pl from sqlbuild.functions import table_fn @@ -195,7 +195,7 @@ SQL functions can reference the same resources as models: These references are resolved at compile time and create DAG edges. If a referenced model changes, the function is redeployed. -A SQL function uses macros, constants, and enums available from its file under `functions/sql/`. +A SQL function uses macros, constants, and enums available from its file under `sql/functions/sql/`. See [How Visibility Works](declaration-scopes/visibility.md) to limit declarations to one function folder or to that folder and its children. @@ -208,7 +208,7 @@ A model that calls a changed function directly plans as `Function changed`, with ## Project layout ``` -functions/ +sql/functions/ sql/ udf__is_completed_order.sql # scalar SQL UDF table_fn__customer_orders.sql # table function (returns table) diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/incremental.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/incremental.md index beb0a47260..1015a2a290 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/incremental.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/incremental.md @@ -220,7 +220,7 @@ A cursor-based model must read at least one input that can bound its window, eit ``` error[P011]: incremental model 'daily_revenue' reads no inputs, so builds after the first cannot work out their cursor window - --> models/finance/daily_revenue.sql:5:3 + --> sql/models/finance/daily_revenue.sql:5:3 | 5 | cursor revenue_date, | ^^^^^^^^^^^^^^^^^^^ diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/interpolation.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/interpolation.md index 72b6c8528e..249b1bb5a6 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/interpolation.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/interpolation.md @@ -222,7 +222,7 @@ This is distinct from `@@name` (project variables) and `@sql.name()` or `@py.nam ## Named SQL hook parameters -Reusable hooks under `hooks/sql/` use `@name` for raw SQL substitution and `@'name'` for escaped SQL-literal substitution. These parameters are supplied by `sql("name", args...)` and resolved before the rest of the hook SQL is compiled. See [SQL hooks](models/hooks/sql.md#sql-hook-arguments) for value rendering and validation rules. +Reusable hooks under `sql/hooks/sql/` use `@name` for raw SQL substitution and `@'name'` for escaped SQL-literal substitution. These parameters are supplied by `sql("name", args...)` and resolved before the rest of the hook SQL is compiled. See [SQL hooks](models/hooks/sql.md#sql-hook-arguments) for value rendering and validation rules. ## Compilation order diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros.md index dc52f461d9..56b2a50d48 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros.md @@ -15,7 +15,7 @@ There are two kinds: |---|---|---| | Written as | A `.sql` file: a `MACRO` header and a SQL body | A Python function that returns SQL | | Called as | `@sql.name(...)` | `@py.name(...)` | -| Lives in | `macros/sql/` | `macros/python/` | +| Lives in | `sql/macros/sql/` | `sql/macros/python/` | | Arguments | Typed SQL expressions, checked against the caller's column types | Python values: strings, numbers, lists, dictionaries, references | | Logic | None: the body is SQL | Any Python: loops, conditions, adapter and target context | | Checks and tools | Each macro is checked on its own; `sqb format`, Rules and lineage see inside every call | Rules and lineage see the SQL each call returns | @@ -32,16 +32,17 @@ Each kind has its own folder: ```text my_project/ -├── macros/ -│ ├── python/ -│ │ └── labels.py -│ └── sql/ -│ └── cents_to_dollars.sql -├── models/ +├── sql/ +│ ├── macros/ +│ │ ├── python/ +│ │ │ └── labels.py +│ │ └── sql/ +│ │ └── cents_to_dollars.sql +│ └── models/ └── sqlbuild_project.toml ``` -A file directly under a `macros/` folder fails with `D013`, which names the subfolder to move it +A file directly under a `sql/macros/` folder fails with `D013`, which names the subfolder to move it to. A macro used by only part of the project can live in that folder instead, as `_sqlbuild/macros/sql/` or `_sqlbuild/_macros/python/`, and is then visible only there. See [Declarations and Scopes](declaration-scopes.md). @@ -90,7 +91,7 @@ exception because their contents are SQL. A macro that only tests use follows the usual [placement](declaration-scopes/placement.md) rule: it must be private to the narrowest folder that contains its uses, so the project-wide -`macros/` directory rejects it with `S024`. Put it in `_sqlbuild/_macros/python/` or +`sql/macros/` directory rejects it with `S024`. Put it in `_sqlbuild/_macros/python/` or `_sqlbuild/_macros/sql/` in the folder of the tests that call it, such as `tests/unit/orders/_sqlbuild/_macros/python/`, or, when those tests define `__expected__` output for a model, in that model's `_sqlbuild/_macros/`. The `S024` error names the folder to use. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/composition-and-context.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/composition-and-context.md index b58436f520..04e3606b54 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/composition-and-context.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/composition-and-context.md @@ -24,7 +24,7 @@ calling each other in their bodies. Use underscore-prefixed helpers for implementation details that should not be callable from SQL: ```python -# macros/python/currency.py +# sql/macros/python/currency.py def _divide_by_100(expression: str) -> str: return f"({expression} / 100.0)" @@ -52,8 +52,8 @@ def formatted_total(expression: str) -> str: Import another project macro when it is visible from the importing macro file: ```python -# macros/python/orders.py -from macros.python.currency import add_tax, round_money +# sql/macros/python/orders.py +from sql.macros.python.currency import add_tax, round_money def formatted_order_total(expression: str) -> str: return round_money(add_tax(expression)) @@ -73,7 +73,7 @@ The same visibility direction applies to scoped macros: - A project-wide macro cannot import a narrower macro. - A macro cannot import from a sibling or unrelated scope. -See [Declarations and Scopes](../declaration-scopes.md) when macros are stored under `macros/` +See [Declarations and Scopes](../declaration-scopes.md) when macros are stored under `sql/macros/` or `_macros/`. ## Macro output is final SQL @@ -89,7 +89,7 @@ def formatted_order_total(expression: str) -> str: SQLBuild rejects this output. Import and call the Python functions instead: ```python -from macros.python.currency import add_tax, round_money +from sql.macros.python.currency import add_tax, round_money def formatted_order_total(expression: str) -> str: return round_money(add_tax(expression)) @@ -117,7 +117,7 @@ When the first parameter is named `ctx`, SQLBuild passes a `MacroContext` with a project-variable information: ```python -# macros/python/datetime.py +# sql/macros/python/datetime.py def timestamp_trunc(ctx, grain: str, expression: str) -> str: if ctx.adapter_name == "bigquery": return f"TIMESTAMP_TRUNC({expression}, {grain.upper()})" diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/python-macros.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/python-macros.md index bf3eb2b3fa..aec3abb502 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/python-macros.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/python-macros.md @@ -25,13 +25,13 @@ compiler can see inside it. See [Macros](../macros.md) for how the two kinds com ## Create a Python macro -Put project-wide Python macros in Python files under `macros/python/`. Folder-scoped macros use the -same layout, such as `models/marts/_sqlbuild/_macros/python/`. +Put project-wide Python macros in Python files under `sql/macros/python/`. Folder-scoped macros use the +same layout, such as `sql/models/marts/_sqlbuild/_macros/python/`. Every public function defined by a macro file becomes callable from SQL: ```python -# macros/python/currency.py +# sql/macros/python/currency.py def cents_to_dollars(expression: str) -> str: """Convert a cents expression to dollars.""" return f"ROUND(CAST({expression} AS DOUBLE) / 100, 2)" @@ -109,7 +109,7 @@ Python nodes use. It has `kind` and `name` attributes, and formatting it into SQ relation with the adapter's quoting: ```python -# models/marts/_sqlbuild/_macros/python/unions.py +# sql/models/marts/_sqlbuild/_macros/python/unions.py from sqlbuild.refs import SqlResourceRef def union_all(relations: list[SqlResourceRef]) -> str: @@ -129,7 +129,7 @@ it arrived as a quoted string argument such as `@py.wrap('__ref("stg_orders")')` ``` error[P006]: model:order_summary depends on model:stg_orders through macro orders_base() model: order_summary - --> models/marts/_sqlbuild/_macros/python/orders.py + --> sql/models/marts/_sqlbuild/_macros/python/orders.py = help: write the reference in the model, or pass it in: @py.orders_base(__ref("stg_orders")) = help: the current value is [references] enforce_explicit = true (from sqlbuild_project.toml or its default); while migrating a project, to allow macro-generated references, set this in sqlbuild_project.toml: [references] @@ -147,7 +147,7 @@ Only public functions owned by the file are exported as macros. Prefix helpers, and type aliases with `_`: ```python -# macros/python/orders.py +# sql/macros/python/orders.py _DEFAULT_STATUS = "completed" def _status_filter(status: str) -> str: @@ -199,7 +199,7 @@ See [where a test-only macro lives](../macros.md#macros-used-only-by-tests). Macros work inside inline and named SQL hooks: ```python -# macros/python/permissions.py +# sql/macros/python/permissions.py def grant_target(target: str) -> str: return f"GRANT SELECT ON {target} TO analyst_role" ``` diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/sql-macro-reference.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/sql-macro-reference.md index 0eb7afd699..5c12fd372f 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/sql-macro-reference.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/sql-macro-reference.md @@ -162,9 +162,9 @@ These fail with `P017`, naming the argument, the expected type or column and wha ``` error[P017]: argument src of macro clean_orders() needs column is_deleted BOOLEAN; orders_raw has no column is_deleted - --> models/marts/orders_clean.sql:2:1 + --> sql/models/marts/orders_clean.sql:2:1 parameter declared here: - --> macros/sql/clean_orders.sql:3:14 + --> sql/macros/sql/clean_orders.sql:3:14 = help: pass a relation with these columns: order_id BIGINT, updated_at TIMESTAMP, is_deleted BOOLEAN ``` diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/sql-macros.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/sql-macros.md index db5b45f30c..ee9aebb54e 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/sql-macros.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/sql-macros.md @@ -37,34 +37,35 @@ that dialect. ## Create a SQL macro -Put each SQL macro in its own `.sql` file under `macros/sql/`. The file name is the macro name. -Python macros live next to it in `macros/python/`: +Put each SQL macro in its own `.sql` file under `sql/macros/sql/`. The file name is the macro name. +Python macros live next to it in `sql/macros/python/`: ```text my_project/ -├── macros/ -│ ├── python/ -│ │ └── labels.py -│ └── sql/ -│ ├── cents_to_dollars.sql -│ ├── clean_orders.sql -│ └── audit_columns.sql -├── models/ +├── sql/ +│ ├── macros/ +│ │ ├── python/ +│ │ │ └── labels.py +│ │ └── sql/ +│ │ ├── cents_to_dollars.sql +│ │ ├── clean_orders.sql +│ │ └── audit_columns.sql +│ └── models/ └── sqlbuild_project.toml ``` -A file directly under a `macros/` folder fails with `D013`, which names the subfolder to move it -to. Folder scopes use the same layout, such as `models/marts/_sqlbuild/_macros/sql/`. +A file directly under a `sql/macros/` folder fails with `D013`, which names the subfolder to move it +to. Folder scopes use the same layout, such as `sql/models/marts/_sqlbuild/_macros/sql/`. Rules that bound declaration folders, such as `SQBRDECLARATION304` (files per folder) and -`SQBRDECLARATION306` (shared filename prefixes), count `python/` and `sql/` as separate folders. To -split a full `sql/` folder, move files into subfolders such as `macros/sql/text/`: a SQL macro is +`SQBRDECLARATION306` (shared filename prefixes), count `python/nodes/` and `sql/` as separate folders. To +split a full `sql/` folder, move files into subfolders such as `sql/macros/sql/text/`: a SQL macro is named by its file, so it keeps its name and its callers stay unchanged. A SQL macro file starts with a `MACRO` header, then the body: ```sql --- macros/sql/cents_to_dollars.sql +-- sql/macros/sql/cents_to_dollars.sql MACRO ( description "Cents to dollars", arguments (amount_cents BIGINT, places INT CONST DEFAULT 2), @@ -114,7 +115,7 @@ scope, so a model can pass its own private constant; the macro receives only the A CTE-list macro inserts its CTEs, with its own names, into the caller's `WITH` list at the call: ```sql --- macros/sql/clean_orders.sql +-- sql/macros/sql/clean_orders.sql MACRO ( description "Deduplicated, non-deleted orders", arguments (src RELATION (order_id BIGINT, updated_at TIMESTAMP, is_deleted BOOLEAN)), @@ -166,7 +167,7 @@ even one named like a macro CTE. Later CTEs may read the prefixed ones too. A column-list macro inserts its columns into the caller's select list. Every column needs a name: ```sql --- macros/sql/audit_columns.sql +-- sql/macros/sql/audit_columns.sql MACRO ( description "Standard audit columns", arguments (src RELATION (created_at TIMESTAMP, updated_at TIMESTAMP)), @@ -232,7 +233,7 @@ Write every parameter as `@name` in the body, as [generic audits](../audits.md) identifier is always plain SQL, a column, CTE or table, never the parameter: ```sql --- macros/sql/is_status.sql +-- sql/macros/sql/is_status.sql MACRO ( description "Whether the status column matches", arguments (status VARCHAR), @@ -260,7 +261,7 @@ either one typed column or a `COLUMNS` group of columns the caller chooses, so o any grain: ```sql --- macros/sql/weekly_rates.sql +-- sql/macros/sql/weekly_rates.sql MACRO ( description "Weekly refund rate per grain", arguments (weekly RELATION (keys COLUMNS, order_count BIGINT, refund_count BIGINT)), @@ -291,7 +292,7 @@ fully typed. A SQL macro may call other SQL macros, and pass its own parameters on as `@name`: ```sql --- macros/sql/net_amount.sql +-- sql/macros/sql/net_amount.sql MACRO ( description "Net amount in dollars", arguments (gross_cents BIGINT, refund_cents BIGINT), @@ -320,7 +321,7 @@ folder-local macro beside it that its callers cannot see. - [Rules](../rules.md) and [column lineage](../column-lineage.md) read the expanded SQL, so they see through every call. A Rule finding inside an expansion is reported at the call, marked `(in SQL generated by @sql.name(...))`. The model's expanded SQL is in - `target/compiled/models/`, or in `target/compiled-failed/models/` when the Rules fail; see + `target/compiled/sql/models/`, or in `target/compiled-failed/sql/models/` when the Rules fail; see [When Rules fail](../../cli/compile.md#when-rules-fail). - Editing a macro recompiles its callers. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/model-private-values.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/model-private-values.md index ce3a77d0c4..5c53bad92e 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/model-private-values.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/model-private-values.md @@ -40,7 +40,7 @@ It is not available in: - Another model - A child or sibling model directory - A unit test or scenario -- A named SQL hook stored under `hooks/sql/` +- A named SQL hook stored under `sql/hooks/sql/` Private names begin with exactly one `_`. Names beginning with `__` are reserved for SQLBuild. Because the model owns the name, different models may each define `_state` without creating a diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models.md index 9a19b1ad84..8032496356 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models.md @@ -46,7 +46,7 @@ Write the name as exactly one double-quoted string, with no spaces or comments i ```text error[P012]: __ref(stg_orders) is not a valid __ref() call model: fact_orders - --> models/marts/fact_orders.sql:24:6 + --> sql/models/marts/fact_orders.sql:24:6 | 24 | FROM __ref(stg_orders) o | ^^^^^^^^^^^^^^^^^ diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/configuration.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/configuration.md index 56d8e08653..70ac9831d5 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/configuration.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/configuration.md @@ -24,7 +24,7 @@ Every `MODEL()` key must be one of the fields on this page. Any other key fails (`-- ...` and `/* ... */`) inside a header are ignored: ```text -error[D002]: MODEL() in 'models/fct_orders.sql:3' has unsupported keys: descripton +error[D002]: MODEL() in 'sql/models/fct_orders.sql:3' has unsupported keys: descripton = help: did you mean 'description'? ``` @@ -66,8 +66,8 @@ to add: ```text error[P010]: model 'orders_summary' has no description - --> models/marts/orders_summary.sql:1:1 - = help: to describe model 'orders_summary', add this to the MODEL header in models/marts/orders_summary.sql: + --> sql/models/marts/orders_summary.sql:1:1 + = help: to describe model 'orders_summary', add this to the MODEL header in sql/models/marts/orders_summary.sql: MODEL ( description "What one row of orders_summary represents", ... @@ -78,8 +78,8 @@ error[P010]: model 'orders_summary' has no description |----------|----------------------------| | Model | `MODEL (description "...")`, or the `description` of its `model_schema` | | Scenario | `SCENARIO (description "...")` | -| Seed | `description:` on its entry in `seeds/*.yml` | -| Source | `description:` on its entry in `sources/*.yml` | +| Seed | `description:` on its entry in `sql/seeds/*.yml` | +| Source | `description:` on its entry in `sql/sources/*.yml` | | SQL function or table function | `FUNCTION (description "...")` | | Python UDF | `@udf(description="...")` or the function docstring | | Named SQL hook | `HOOK (description "...")` | @@ -122,7 +122,7 @@ Quotes inside strings: - In a `'...'` string, `\'` and `''` both stand for one `'`, as in `'it\'s'` and `'it''s'`. ```text -error[D002]: MODEL(...) in 'models/customers.sql:2:34' contains invalid SQLBuild header syntax: a double quote ends this "..." string early; use """…""" for text containing double quotes +error[D002]: MODEL(...) in 'sql/models/customers.sql:2:34' contains invalid SQLBuild header syntax: a double quote ends this "..." string early; use """…""" for text containing double quotes = help: write the text between triple quotes, where quotes need no escaping: description """Matches "Miss"."""; sqb format --fix rewrites a description that escapes its quotes as \" or doubles them as "" ``` @@ -200,7 +200,7 @@ by kind: ```text error[P009]: `sql_analysis false` is not needed for model 'orders_summary' - --> models/marts/orders_summary.sql:4:3 + --> sql/models/marts/orders_summary.sql:4:3 = note: sqlbuild_project.toml sets [settings] require_sql_analysis = true, which only allows `sql_analysis false` on SQL that SQLBuild cannot parse; this model parses successfully. = help: remove `sql_analysis false` and fix the findings it was hiding: 2 unknown columns, 1 type mismatch (run `sqb compile` to see them) = help: to allow `sql_analysis false` on any model, SQL test or audit, set this in sqlbuild_project.toml: diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks.md index 4ccb251df4..2e8eb6e314 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks.md @@ -23,31 +23,32 @@ SQL and Python hooks live in language-specific directories: ```text my_project/ - models/ - marts/ - orders.sql - hooks/ - sql/ - permissions/ - grant_access.sql - record_access.sql - python/ - notifications.py + sql/ + models/ + marts/ + orders.sql + hooks/ + sql/ + permissions/ + grant_access.sql + record_access.sql + python/ + notifications.py ``` -Directories below `hooks/sql/` and `hooks/python/` are organizational. They do not namespace resource names: `hooks/sql/permissions/grant_access.sql` is still invoked as `sql("grant_access")`. +Directories below `sql/hooks/sql/` and `sql/hooks/python/` are organizational. They do not namespace resource names: `sql/hooks/sql/permissions/grant_access.sql` is still invoked as `sql("grant_access")`. Named hooks follow the same scope rules as macros. A hook used only by models under one folder lives under that folder's `_sqlbuild/`: | Location | Who can call it | |----------|-----------------| -| `hooks/sql/`, `hooks/python/` | Models anywhere in the project | +| `sql/hooks/sql/`, `sql/hooks/python/` | Models anywhere in the project | | `/_sqlbuild/hooks/sql/`, `/_sqlbuild/hooks/python/` | Models in `` and below | | `/_sqlbuild/_hooks/sql/`, `/_sqlbuild/_hooks/python/` | Models directly in `` only | ```text -models/ +sql/models/ marts/ _sqlbuild/ _hooks/ @@ -57,7 +58,7 @@ models/ ``` A hook must live under the nearest folder containing every model that calls it; a top-level hook -called only under `models/marts/` fails with `S024` and names the destination. Calling a hook that +called only under `sql/models/marts/` fails with `S024` and names the destination. Calling a hook that is not visible from the model's folder fails with `S006`. `inline_sql(...)` hooks are part of their model and are unaffected. See [Where to Put Declarations](../declaration-scopes/placement.md). @@ -78,8 +79,8 @@ Hook lists use three explicit entry types: | Entry | Definition | Use | |-------|------------|-----| | [`inline_sql("...")`](hooks/sql.md#inline-sql-hooks) | SQL written directly in the model header | Short, model-specific SQL | -| [`sql("name", args...)`](hooks/sql.md) | A reusable resource in a `hooks/sql/` role | Shared, parameterized SQL | -| [`python("name", args...)`](hooks/python.md) | A decorated function in a `hooks/python/` role | Control flow, providers, queries, or skips | +| [`sql("name", args...)`](hooks/sql.md) | A reusable resource in a `sql/hooks/sql/` role | Shared, parameterized SQL | +| [`python("name", args...)`](hooks/python.md) | A decorated function in a `sql/hooks/python/` role | Control flow, providers, queries, or skips | Bare SQL strings are not hook entries. The singular `pre_hook` and `post_hook` fields are also invalid; use `pre_hooks` and `post_hooks` with one of the three typed forms above. `sql("...")` always means a named SQL hook and never falls back to inline SQL. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks/python.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks/python.md index deab321342..e3418fa1c0 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks/python.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks/python.md @@ -23,11 +23,11 @@ For shared lifecycle ordering, failure timing, naming, and identity rules, see t ## Define a Python hook -SQLBuild discovers decorated functions recursively from `.py` files under `hooks/python/` and +SQLBuild discovers decorated functions recursively from `.py` files under `sql/hooks/python/` and under scoped `/_sqlbuild/hooks/python/` and `/_sqlbuild/_hooks/python/` roles; see [Hooks](../hooks.md#project-layout) for who can call each: -**`hooks/python/notifications.py`** +**`sql/hooks/python/notifications.py`** ```python from sqlbuild.hooks import hook diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks/sql.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks/sql.md index 6b8e75009c..0f0168ec71 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks/sql.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks/sql.md @@ -22,11 +22,11 @@ For shared lifecycle ordering, failure timing, naming, and identity rules, see t ## Reusable SQL hooks -SQLBuild discovers `.sql` files recursively under `hooks/sql/` and under scoped +SQLBuild discovers `.sql` files recursively under `sql/hooks/sql/` and under scoped `/_sqlbuild/hooks/sql/` and `/_sqlbuild/_hooks/sql/` roles; see [Hooks](../hooks.md#project-layout) for who can call each. Each file defines exactly one hook and must start with a `HOOK(...)` header as its first non-whitespace content. -**`hooks/sql/permissions/grant_access.sql`** +**`sql/hooks/sql/permissions/grant_access.sql`** ```sql HOOK ( @@ -36,17 +36,17 @@ HOOK ( GRANT SELECT ON @relation TO @role ``` -The hook name is always the filename stem, so this resource is invoked as `sql("grant_access", ...)`. Nested directories organize files but do not namespace names: `hooks/sql/admin/grant_access.sql` is still named `grant_access`. +The hook name is always the filename stem, so this resource is invoked as `sql("grant_access", ...)`. Nested directories organize files but do not namespace names: `sql/hooks/sql/admin/grant_access.sql` is still named `grant_access`. `HOOK()` accepts only a required, non-empty `description` ([Descriptions](../configuration.md#descriptions)). It does not accept a `name`; rename the file to rename the hook. The content after the header must be non-empty and becomes the SQL payload for each invocation. -Files beginning with `_` are skipped. All other `.sql` files under `hooks/sql/` are parsed as hook resources and must have a valid `HOOK()` header. +Files beginning with `_` are skipped. All other `.sql` files under `sql/hooks/sql/` are parsed as hook resources and must have a valid `HOOK()` header. ## Invoke a named hook Pass the hook name and its arguments from a model's `pre_hooks` or `post_hooks` list: -**`models/marts/orders.sql`** +**`sql/models/marts/orders.sql`** ```sql MODEL ( @@ -75,7 +75,7 @@ Named SQL hooks declare parameters by using them in the SQL body. Arguments are | `@name` | Raw substitution. Strings are inserted verbatim for relations, identifiers, keywords, or SQL fragments. | | `@'name'` | SQL-literal substitution. Strings are single-quoted and embedded quotes are escaped. | -**`hooks/sql/record_access.sql`** +**`sql/hooks/sql/record_access.sql`** ```sql HOOK ( @@ -136,7 +136,7 @@ Both named and inline SQL hooks receive the invoking model's runtime context. Th For named hooks, SQLBuild first substitutes `@name` and `@'name'` arguments into the hook body. A supplied argument such as `relation: "@@CTX:destination.qualified"` therefore resolves to the invoking model's final target-overridden destination. An inline hook uses macros, constants, and enums available to its model file. A named hook uses those -available from the folder that owns its role: project-wide declarations for `hooks/sql/`, or the +available from the folder that owns its role: project-wide declarations for `sql/hooks/sql/`, or the owner folder's declarations for `/_sqlbuild/hooks/sql/`. See [How Visibility Works](../../declaration-scopes/visibility.md#which-file-controls-visibility). @@ -185,7 +185,7 @@ MODEL ( SELECT order_id FROM __ref("stg_orders") ``` -**`models/marts/_sqlbuild/_hooks/sql/record_counts.sql`** +**`sql/models/marts/_sqlbuild/_hooks/sql/record_counts.sql`** ```sql HOOK (description "Record counts"); diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/schemas.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/schemas.md index b2ade1f3ef..775dbd35b2 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/schemas.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/schemas.md @@ -49,18 +49,18 @@ When multiple models implement the same relation shape, declare it once in a sch | Location | Who can bind it | |----------|-----------------| -| `schemas/` | Models anywhere in the project | +| `sql/schemas/` | Models anywhere in the project | | `/_sqlbuild/schemas/` | Models in `` and below | | `/_sqlbuild/_schemas/` | Models directly in `` only | A reusable schema must live under the nearest folder containing every model that binds it or -schema that extends it. A top-level schema bound only by models under `models/marts/` fails to -compile with `S024` and names the destination, such as `models/marts/_sqlbuild/_schemas/`. Binding +schema that extends it. A top-level schema bound only by models under `sql/models/marts/` fails to +compile with `S024` and names the destination, such as `sql/models/marts/_sqlbuild/_schemas/`. Binding a schema that is not visible from the model's folder fails with `S006`. See [Where to Put Declarations](../declaration-scopes/placement.md). ```sql --- schemas/orders/order.sql +-- sql/schemas/orders/order.sql SCHEMA ( name order, description "Canonical staged order shape", diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability.md index bd446baa2c..76f5c8fb71 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability.md @@ -12,11 +12,11 @@ of parsing terminal output. | You want to | Use | |-------------|-----| | Find out what a past run did: what ran, its SQL, audit results, errors and output | [Recall](observability/recall.md) and [`sqb recall`](../cli/recall.md) | -| Send events or output to your own systems, such as a message queue or a monitoring tool | [Typed sinks](observability/sinks.md) | +| Send events or output to your own systems, such as a message queue or a monitoring tool | [Typed sinks](observability/event-sinks.md) | | Store lifecycle events and query run state from your own Python application | [Execution history](observability/execution-history.md) | | Read the result of the command you just ran | Its final `--json` output | -Recall is on by default and covers investigation for people and agents. Sinks and execution history +Recall is on by default and covers investigation for people and agents. Event sinks and execution history are for building on SQLBuild's events elsewhere. The `stdout.log`, `stderr.log` and `diagnostics.jsonl` files under `logs//` hold the same output as Recall; prefer `sqb recall output`, which also works with a shared store. @@ -96,4 +96,4 @@ or failure. Sink delivery is bounded and best effort; destination failure does n warehouse work, and successful delivery does not prove the command succeeded. See [Recall](observability/recall.md) for the local history `sqb recall` queries, and -[Typed Sinks](observability/sinks.md) to export lifecycle and command-output records. +[Event sinks](observability/event-sinks.md) to export lifecycle and command-output records. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/sinks.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/event-sinks.md similarity index 58% rename from src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/sinks.md rename to src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/event-sinks.md index b24d36117f..3f8a4a3c8f 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/sinks.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/event-sinks.md @@ -1,27 +1,28 @@ -# Typed Sinks +# Event Sinks > Export lifecycle facts and command output through project-owned providers. -Online: https://sqlbuild.com/docs/concepts/observability/sinks/ +Online: https://sqlbuild.com/docs/concepts/observability/event-sinks/ ## Contents -- Lifecycle sink -- Command-output sink +- Lifecycle event sink +- Command-output event sink - Configuration - Delivery behavior -Project sinks consume one declared record type. Lifecycle and command-output streams remain separate +Project event sinks live in `python/event_sinks/` and are imported from `sqlbuild.event_sinks`. +Each consumes one declared record type. Lifecycle and command-output streams remain separate even when they share a provider and destination. -## Lifecycle sink +## Lifecycle event sink ```python -# sinks/publish.py -from providers.destination_client import DestinationClient -from sqlbuild.sinks import ( +# python/event_sinks/publish.py +from python.providers.destination_client import DestinationClient +from sqlbuild.event_sinks import ( LifecycleEvent, LifecycleEventKind, lifecycle_event_sink, @@ -48,12 +49,32 @@ Using `invocation_id` as a partition key keeps one invocation on one Kafka parti `event_id` in the payload as the deduplication identity. Confirm the destination topic is not compacted when complete lifecycle history must remain replayable. -## Command-output sink +### Invocation phases + +Before a command runs its first node, it publishes one `invocation_phase` event (kind +`invocation`) as each step of its preparation finishes. The payload's `phase` names the step, +`duration_ms` says how long it took, and `count`, `name` and `detail` add what the step reports: + +| `phase` | When | Also carries | +| ------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------- | +| `discovered` | the project's declarations and Python were read | `duration_ms` | +| `compiled` | the project compiled | `duration_ms`, `count` (models) | +| `matched` | a worker's compile matched its run's published snapshot | `duration_ms` | +| `discovered_set` | a worker read a saved discovered set its run uses | `name` (the set), `count` (items), `detail` (tags and when it was discovered) | +| `connected` | warehouse connections opened | `duration_ms`, `name` (adapter), `count` (connections) | +| `inspected` | the warehouse state the plan needs was read | `duration_ms` | +| `planned` | the plan was generated | `duration_ms`, `count` (nodes selected), `detail` (sub-steps) | +| `started_execution` | a build opened its connections and starts its nodes | `count` (concurrency), `detail` (connections) | + +A run's page shows these steps in its events, and a "Preparing" bar before the first node on its +timeline. A consumer that doesn't know a `phase` can ignore the event. + +## Command-output event sink ```python -from sqlbuild.sinks import CommandOutputRecord, command_output_sink, command_output_to_json +from sqlbuild.event_sinks import CommandOutputRecord, command_output_event_sink, command_output_to_json -@command_output_sink(streams={"stdout", "stderr"}) +@command_output_event_sink(streams={"stdout", "stderr"}) def publish_output(record: CommandOutputRecord, destination_client: DestinationClient) -> None: destination_client.publish( route="sqlbuild.command_output.v1", @@ -75,18 +96,18 @@ its stream. Runtime configuration can narrow declaration filters: ```toml -[sinks.lifecycle] +[event_sinks.lifecycle] event_kinds = ["run", "resource", "operation", "statement", "audit"] min_severity = "info" -[sinks.lifecycle.named.publish_lifecycle] +[event_sinks.lifecycle.named.publish_lifecycle] event_kinds = ["resource", "statement"] min_severity = "warning" ``` `shutdown_timeout` sets how long a command waits at exit for lifecycle sinks to drain queued events. It is a fixed duration from `"0s"` to `"10m"`, defaults to `"2s"`, and is accepted only -under `[sinks.lifecycle]`, not per named sink. `"0s"` drops anything still queued at exit. The +under `[event_sinks.lifecycle]`, not per named sink. `"0s"` drops anything still queued at exit. The final quarter of the budget is reserved for run and invocation outcomes: when it begins, other queued events are dropped and counted so the outcomes still arrive. The setting does not change the one-second timeout for each sink call. A sink call still running when the budget ends gets up to that one second to return before providers are torn down; teardown @@ -94,7 +115,7 @@ always runs on the command's own thread. A cancel that leaves a step running ski as described under [Providers](../python-nodes/providers.md#lifecycle). ```toml -[sinks.lifecycle] +[event_sinks.lifecycle] shutdown_timeout = "30s" ``` @@ -104,9 +125,9 @@ durability. SQLBuild core does not provide a Kafka or ClickHouse implementation. ## Delivery behavior -- `sqb compile` sends lifecycle sinks only its invocation events (`invocation_started` and its - outcome), never its phase `operation` events, so a sink never lengthens a compile with phase - deliveries. Other commands send every subscribed kind. +- `sqb compile` sends lifecycle sinks only its invocation start and outcome, never its + `invocation_phase` steps or phase `operation` events, so a sink never lengthens a compile with + phase deliveries. Other commands send every subscribed kind. - Each sink receives events on its own long-lived delivery thread. - An invocation's `invocation_started` arrives before its other events, and `invocation_completed` or `invocation_failed` after every other queued event. Events between them are prioritized: @@ -125,10 +146,15 @@ durability. SQLBuild core does not provide a Kafka or ClickHouse implementation. their model finishes), not in one burst at the end of the run. - When lifecycle events are dropped or fail, the command prints one warning to stderr with the counts and affected sinks, for example - `Warning: command completed successfully, but lifecycle event export was incomplete: 140 of 248 events dropped, 0 failed (sink 'orders_events'). Check sink health: a sink call slower than 1s drops that sink's events until it returns; events still queued at exit need a longer sinks.lifecycle.shutdown_timeout.` + `Warning: command completed successfully, but lifecycle event export was incomplete: 140 of 248 events dropped, 0 failed (sink 'orders_events'). Check sink health: a sink call slower than 1s drops that sink's events until it returns; events still queued at exit need a longer event_sinks.lifecycle.shutdown_timeout.` A successful command then ends with `sqb audit completed successfully; only its lifecycle event export is affected.` The exit code and stdout, including `--json` output, are unchanged. +- When a sink provider's `teardown` raises, the same warning reports it with the provider and the + error type, for example + `sink provider teardown failed ('kafka' (KafkaProducer) raised KafkaException); events the provider still held may not have been delivered.` + The error's message is not printed, because it can carry destination details. The exit code is + unchanged. In a run, the warning appears with the run's output and events. - Provider setup and declaration errors fail before execution because the project configuration is invalid. - Providers shared by multiple sinks are set up and torn down once per command. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/recall.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/recall.md index 63af938494..3528f1821a 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/recall.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/observability/recall.md @@ -321,20 +321,20 @@ runs, point it at ClickHouse; see ## Filtering what Recall stores By default Recall stores every lifecycle event and every output byte. To decide yourself, write a -[sink](sinks.md) with a parameter annotated `RecallWriter`: it replaces +[sink](event-sinks.md) with a parameter annotated `RecallWriter`: it replaces Recall's default for its stream, and Recall stores only what it publishes. ```python from sqlbuild.recall import RecallWriter -from sqlbuild.sinks import CommandOutputRecord, command_output_sink +from sqlbuild.event_sinks import CommandOutputRecord, command_output_event_sink -@command_output_sink +@command_output_event_sink def recall_output(record: CommandOutputRecord, writer: RecallWriter) -> None: redacted: bytes = record.data.replace(b"secret-token", b"[redacted]") writer.publish_command_output(record.replace(data=redacted)) ``` -- A `@command_output_sink` replacement receives each output chunk with its exact bytes in +- A `@command_output_event_sink` replacement receives each output chunk with its exact bytes in `record.data` (record schema version 2). `record.replace(data=…, message=…)` returns a copy that keeps the record ID and sequence; publish at most one record per call. - A `@lifecycle_event_sink` replacement receives each event its `event_kinds` and `min_severity` diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md index 61679c8862..3991713343 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md @@ -405,9 +405,9 @@ sqb rename stg_orders stg_orders_clean ```text Rename model stg_orders -> stg_orders_clean -├── models/marts/fact_orders.sql +├── sql/models/marts/fact_orders.sql │ └── 10:13 reference __ref("stg_orders") -> __ref("stg_orders_clean") -├── models/staging/stg_orders_clean.sql (moved from models/staging/stg_orders.sql) +├── sql/models/staging/stg_orders_clean.sql (moved from sql/models/staging/stg_orders.sql) │ └── 1:8 migration + migrate_from stg_orders └── orchestration/jobs/orders_refresh_job.toml └── 3:10 selector "+stg_orders+ fact_orders" -> "+stg_orders_clean+ fact_orders" @@ -415,7 +415,7 @@ Rename model stg_orders -> stg_orders_clean - Exact names are rewritten, including inside graph operators such as `+stg_orders+`, `,` and `~`. Tags, globs and `job:` selectors stay as written. -- A folder selector, such as `models/staging` or `path:models/staging/`, moves when every model +- A folder selector, such as `sql/models/staging` or `path:sql/models/staging/`, moves when every model under it moves to the same folder. When only some leave, the command lists a note at the selector to check by hand. - A selector in a multi-line TOML string is reported for a manual edit and blocks the refactor. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/planning/source-freshness.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/planning/source-freshness.md index d6d95a21f6..e8e6ba3e09 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/planning/source-freshness.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/planning/source-freshness.md @@ -41,7 +41,7 @@ read it, and pointing at the source declaration: ``` error[S405]: cannot build selected scope: 1 source table read by selected resources does not exist in the warehouse: - source 'raw_payments' (raw.payments), read by payments - = help: create or load the table, correct its database, schema, or table in the source declaration, or stop reading it from the selected models; declared 'raw_payments' at sources/raw.yml:16 + = help: create or load the table, correct its database, schema, or table in the source declaration, or stop reading it from the selected models; declared 'raw_payments' at sql/sources/raw.yml:16 ``` Create the table, fix the declaration, or leave the reading models out of the selection. Managed diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/project-configuration.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/project-configuration.md index 6fbd3b2b1a..b1c5c7cf2d 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/project-configuration.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/project-configuration.md @@ -28,7 +28,7 @@ Online: https://sqlbuild.com/docs/concepts/project-configuration/ - Pools - dbt - Skills -- Project Python +- Project layout - sqlbuild_local.toml Every key in `sqlbuild_project.toml`, which you commit, and `sqlbuild_local.toml`, which each @@ -531,7 +531,7 @@ This setting does not make unsupported adapter features portable. In particular, Per-directory model defaults. Useful for applying different config to different parts of your project. Each path default accepts any `MODEL()` header field; an unknown key fails compilation with `D001`: ```toml -[path_defaults."models/staging"] +[path_defaults."sql/models/staging"] materialized = "view" tags = ["staging"] @@ -541,7 +541,7 @@ tags = ["marts"] replay_on_change = "full" ``` -Path matching uses the path below `models/`. A model at `models/staging/stg_orders.sql` matches the +Path matching uses the path below `sql/models/`. A model at `sql/models/staging/stg_orders.sql` matches the `staging` path default. A key matches its folder and every folder below it. In a key, `*` matches one folder name and `**` matches any number of folders, so `"**"` matches every model. @@ -556,8 +556,8 @@ a model gets nothing from a broader key when a more specific key also matches it `*` segments, then fewer `**` segments. Two equally specific matches fail compilation. A broad `"**"` default therefore applies only to models that no other key matches. With the -configuration below, `models/orders.sql` gets the `"**"` description, but -`models/staging/stg_customers.sql` uses only the `staging` entry. It has no description and fails +configuration below, `sql/models/orders.sql` gets the `"**"` description, but +`sql/models/staging/stg_customers.sql` uses only the `staging` entry. It has no description and fails with `P010`: ```toml @@ -906,35 +906,89 @@ auto_update = false See [skills CLI reference](../cli/skills.md) for usage details. -## Project Python +## Project layout -Project-owned Python lives in a small set of roots. Anything that runs as part of the pipeline graph -goes in `python/`: loaders, assets, checks, factories, and the helper modules they import. -Modules under `python/` are normal Python: constants, classes, undecorated helper functions, and -helper-only modules such as `python/_helpers.py` are allowed, while decorators determine which -functions become graph nodes. See [Python nodes](python-nodes/overview.md#the-python-folder). +A project keeps everything the warehouse runs under `sql/` and everything SQLBuild imports as Python +under `python/`: -Code that extends SQLBuild itself keeps its own root: +```text +/ +├── sql/ everything the warehouse runs +│ ├── models/ +│ ├── seeds/ +│ ├── sources/ +│ ├── schemas/ +│ ├── macros/ +│ ├── functions/ SQL UDFs in functions/sql/, Python UDFs in functions/python/ +│ ├── enums/ +│ ├── constants/ +│ ├── audits/ +│ └── hooks/ +├── python/ everything SQLBuild imports as Python, as the `python` package +│ ├── nodes/ loaders, assets, checks and factories +│ ├── providers/ runtime providers +│ ├── event_sinks/ lifecycle event and command output event sinks +│ ├── materializations/ custom materializations +│ ├── adapters/ custom adapters (or a single python/adapter.py) +│ └── __init__.py optional +├── orchestration/ jobs, job groups, sensors and calendars +├── rules/ custom project rules +├── tests/ SQL tests, scenarios and Python tests +├── README.md optional +├── roles.toml optional project roles +├── sqlbuild_project.toml +└── sqlbuild_local.toml +``` + +Scoped declarations (`_sqlbuild/` folders beside models) live inside the resource tree they belong to. +Python modules are imported by their path below the project directory, such as +`python.nodes.orders.export.asset` or `python.providers.warehouse_client.provider`; see +[Python nodes](python-nodes/overview.md#the-pythonnodes-folder) for how node files are named. + +Compilation rejects any other entry at the top level, or inside `sql/` or `python/`, with `D018`: + +```text +error[D018]: 'migrations/' is not part of a SQLBuild project + = help: move it under one of: sql/, python/, orchestration/, rules/, tests/, + or list it in extra_paths in sqlbuild_project.toml if it belongs here on purpose +``` + +These entries are always allowed: + +- the two configuration files, `roles.toml` (see [project roles](../cli/server.md#define-project-roles)) and `README.md`; +- hidden entries such as `.gitignore`, `.env` and the `.agents/` and `.claude/` skill folders; +- `__pycache__/` at any level, and the `target/` and `logs/` folders SQLBuild writes at the top + level; +- local database files at the top level, ending in `.duckdb`, `.db`, `.sqlite` or `.sqlite3`, and + the write-ahead log, shared-memory and journal files beside them (ending in `.wal`, `-wal`, + `-shm` or `-journal`), such as `warehouse.duckdb` and `warehouse.duckdb.wal`; +- Python dependency files at the top level: `pyproject.toml`, `uv.lock`, `poetry.lock`, `pdm.lock`, + `Pipfile.lock` and `requirements*.txt`; +- the control store file and the run output folder `sqb dev` writes, when they are inside the + project; +- the file each `env_file` setting names (the project's and every target's), when it is inside the + project, such as `development.env`; +- anything the project's `.gitignore` files ignore, read from the project directory up to the + repository root, with the repository's `.git/info/exclude`. + +List anything else the project keeps on purpose in `extra_paths`, relative to the project directory: + +```toml +extra_paths = ["docs/", "sql/notes/"] +``` -| Location | Holds | -|----------|-------| -| `rules/` | Custom project rules | -| `materializations/` | Custom materializations | -| `adapters/`, `adapter.py` | Custom adapters | -| `providers/` | Runtime providers | -| `sinks/` | Lifecycle event and command output sinks | -| `hooks/python/` | Python model lifecycle hooks | -| `functions/python/` | Python UDFs | -| `macros/python/`, `enums/`, `constants/` and scoped `_macros/python/`, `_enums/`, `_constants/` | Python macros and declarations | -| `orchestration/` | Jobs and job groups as TOML in `jobs/` and `job_groups/`; calendars and sensors as Python in `calendars/` and `sensors/`. See [Orchestration](orchestration.md) | +Each entry names an entry at the top level, or directly inside `sql/` or `python/`, and must stay +inside the project. -Compilation rejects Python anywhere else with `D016`, so indirectly importable modules cannot create -an unofficial project structure. +Python is supported only under `python/`, `rules/`, `orchestration/`, `sql/hooks/python/`, +`sql/functions/python/`, `sql/macros/`, `sql/enums/`, `sql/constants/` and the scoped `_macros/`, +`_enums/` and `_constants/` folders. Compilation rejects Python anywhere else, such as a `.py` file in +`sql/models/`, with `D016`. The project's `tests/` directory holds SQL tests and scenarios, and pytest tests of project Python -under `tests/python/`, `tests/providers/` and `tests/orchestration/`, which `sqb test` runs; see -[Python tests](../cli/test.md#python-tests). Orchestrator code such as Dagster or Rivers definitions -lives outside the SQLBuild project directory and points at it; see +under `tests/python/nodes/`, `tests/python/providers/` and `tests/orchestration/`, which `sqb test` +runs; see [Python tests](../cli/test.md#python-tests). Orchestrator code such as Dagster or Rivers +definitions lives outside the SQLBuild project directory and points at it; see [Dagster](../integrations/dagster.md) and [Rivers](../integrations/rivers.md). ## sqlbuild_local.toml diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/assets.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/assets.md index ef57f80c6d..0c87689c16 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/assets.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/assets.md @@ -24,10 +24,10 @@ See [Python Nodes](overview.md) for the shared model and the SQL boundary rules. ## Defining an asset -Place Python files under `python/` and decorate functions with `@asset`: +Place Python files under `python/nodes/` and decorate functions with `@asset`: ```python -# python/exports/orders_export.py +# python/nodes/exports/orders_export.py from sqlbuild.assets import asset, AssetContext @asset diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/checks.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/checks.md index f37af2fd34..b654221e54 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/checks.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/checks.md @@ -22,12 +22,12 @@ Checks are separate graph nodes, not callbacks embedded in an asset. A check dec ## Defining a check -Place Python files under `python/` (the playgrounds use `python/checks/`) and decorate functions with `@check`. `depends_on` is required: +Place Python files under `python/nodes/` (the playgrounds use `python/nodes/checks/`) and decorate functions with `@check`. `depends_on` is required: ```python -# python/checks/orders.py +# python/nodes/checks/orders.py from sqlbuild.checks import check, CheckContext -from python.exports.orders import export_orders +from python.nodes.exports.orders import export_orders @check(depends_on=export_orders) def check_orders_exported(ctx: CheckContext): @@ -144,7 +144,7 @@ sqb check --select tag:exports | | Checks | Audits | |---|--------|--------| | Validates | Python assets, loaders, and SQL relations | SQL relations | -| Authored in | `python/` (Python) | `MODEL()` headers / `audits/` (SQL) | +| Authored in | `python/nodes/` (Python) | `MODEL()` headers / `sql/audits/` (SQL) | | Run by | `sqb build`, `sqb check` | `sqb build`, `sqb audit` | | Severity | `error`, `warn` | `error`, `warn` | diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/discovered-nodes.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/discovered-nodes.md index a8f09eefad..e95e02efdf 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/discovered-nodes.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/discovered-nodes.md @@ -21,7 +21,7 @@ Online: https://sqlbuild.com/docs/concepts/python-nodes/discovered-nodes/ A discover function asks an external system which items exist, and an asset with `for_each` runs once per item. The location calls the function when it publishes and saves its result in the snapshot, so every run executes exactly the nodes it published. ```python -# python/fulfilment/nodes.py +# python/nodes/fulfilment/nodes.py from sqlbuild.assets import AssetContext, asset from sqlbuild.discovery import Discovered, Item, discover from sqlbuild.refs import model @@ -50,7 +50,7 @@ With steps `pick`, `pack` and `ship`, where each waits on the one before, the gr ## Declaring a discovered set -- **`@discover`** marks a project function under `python/` that returns `Discovered`. Providers are injected by parameter name, as for any Python node. Pass `name=` to name the set something other than the function, and `check_every=` to have the location check it for changes (see [When discovery runs](#when-discovery-runs)). +- **`@discover`** marks a project function under `python/nodes/` that returns `Discovered`. Providers are injected by parameter name, as for any Python node. Pass `name=` to name the set something other than the function, and `check_every=` to have the location check it for changes (see [When discovery runs](#when-discovery-runs)). - **`Discovered`** is the only return form: `items`, plus optional set-wide `tags` and `max_parallel`. - **`Item`** has an `id`, a `depends_on` and `args`. - `id` is unique in the set, at most 200 characters, and uses only letters, digits and `_ . : -`. @@ -127,7 +127,7 @@ Only a location, including `sqb dev`, calls discover functions. Every other comp - **A set fails on its own.** It keeps its last good items, the location's health shows **Discovery failed** with the set and its error, and everything else publishes normally. A location that restarts reads the last good items from the server's current snapshot. - **Last good items that name a model, source, seed or job the project no longer has** aren't kept. That covers a publish that reuses a set after the model it names was renamed or removed: the set fails with an error naming the item and the missing node, and compiles as its placeholder until it's discovered again. -- **An item that depends on a `tag()` no node carries** still fails the whole publish, not only its set: tags are known only once the project compiles. The location keeps its current snapshot and reports the error. +- **An item that depends on a `tag()` no node carries** fails only its own set, with an error naming the item and the tag. Tags are known only once the project compiles, so the location compiles once more with that set's last good items, and everything else publishes. When those items name the missing tag too, the set compiles as its placeholder. - **A set that never succeeded** compiles as its **placeholder node**, `[*]`. Its `job()` and `tag()` dependants stay valid. A run that reaches it fails that node with `never discovered: `, and its downstream nodes are skipped. ## Outside a location diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/factories.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/factories.md index 6d2d78d77b..fafad76551 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/factories.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/factories.md @@ -15,7 +15,7 @@ Factories are an advanced feature. Most projects author nodes directly; reach fo A `@factory` function takes **no arguments** and returns one or more decorated node functions: ```python -# python/factories/exports.py +# python/nodes/factories/exports.py from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -39,16 +39,16 @@ A factory may return a single node or a list, tuple, or set of nodes. Every retu ## Where factories live -Factories live anywhere under `python/`, like every other Python node. The decorators on the returned functions decide each node's kind, so a factory may emit a single kind or a mix, and it can sit next to hand-written nodes in the same file. The playgrounds keep factories in `python/factories/`. +Factories live anywhere under `python/nodes/`, like every other Python node. The decorators on the returned functions decide each node's kind, so a factory may emit a single kind or a mix, and it can sit next to hand-written nodes in the same file. The playgrounds keep factories in `python/nodes/factories/`. -Factory modules are normal Python: constants, classes, and undecorated helpers are allowed, and shared helpers can live in their own modules, for example `python/factories/_helpers.py` imported as `from python.factories._helpers import TABLES`. +Factory modules are normal Python: constants, classes, and undecorated helpers are allowed, and shared helpers can live in their own modules, for example `python/nodes/factories/_helpers.py` imported as `from python.nodes.factories._helpers import TABLES`. ## Mixed-kind factories A single factory can generate a whole related pipeline at once - a loader, the asset that reads it, and a check on the result: ```python -# python/factories/orders.py +# python/nodes/factories/orders.py from sqlbuild.factories import factory from sqlbuild.loaders import loader from sqlbuild.assets import asset diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md index ed44768bec..2ee44a3cc1 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md @@ -27,18 +27,18 @@ Loaders are Python functions that load data into source tables. They replace exp ## How it works -1. Write a Python function under `python/` decorated with `@loader` -2. Declare a managed source in `sources/*.yml` with `managed: true` and **the same name as the loader function** +1. Write a Python function under `python/nodes/` decorated with `@loader` +2. Declare a managed source in `sql/sources/*.yml` with `managed: true` and **the same name as the loader function** 3. SQLBuild calls the function, writes returned rows to a staging table, then applies the configured write strategy to the target Loaders participate in the build lifecycle. When `sqb build` runs, managed sources are loaded before any dependent model is materialized. ## Defining a loader -Place Python files under `python/` in your project directory (the playgrounds use `python/loaders/`). Each file can contain one or more loader functions: +Place Python files under `python/nodes/` in your project directory (the playgrounds use `python/nodes/loaders/`). Each file can contain one or more loader functions: ```python -# python/loaders/raw_sources.py +# python/nodes/loaders/raw_sources.py from sqlbuild.loaders import loader from sqlbuild.executor.load.models import LoaderContext @@ -55,7 +55,7 @@ The function receives a `LoaderContext` and returns rows as a list of dicts, an ## Binding to a source -Declare a managed source in `sources/*.yml`. A managed source is bound to the loader function **with the same name** - there is no separate `loader` field: +Declare a managed source in `sql/sources/*.yml`. A managed source is bound to the loader function **with the same name** - there is no separate `loader` field: ```yaml sources: @@ -372,7 +372,7 @@ The `@loader` decorator accepts optional parameters that can also be set in the | Parameter | Description | |-----------|-------------| -| `depends_on` | List of loader and asset functions this loader depends on. Depending on one that reads SQL is a [warehouse round trip](overview.md#warehouse-round-trips) | +| `depends_on` | List of loader and asset functions this loader depends on, and [`job()` or `tag()` sets](sql-references.md#depending-on-a-job-or-a-tag), as for assets. Depending on one that reads SQL is a [warehouse round trip](overview.md#warehouse-round-trips) | | `destination` | Override the destination relation name (can include schema or database) | | `write_strategy` | `table`, `append`, `delete_insert`, or `merge` | | `cursor_column` | Column used for incremental cursor tracking | @@ -452,17 +452,22 @@ When a loader returns rows with columns not present in the existing target table ``` my-project/ python/ - loaders/ - raw_sources.py # loader functions - api_sources.py # more loader functions - sources/ - raw.yml # managed source declarations (managed: true) - models/ - staging/ - stg_customers.sql # __source("raw_customers") + nodes/ + raw/ + raw_customers/ + loader.py # one @loader + main.py + api_sources/ + loaders.py # a @factory that makes several loaders + sql/ + sources/ + raw.yml # managed source declarations (managed: true) + models/ + staging/ + stg_customers.sql # __source("raw_customers") ``` -SQLBuild imports all `.py` files under `python/` recursively (excluding `__init__.py`). Functions decorated with `@loader` become loaders; undecorated helpers do not become nodes. +SQLBuild imports all `.py` files under `python/nodes/` recursively (excluding `__init__.py`). Functions decorated with `@loader` become loaders; undecorated helpers do not become nodes. A `@loader` is declared in a file named `loader.py`, and a factory that makes only loaders in `loaders.py`; any other file name fails compilation with `D011` naming the file the declaration belongs in. ## Config reference diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/overview.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/overview.md index 43d0543a09..b3315617f5 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/overview.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/overview.md @@ -8,7 +8,7 @@ Online: https://sqlbuild.com/docs/concepts/python-nodes/overview/ ## Contents -- The `python/` folder +- The `python/nodes/` folder - The SQL boundary - Decorators - Identity tracking @@ -21,7 +21,7 @@ Online: https://sqlbuild.com/docs/concepts/python-nodes/overview/ Python nodes let your project grow beyond warehouse-only SQL while keeping the SQL graph clean. They are ordinary Python functions, decorated to become nodes in the same DAG as your SQL models, and they run as part of `sqb build`. -There are three kinds. The decorator says what each function is, so all of them live under one `python/` folder: +There are three kinds. The decorator says what each function is, so all of them live under one `python/nodes/` folder: | Kind | Decorator | Purpose | |------|-----------|---------| @@ -39,25 +39,44 @@ All three share the same decorator conventions, dependency model, selection synt Nodes can also be generated programmatically with [`@factory`](factories.md) instead of authored one at a time. -## The `python/` folder +## The `python/nodes/` folder -Anything that runs as part of the pipeline graph goes in `python/`: loaders, assets, checks, [factories](factories.md), and the helper modules they import. SQLBuild imports every `.py` file under `python/` recursively (except `__init__.py`) and registers each decorated function by its decorator. Undecorated functions and helper-only modules are allowed and never become nodes. +Anything that runs as part of the pipeline graph goes in `python/nodes/`: loaders, assets, checks, [factories](factories.md), and the helper modules they import. SQLBuild imports every `.py` file under `python/nodes/` recursively (except `__init__.py`) and registers each decorated function by its decorator. Undecorated functions and helper-only modules are allowed and never become nodes. -How you organize files inside `python/` is up to you. The playgrounds group nodes by kind: +Each node lives in a folder of its own under `python/nodes/`, in a file named for what it declares: + +| File | Declares | +|------|----------| +| `loader.py` | one `@loader` | +| `asset.py` | one `@asset` | +| `checks.py` | `@check` functions, or a factory that makes only checks | +| `loaders.py` | a `@factory` that makes only loaders | +| `assets.py` | a `@factory` that makes only assets | +| `factory.py` | a `@factory` that makes more than one kind | + +A folder holds one of these declaration files, plus `checks.py` for the checks of its node. Any other +file name for a declaration fails compilation with `D011`, which names the file the declaration +belongs in: + +```text +error[D011]: @asset 'orders_export' is declared in python/nodes/orders/export/node.py; an @asset is declared in asset.py +``` + +Helper modules, `main.py`, and role files such as `constants.py` and `models.py` may sit beside the +declaration file. `@discover` and `@audit_factory` functions are not node declarations and may sit in +any module under `python/nodes/`. The playgrounds group nodes by kind: ``` -python/ - _helpers.py # shared helpers, not nodes - loaders/orders.py - assets/orders_inputs.py - assets/orders_export.py - checks/orders_export.py - factories/regional.py +python/nodes/ + loaders/orders/loader.py + assets/prepare_raw_orders/asset.py + assets/orders_export/asset.py + checks/orders_export/checks.py ``` -Grouping by domain (`python/orders/`, `python/customers/`) works just as well, and a single file may mix kinds. A project that selects the [Python Rules](../rules/python-rules.md#laying-out-python) commits to grouping by domain, with each node in its own [unit folder](../rules/python-rules.md#writing-nodes-as-units) holding `node.py` and `main.py`: `SQBRPYTHON001` reports node-kind folders such as `python/loaders/` and modules directly under `python/`, and `SQBRPYTHON012` reports nodes declared outside a unit's `node.py`. Import other project modules through the `python` package, for example `from python.assets.orders_inputs import prepare_raw_orders` or `from python._helpers import normalize_status`. +Grouping by domain (`python/nodes/orders/`, `python/nodes/customers/`) works just as well. A project that selects the [Python Rules](../rules/python-rules.md#laying-out-pythonnodes) commits to grouping by domain, with each node in its own [unit folder](../rules/python-rules.md#writing-nodes-as-units) holding its declaration file and `main.py`: `SQBRPYTHON001` reports node-kind folders such as `python/nodes/loaders/` and modules directly under `python/nodes/`. Import other project modules by their path, for example `from python.nodes.assets.prepare_raw_orders.asset import prepare_raw_orders` or `from python.providers.warehouse_client.provider import WarehouseClient`. -Code that extends SQLBuild itself keeps its own folder, such as `rules/`, `materializations/`, `adapters/`, `providers/`, `sinks/`, `hooks/python/`, `functions/python/`, and `macros/`. Python outside the supported locations fails compilation with `D016`; see [Project Python](../project-configuration.md#project-python) for the full list. +Code that extends SQLBuild itself keeps its own folder, such as `rules/`, `python/materializations/`, `python/adapters/`, `python/providers/`, `python/event_sinks/`, `sql/hooks/python/`, `sql/functions/python/`, and `sql/macros/`. Python outside the supported locations fails compilation with `D016`; see [Project layout](../project-configuration.md#project-layout) for the full list. ## The SQL boundary diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/providers.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/providers.md index 2a3797646f..c7e4ebaf30 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/providers.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/providers.md @@ -25,10 +25,10 @@ Providers are shared runtime services that SQLBuild discovers, configures, and i ## Defining a provider -Create a `provider.py` in a capability folder under `providers/` (see [Project layout](#project-layout)). A provider is a class that subclasses `Provider` from `sqlbuild.providers`: +Create a `provider.py` in a capability folder under `python/providers/` (see [Project layout](#project-layout)). A provider is a class that subclasses `Provider` from `sqlbuild.providers`: ```python -# providers/warehouse_client/provider.py +# python/providers/warehouse_client/provider.py from sqlbuild.providers import Provider class WarehouseClient(Provider): @@ -84,7 +84,7 @@ You can also type-annotate the parameter for IDE support and compile-time valida ```python from sqlbuild.assets import asset -from providers.warehouse_client.provider import WarehouseClient +from python.providers.warehouse_client.provider import WarehouseClient @asset def export_orders(ctx, warehouse_client: WarehouseClient): @@ -105,7 +105,7 @@ Provider injection works in all Python node types: Python lifecycle hooks also support provider injection by parameter name: ```python -# hooks/python/notify.py +# sql/hooks/python/notify.py from sqlbuild.hooks import hook @hook @@ -150,7 +150,7 @@ Both approaches (parameter injection and `ctx.providers`) are equivalent. Parame Providers follow a lazy setup, reverse-teardown lifecycle scoped to the command invocation: -1. **Discovery** - on compile, SQLBuild discovers all `Provider` subclasses under `providers/` and validates their settings (from environment variables or field defaults). Missing [secrets](#secrets) follow the command's rules. +1. **Discovery** - on compile, SQLBuild discovers all `Provider` subclasses under `python/providers/` and validates their settings (from environment variables or field defaults). Missing [secrets](#secrets) follow the command's rules. 2. **Lazy setup** - the first time a provider is accessed during a build, SQLBuild reads its settings and calls `setup(ctx)`. Providers that are never used are never set up. 3. **Teardown** - after the command completes, `teardown()` is called on all providers that were set up, in reverse setup order. Teardown runs even if the build failed. The exception is a cancel that leaves a step with `max_parallel` running after 5 seconds: providers are then not torn down, as that step may still use them (see [Running items in parallel](discovered-nodes.md#running-items-in-parallel)). @@ -252,7 +252,7 @@ SQLBuild looks for each variable in the environment and then in the project's ```text $ sqb compile -error[D012]: provider 'slack_alerts' (providers/slack_alerts/provider.py) is missing secret SLACK_WEBHOOK_URL +error[D012]: provider 'slack_alerts' (python/providers/slack_alerts/provider.py) is missing secret SLACK_WEBHOOK_URL = help: set SLACK_WEBHOOK_URL in this shell or in .env, or pass --allow-missing-secrets where secrets aren't available ``` @@ -314,7 +314,7 @@ In the web UI, the plan page lists these nodes under **Can't run**, leaves them run** count, and disables **Run** until the secret is set. **Plan without these nodes** excludes them and plans the rest. -A [sink](../observability/sinks.md) runs with every command, so when its provider is missing +A [sink](../observability/event-sinks.md) runs with every command, so when its provider is missing a secret nothing can run: the plan says `sink needs ; every run uses sinks`, `sqb build` lists the same line in its `D012` error, and there is no selection that leaves the sink out. In `--json`, `cant_run` names the sink under `sinks`. @@ -332,7 +332,7 @@ location. ## Discovery rules -- Provider classes are discovered from `.py` files under `providers/` recursively +- Provider classes are discovered from `.py` files under `python/providers/` recursively - Files named `__init__.py` or starting with `_` are skipped - Each concrete (non-abstract) subclass of `Provider` is registered - Provider names must be globally unique across project resources @@ -364,30 +364,32 @@ Setting values, defaults included, are never published. ## Project layout -Give each provider its own folder under `providers/`, named for the capability it provides: +Give each provider its own folder under `python/providers/`, named for the capability it provides: ``` my-project/ - providers/ - warehouse_client/ - provider.py # the Provider subclass - constants.py - _helpers/ # private to warehouse_client - slack_notifier/ - provider.py - hooks/ - sql/ - record_notification.sql - python/ - notify.py python/ - orders/ - load_orders/ - node.py - main.py + providers/ + warehouse_client/ + provider.py # the Provider subclass + constants.py + _helpers/ # private to warehouse_client + slack_notifier/ + provider.py + nodes/ + orders/ + load_orders/ + loader.py + main.py + sql/ + hooks/ + sql/ + record_notification.sql + python/ + notify.py ``` -Discovery also accepts `.py` files directly in `providers/`. A project that selects the +Discovery also accepts `.py` files directly in `python/providers/`. A project that selects the [Python Rules](../rules/python-rules.md#laying-out-providers) reports them, along with anything else in a provider folder besides `provider.py`, its role files, `_helpers/` and `_classes/`. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/sql-references.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/sql-references.md index bddf27ac70..b5355016c3 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/sql-references.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/sql-references.md @@ -79,7 +79,7 @@ with `P008`: ``` error[P008]: asset:export_orders names model:fact_orders as 'fact_orders' in SQL passed to ctx.query() - --> python/exports/export.py:9 + --> python/nodes/exports/export.py:9 = help: declare it with depends_on=model("fact_orders") and use ctx.relation(model("fact_orders")) instead of the relation name = help: if 'fact_orders' is an external table that shares the name, qualify it with its schema = help: while migrating a project, allow hard-coded relation names with [references] enforce_explicit = false in sqlbuild_project.toml @@ -123,7 +123,8 @@ set [`[references] enforce_explicit = false`](../project-configuration.md#refere ## Depending on a job or a tag Naming every upstream model ties a node to model names that change with each rename or split. -`job()` and `tag()` from `sqlbuild.refs` depend on a whole set instead: +`job()` and `tag()` from `sqlbuild.refs` depend on a whole set instead, in an asset's or a loader's +`depends_on`: ```python from sqlbuild.refs import job, tag @@ -171,7 +172,6 @@ Compile fails when: by job, so if the dependant's job waits for the job it depends on while that job reads a node of the dependant's job, neither can start. The error names the nodes that close the loop; move them to another job; -- a loader declares one: loaders depend on loaders and assets named one by one; - the name has a code location prefix such as `job("billing:nightly_job")`, which is reserved for depending on other locations' jobs. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/refactoring.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/refactoring.md index 4eadfaf1cb..e80fced87a 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/refactoring.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/refactoring.md @@ -26,13 +26,13 @@ sqb rename hourly_order_activity order_activity_by_hour ```text Rename model hourly_order_activity -> order_activity_by_hour -├── models/marts/daily_activity_rollup.sql +├── sql/models/marts/daily_activity_rollup.sql │ ├── 10:5 header hourly_order_activity -> order_activity_by_hour │ └── 34:13 reference __ref("hourly_order_activity") -> __ref("order_activity_by_hour") -├── models/marts/hourly_activity_with_daily_context.sql +├── sql/models/marts/hourly_activity_with_daily_context.sql │ ├── 10:5 header hourly_order_activity -> order_activity_by_hour │ └── 36:15 reference __ref("hourly_order_activity") -> __ref("order_activity_by_hour") -└── models/marts/order_activity_by_hour.sql (moved from models/marts/hourly_order_activity.sql) +└── sql/models/marts/order_activity_by_hour.sql (moved from sql/models/marts/hourly_order_activity.sql) └── 1:8 migration + migrate_from hourly_order_activity Compiled: ok, 3 files changed ``` @@ -59,8 +59,8 @@ carries on from where it was. Nothing is backfilled. `sqb mv` does the same for a move to another folder, optionally with a new name: ```bash -sqb mv fact_orders models/reporting/ -sqb mv fact_orders models/reporting/order_facts.sql +sqb mv fact_orders sql/models/reporting/ +sqb mv fact_orders sql/models/reporting/order_facts.sql ``` A move also takes the model's private macros, enums, constants and other scoped declarations with it, @@ -74,11 +74,11 @@ sqb rename stg_customers.email email_address --dry-run ```text Rename column stg_customers.email -> email_address -├── models/marts/dim_customers.sql +├── sql/models/marts/dim_customers.sql │ ├── 16:5 column email -> email_address │ ├── 16:10 column + AS email │ └── 23:54 column email -> email_address -└── models/staging/stg_customers.sql +└── sql/models/staging/stg_customers.sql ├── 7:5 header email -> email_address └── 15:8 column + AS email_address Dry run: compiles, 2 files would change; nothing written @@ -110,7 +110,7 @@ If any location cannot be rewritten safely, the command lists it and writes noth ```text Rename column stg_payments.amount_cents -> amount_minor Cannot rename column:stg_payments.amount_cents automatically -└── models/marts/daily_revenue.sql:21:3 column amount_cents is referenced in SQL a macro generates; update the macro call by hand +└── sql/models/marts/daily_revenue.sql:21:3 column amount_cents is referenced in SQL a macro generates; update the macro call by hand Edit the listed locations, then run the command again. Refused; no files changed ``` diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/resource-identities.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/resource-identities.md index 6df3063a67..fc4620a5c0 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/resource-identities.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/resource-identities.md @@ -12,7 +12,7 @@ file by hand creates a new resource with no history, so use [`sqb rename`](../cl keep it. ```text -error[D016]: Invalid model identity 'DailyOrders' in models/DailyOrders.sql; +error[D016]: Invalid model identity 'DailyOrders' in sql/models/DailyOrders.sql; use snake_case 'daily_orders' ``` @@ -21,7 +21,7 @@ lowercase letters, digits and underscores. Double underscores are fine, as in `commerce__mart_v_order`. A resource named after its file takes the file name without the extension: -`models/daily_orders.sql` is the model `daily_orders`. Folders organise files but are not part of +`sql/models/daily_orders.sql` is the model `daily_orders`. Folders organise files but are not part of the name. ## Renaming a resource diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules.md index 1cb2bc4c52..aa9611b3d7 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules.md @@ -85,7 +85,7 @@ correctness still applies. Now consider a model that returns an arbitrary row because its `LIMIT` has no ordering: ```sql --- models/orders.sql +-- sql/models/orders.sql SELECT order_id FROM orders LIMIT 1 ``` @@ -99,7 +99,7 @@ The selected Rule reports the source location, problem, and remediation: ```text error[SQLCLEAN004]: Row selection is nondeterministic - --> models/orders.sql:2:36 + --> sql/models/orders.sql:2:36 | 2 | SELECT order_id FROM orders LIMIT 1 | ^ @@ -162,7 +162,7 @@ passes its configured Rules. This keeps diagnostics and source mutation separate SQLBuild maintains native built-in Rules for reusable requirements. SQL Rule codes begin with `SQLCLEAN`, for example `SQLCLEAN004`. Rules that read the project, such as `SQBRGRAPH101`, begin with `SQBR`. The `SQBRPYTHON` Rules check the project's Python: annotations, imports, function -shape and the layout of `python/`. They run only when `select` names `SQBRPYTHON` or one of its +shape and the layout of `python/nodes/`. They run only when `select` names `SQBRPYTHON` or one of its codes; see [Python Rules](rules/python-rules.md). `SQBRORCHESTRATION101` keeps job and sensor selections from listing nodes one by one; see [Orchestration Rules](rules/orchestration-rules.md). The `SQBRPERFORMANCE` Rules find @@ -255,7 +255,7 @@ Rules add about 14% to a cold compile and nothing to a warm one. See Select exact Rules or families and configure project-owned options. Understand diagnostics, exact exceptions, path ignores, and stale checks. - Check the project's Python for annotations, imports, function shape and the layout of `python/`. + Check the project's Python for annotations, imports, function shape and the layout of `python/nodes/`. Keep each domain's published layer free of consumer-specific variants. Catch Snowflake JSON payloads copied onto every row of a finer grain. Learn evaluation order, focused execution, and dependency-aware reuse. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/configuration-and-selection.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/configuration-and-selection.md index 66aa68cf3c..65dd96c9cc 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/configuration-and-selection.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/configuration-and-selection.md @@ -229,7 +229,7 @@ max_ranking_order_by = 5 # default `@const`: a model-private `constants (_status_pattern '...')` entry in the `MODEL` header when only that model uses it; a `CONSTANT (name status_pattern, value '...');` file in `_sqlbuild/_constants/` (that folder only) or `_sqlbuild/constants/` (that folder and below) of - the nearest folder holding every use; top-level `constants/` only for project-wide values. + the nearest folder holding every use; top-level `sql/constants/` only for project-wide values. Otherwise shorten the literal. When the identical literal is reported in other files, the help lists them (up to five) and names the nearest common folder and its constants directory. Literals produced by `@const` or a macro are not reported, and there is no automatic fix. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/overview.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/overview.md index 269095813b..7236c09f28 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/overview.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/overview.md @@ -38,11 +38,11 @@ from sqlbuild.rules import Finding, Project, RuleContext, rule @rule( code="XSQBRARCH002", message="The project must contain a final model directory", - remediation="Add models/final and place final outputs beneath it.", + remediation="Add sql/models/final and place final outputs beneath it.", ) def final_directory(*, ctx: RuleContext, project: Project) -> list[Finding]: del project - paths = ctx.project.tree.glob("models/final/**") + paths = ctx.project.tree.glob("sql/models/final/**") return [] if paths else [ctx.finding(subject="models")] ``` diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/rule-context.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/rule-context.md index 9e00f5d188..c6be80f9c2 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/rule-context.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/rule-context.md @@ -180,8 +180,8 @@ Reading the tree, or any common structure, raises `RuleUsageError` when: Use the compiler-owned tree rather than direct filesystem calls: ```python -parts = ctx.project.tree.relative_parts(path=model.path, under="models") -models = ctx.project.tree.resources_under("models/orders") +parts = ctx.project.tree.relative_parts(path=model.path, under="sql/models") +models = ctx.project.tree.resources_under("sql/models/orders") config = ctx.project.tree.read_text("rules/requirements.yaml") ``` diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/testing-and-determinism.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/testing-and-determinism.md index ebe9518280..3966585209 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/testing-and-determinism.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/custom-rules/testing-and-determinism.md @@ -28,7 +28,7 @@ def test_given_missing_order_id_when_evaluating_then_reports_finding() -> None: test_case=RuleCase( description="missing order identifier", source='MODEL (description "Orders");\nSELECT 1 AS customer_id\n', - path="models/final/customer_orders.sql", + path="sql/models/final/customer_orders.sql", expected_finding_count=1, ), ) @@ -60,7 +60,7 @@ passes, the case fails with `custom rule is not deterministic`. The usual module-level state, such as a set of already-seen models, that carries over from one subject to the next. Compute findings from the subject and `ctx` alone. -Keep Rule tests under the project's `tests/` directory, outside `tests/python/`, `tests/providers/` +Keep Rule tests under the project's `tests/` directory, outside `tests/python/nodes/`, `tests/python/providers/` and `tests/orchestration/`, such as in `tests/rules/`. `sqb test` runs only those three folders, so run Rule tests with pytest. @@ -137,7 +137,7 @@ Read supported project text and structure through `ctx.project.tree`: ```python text = ctx.project.tree.read_text("rules/requirements.yaml") -matches = ctx.project.tree.glob("models/*/interface/*.sql") +matches = ctx.project.tree.glob("sql/models/*/interface/*.sql") ``` Both positive and negative observations are tracked. If `glob` returns no paths, adding a matching diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/findings-and-exceptions.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/findings-and-exceptions.md index 833de2dc37..5b0ae237cd 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/findings-and-exceptions.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/findings-and-exceptions.md @@ -29,7 +29,7 @@ Use an exact exception for one known finding. Exceptions require a reason and ar ```toml [[rules.rule_exceptions]] rule = "SQLCLEAN004" -path = "models/examples/sample_orders.sql" +path = "sql/models/examples/sample_orders.sql" reason = "This example intentionally demonstrates one sampled row." ``` @@ -49,7 +49,7 @@ that CTE, so an exception can cover exactly one join: ```toml [[rules.rule_exceptions]] rule = "SQLCLEAN038" -path = "models/orders/order_checks.sql" +path = "sql/models/orders/order_checks.sql" relation = "order_policy" cte = "policy_checks" # optional: only the join inside this top-level CTE reason = "Every order is evaluated against every policy check." @@ -79,7 +79,7 @@ Use a path ignore when a documented project area intentionally follows a differe ```toml [[rules.rule_ignores]] rules = ["SQLCLEAN"] -paths = ["models/examples/**"] +paths = ["sql/models/examples/**"] reason = "Examples retain intentionally minimal SQL." ``` @@ -104,7 +104,7 @@ matching, including SQL tests and audits that are not graph resources: ```toml [[rules.rule_ignores]] rules = ["SQLCLEAN021"] -paths = ["models/**/intermediate_*.sql"] +paths = ["sql/models/**/intermediate_*.sql"] reason = "These intermediate SQL files intentionally preserve upstream columns." ``` @@ -120,11 +120,11 @@ exact entry to add instead: ```text error[SQBRSUPPRESSION000]: Inline Rule suppressions are not supported; declare the exception in sqlbuild_project.toml - --> models/orders/order_checks.sql:4:1 + --> sql/models/orders/order_checks.sql:4:1 = help: Remove this comment, then fix the SQLCLEAN038 finding, or record it as a reviewed exception in sqlbuild_project.toml: [[rules.rule_exceptions]] rule = "SQLCLEAN038" - path = "models/orders/order_checks.sql" + path = "sql/models/orders/order_checks.sql" relation = "order_policy" reason = "every order meets every policy" ``` diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/orchestration-rules.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/orchestration-rules.md index 31905927a5..c372c0f2ee 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/orchestration-rules.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/orchestration-rules.md @@ -23,7 +23,7 @@ error[SQBRORCHESTRATION101]: job 'nightly_orders_job' names 4 nodes in its selec ``` ```toml -select = "models/orders" +select = "sql/models/orders" ``` The Rule is selected with `SQBR` or `SQBRORCHESTRATION`, and with its exact code. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/performance-rules.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/performance-rules.md index f1f4d02b2d..b5b3f59563 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/performance-rules.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/performance-rules.md @@ -46,7 +46,7 @@ FROM __ref("orders") r, LATERAL FLATTEN(input => r.payload:lines) o, LATERAL FLA ```text error[SQBRPERFORMANCE101]: line_json copies o.value whole onto every row flattened from o.value:options - --> models/line_options.sql:7:3 + --> sql/models/line_options.sql:7:3 ``` The parent also counts as copied through a cast, a conversion such as `TO_JSON` or `TO_VARIANT`, @@ -83,7 +83,7 @@ JOIN __ref("orders") o ON o.order_id = l.order_id ```text error[SQBRPERFORMANCE102]: order_payload copies VARIANT from orders, one row per (order_id), onto rows keyed by (order_id, line_no), so the same value repeats on every row - --> models/order_lines_enriched.sql:12:3 + --> sql/models/order_lines_enriched.sql:12:3 ``` Read the fields the model needs, such as `o.payload:customer::string`, or leave the payload on the diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/published-layer-rules.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/published-layer-rules.md index 5be493a672..f992e47198 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/published-layer-rules.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/published-layer-rules.md @@ -40,8 +40,8 @@ them and is allowed. ```text error[SQBRGRAPH103]: sales__mart__orders__finance reads sales__mart__orders; published models must not read published models of their own domain - --> models/sales/mart/sales__mart__orders__finance.sql:1:1 - = help: Move the shared logic into a sales__int_* model that both published models read, or move this model into the domain that consumes it. To move it into intermediate: sqb mv sales__mart__orders__finance models/sales/intermediate/enriched/sales__int_enriched__orders__finance.sql + --> sql/models/sales/mart/sales__mart__orders__finance.sql:1:1 + = help: Move the shared logic into a sales__int_* model that both published models read, or move this model into the domain that consumes it. To move it into intermediate: sqb mv sales__mart__orders__finance sql/models/sales/intermediate/enriched/sales__int_enriched__orders__finance.sql ``` ## SQBRPROJECT107: one name shape per domain @@ -83,13 +83,13 @@ allowed_qualifiers = [ An entry with `paths` instead leaves out the published models whose file path, relative to the project and written with `/` separators, matches any of its globs. As in selectors and janitor -`exclude_patterns`, `*` also matches `/`, so `models/sales/mart/*` covers nested folders too. A +`exclude_patterns`, `*` also matches `/`, so `sql/models/sales/mart/*` covers nested folders too. A family published once per qualifier usually lives in one folder: ```toml [rules.rule_options.SQBRPROJECT107] allowed_qualifiers = [ - { paths = ["models/sales/mart/regional/*"], reason = "Published once per region." }, + { paths = ["sql/models/sales/mart/regional/*"], reason = "Published once per region." }, ] ``` diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/python-rules.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/python-rules.md index a5b92341ce..8e50231a65 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/python-rules.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/rules/python-rules.md @@ -2,7 +2,7 @@ # Python Rules -> Check the project's Python for annotations, imports, function shape and the layout of python/. +> Check the project's Python for annotations, imports, function shape and the layout of python/nodes/. Online: https://sqlbuild.com/docs/concepts/rules/python-rules/ @@ -10,7 +10,7 @@ Online: https://sqlbuild.com/docs/concepts/rules/python-rules/ - Selecting the Python Rules - Which files are checked -- Laying out `python/` +- Laying out `python/nodes/` - Writing nodes as units - Laying out providers - Laying out sensors and calendars @@ -32,7 +32,7 @@ select = ["SQBR", "SQBRPYTHON"] ```text error[SQBRPYTHON101]: function parameter 'ctx' must define a type annotation - --> hooks/python/alert.py:4:11 + --> sql/hooks/python/alert.py:4:11 = help: Annotate every parameter with the value type accepted by the function. ``` @@ -62,28 +62,28 @@ sqb rules run SQBRPYTHON ## Which files are checked -The Python Rules read every supported project Python file: the runtime package under `python/` and -the folders that extend SQLBuild, such as `hooks/python/`, `functions/python/`, `providers/`, -`rules/` and `macros/`. See [Project Python](../project-configuration.md#project-python) -for the full list. Under `tests/`, only the [Python tests](#testing-python) in `tests/python/` and -`tests/providers/` are checked, and only by the Rules marked `tests/`. +The Python Rules read every supported project Python file: the runtime package under `python/nodes/` and +the folders that extend SQLBuild, such as `sql/hooks/python/`, `sql/functions/python/`, `python/providers/`, +`rules/` and `sql/macros/`. See [Project layout](../project-configuration.md#project-layout) +for the full list. Under `tests/`, only the [Python tests](#testing-python) in `tests/python/nodes/` and +`tests/python/providers/` are checked, and only by the Rules marked `tests/`. -Rules marked `python/` in the [reference](#rule-reference) check only the runtime package, because +Rules marked `python/nodes/` in the [reference](#rule-reference) check only the runtime package, because they describe how its packages are organised. Rules marked `tests/` check only Python tests. The others check every file except Python tests. -## Laying out `python/` +## Laying out `python/nodes/` -`SQBRPYTHON001` and `SQBRPYTHON002` keep `python/` organised by what the code is for, not by what -kind of node it holds. Directly under `python/`, keep only domain packages, `utils/` for code no +`SQBRPYTHON001` and `SQBRPYTHON002` keep `python/nodes/` organised by what the code is for, not by what +kind of node it holds. Directly under `python/nodes/`, keep only domain packages, `utils/` for code no domain owns, and `__init__.py`: ```text -python/ +python/nodes/ __init__.py fulfillment/ shipment_export/ - node.py # @asset shipment_export + asset.py # @asset shipment_export main.py # main(), the unit's implementation utils/ currency/ @@ -94,29 +94,32 @@ These layouts are reported: | Finding | Example | Fix | |---|---|---| -| A module directly under `python/` | `python/report.py` | Move it into the domain that owns it | -| A folder named for a node kind or a role | `python/loaders/`, `python/_helpers/` | Group the nodes by domain instead | -| A package with a generic name | `python/inventory/common/` | Name it after what it owns | +| A module directly under `python/nodes/` | `python/nodes/report.py` | Move it into the domain that owns it | +| A folder named for a node kind or a role | `python/nodes/loaders/`, `python/nodes/_helpers/` | Group the nodes by domain instead | +| A package with a generic name | `python/nodes/inventory/common/` | Name it after what it owns | The generic names are `base`, `common`, `general`, `helpers`, `lib`, `misc`, `shared`, `util` and -`utils`. `utils/` is allowed directly under `python/`. A finding about a folder points at its +`utils`. `utils/` is allowed directly under `python/nodes/`. A finding about a folder points at its `__init__.py`, or at its first Python file when it has none. ## Writing nodes as units -A unit is one folder that declares one node, or one factory, and holds its implementation. +A unit is one folder that declares one node, or one factory, and holds its implementation. Its +declaration file is named for what it declares: `loader.py`, `asset.py`, `loaders.py`, `assets.py`, +`factory.py` or `checks.py`, as compilation requires (see +[Python nodes](../python-nodes/overview.md#the-pythonnodes-folder)). `SQBRPYTHON003` to `SQBRPYTHON012` keep each node in its own unit, grouped by domain: ```text -python/orders/ +python/nodes/orders/ constants.py # shared by the orders units partner_export/ - node.py # the @asset declaration + asset.py # the @asset declaration main.py # main(), the implementation checks.py # @check declarations for this unit _helpers/ # private functions for this unit refund_review/ - node.py # @asset + asset.py # @asset main.py ``` @@ -124,12 +127,12 @@ A unit folder may also hold `models.py`, `types.py`, `constants.py`, `exceptions `__init__.py`. The declaration only passes its arguments to `main()`: ```python -# python/orders/partner_export/node.py +# python/nodes/orders/partner_export/asset.py from sqlbuild.assets import AssetContext, asset from sqlbuild.executor.python_nodes.models import PythonNodeResult -from providers.partner_files.provider import PartnerFiles -from python.orders.partner_export.main import main +from python.providers.partner_files.provider import PartnerFiles +from python.nodes.orders.partner_export.main import main @asset(description="Write the daily partner orders file.") def partner_export(ctx: AssetContext, *, partner_files: PartnerFiles) -> PythonNodeResult: @@ -141,15 +144,15 @@ These are reported: | Code | Finding | Fix | |---|---|---| | `SQBRPYTHON003` | A unit without `main.py`, or another module or folder in it | Add `main.py`; move other code into `_helpers/` or a role file | -| `SQBRPYTHON004` | `node.py` holding a helper, a constant, a class or a second declaration | Keep one `@loader`, `@asset` or `@factory` function and its imports | +| `SQBRPYTHON004` | A declaration file holding a helper, a constant, a class or a second declaration | Keep one `@loader`, `@asset` or `@factory` function and its imports | | `SQBRPYTHON005` | A declaration that does more than `return main(...)`, or passes a positional argument | Move the logic into `main()` and pass every argument as `name=value` | | `SQBRPYTHON006` | `main.py` holding more than one function, or a `main()` whose return annotation does not fit the node | Move other code into `_helpers/` and annotate `main()` with its result | | `SQBRPYTHON007` | A signature other than `(ctx: Context, *, provider: ProviderClass)` | Take `ctx` positionally and providers after `*`, each annotated | -| `SQBRPYTHON008` | An import of another unit's `main.py`, role files or `_helpers/`, or another domain's code | Import shared code from `python/utils/` or the domain's role files | +| `SQBRPYTHON008` | An import of another unit's `main.py`, role files or `_helpers/`, or another domain's code | Import shared code from `python/nodes/utils/` or the domain's role files | | `SQBRPYTHON009` | `checks.py` holding other code, or a check that does not depend on the unit's node | Name the unit's node in `depends_on` and return directly | | `SQBRPYTHON010` | A factory that does not loop over the unit's specs, or a generated node without `name=` | Loop over specs from the unit's `constants.py` or `models.py` and name each node | | `SQBRPYTHON011` | A docstring on a node or check, an asset or check without `description=`, or a described loader | Use `description=`; a loader takes its description from its managed source | -| `SQBRPYTHON012` | A node declared outside a unit's `node.py`, or a check outside its `checks.py` | Move it into its own unit folder | +| `SQBRPYTHON012` | A node declared outside the unit file named for its kind, or a check outside its `checks.py` | Move it into its own unit folder, in the file named for what it declares | `main()` returns: @@ -158,12 +161,12 @@ These are reported: | `@asset` | `PythonNodeResult` or `PythonNodeSkipResult`, from `ctx.result(...)` and `ctx.skip(...)` | | `@loader` | rows such as `list[...]` or `Iterator[...]`, `LoaderResult`, `LoaderSkipResult`, or `None` | -A unit may import another unit's `node.py` only to name that node in `depends_on`. It may import +A unit may import another unit's declaration file only to name that node in `depends_on`. It may import `provider.py`, `models.py`, `types.py`, `constants.py` and `exceptions.py` from -`providers//`. +`python/providers//`. -A factory's `node.py` holds one `@factory` function, and a check generated by a factory may stay in -`node.py`. `@audit_factory` functions are not units and may sit anywhere under `python/`. +A factory's declaration file holds one `@factory` function, and a check generated by a factory may +stay in it. `@audit_factory` functions are not units and may sit anywhere under `python/nodes/`. ## Laying out providers @@ -171,7 +174,7 @@ A factory's `node.py` holds one `@factory` function, and a check generated by a private code beside it: ```text -providers/ +python/providers/ storefront_api/ provider.py # the one public Provider subclass models.py @@ -186,9 +189,9 @@ A capability folder may also hold `types.py`, `constants.py`, `exceptions.py`, ` | Code | Finding | Fix | |---|---|---| -| `SQBRPYTHON013` | A module directly in `providers/`, a capability folder without `provider.py`, or another module or folder in it | Move it to `providers//provider.py`, `_helpers/`, `_classes/` or a role file | +| `SQBRPYTHON013` | A module directly in `python/providers/`, a capability folder without `provider.py`, or another module or folder in it | Move it to `python/providers//provider.py`, `_helpers/`, `_classes/` or a role file | | `SQBRPYTHON014` | `provider.py` holding a function, a public constant, another class or a second provider | Keep one public `Provider` subclass and private constants; move the rest to `_helpers/`, `_classes/` or `constants.py` | -| `SQBRPYTHON015` | An import of a provider's `_helpers/` or `_classes/` from outside its folder, or a provider importing `python/` outside `utils/` or anything in `orchestration/` | Import the provider through `provider.py` or its role files; share code through `python/utils/` | +| `SQBRPYTHON015` | An import of a provider's `_helpers/` or `_classes/` from outside its folder, or a provider importing `python/nodes/` outside `utils/` or anything in `orchestration/` | Import the provider through `provider.py` or its role files; share code through `python/nodes/utils/` | `SQBRPYTHON014` follows a class's bases through the project's modules, so a provider may subclass `Provider` through an alias or a base class in `_classes/`. A class whose base comes from another @@ -218,38 +221,39 @@ A domain folder's private support is `_models.py`, `_types.py`, `_constants.py`, | Code | Finding | Fix | |---|---|---| | `SQBRPYTHON016` | A module directly in `sensors/` or `calendars/`, nested below its domain folder, or named `main.py`, `definitions.py`, `sensors.py`, `calendars.py` or `processing.py` | Move it to `//.py` | -| `SQBRPYTHON017` | Other private files or folders, private support outside a domain folder, or an import of another domain's private support | Use the support files or `_helpers/`; share code through `python/utils/` or a provider | +| `SQBRPYTHON017` | Other private files or folders, private support outside a domain folder, or an import of another domain's private support | Use the support files or `_helpers/`; share code through `python/nodes/utils/` or a provider | | `SQBRPYTHON018` | A sensor or calendar module holding a function, a class, a public constant or another statement besides its declaration | Move it to `_helpers/`, `_models.py` or `_constants.py` | -| `SQBRPYTHON019` | A sensor or calendar importing `python/` outside `utils/`, or code outside `orchestration/` importing it | Read node results through the sensor's context; share code through `python/utils/` or a provider | +| `SQBRPYTHON019` | A sensor or calendar importing `python/nodes/` outside `utils/`, or code outside `orchestration/` importing it | Read node results through the sensor's context; share code through `python/nodes/utils/` or a provider | | `SQBRPYTHON020` | A sensor or calendar function with a docstring | Keep the text in `description=` only | Providers importing `orchestration/` are reported by `SQBRPYTHON015` instead. ## Testing Python -`sqb test` runs the pytest modules under `tests/python/`, `tests/providers/` and +`sqb test` runs the pytest modules under `tests/python/nodes/`, `tests/python/providers/` and `tests/orchestration/`; see [Python tests](../../cli/test.md#python-tests). `SQBRPYTHON021` keeps each test beside a mirror of the code it tests, and `SQBRPYTHON701` to `SQBRPYTHON724` keep tests table-driven: ```text -python/ +python/nodes/ orders/ storefront_import/ - node.py + asset.py _helpers/ row_mapping.py tests/ python/ - orders/ - storefront_import/ - _helpers/ - _test_types.py # the test-case dataclasses - test_row_mapping.py # tests row_mapping.py + nodes/ + orders/ + storefront_import/ + _helpers/ + _test_types.py # the test-case dataclasses + test_row_mapping.py # tests row_mapping.py ``` ```python -# tests/python/orders/storefront_import/_helpers/_test_types.py +# tests/python/nodes/orders/storefront_import/_helpers/_test_types.py from dataclasses import dataclass @dataclass(frozen=True) @@ -260,11 +264,11 @@ class RowMappingTestCase: ``` ```python -# tests/python/orders/storefront_import/_helpers/test_row_mapping.py +# tests/python/nodes/orders/storefront_import/_helpers/test_row_mapping.py import pytest -from python.orders.storefront_import._helpers.row_mapping import status_label -from tests.python.orders.storefront_import._helpers._test_types import RowMappingTestCase +from python.nodes.orders.storefront_import._helpers.row_mapping import status_label +from tests.python.nodes.orders.storefront_import._helpers._test_types import RowMappingTestCase @pytest.mark.parametrize( "test_case", @@ -280,7 +284,7 @@ def test_given_a_status_when_mapping_then_returns_its_label(test_case: RowMappin | Code | Finding | Fix | |---|---|---| -| `SQBRPYTHON021` | A test module whose folder does not mirror one under `python/`, `providers/` or `orchestration/`, or a `test_.py` with no `.py` or `/` package beside the code it tests | Move the test to the mirrored folder, or rename it for the module it tests | +| `SQBRPYTHON021` | A test module whose folder does not mirror one under `python/nodes/`, `python/providers/` or `orchestration/`, or a `test_.py` with no `.py` or `/` package beside the code it tests | Move the test to the mirrored folder, or rename it for the module it tests | | `SQBRPYTHON701` to `SQBRPYTHON711` | A test folder or module whose layout, imports, helpers, conditionals or test-case dataclasses break the pattern above | Follow the pattern above | | `SQBRPYTHON712` to `SQBRPYTHON724` | A test function or `pytest.mark.parametrize` that is not named `test_given__when__then_`, or does not take dataclass cases through `test_case` with ids from each `description` | Follow the pattern above | @@ -293,7 +297,7 @@ those calls reach. A call that reaches a subprocess, an HTTP request, a socket, warehouse driver, or a cloud or SSH client is reported at the call where the walk started: ```python -# python/orders/storefront_import/constants.py +# python/nodes/orders/storefront_import/constants.py import requests STOREFRONT_REGIONS = requests.get("https://example.com/regions").json() # reported @@ -301,11 +305,11 @@ STOREFRONT_REGIONS = requests.get("https://example.com/regions").json() # repor ```text error[SQBRPYTHON022]: Python that runs while the project compiles must not reach a subprocess, the network, a database or a remote client: calls requests.get - --> python/orders/storefront_import/constants.py:3:22 + --> python/nodes/orders/storefront_import/constants.py:3:22 ``` When the external call sits in a project function, the message names it and its line instead, such -as `reaches requests.get at python/orders/storefront_import/_helpers/regions.py:8`. +as `reaches requests.get at python/nodes/orders/storefront_import/_helpers/regions.py:8`. Calls inside node bodies, `main()`, the nodes a factory generates, and provider methods run when the node runs, so they are not checked. Only calls whose target is known from the imports are @@ -318,7 +322,7 @@ enter an approved function, and an approved factory's body is not checked: ```toml [rules.rule_options.SQBRPYTHON022] approved_loader_boundaries = [ - "python.inventory.warehouse_snapshots._helpers.spec_loading.load_warehouse_specs", + "python.nodes.inventory.warehouse_snapshots._helpers.spec_loading.load_warehouse_specs", ] ``` @@ -328,7 +332,7 @@ Each entry is the fully qualified name of a project function. A glob fails confi ## Main modules and entry modules Some Rules apply only to a domain's main modules: files under a `main/` folder, and a unit's -`main.py`, such as `python/fulfillment/shipment_export/main.py`. A main module that is not +`main.py`, such as `python/nodes/fulfillment/shipment_export/main.py`. A main module that is not `__init__.py` is an entry module. `SQBRPYTHON617` requires it to expose one public function, and `SQBRPYTHON305` requires something outside its domain to import it. @@ -338,8 +342,8 @@ The other size limits check every function. ## Unreachable definitions `SQBRPYTHON306` reports functions, classes and module values that nothing SQLBuild loads can reach. -SQLBuild loads every decorated function under `python/` (`@loader`, `@asset`, `@check`, -`@factory` and `@audit_factory`) and everything defined outside `python/`, such as hooks and +SQLBuild loads every decorated function under `python/nodes/` (`@loader`, `@asset`, `@check`, +`@factory` and `@audit_factory`) and everything defined outside `python/nodes/`, such as hooks and providers. A definition reached only through them is live. Imports through folders without an `__init__.py` count too. @@ -349,7 +353,7 @@ exception with a reason: ```toml [[rules.rule_exceptions]] rule = "SQBRPYTHON306" -path = "python/fulfillment/carriers/registry.py" +path = "python/nodes/fulfillment/carriers/registry.py" reason = "Carriers are looked up by name from the shipment's carrier code." ``` @@ -386,35 +390,35 @@ numbers fail configuration with `C000`. `Default` says whether `SQBRPYTHON` selects the Rule. `sqb rules show ` prints the full remediation. -### Layout of `python/` +### Layout of `python/nodes/` | Code | Name | Files | Default | Checks | |---|---|---|---|---| -| `SQBRPYTHON001` | project-root-allowlist | `python/` | yes | `python/` may hold only domain packages, `utils/` and `__init__.py` | -| `SQBRPYTHON002` | runtime-package-owner-names | `python/` | yes | Packages under `python/` must be named for what they own | +| `SQBRPYTHON001` | project-root-allowlist | `python/nodes/` | yes | `python/nodes/` may hold only domain packages, `utils/` and `__init__.py` | +| `SQBRPYTHON002` | runtime-package-owner-names | `python/nodes/` | yes | Packages under `python/nodes/` must be named for what they own | ### Node units | Code | Name | Files | Default | Checks | |---|---|---|---|---| -| `SQBRPYTHON003` | node-unit-layout | `python/` | yes | A unit folder holds `node.py`, `main.py`, optional role files and `_helpers/` only | -| `SQBRPYTHON004` | node-module-shape | `python/` | yes | `node.py` holds imports and exactly one node or factory declaration | -| `SQBRPYTHON005` | node-delegates-to-main | `python/` | yes | A declaration's body is `return main(...)` from its unit, with keyword arguments | -| `SQBRPYTHON006` | main-module-shape | `python/` | yes | `main.py` holds imports and one `main()` whose return annotation fits the node | -| `SQBRPYTHON007` | node-signature | `python/` | yes | `ctx` is the only positional parameter; providers are annotated and keyword-only | -| `SQBRPYTHON008` | node-import-boundaries | `python/` | yes | A unit imports only what it owns, its domain's role files, `python/utils/`, provider role files and other nodes for `depends_on` | -| `SQBRPYTHON009` | checks-module-shape | `python/` | yes | `checks.py` holds checks of the unit's node that return directly, or one factory | -| `SQBRPYTHON010` | factory-shape | `python/` | yes | A factory loops over its unit's specs and names every node it generates | -| `SQBRPYTHON011` | node-description-not-docstring | `python/` | yes | Assets and checks set `description=` without a docstring; loaders set neither | -| `SQBRPYTHON012` | node-declared-in-unit | `python/` | yes | Nodes are declared in a unit's `node.py`, and checks in its `checks.py` | +| `SQBRPYTHON003` | node-unit-layout | `python/nodes/` | yes | A unit folder holds one declaration file, `main.py`, optional role files and `_helpers/` only | +| `SQBRPYTHON004` | node-module-shape | `python/nodes/` | yes | A declaration file holds imports and exactly one node or factory declaration | +| `SQBRPYTHON005` | node-delegates-to-main | `python/nodes/` | yes | A declaration's body is `return main(...)` from its unit, with keyword arguments | +| `SQBRPYTHON006` | main-module-shape | `python/nodes/` | yes | `main.py` holds imports and one `main()` whose return annotation fits the node | +| `SQBRPYTHON007` | node-signature | `python/nodes/` | yes | `ctx` is the only positional parameter; providers are annotated and keyword-only | +| `SQBRPYTHON008` | node-import-boundaries | `python/nodes/` | yes | A unit imports only what it owns, its domain's role files, `python/nodes/utils/`, provider role files and other nodes for `depends_on` | +| `SQBRPYTHON009` | checks-module-shape | `python/nodes/` | yes | `checks.py` holds checks of the unit's node that return directly, or one factory | +| `SQBRPYTHON010` | factory-shape | `python/nodes/` | yes | A factory loops over its unit's specs and names every node it generates | +| `SQBRPYTHON011` | node-description-not-docstring | `python/nodes/` | yes | Assets and checks set `description=` without a docstring; loaders set neither | +| `SQBRPYTHON012` | node-declared-in-unit | `python/nodes/` | yes | Nodes are declared in a unit's file named for their kind, and checks in its `checks.py` | ### Providers | Code | Name | Files | Default | Checks | |---|---|---|---|---| -| `SQBRPYTHON013` | provider-layout | All | yes | `providers/` holds capability folders with `provider.py`, role files, `_helpers/` and `_classes/` only | +| `SQBRPYTHON013` | provider-layout | All | yes | `python/providers/` holds capability folders with `provider.py`, role files, `_helpers/` and `_classes/` only | | `SQBRPYTHON014` | provider-module-shape | All | yes | `provider.py` holds imports, private constants and one public `Provider` subclass | -| `SQBRPYTHON015` | provider-import-boundaries | All | yes | A provider's `_helpers/` and `_classes/` are private to it; providers import only `python/utils/` from `python/` and nothing from `orchestration/` | +| `SQBRPYTHON015` | provider-import-boundaries | All | yes | A provider's `_helpers/` and `_classes/` are private to it; providers import only `python/nodes/utils/` from `python/nodes/` and nothing from `orchestration/` | ### Sensors and calendars @@ -423,7 +427,7 @@ remediation. | `SQBRPYTHON016` | orchestration-module-paths | All | yes | Sensor and calendar modules sit at `orchestration///.py` with a specific name | | `SQBRPYTHON017` | orchestration-private-support | All | yes | A domain folder's private support is its support files and `_helpers/`, imported only from that folder | | `SQBRPYTHON018` | orchestration-module-surface | All | yes | A sensor or calendar module holds imports, private constants and its one declaration | -| `SQBRPYTHON019` | orchestration-import-direction | All | yes | Sensors and calendars import only providers, `python/utils/` and their own support; nothing outside `orchestration/` imports them | +| `SQBRPYTHON019` | orchestration-import-direction | All | yes | Sensors and calendars import only providers, `python/nodes/utils/` and their own support; nothing outside `orchestration/` imports them | | `SQBRPYTHON020` | orchestration-no-docstring | All | yes | Sensor and calendar functions have no docstring | ### Compile-time purity @@ -436,7 +440,7 @@ remediation. | Code | Name | Files | Default | Checks | |---|---|---|---|---| -| `SQBRPYTHON021` | python-test-placement | `tests/` | yes | Python tests must mirror an existing module under `python/`, `providers/` or `orchestration/` | +| `SQBRPYTHON021` | python-test-placement | `tests/` | yes | Python tests must mirror an existing module under `python/nodes/`, `python/providers/` or `orchestration/` | | `SQBRPYTHON701` | test-init-module-empty | `tests/` | yes | Test package `__init__.py` files must be empty or docstring-only | | `SQBRPYTHON702` | test-absolute-imports | `tests/` | yes | Tests must use absolute imports | | `SQBRPYTHON703` | test-no-top-level-helpers | `tests/` | yes | Test modules may contain only tests, imports, and declarations | @@ -491,11 +495,11 @@ remediation. |---|---|---|---|---| | `SQBRPYTHON301` | absolute-imports-only | All | yes | Use absolute imports; relative imports hide package boundaries | | `SQBRPYTHON302` | no-star-imports | All | yes | Star imports hide names from dependency-boundary analysis | -| `SQBRPYTHON303` | no-internal-public-surface-imports | `python/` | yes | Internal code must import from the owning module, not the bare package | -| `SQBRPYTHON304` | no-cross-domain-private-main-imports | `python/` | yes | Domain-private main entries may only be imported within their owning domain | -| `SQBRPYTHON305` | public-main-entry-external-use | `python/` | yes | Public main entries must have an importer outside their owning domain | -| `SQBRPYTHON306` | unreachable-definition | `python/` | no | Definition is unreachable from production roots | -| `SQBRPYTHON307` | no-cross-file-use-of-helper-private-class | `python/` | yes | Helper-private classes are file-local details; move shared classes to `classes/` | +| `SQBRPYTHON303` | no-internal-public-surface-imports | `python/nodes/` | yes | Internal code must import from the owning module, not the bare package | +| `SQBRPYTHON304` | no-cross-domain-private-main-imports | `python/nodes/` | yes | Domain-private main entries may only be imported within their owning domain | +| `SQBRPYTHON305` | public-main-entry-external-use | `python/nodes/` | yes | Public main entries must have an importer outside their owning domain | +| `SQBRPYTHON306` | unreachable-definition | `python/nodes/` | no | Definition is unreachable from production roots | +| `SQBRPYTHON307` | no-cross-file-use-of-helper-private-class | `python/nodes/` | yes | Helper-private classes are file-local details; move shared classes to `classes/` | ### Naming contracts @@ -526,32 +530,32 @@ remediation. | Code | Name | Files | Default | Checks | |---|---|---|---|---| -| `SQBRPYTHON601` | models-only-models | `python/` | yes | Models role files may contain only structured runtime models | -| `SQBRPYTHON602` | types-only-types | `python/` | yes | Types role files may contain only type-layer declarations | -| `SQBRPYTHON603` | constants-only-constants | `python/` | yes | Constants role files may contain only assignments and imports | -| `SQBRPYTHON604` | exceptions-only-exceptions | `python/` | yes | Exceptions role files may contain only custom exceptions | -| `SQBRPYTHON605` | constant-outside-constants | `python/` | yes | Public uppercase constants must be defined in the constants role | +| `SQBRPYTHON601` | models-only-models | `python/nodes/` | yes | Models role files may contain only structured runtime models | +| `SQBRPYTHON602` | types-only-types | `python/nodes/` | yes | Types role files may contain only type-layer declarations | +| `SQBRPYTHON603` | constants-only-constants | `python/nodes/` | yes | Constants role files may contain only assignments and imports | +| `SQBRPYTHON604` | exceptions-only-exceptions | `python/nodes/` | yes | Exceptions role files may contain only custom exceptions | +| `SQBRPYTHON605` | constant-outside-constants | `python/nodes/` | yes | Public uppercase constants must be defined in the constants role | | `SQBRPYTHON606` | banned-generic-filename | All | yes | Generic filenames hide module ownership | -| `SQBRPYTHON607` | helpers-module-name | `python/` | yes | Use an _helpers package instead of `helpers.py` | -| `SQBRPYTHON608` | classes-module-name | `python/` | yes | Use a classes package instead of `classes.py` | -| `SQBRPYTHON609` | helpers-classes-file-private | `python/` | yes | Plain classes in _helpers modules must be file-private | -| `SQBRPYTHON610` | helpers-package-layout | `python/` | yes | `_helpers/` packages must use bounded flat-or-grouped containers | -| `SQBRPYTHON611` | main-package-layout | `python/` | yes | `main/` packages must use bounded flat-or-grouped orchestration containers | -| `SQBRPYTHON612` | helpers-reserved-role-filenames | `python/` | yes | `_helpers/` packages must not contain reserved role filenames | -| `SQBRPYTHON613` | top-level-domain-shape | `python/` | yes | Top-level domains must be either role leaves or subdomain branches | -| `SQBRPYTHON614` | top-level-direct-modules | `python/` | yes | Runtime roots and top-level domains must not contain ad hoc direct modules | -| `SQBRPYTHON615` | shared-domain-prefix | `python/` | yes | Sibling domains must not encode one parent domain through a shared name prefix | -| `SQBRPYTHON616` | public-facade-import-direction | `python/` | yes | Runtime modules must not import public facade modules | -| `SQBRPYTHON617` | entry-module-shape | `python/` | yes | `main/` entry modules must expose one focused public function | -| `SQBRPYTHON618` | init-module-empty | `python/` | yes | Nested `__init__.py` files must be empty or docstring-only | -| `SQBRPYTHON619` | no-reexport-shim | `python/` | yes | Internal modules must not exist only to re-export imports | -| `SQBRPYTHON620` | no-internal-helper-exports | `python/` | yes | `_helpers/` modules must not publish an `__all__` surface | -| `SQBRPYTHON621` | main-entry-name-collision | `python/` | yes | `main/` cannot define a module and package with the same entry name | -| `SQBRPYTHON622` | public-surface-shape | `python/` | yes | Root package surfaces may contain only imports and one `__all__` declaration | -| `SQBRPYTHON623` | classes-one-class-per-module | `python/` | yes | `classes/` modules must define exactly one top-level class | -| `SQBRPYTHON624` | helpers-package-shape | `python/` | yes | `_helpers/` packages must contain no main.py orchestration entrypoints | -| `SQBRPYTHON625` | private-definition-ordering | `python/` | yes | Private constants and dataclasses must appear before top-level functions | -| `SQBRPYTHON626` | classes-runtime-reexport | `python/` | yes | `classes/` modules must not publicly re-export imported runtime symbols | +| `SQBRPYTHON607` | helpers-module-name | `python/nodes/` | yes | Use an _helpers package instead of `helpers.py` | +| `SQBRPYTHON608` | classes-module-name | `python/nodes/` | yes | Use a classes package instead of `classes.py` | +| `SQBRPYTHON609` | helpers-classes-file-private | `python/nodes/` | yes | Plain classes in _helpers modules must be file-private | +| `SQBRPYTHON610` | helpers-package-layout | `python/nodes/` | yes | `_helpers/` packages must use bounded flat-or-grouped containers | +| `SQBRPYTHON611` | main-package-layout | `python/nodes/` | yes | `main/` packages must use bounded flat-or-grouped orchestration containers | +| `SQBRPYTHON612` | helpers-reserved-role-filenames | `python/nodes/` | yes | `_helpers/` packages must not contain reserved role filenames | +| `SQBRPYTHON613` | top-level-domain-shape | `python/nodes/` | yes | Top-level domains must be either role leaves or subdomain branches | +| `SQBRPYTHON614` | top-level-direct-modules | `python/nodes/` | yes | Runtime roots and top-level domains must not contain ad hoc direct modules | +| `SQBRPYTHON615` | shared-domain-prefix | `python/nodes/` | yes | Sibling domains must not encode one parent domain through a shared name prefix | +| `SQBRPYTHON616` | public-facade-import-direction | `python/nodes/` | yes | Runtime modules must not import public facade modules | +| `SQBRPYTHON617` | entry-module-shape | `python/nodes/` | yes | `main/` entry modules must expose one focused public function | +| `SQBRPYTHON618` | init-module-empty | `python/nodes/` | yes | Nested `__init__.py` files must be empty or docstring-only | +| `SQBRPYTHON619` | no-reexport-shim | `python/nodes/` | yes | Internal modules must not exist only to re-export imports | +| `SQBRPYTHON620` | no-internal-helper-exports | `python/nodes/` | yes | `_helpers/` modules must not publish an `__all__` surface | +| `SQBRPYTHON621` | main-entry-name-collision | `python/nodes/` | yes | `main/` cannot define a module and package with the same entry name | +| `SQBRPYTHON622` | public-surface-shape | `python/nodes/` | yes | Root package surfaces may contain only imports and one `__all__` declaration | +| `SQBRPYTHON623` | classes-one-class-per-module | `python/nodes/` | yes | `classes/` modules must define exactly one top-level class | +| `SQBRPYTHON624` | helpers-package-shape | `python/nodes/` | yes | `_helpers/` packages must contain no main.py orchestration entrypoints | +| `SQBRPYTHON625` | private-definition-ordering | `python/nodes/` | yes | Private constants and dataclasses must appear before top-level functions | +| `SQBRPYTHON626` | classes-runtime-reexport | `python/nodes/` | yes | `classes/` modules must not publicly re-export imported runtime symbols | | `SQBRPYTHON627` | source-file-line-count | All | yes | Source files must stay below the configured line limit | ## Details diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/seeds.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/seeds.md index bdf725e9be..f4f7863632 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/seeds.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/seeds.md @@ -15,11 +15,11 @@ Online: https://sqlbuild.com/docs/concepts/seeds/ - Target overrides - CSV settings -Seeds are CSV files under `seeds/` that SQLBuild loads as tables in the warehouse. They're useful for small, static reference data like lookup tables, category mappings, or configuration values. +Seeds are CSV files under `sql/seeds/` that SQLBuild loads as tables in the warehouse. They're useful for small, static reference data like lookup tables, category mappings, or configuration values. ## Defining a seed -Place a CSV file in your `seeds/` directory: +Place a CSV file in your `sql/seeds/` directory: ```csv waffle_type_id,waffle_name,category,price_cents @@ -29,10 +29,10 @@ waffle_type_id,waffle_name,category,price_cents 4,Cheddar Herb,savory,1050 ``` -Declare the seed's column types in any `.yml` file under `seeds/`. You can use any filename and organize declarations however you like - one file per seed, or group related seeds together: +Declare the seed's column types in any `.yml` file under `sql/seeds/`. You can use any filename and organize declarations however you like - one file per seed, or group related seeds together: ```yaml -# seeds/lookups.yml +# sql/seeds/lookups.yml seeds: - name: waffle_types description: Waffle menu items with pricing. @@ -55,7 +55,7 @@ Seed YAML accepts only these keys; any other key is a compile error: | Seed | `name`, `description`, `database`, `schema`, `meta`, `tags`, `csv_settings`, `columns`, `audits` | | Column | `name`, `type`, `nullable`, `description`, `meta`, `audits` | -Every seed must have a YAML declaration with a non-empty `description` ([Descriptions](models/configuration.md#descriptions)) and at least one typed column. CSV filenames must be unique across the entire `seeds/` directory (including subdirectories). The seed name in the YAML must match the CSV filename (without the `.csv` extension). +Every seed must have a YAML declaration with a non-empty `description` ([Descriptions](models/configuration.md#descriptions)) and at least one typed column. CSV filenames must be unique across the entire `sql/seeds/` directory (including subdirectories). The seed name in the YAML must match the CSV filename (without the `.csv` extension). ## Referencing seeds @@ -106,7 +106,7 @@ seeds: works on seeds reads the attached relation through `@relation`: ```sql --- audits/generic/expression_is_true.sql +-- sql/audits/generic/expression_is_true.sql AUDIT (); SELECT * diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/selectors.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/selectors.md index 91a2da4d47..efee250736 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/selectors.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/selectors.md @@ -66,12 +66,12 @@ sqb build --select tag:acceptance Select all models under a directory path: ```bash -sqb build --select path:models/marts -sqb build --select models/marts -sqb build --select path:models/intermediate +sqb build --select path:sql/models/marts +sqb build --select sql/models/marts +sqb build --select path:sql/models/intermediate ``` -Any name containing `/` is treated as a path selector, so `path:models/marts` and a bare `models/marts` work the same way. Path selectors require an explicit root directory: `models/` for SQL models or `python/` for Python nodes. Nested paths work too: `models/staging/orders` or `python/exports`. +Any name containing `/` is treated as a path selector, so `path:sql/models/marts` and a bare `sql/models/marts` work the same way. Path selectors require an explicit root directory: `sql/models/` for SQL models or `python/nodes/` for Python nodes. Nested paths work too: `sql/models/staging/orders` or `python/nodes/exports`. ### Seed and source @@ -86,7 +86,7 @@ Select every node of one kind: ```bash sqb build --select kind:seed -sqb build --select "kind:model,path:models/marts" +sqb build --select "kind:model,path:sql/models/marts" sqb build --select +kind:asset ``` @@ -158,7 +158,7 @@ Graph expansion works with all selector types: ```bash sqb build --select +tag:marts -sqb build --select path:models/staging+ +sqb build --select path:sql/models/staging+ ``` ## Path-between selectors @@ -187,10 +187,10 @@ This is useful for rebuilding a specific slice of the DAG without manually listi Use commas to intersect selector results: ```bash -sqb build --select "tag:staging,path:models/finance" +sqb build --select "tag:staging,path:sql/models/finance" ``` -This selects only models that match *both* conditions - in this case, models tagged `staging` that are also under the `models/finance` directory. +This selects only models that match *both* conditions - in this case, models tagged `staging` that are also under the `sql/models/finance` directory. Graph expansion applies to the part it is written on, before the parts are intersected. `+orders,kind:source` selects `orders` and everything upstream of it, then keeps only the sources: @@ -201,7 +201,7 @@ results are unioned, so `tag:finance kind:seed` selects nodes tagged `finance` a ```bash # Build all marts except daily_revenue -sqb build --select path:models/marts --exclude daily_revenue +sqb build --select path:sql/models/marts --exclude daily_revenue # Build everything upstream of fact_orders, excluding staging models sqb build --select +fact_orders --exclude tag:staging @@ -215,7 +215,7 @@ clear error messages: ``` error[S007]: unknown selector name 'nonexistent_model' error[S007]: unknown selector name 'missing_*' -error[S009]: no models found under path 'models/nonexistent'. +error[S009]: no models found under path 'sql/models/nonexistent'. error[S000]: no SQL resources or Python nodes found with tag 'nonexistent_tag' error[S007]: unknown node kind 'modle' error[S003]: path selector 'fact_orders~' requires names on both sides of '~' @@ -232,5 +232,5 @@ error[S007]: unknown selector name 'order_status_rule' If a path selector omits the root directory, SQLBuild asks for the explicit form: ``` -error[S012]: path selectors require an explicit root: use 'models/' or 'python/' +error[S012]: path selectors require an explicit root: use 'sql/models/' or 'python/nodes/' ``` diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/semantic-compilation.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/semantic-compilation.md index 7e4aaf8df6..5892e7c9dd 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/semantic-compilation.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/semantic-compilation.md @@ -21,7 +21,7 @@ misspelled functions, invalid grouping, and more. It works offline, from your pr ```text error[B002]: Unknown column 'qty' in stg_orders (as o) model: fact_orders - --> models/marts/fact_orders.sql:16:5 + --> sql/models/marts/fact_orders.sql:16:5 | 16 | o.qty, | ^^^ diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/sources.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/sources.md index 36d598b7e2..e91bb33843 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/sources.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/sources.md @@ -17,7 +17,7 @@ Online: https://sqlbuild.com/docs/concepts/sources/ - Config reference - YAML that SQLBuild reads -Sources declare external data that your models depend on. They are defined in YAML files under `sources/` in your project directory. +Sources declare external data that your models depend on. They are defined in YAML files under `sql/sources/` in your project directory. ## Table sources @@ -52,7 +52,7 @@ sources: Expression sources are resolved at compile time. They're the escape hatch for anything the framework doesn't natively model: external tables, warehouse-specific syntax, function calls, or any other relation type that doesn't fit a standard table reference. An inline source expression uses macros, constants, and enums available from its source definition -under `sources/`. Declarations limited to one source folder are not available in sibling folders. +under `sql/sources/`. Declarations limited to one source folder are not available in sibling folders. See [How Visibility Works](declaration-scopes/visibility.md). ## Source audits diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing.md index afb0fa90d1..70122f67ad 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing.md @@ -381,7 +381,7 @@ should supply the rows. SQLBuild replaces the whole call, arguments included, wi mocked function isn't deployed for the test. ```sql --- models/customer_order_totals.sql reads: +-- sql/models/customer_order_totals.sql reads: -- __table_fn("customer_orders")(42) TEST(); @@ -421,7 +421,7 @@ How often the fixture's rows appear depends on the call: read as NULL in the later call's rows. ```sql --- models/smoothed_payments.sql reads: +-- sql/models/smoothed_payments.sql reads: -- FROM __ref("payments") p, -- __table_fn("smooth_payments")(p.customer_id, p.paid_at, p.amount) -- OVER (PARTITION BY p.customer_id) s @@ -507,7 +507,7 @@ model path doesn't. Model-private values and macros are never available to tests A macro used only by tests must be private to them. Put it in a `_sqlbuild/_macros/` folder among the tests, such as `tests/unit/orders/_sqlbuild/_macros/`, or in the `_sqlbuild/_macros/` of a model -the tests define `__expected__` output for. The project `macros/` directory rejects a test-only +the tests define `__expected__` output for. The project `sql/macros/` directory rejects a test-only macro with `S024`, which names the folder to use, and `tests/unit/_sqlbuild/` is rejected with `D013`. @@ -577,7 +577,7 @@ sqb test sqb test --select stg_orders ``` -`sqb test` also runs the project's pytest modules under `tests/python/`, `tests/providers/` and +`sqb test` also runs the project's pytest modules under `tests/python/nodes/`, `tests/python/providers/` and `tests/orchestration/`; `sqb build` never runs them. See [Python tests](../cli/test.md#python-tests). ## More test features diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/integrations/dagster-reference.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/integrations/dagster-reference.md index 4bd4f118fc..190b97c485 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/integrations/dagster-reference.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/integrations/dagster-reference.md @@ -236,7 +236,7 @@ Each `node` dict passed to translator methods contains: "name": "fact_orders", "qualified_name": "dev.fact_orders" }, - "path": "models/marts/fact_orders.sql", + "path": "sql/models/marts/fact_orders.sql", "description": "Order fact table with waffle and payment details.", "tags": ["marts"], "columns": [ @@ -278,7 +278,7 @@ Each `check` dict passed to check translator methods contains: "kind": "audit", "name": "not_null", "checked_asset_ids": ["model:fact_orders"], - "path": "audits/generic/not_null.sql", + "path": "sql/audits/generic/not_null.sql", "severity": "error", "attached_target_name": "fact_orders", "attached_column_name": "order_id" diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/quickstart.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/quickstart.md index 77f2596196..a5a213a754 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/quickstart.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/quickstart.md @@ -77,7 +77,7 @@ Seeds (1) ✓ Plan complete 15 selected, 2 sources to load ``` -`raw__customers` and `raw__orders` are loaded by a Python loader (`python/loaders/waffle_sources.py`) at the start of the build; `raw__payments` is an inline expression in `sources/raw.yml`. Incremental models also list their cursor and window under their row; they are left out here. +`raw__customers` and `raw__orders` are loaded by a Python loader (`python/nodes/loaders/waffle_sources.py`) at the start of the build; `raw__payments` is an inline expression in `sql/sources/raw.yml`. Incremental models also list their cursor and window under their row; they are left out here. ## 3. Build @@ -157,7 +157,7 @@ The models and functions are no longer listed as first run, and the seed is curr ## 5. Change a model -Edit `models/staging/stg_orders.sql` to drop cancelled orders, by adding this line at the end: +Edit `sql/models/staging/stg_orders.sql` to drop cancelled orders, by adding this line at the end: ```sql WHERE status <> 'cancelled' @@ -195,7 +195,7 @@ history. See [Planning](concepts/planning.md). sqb build daily_revenue # Rebuild models under a path -sqb build path:models/marts +sqb build path:sql/models/marts # Full refresh of everything sqb build --full-refresh diff --git a/src/sqlbuild/_native.pyi b/src/sqlbuild/_native.pyi index dfa2d5e7c5..e9a8bd9bc7 100644 --- a/src/sqlbuild/_native.pyi +++ b/src/sqlbuild/_native.pyi @@ -167,6 +167,10 @@ SNAPSHOT_DEFAULT_VALID_TO_COLUMN: str PROJECT_CONFIG_FILENAME: str PYTHON_INIT_MODULE_STEM: str PYTHON_NODE_ROOT: str +PYTHON_PACKAGE_NAME: str +EVENT_SINKS_PATH: str +ADAPTERS_PATH: str +ADAPTER_FILE_PATH: str SETTINGS_SECTION: str TABLE_PROMOTION_MODE_SETTING_KEY: str STAGED_PROMOTION_MODE: str @@ -2928,6 +2932,7 @@ class EventExporterCommandScope: | None ): ... def close(self) -> EventExportSummary: ... + def teardown_failures(self) -> list[str]: ... def export_output(self, records: tuple[CommandOutputRecord, ...]) -> None: ... def current_event_exporter_command_scope() -> EventExporterCommandScope | None: ... @@ -5586,6 +5591,13 @@ def build_observations_prune_sql( render_qualified_name: Callable[..., str | None], retain_versions: int, ) -> str: ... +def build_resource_costs_add_columns_sql( + *, + database: str | None, + schema: str, + render_qualified_name: Callable[..., str | None], + render_framework_type: Callable[[FrameworkType], str], +) -> list[str]: ... def build_resource_costs_create_table_sql( *, database: str | None, @@ -8502,7 +8514,7 @@ class SchemaParseError(DiscoveryError): """Raised when a schema.yml file has an invalid shape.""" class SourceParseError(DiscoveryError): - """Raised when a sources/*.yml file has an invalid shape.""" + """Raised when a sql/sources/*.yml file has an invalid shape.""" class DiscoveryConflictError(DiscoveryError): """Raised when discovered project inputs conflict across files.""" @@ -8531,6 +8543,9 @@ class EventExporterDiscoveryError(DiscoveryError): class OrchestrationDeclarationError(DiscoveryError): """Raised when an orchestration job, job group, calendar or sensor declaration is invalid.""" +class ProjectLayoutError(DiscoveryError): + """Raised when a project holds an entry outside the SQLBuild project layout.""" + class ProjectPythonPathError(DiscoveryError): """Raised when project-owned Python lives outside a supported extension root.""" @@ -12533,8 +12548,9 @@ class ProjectConfig(NativeRecord): snapshots: SnapshotsConfig scenario: ScenarioConfig dbt: DbtConfig - sinks: SinksConfig + event_sinks: SinksConfig env_file: str | None + extra_paths: tuple[str, ...] def __init__( self, name: str, @@ -12560,8 +12576,9 @@ class ProjectConfig(NativeRecord): snapshots: SnapshotsConfig = ..., scenario: ScenarioConfig = ..., dbt: DbtConfig = ..., - sinks: SinksConfig = ..., + event_sinks: SinksConfig = ..., env_file: str | None = ..., + extra_paths: tuple[str, ...] = ..., ) -> None: ... class LocalConfig(NativeRecord): @@ -12789,7 +12806,7 @@ class SourceFreshnessConfig(NativeRecord): ) -> None: ... class SourceColumnEntry(NativeRecord): - """One source column entry from sources/*.yml.""" + """One source column entry from sql/sources/*.yml.""" name: str type: str | None @@ -12808,7 +12825,7 @@ class SourceColumnEntry(NativeRecord): ) -> None: ... class SourceEntry(NativeRecord): - """One source declaration from sources/*.yml.""" + """One source declaration from sql/sources/*.yml.""" name: str database: str | None diff --git a/src/sqlbuild/_native_host.py b/src/sqlbuild/_native_host.py index 808cd440c7..8a53a8c20b 100644 --- a/src/sqlbuild/_native_host.py +++ b/src/sqlbuild/_native_host.py @@ -164,9 +164,9 @@ "sqlbuild.compiler.discovery._helpers.filesystem.project_modules", "load_python_node_module", ), - "load_sink_module": ( + "load_event_sink_module": ( "sqlbuild.compiler.discovery._helpers.filesystem.project_modules", - "load_sink_module", + "load_event_sink_module", ), "load_orchestration_module": ( "sqlbuild.compiler.discovery._helpers.filesystem.project_modules", @@ -638,6 +638,10 @@ "sqlbuild.runtime.observability.main.current_execution_identity", "current_execution_identity", ), + "current_event_dispatcher": ( + "sqlbuild.runtime.observability.main.current_event_dispatcher", + "current_event_dispatcher", + ), "diagnostic_log_to_json": ( "sqlbuild.runtime.observability.main.diagnostic_log_to_json", "diagnostic_log_to_json", diff --git a/src/sqlbuild/_native_host.pyi b/src/sqlbuild/_native_host.pyi index 38b2afd00e..46546825ce 100644 --- a/src/sqlbuild/_native_host.pyi +++ b/src/sqlbuild/_native_host.pyi @@ -127,6 +127,9 @@ from sqlbuild.compiler.discovery._helpers.filesystem.project_modules import ( from sqlbuild.compiler.discovery._helpers.filesystem.project_modules import ( install_python_root_package as install_python_root_package, ) +from sqlbuild.compiler.discovery._helpers.filesystem.project_modules import ( + load_event_sink_module as load_event_sink_module, +) from sqlbuild.compiler.discovery._helpers.filesystem.project_modules import ( load_materialize_function as load_materialize_function, ) @@ -139,9 +142,6 @@ from sqlbuild.compiler.discovery._helpers.filesystem.project_modules import ( from sqlbuild.compiler.discovery._helpers.filesystem.project_modules import ( load_python_node_module as load_python_node_module, ) -from sqlbuild.compiler.discovery._helpers.filesystem.project_modules import ( - load_sink_module as load_sink_module, -) from sqlbuild.compiler.discovery._helpers.filesystem.project_modules import ( module_functions as module_functions, ) @@ -571,6 +571,9 @@ from sqlbuild.runtime.observability.exceptions import ( from sqlbuild.runtime.observability.main.create_lifecycle_event import ( create_lifecycle_event as create_lifecycle_event, ) +from sqlbuild.runtime.observability.main.current_event_dispatcher import ( + current_event_dispatcher as current_event_dispatcher, +) from sqlbuild.runtime.observability.main.current_execution_identity import ( current_execution_identity as current_execution_identity, ) diff --git a/src/sqlbuild/adapter/contract/classes/resource_costs.py b/src/sqlbuild/adapter/contract/classes/resource_costs.py index 0eb9449207..16f97b9737 100644 --- a/src/sqlbuild/adapter/contract/classes/resource_costs.py +++ b/src/sqlbuild/adapter/contract/classes/resource_costs.py @@ -21,6 +21,21 @@ def render_create_resource_costs_table_sql(self, *, database: str | None, schema render_framework_type=adapter.render_framework_type, ) + def render_add_resource_costs_columns_sql( + self, *, database: str | None, schema: str + ) -> list[str]: + """Render one `ADD COLUMN IF NOT EXISTS` per column added after the first release.""" + + from sqlbuild._native import build_resource_costs_add_columns_sql + + adapter: Any = cast(Any, self) + return build_resource_costs_add_columns_sql( + database=database, + schema=schema, + render_qualified_name=adapter.render_qualified_name, + render_framework_type=adapter.render_framework_type, + ) + def render_prune_resource_costs_history_sql( self, *, database: str | None, schema: str, retain_versions: int ) -> str: diff --git a/src/sqlbuild/adapter/discovery/_helpers/project_adapters.py b/src/sqlbuild/adapter/discovery/_helpers/project_adapters.py index 78f13d4760..4b406c0b31 100644 --- a/src/sqlbuild/adapter/discovery/_helpers/project_adapters.py +++ b/src/sqlbuild/adapter/discovery/_helpers/project_adapters.py @@ -10,6 +10,7 @@ from types import ModuleType from typing import Any, cast +from sqlbuild._native import ADAPTERS_PATH from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter from sqlbuild.adapter.contract.classes.strict_adapter import StrictAdapter from sqlbuild.adapter.contract.constants import PYTHON_IDENTIFIER_REPLACEMENT, PYTHON_INIT_FILE_NAME @@ -23,9 +24,9 @@ def discover_project_adapters( project_dir: Path, reserved_names: frozenset[str] = frozenset(), ) -> dict[str, type[StrictAdapter]]: - """Discover adapter classes from a project's adapters directory.""" + """Discover adapter classes from a project's python/adapters directory.""" - adapters_dir: Path = project_dir / "adapters" + adapters_dir: Path = project_dir / ADAPTERS_PATH if not adapters_dir.is_dir(): return {} diff --git a/src/sqlbuild/adapter/discovery/main/resolve_adapter.py b/src/sqlbuild/adapter/discovery/main/resolve_adapter.py index 49b53716b7..d62d4f3e1e 100644 --- a/src/sqlbuild/adapter/discovery/main/resolve_adapter.py +++ b/src/sqlbuild/adapter/discovery/main/resolve_adapter.py @@ -28,7 +28,7 @@ def resolve_adapter(*, adapter_name: str, project_dir: Path | None = None) -> Ba if adapter_class is None: available: str = ", ".join(sorted(builtin_names)) local_text: str = ( - " Project-local adapters are discovered from adapters/**/*.py." + " Project-local adapters are discovered from python/adapters/**/*.py." if project_dir is not None else "" ) diff --git a/src/sqlbuild/adapter/relations/main/run_recorded_inspection_query.py b/src/sqlbuild/adapter/relations/main/run_recorded_inspection_query.py index 026d0a9c7b..3650d6fcc6 100644 --- a/src/sqlbuild/adapter/relations/main/run_recorded_inspection_query.py +++ b/src/sqlbuild/adapter/relations/main/run_recorded_inspection_query.py @@ -10,22 +10,34 @@ from sqlbuild.adapter.relations.models import InspectionQueryRecord -def run_recorded_inspection_query(*, sql: str, run: Callable[[], list[Any]]) -> list[Any]: - """Run one inspection read, then record its text, elapsed time, and row count.""" +def run_recorded_inspection_query( + *, + sql: str, + run: Callable[[], list[Any]], + answers_empty: Callable[[Exception], bool] | None = None, +) -> list[Any]: + """Record one inspection read; an error ``answers_empty`` accepts records as an empty read.""" started: float = time.monotonic() try: rows: list[Any] = run() except Exception as error: + elapsed: float = time.monotonic() - started + failure: InspectionQueryRecord = InspectionQueryRecord( + sql=sql, elapsed_seconds=elapsed, row_count=None, error=str(error) + ) + try: + empty: bool = answers_empty is not None and answers_empty(error) + except Exception: + _ = emit_inspection_record(record=failure) + raise + if not empty: + _ = emit_inspection_record(record=failure) + raise _ = emit_inspection_record( - record=InspectionQueryRecord( - sql=sql, - elapsed_seconds=time.monotonic() - started, - row_count=None, - error=str(error), - ) + record=InspectionQueryRecord(sql=sql, elapsed_seconds=elapsed, row_count=0) ) - raise + return [] _ = emit_inspection_record( record=InspectionQueryRecord( sql=sql, elapsed_seconds=time.monotonic() - started, row_count=len(rows) diff --git a/src/sqlbuild/adapters/snowflake/_helpers/cost.py b/src/sqlbuild/adapters/snowflake/_helpers/cost.py index 149fa8f000..c38b13c0fb 100644 --- a/src/sqlbuild/adapters/snowflake/_helpers/cost.py +++ b/src/sqlbuild/adapters/snowflake/_helpers/cost.py @@ -1,7 +1,27 @@ -"""Describe Snowflake cost-collection failures.""" +"""Describe Snowflake cost-collection failures and price credits the project leaves unpriced.""" from __future__ import annotations +import json +from datetime import UTC, datetime +from decimal import Decimal, InvalidOperation +from pathlib import Path +from typing import Any + +from sqlbuild.adapters.snowflake.constants import ( + ACCOUNT_SQL, + CREDIT_PRICE_CACHE_FILE, + DEFAULT_LIST_PRICE_EDITION, + FALLBACK_LIST_PRICE_REGION, + LIST_PRICE_EDITIONS, + LIST_PRICE_SOURCE, + LIST_PRICES, + RATE_SHEET_CURRENCY, + RATE_SHEET_SOURCE, + RATE_SHEET_SQL, +) +from sqlbuild.adapters.snowflake.models import CreditPrice + _FAILURE_DETAIL_LIMIT: int = 200 @@ -14,3 +34,91 @@ def cost_failure_cause(error: Exception) -> str: if len(detail) > _FAILURE_DETAIL_LIMIT: detail = f"{detail[: _FAILURE_DETAIL_LIMIT - 3]}..." return f"{type(error).__name__}: {detail}" + + +def list_price(*, region: str | None, edition: str = DEFAULT_LIST_PRICE_EDITION) -> CreditPrice: + """The list price for `region` and `edition`, per Snowflake's price table of 2026-11-20.""" + + name: str = (region or "").rsplit(".", 1)[-1].upper() + prices: tuple[str, str, str] = LIST_PRICES.get(name, LIST_PRICES[FALLBACK_LIST_PRICE_REGION]) + edition_name: str = edition if edition in LIST_PRICE_EDITIONS else DEFAULT_LIST_PRICE_EDITION + return CreditPrice(Decimal(prices[LIST_PRICE_EDITIONS.index(edition_name)]), LIST_PRICE_SOURCE) + + +def resolve_credit_price( + *, connection: Any, cache_dir: Path | None, today: datetime | None = None +) -> CreditPrice: + """The account's rate-sheet price, else its region's list price; kept for the UTC day.""" + + row: tuple[Any, ...] | None = _account(connection=connection) + account: str = str(row[0]) if row and row[0] else "" + region: str | None = str(row[1]) if row and len(row) > 1 and row[1] else None + if not account: + return _rate_sheet(connection=connection) or list_price(region=region) + key: str = f"{account}|{(today or datetime.now(UTC)).date().isoformat()}" + held: CreditPrice | None = _read_cache(cache_dir=cache_dir, key=key) + if held is not None: + return held + price: CreditPrice = _rate_sheet(connection=connection) or list_price(region=region) + _write_cache(cache_dir=cache_dir, key=key, price=price) + return price + + +def _fetchone(*, connection: Any, sql: str) -> tuple[Any, ...] | None: + cursor: Any = connection.cursor() + try: + cursor.execute(sql) + row: tuple[Any, ...] | None = cursor.fetchone() + return row + finally: + cursor.close() + + +def _account(*, connection: Any) -> tuple[Any, ...] | None: + """The account locator and region; none when Snowflake refuses the read.""" + + from snowflake.connector.errors import DatabaseError + + try: + return _fetchone(connection=connection, sql=ACCOUNT_SQL) + except DatabaseError: + return None + + +def _rate_sheet(*, connection: Any) -> CreditPrice | None: + """The rate sheet's newest USD compute price; none without an organisation role to read it.""" + + from snowflake.connector.errors import DatabaseError + + try: + row: tuple[Any, ...] | None = _fetchone(connection=connection, sql=RATE_SHEET_SQL) + except DatabaseError: + return None + if not row or row[0] is None or str(row[1] or "").upper() != RATE_SHEET_CURRENCY: + return None + try: + rate: Decimal = Decimal(str(row[0])) + except InvalidOperation: + return None + return CreditPrice(rate, RATE_SHEET_SOURCE) if rate > 0 else None + + +def _read_cache(*, cache_dir: Path | None, key: str) -> CreditPrice | None: + if cache_dir is None: + return None + try: + entry: Any = json.loads((cache_dir / CREDIT_PRICE_CACHE_FILE).read_text()).get(key) + return CreditPrice(Decimal(str(entry["usd_per_credit"])), str(entry["source"])) + except (OSError, ValueError, KeyError, TypeError, AttributeError, InvalidOperation): + return None + + +def _write_cache(*, cache_dir: Path | None, key: str, price: CreditPrice) -> None: + if cache_dir is None: + return + entry: dict[str, str] = {"usd_per_credit": str(price.usd_per_credit), "source": price.source} + try: + cache_dir.mkdir(parents=True, exist_ok=True) + (cache_dir / CREDIT_PRICE_CACHE_FILE).write_text(json.dumps({key: entry})) + except OSError: + return diff --git a/src/sqlbuild/adapters/snowflake/classes/snowflake_adapter.py b/src/sqlbuild/adapters/snowflake/classes/snowflake_adapter.py index 041c1bf535..88e4c7a573 100644 --- a/src/sqlbuild/adapters/snowflake/classes/snowflake_adapter.py +++ b/src/sqlbuild/adapters/snowflake/classes/snowflake_adapter.py @@ -137,7 +137,7 @@ from sqlbuild.adapter.type_system.main.normalize_numeric_family import normalize_numeric_family from sqlbuild.adapter.type_system.main.types_equal import types_equal from sqlbuild.adapters.snowflake._helpers.column_names import logical_column_name -from sqlbuild.adapters.snowflake._helpers.cost import cost_failure_cause +from sqlbuild.adapters.snowflake._helpers.cost import cost_failure_cause, resolve_credit_price from sqlbuild.adapters.snowflake._helpers.grants import ( render_snowflake_view_grants, render_snowflake_view_revokes, @@ -168,7 +168,9 @@ ) from sqlbuild.adapters.snowflake.constants import ( BASE_TABLE_METADATA_TYPE, + CREDIT_PRICE_CACHE_DIR, CURRENT_DATABASE_ATTRIBUTE, + DEFAULT_RATE_SOURCE, EXTERNAL_BROWSER_AUTHENTICATOR, FIXED_POINT_RESULT_TYPE, MAX_STATEMENT_TIMEOUT_SECONDS, @@ -187,6 +189,7 @@ TRUE_METADATA_VALUE, VIEW_RELATION_TYPE_TOKEN, ) +from sqlbuild.adapters.snowflake.models import CreditPrice from sqlbuild.compiler.compile.types import FunctionLanguage from sqlbuild.cost.models import RunCostSummary from sqlbuild.cost.types import CostCapability, CostStatus @@ -482,6 +485,12 @@ def _collect_run_cost( rate_source=rate_source, message=f"Snowflake cost collection failed to connect ({type(error).__name__}).", ) + if rate_source == DEFAULT_RATE_SOURCE: + price: CreditPrice = resolve_credit_price( + connection=connection, + cache_dir=statement_ledger_path.parent.parent.parent / CREDIT_PRICE_CACHE_DIR, + ) + usd_per_credit, rate_source = price.usd_per_credit, price.source try: summary: RunCostSummary = collect_snowflake_cost( connection=connection, @@ -2586,7 +2595,10 @@ def _fetch_paged_show_rows( @staticmethod def _fetch_show_rows( - *, connection: _SnowflakeConnection, query: str + *, + connection: _SnowflakeConnection, + query: str, + answers_empty: Callable[[Exception], bool] | None = None, ) -> list[dict[str, object]]: """Run one SHOW command and return its rows keyed by lowercase output column.""" @@ -2599,21 +2611,21 @@ def fetch() -> list[dict[str, object]]: finally: cursor.close() - return run_recorded_inspection_query(sql=query, run=fetch) + return run_recorded_inspection_query(sql=query, run=fetch, answers_empty=answers_empty) def _fetch_schema_show_rows( self, *, connection: _SnowflakeConnection, query: str, show_database: str, schema: str ) -> list[dict[str, object]]: - """Run SHOW ... IN SCHEMA; a schema that does not exist lists nothing, as before.""" + """Run SHOW ... IN SCHEMA; a schema that does not exist lists nothing, recorded as such.""" - try: - return self._fetch_show_rows(connection=connection, query=query) - except Exception as error: - if not is_missing_object_error(error) or self._schema_exists( + def schema_missing(error: Exception) -> bool: + return is_missing_object_error(error) and not self._schema_exists( connection=connection, show_database=show_database, schema=schema - ): - raise - return [] + ) + + return self._fetch_show_rows( + connection=connection, query=query, answers_empty=schema_missing + ) def _schema_exists( self, *, connection: _SnowflakeConnection, show_database: str, schema: str diff --git a/src/sqlbuild/adapters/snowflake/constants.py b/src/sqlbuild/adapters/snowflake/constants.py index ffe893ff4d..73d1ca1441 100644 --- a/src/sqlbuild/adapters/snowflake/constants.py +++ b/src/sqlbuild/adapters/snowflake/constants.py @@ -54,3 +54,38 @@ PYTHON_TABLE_FUNCTION_HANDLER: str = "_SqbHandler" PANDAS_PACKAGES: tuple[str, ...] = ("pandas",) POLARS_PACKAGES: tuple[str, ...] = ("pandas", "polars", "pyarrow") + +DEFAULT_RATE_SOURCE: str = "default" +RATE_SHEET_SOURCE: str = "rate_sheet" +LIST_PRICE_SOURCE: str = "list_price" +RATE_SHEET_CURRENCY: str = "USD" +CREDIT_PRICE_CACHE_DIR: str = "cost" +CREDIT_PRICE_CACHE_FILE: str = "credit_price.json" +RATE_SHEET_SQL: str = ( + "SELECT EFFECTIVE_RATE, CURRENCY FROM SNOWFLAKE.ORGANIZATION_USAGE.RATE_SHEET_DAILY " + "WHERE ACCOUNT_LOCATOR = CURRENT_ACCOUNT() AND SERVICE_TYPE = 'WAREHOUSE_METERING' " + "AND USAGE_TYPE = 'compute' AND DATE >= DATEADD(day, -31, CURRENT_DATE()) " + "ORDER BY DATE DESC LIMIT 1" +) +ACCOUNT_SQL: str = "SELECT CURRENT_ACCOUNT(), CURRENT_REGION()" +LIST_PRICE_EDITIONS: tuple[str, str, str] = ("STANDARD", "ENTERPRISE", "BUSINESS_CRITICAL") +DEFAULT_LIST_PRICE_EDITION: str = "ENTERPRISE" +FALLBACK_LIST_PRICE_REGION: str = "AWS_US_EAST_1" +LIST_PRICES: dict[str, tuple[str, str, str]] = { + "AWS_US_EAST_1": ("2.00", "3.00", "4.00"), + "AWS_US_EAST_2": ("2.00", "3.00", "4.00"), + "AWS_US_WEST_2": ("2.00", "3.00", "4.00"), + "AWS_CA_CENTRAL_1": ("2.25", "3.50", "4.50"), + "AWS_EU_WEST_1": ("2.60", "3.90", "5.20"), + "AWS_EU_CENTRAL_1": ("2.60", "3.90", "5.20"), + "AWS_EU_WEST_2": ("2.70", "4.00", "5.40"), + "AWS_AP_SOUTHEAST_1": ("2.50", "3.70", "5.00"), + "AWS_AP_SOUTHEAST_2": ("2.75", "4.05", "5.50"), + "AWS_AP_NORTHEAST_1": ("2.85", "4.30", "5.70"), + "AWS_AP_SOUTH_1": ("2.00", "3.00", "4.00"), + "AWS_SA_EAST_1": ("3.10", "4.65", "6.20"), + "AZURE_EASTUS2": ("2.00", "3.00", "4.00"), + "AZURE_WESTEUROPE": ("2.60", "3.90", "5.20"), + "AZURE_JAPANEAST": ("2.85", "4.30", "5.70"), + "GCP_US_CENTRAL1": ("2.00", "3.00", "4.00"), +} diff --git a/src/sqlbuild/adapters/snowflake/models.py b/src/sqlbuild/adapters/snowflake/models.py index f610a01d2c..f3c2e3f225 100644 --- a/src/sqlbuild/adapters/snowflake/models.py +++ b/src/sqlbuild/adapters/snowflake/models.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass +from decimal import Decimal @dataclass(frozen=True) @@ -11,3 +12,11 @@ class UsageQuery: sql: str params: tuple[object, ...] + + +@dataclass(frozen=True) +class CreditPrice: + """A price per Snowflake credit in USD and where it came from: `rate_sheet` or `list_price`.""" + + usd_per_credit: Decimal + source: str diff --git a/src/sqlbuild/compiler/discovery/_helpers/filesystem/command_output_sinks.py b/src/sqlbuild/compiler/discovery/_helpers/filesystem/command_output_sinks.py index b2604f76b5..e42fd0c5af 100644 --- a/src/sqlbuild/compiler/discovery/_helpers/filesystem/command_output_sinks.py +++ b/src/sqlbuild/compiler/discovery/_helpers/filesystem/command_output_sinks.py @@ -19,21 +19,24 @@ RecallWriter, ) from sqlbuild.compiler.discovery._helpers.filesystem.project_modules import ( - load_sink_module, + load_event_sink_module, provider_usages, ) from sqlbuild.compiler.discovery._helpers.filesystem.recall_sinks import split_recall_sinks -from sqlbuild.runtime.event_exporting.main.get_command_output_sink_definition import ( - get_command_output_sink_definition, +from sqlbuild.runtime.event_exporting.main.get_command_output_event_sink_definition import ( + get_command_output_event_sink_definition, ) from sqlbuild.runtime.output_capture.constants import COMMAND_OUTPUT_SINK_RECORD_PARAMETER_NAME -from sqlbuild.runtime.output_capture.models import CommandOutputRecord, CommandOutputSinkDefinition +from sqlbuild.runtime.output_capture.models import ( + CommandOutputEventSinkDefinition, + CommandOutputRecord, +) def discover_command_output_sink_functions( *, project_dir: Path, providers: tuple[DiscoveredProvider, ...] = () ) -> tuple[DiscoveredCommandOutputSink, ...]: - """Discover validated command-output sink declarations under sinks/, without Recall's.""" + """Discover validated python/event_sinks/ command-output event sinks, without Recall's.""" cached: ( tuple[ @@ -62,17 +65,17 @@ def discover_command_output_sink_functions( def discover_command_output_sink_declarations( *, project_dir: Path ) -> tuple[DiscoveredCommandOutputSinkDeclaration, ...]: - """Import sink modules and collect command-output declarations.""" + """Import event sink modules and collect command-output declarations.""" - sinks_root: Path = project_dir / "sinks" + sinks_root: Path = project_dir / _native.EVENT_SINKS_PATH if not sinks_root.is_dir(): return () discovered: list[DiscoveredCommandOutputSinkDeclaration] = [] seen_names: dict[str, Path] = {} for file_path in _native.discover_python_module_files( - project_dir=project_dir, root="sinks", public_only=True + project_dir=project_dir, root=_native.EVENT_SINKS_PATH, public_only=True ): - module: ModuleType = load_sink_module(file_path=file_path, project_dir=project_dir) + module: ModuleType = load_event_sink_module(file_path=file_path, project_dir=project_dir) seen_function_ids: set[int] = set() for _, value in inspect.getmembers(module, inspect.isfunction): if value.__module__ != module.__name__: @@ -81,8 +84,8 @@ def discover_command_output_sink_declarations( if function_id in seen_function_ids: continue seen_function_ids.add(function_id) - definition: CommandOutputSinkDefinition | None = get_command_output_sink_definition( - value + definition: CommandOutputEventSinkDefinition | None = ( + get_command_output_event_sink_definition(value) ) if definition is None: continue diff --git a/src/sqlbuild/compiler/discovery/_helpers/filesystem/project_modules.py b/src/sqlbuild/compiler/discovery/_helpers/filesystem/project_modules.py index 69a660a177..721b741da6 100644 --- a/src/sqlbuild/compiler/discovery/_helpers/filesystem/project_modules.py +++ b/src/sqlbuild/compiler/discovery/_helpers/filesystem/project_modules.py @@ -15,6 +15,7 @@ from sqlbuild._native import ( PYTHON_INIT_MODULE_STEM, PYTHON_NODE_ROOT, + PYTHON_PACKAGE_NAME, DiscoveredProvider, DiscoveredProviderUsage, EventExporterDiscoveryError, @@ -136,9 +137,28 @@ def validate_event_exporter_signature( def install_python_root_package(*, node_root: Path, project_dir: Path) -> dict[str, ModuleType]: - """Bind python to this project's python/ folder and return displaced unrelated modules.""" + """Bind python to this project's python/ folder and return the unrelated modules displaced.""" - existing: ModuleType | None = sys.modules.get(PYTHON_NODE_ROOT) + saved_modules: dict[str, ModuleType] = _ensure_python_package(project_dir=project_dir) + nodes_package: str = ".".join(Path(PYTHON_NODE_ROOT).parts) + module_name: str + for module_name in tuple(sys.modules): + if module_name == nodes_package or module_name.startswith(f"{nodes_package}."): + sys.modules.pop(module_name, None) + importlib.invalidate_caches() + del node_root + return saved_modules + + +def _ensure_python_package(*, project_dir: Path) -> dict[str, ModuleType]: + """Bind python to `project_dir`'s python/ folder, keeping a binding already made to it.""" + + package_root: Path = project_dir / PYTHON_PACKAGE_NAME + existing: ModuleType | None = sys.modules.get(PYTHON_PACKAGE_NAME) + if existing is not None and getattr(existing, _PROJECT_PYTHON_PACKAGE_MARKER, None) == str( + package_root.resolve() + ): + return {} owned: bool = existing is None or bool(getattr(existing, _PROJECT_PYTHON_PACKAGE_MARKER, False)) saved_modules: dict[str, ModuleType] = {} module_name: str @@ -148,23 +168,23 @@ def install_python_root_package(*, node_root: Path, project_dir: Path) -> dict[s saved_modules[module_name] = module importlib.invalidate_caches() _ = register_user_code_root(project_dir) - init_file: Path = node_root / f"{PYTHON_INIT_MODULE_STEM}.py" + init_file: Path = package_root / f"{PYTHON_INIT_MODULE_STEM}.py" spec: ModuleSpec | None = ( user_code_spec( - name=PYTHON_NODE_ROOT, + name=PYTHON_PACKAGE_NAME, file_path=init_file, root=project_dir, - submodule_search_locations=[str(node_root)], + submodule_search_locations=[str(package_root)], ) if init_file.is_file() - else ModuleSpec(PYTHON_NODE_ROOT, None, is_package=True) + else ModuleSpec(PYTHON_PACKAGE_NAME, None, is_package=True) ) if spec is None: - raise PythonNodeDiscoveryError(f"Could not load Python node package {node_root}") - spec.submodule_search_locations = [str(node_root)] + raise PythonNodeDiscoveryError(f"Could not load Python package {package_root}") + spec.submodule_search_locations = [str(package_root)] package: ModuleType = importlib.util.module_from_spec(spec) - setattr(package, _PROJECT_PYTHON_PACKAGE_MARKER, True) - sys.modules[PYTHON_NODE_ROOT] = package + setattr(package, _PROJECT_PYTHON_PACKAGE_MARKER, str(package_root.resolve())) + sys.modules[PYTHON_PACKAGE_NAME] = package if spec.loader is None: return saved_modules old_path: list[str] = list(sys.path) @@ -174,7 +194,7 @@ def install_python_root_package(*, node_root: Path, project_dir: Path) -> dict[s except Exception as error: restore_python_root_modules(saved_modules=saved_modules) raise PythonNodeDiscoveryError( - f"Failed to import Python node file {init_file.relative_to(project_dir)}: {error}" + f"Failed to import Python package file {init_file.relative_to(project_dir)}: {error}" ) from error finally: sys.path = old_path @@ -226,8 +246,9 @@ def load_python_node_module(*, file_path: Path, project_dir: Path) -> ModuleType def load_provider_module(*, file_path: Path, project_dir: Path) -> ModuleType: - """Import one providers/ module under its package name.""" + """Import one python/providers/ module under its package name.""" + _ = _ensure_python_package(project_dir=project_dir) return _load_project_package_module( file_path=file_path, project_dir=project_dir, @@ -236,13 +257,14 @@ def load_provider_module(*, file_path: Path, project_dir: Path) -> ModuleType: ) -def load_sink_module(*, file_path: Path, project_dir: Path) -> ModuleType: - """Import one sinks/ module under its package name.""" +def load_event_sink_module(*, file_path: Path, project_dir: Path) -> ModuleType: + """Import one python/event_sinks/ module under its package name.""" + _ = _ensure_python_package(project_dir=project_dir) return _load_project_package_module( file_path=file_path, project_dir=project_dir, - file_label="sink", + file_label="event sink", error_type=EventExporterDiscoveryError, ) @@ -261,8 +283,9 @@ def load_orchestration_module(*, file_path: Path, project_dir: Path) -> ModuleTy def load_materialize_function( *, file_path: Path, project_dir: Path ) -> Callable[..., object] | None: - """Execute one materializations/ module and return its callable `materialize`, if any.""" + """Execute one python/materializations/ module and return its callable `materialize`, if any.""" + _ = _ensure_python_package(project_dir=project_dir) removed_hook_name: str = "prepare_version" removed_hook_message: str = ( f"materialization '{file_path.stem}' at {file_path} defines " @@ -299,7 +322,7 @@ def _python_root_module_names() -> tuple[str, ...]: return tuple( module_name for module_name in sys.modules - if module_name == PYTHON_NODE_ROOT or module_name.startswith(f"{PYTHON_NODE_ROOT}.") + if module_name == PYTHON_PACKAGE_NAME or module_name.startswith(f"{PYTHON_PACKAGE_NAME}.") ) @@ -387,11 +410,19 @@ def _evict_stale_project_package_modules(*, root_module: str, project_dir: Path) if module_paths is None: sys.modules.pop(module_name, None) continue - if any(Path(path).resolve() == root_path for path in module_paths): + if any(_is_within(path=Path(path).resolve(), root=root_path) for path in module_paths): continue sys.modules.pop(module_name, None) +def _is_within(*, path: Path, root: Path) -> bool: + try: + path.relative_to(root) + except ValueError: + return False + return True + + def provider_usages( *, function: Callable[..., object], provider_by_name: dict[str, DiscoveredProvider] ) -> tuple[DiscoveredProviderUsage, ...]: diff --git a/src/sqlbuild/compiler/discovery/main/runtime_extensions.py b/src/sqlbuild/compiler/discovery/main/runtime_extensions.py index 773d40dcee..55f3ff0642 100644 --- a/src/sqlbuild/compiler/discovery/main/runtime_extensions.py +++ b/src/sqlbuild/compiler/discovery/main/runtime_extensions.py @@ -43,12 +43,13 @@ def discover_runtime_extensions(*, project_dir: Path) -> DiscoveredRuntimeExtens return DiscoveredRuntimeExtensions() config: LifecycleEventSinksConfig = _native.load_project_config_file( project_dir - ).sinks.lifecycle + ).event_sinks.lifecycle declaration_names: frozenset[str] = frozenset(item.name for item in declarations) unknown_names: frozenset[str] = frozenset(config.named) - declaration_names if unknown_names: raise ProjectConfigError( - "sinks.lifecycle.named contains unknown sink(s): " + ", ".join(sorted(unknown_names)) + "event_sinks.lifecycle.named contains unknown event sink(s): " + + ", ".join(sorted(unknown_names)) ) if not declarations and not output_declarations: return DiscoveredRuntimeExtensions() diff --git a/src/sqlbuild/compiler/python_nodes/_helpers/user_inventory.py b/src/sqlbuild/compiler/python_nodes/_helpers/user_inventory.py index 42f6aed335..120b7d0fb0 100644 --- a/src/sqlbuild/compiler/python_nodes/_helpers/user_inventory.py +++ b/src/sqlbuild/compiler/python_nodes/_helpers/user_inventory.py @@ -6,7 +6,7 @@ from contextlib import AbstractContextManager from pathlib import Path -from sqlbuild._native import PythonNodeIdentity +from sqlbuild._native import PYTHON_NODE_ROOT, PythonNodeIdentity from sqlbuild.compiler.python_nodes._helpers.identity import build_python_identity, identity_pass from sqlbuild.python_nodes.main.read_asset_definition import read_asset_definition from sqlbuild.python_nodes.main.read_check_definition import read_check_definition @@ -39,11 +39,22 @@ def python_node_identity( node_type=kind, node_name=name, function=function, - project_dir=file_path.parent, + project_dir=_project_dir(file_path), decorator_config=decorator_config, ) +def _project_dir(file_path: Path) -> Path: + """The project holding node file `file_path`: the folder above its `python/nodes/`.""" + + node_root: tuple[str, ...] = Path(PYTHON_NODE_ROOT).parts + parent: Path + for parent in file_path.parents: + if parent.parts[-len(node_root) :] == node_root: + return parent.parents[len(node_root) - 1] + return file_path.parent + + def python_node_dependency_key(dependency: object) -> object | tuple[str, str]: """The node name a decorated dependency or discovered item names, or the dependency itself.""" diff --git a/src/sqlbuild/sinks.py b/src/sqlbuild/event_sinks.py similarity index 77% rename from src/sqlbuild/sinks.py rename to src/sqlbuild/event_sinks.py index c0445e039a..0342a13a0a 100644 --- a/src/sqlbuild/sinks.py +++ b/src/sqlbuild/event_sinks.py @@ -3,11 +3,11 @@ from sqlbuild._native import command_output_context as command_output_context from sqlbuild._native import command_output_from_json as command_output_from_json from sqlbuild._native import command_output_to_json as command_output_to_json -from sqlbuild.runtime.event_exporting.main.command_output_sink import ( - command_output_sink as command_output_sink, +from sqlbuild.runtime.event_exporting.main.command_output_event_sink import ( + command_output_event_sink as command_output_event_sink, ) -from sqlbuild.runtime.event_exporting.main.get_command_output_sink_definition import ( - get_command_output_sink_definition as get_command_output_sink_definition, +from sqlbuild.runtime.event_exporting.main.get_command_output_event_sink_definition import ( + get_command_output_event_sink_definition as get_command_output_event_sink_definition, ) from sqlbuild.runtime.event_exporting.main.get_lifecycle_event_sink_definition import ( get_lifecycle_event_sink_definition as get_lifecycle_event_sink_definition, @@ -27,16 +27,16 @@ CommandOutputValidationError as CommandOutputValidationError, ) from sqlbuild.runtime.output_capture.models import ( - CommandOutputRecord as CommandOutputRecord, + CommandOutputEventSinkDefinition as CommandOutputEventSinkDefinition, ) from sqlbuild.runtime.output_capture.models import ( - CommandOutputSinkDefinition as CommandOutputSinkDefinition, + CommandOutputRecord as CommandOutputRecord, ) from sqlbuild.runtime.output_capture.types import CommandOutputStream as CommandOutputStream __all__ = ( "CommandOutputRecord", - "CommandOutputSinkDefinition", + "CommandOutputEventSinkDefinition", "CommandOutputStream", "CommandOutputValidationError", "LifecycleEventSinkDefinition", @@ -44,9 +44,9 @@ "LifecycleEvent", "command_output_context", "command_output_from_json", - "command_output_sink", + "command_output_event_sink", "command_output_to_json", - "get_command_output_sink_definition", + "get_command_output_event_sink_definition", "get_lifecycle_event_sink_definition", "lifecycle_event_sink", "lifecycle_event_to_json", diff --git a/src/sqlbuild/executor/pipeline/main/run.py b/src/sqlbuild/executor/pipeline/main/run.py index c6a893e488..c5fdbf65be 100644 --- a/src/sqlbuild/executor/pipeline/main/run.py +++ b/src/sqlbuild/executor/pipeline/main/run.py @@ -172,6 +172,10 @@ def _run_build_pipeline( connection_count=effective_concurrency, callbacks=inputs.callbacks, ) + _ = _publish_execution_start( + concurrency=effective_concurrency, + connections=len(preparation.worker_connections) + 1, + ) timing_tracker: BuildPhaseTimingTracker | None = BuildPhaseTimingTracker.current() execution_error: BaseException | None = None execution_start: float = time.monotonic() @@ -212,3 +216,18 @@ def _run_build_pipeline( connections=cleanup_connections, active_error=execution_error, ) + + +def _publish_execution_start(*, concurrency: int, connections: int) -> None: + dispatcher: EventDispatcher | None = current_event_dispatcher() + if dispatcher is not None: + dispatcher.publish_lifecycle( + create_lifecycle_event( + event_type="invocation_phase", + payload={ + "phase": "started_execution", + "count": concurrency, + "detail": f"{connections} connections", + }, + ) + ) diff --git a/src/sqlbuild/loaders.pyi b/src/sqlbuild/loaders.pyi index 4ca3937bce..1ce1268ee9 100644 --- a/src/sqlbuild/loaders.pyi +++ b/src/sqlbuild/loaders.pyi @@ -3,6 +3,7 @@ from typing import overload from sqlbuild._native import SourceColumnEntry from sqlbuild.python_nodes.models import LoaderDefinition as LoaderDefinition +from sqlbuild.python_nodes.models import NodeSetRef from sqlbuild.python_nodes.types import LoaderColumnSpec @overload @@ -11,7 +12,8 @@ def loader(function: Callable[..., object]) -> Callable[..., object]: ... def loader( *, name: str | None = None, - depends_on: tuple[Callable[..., object], ...] | list[Callable[..., object]] = (), + depends_on: tuple[Callable[..., object] | NodeSetRef, ...] + | list[Callable[..., object] | NodeSetRef] = (), destination: str | None = None, write_strategy: str | None = None, cursor_column: str | None = None, diff --git a/src/sqlbuild/playground_templates/loader_waffle_shop/python/loaders/waffle_loaders.py.txt b/src/sqlbuild/playground_templates/loader_waffle_shop/python/loaders/waffle_loaders.py.txt deleted file mode 100644 index dc2c376c64..0000000000 --- a/src/sqlbuild/playground_templates/loader_waffle_shop/python/loaders/waffle_loaders.py.txt +++ /dev/null @@ -1,117 +0,0 @@ -from sqlbuild.loaders import loader - - -@loader( - write_strategy="append", - cursor_column="load_seq", - columns=[ - {"name": "order_id", "type": "INTEGER"}, - {"name": "customer_id", "type": "INTEGER"}, - {"name": "waffle_type", "type": "VARCHAR"}, - {"name": "quantity", "type": "INTEGER"}, - {"name": "load_seq", "type": "INTEGER"}, - ], -) -def fetch_order_events(ctx): - """Fetch new order events since the last loaded sequence number.""" - - if ctx.current_cursor_value is None: - next_seq = 1 - else: - next_seq = ctx.current_cursor_value + 1 - first_order = (next_seq - 1) * 2 + 1 - return [ - { - "order_id": first_order, - "customer_id": 1 if next_seq == 1 else 3, - "waffle_type": "classic", - "quantity": next_seq, - "load_seq": next_seq, - }, - { - "order_id": first_order + 1, - "customer_id": 2, - "waffle_type": "blueberry", - "quantity": next_seq + 1, - "load_seq": next_seq, - }, - ] - - -@loader( - write_strategy="merge", - unique_key="customer_id", - cursor_column="load_seq", - columns=[ - {"name": "customer_id", "type": "INTEGER"}, - {"name": "plan_name", "type": "VARCHAR"}, - {"name": "load_seq", "type": "INTEGER"}, - ], -) -def fetch_customers(ctx): - """Fetch customer records changed since the last load.""" - - if ctx.current_cursor_value is None: - return [ - {"customer_id": 1, "plan_name": "basic", "load_seq": 1}, - {"customer_id": 2, "plan_name": "plus", "load_seq": 1}, - ] - return [ - {"customer_id": 1, "plan_name": "pro", "load_seq": 2}, - {"customer_id": 3, "plan_name": "enterprise", "load_seq": 2}, - ] - - -@loader( - write_strategy="delete_insert", - cursor_column="load_seq", - columns=[ - {"name": "waffle_type", "type": "VARCHAR"}, - {"name": "price_cents", "type": "INTEGER"}, - {"name": "load_seq", "type": "INTEGER"}, - ], -) -def fetch_prices(ctx): - """Fetch the current waffle price list.""" - - classic_price = 600 if ctx.current_cursor_value is None else 650 - return [ - {"waffle_type": "classic", "price_cents": classic_price, "load_seq": 1}, - {"waffle_type": "blueberry", "price_cents": 750, "load_seq": 1}, - ] - - -@loader(depends_on=[fetch_order_events, fetch_prices]) -def raw_orders(ctx): - events = ctx.loader(fetch_order_events) - prices = ctx.loader(fetch_prices) - cursor = ctx.query( - f"SELECT e.order_id, e.customer_id, e.waffle_type, e.quantity, " - f"p.price_cents, e.load_seq FROM {events.destination} e " - f"JOIN {prices.destination} p ON e.waffle_type = p.waffle_type " - f"ORDER BY e.order_id" - ) - return [ - { - "order_id": row[0], - "customer_id": row[1], - "waffle_type": row[2], - "quantity": row[3], - "price_cents": row[4], - "load_seq": row[5], - } - for row in cursor.fetchall() - ] - - -@loader(depends_on=[fetch_customers]) -def raw_customers(ctx): - customers = ctx.loader(fetch_customers) - cursor = ctx.query( - f"SELECT customer_id, plan_name, load_seq FROM {customers.destination} " - "ORDER BY customer_id" - ) - return [ - {"customer_id": row[0], "plan_name": row[1], "load_seq": row[2]} - for row in cursor.fetchall() - ] diff --git a/src/sqlbuild/playground_templates/loader_waffle_shop/python/nodes/loaders/waffle_loaders/loaders.py.txt b/src/sqlbuild/playground_templates/loader_waffle_shop/python/nodes/loaders/waffle_loaders/loaders.py.txt new file mode 100644 index 0000000000..a346252b9d --- /dev/null +++ b/src/sqlbuild/playground_templates/loader_waffle_shop/python/nodes/loaders/waffle_loaders/loaders.py.txt @@ -0,0 +1,120 @@ +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + + +@factory +def waffle_loaders_loaders() -> list[object]: + @loader( + write_strategy="append", + cursor_column="load_seq", + columns=[ + {"name": "order_id", "type": "INTEGER"}, + {"name": "customer_id", "type": "INTEGER"}, + {"name": "waffle_type", "type": "VARCHAR"}, + {"name": "quantity", "type": "INTEGER"}, + {"name": "load_seq", "type": "INTEGER"}, + ], + ) + def fetch_order_events(ctx): + """Fetch new order events since the last loaded sequence number.""" + + if ctx.current_cursor_value is None: + next_seq = 1 + else: + next_seq = ctx.current_cursor_value + 1 + first_order = (next_seq - 1) * 2 + 1 + return [ + { + "order_id": first_order, + "customer_id": 1 if next_seq == 1 else 3, + "waffle_type": "classic", + "quantity": next_seq, + "load_seq": next_seq, + }, + { + "order_id": first_order + 1, + "customer_id": 2, + "waffle_type": "blueberry", + "quantity": next_seq + 1, + "load_seq": next_seq, + }, + ] + + @loader( + write_strategy="merge", + unique_key="customer_id", + cursor_column="load_seq", + columns=[ + {"name": "customer_id", "type": "INTEGER"}, + {"name": "plan_name", "type": "VARCHAR"}, + {"name": "load_seq", "type": "INTEGER"}, + ], + ) + def fetch_customers(ctx): + """Fetch customer records changed since the last load.""" + + if ctx.current_cursor_value is None: + return [ + {"customer_id": 1, "plan_name": "basic", "load_seq": 1}, + {"customer_id": 2, "plan_name": "plus", "load_seq": 1}, + ] + return [ + {"customer_id": 1, "plan_name": "pro", "load_seq": 2}, + {"customer_id": 3, "plan_name": "enterprise", "load_seq": 2}, + ] + + @loader( + write_strategy="delete_insert", + cursor_column="load_seq", + columns=[ + {"name": "waffle_type", "type": "VARCHAR"}, + {"name": "price_cents", "type": "INTEGER"}, + {"name": "load_seq", "type": "INTEGER"}, + ], + ) + def fetch_prices(ctx): + """Fetch the current waffle price list.""" + + classic_price = 600 if ctx.current_cursor_value is None else 650 + return [ + {"waffle_type": "classic", "price_cents": classic_price, "load_seq": 1}, + {"waffle_type": "blueberry", "price_cents": 750, "load_seq": 1}, + ] + + @loader(depends_on=[fetch_order_events, fetch_prices]) + def raw_orders(ctx): + events = ctx.loader(fetch_order_events) + prices = ctx.loader(fetch_prices) + cursor = ctx.query( + f"SELECT e.order_id, e.customer_id, e.waffle_type, e.quantity, " + f"p.price_cents, e.load_seq FROM {events.destination} e " + f"JOIN {prices.destination} p ON e.waffle_type = p.waffle_type " + f"ORDER BY e.order_id" + ) + return [ + { + "order_id": row[0], + "customer_id": row[1], + "waffle_type": row[2], + "quantity": row[3], + "price_cents": row[4], + "load_seq": row[5], + } + for row in cursor.fetchall() + ] + + @loader(depends_on=[fetch_customers]) + def raw_customers(ctx): + customers = ctx.loader(fetch_customers) + cursor = ctx.query( + f"SELECT customer_id, plan_name, load_seq FROM {customers.destination} " + "ORDER BY customer_id" + ) + return [ + {"customer_id": row[0], "plan_name": row[1], "load_seq": row[2]} + for row in cursor.fetchall() + ] + + + return [fetch_order_events, fetch_customers, fetch_prices, raw_orders, raw_customers] diff --git a/src/sqlbuild/playground_templates/loader_waffle_shop/hooks/python/.gitkeep b/src/sqlbuild/playground_templates/loader_waffle_shop/sql/hooks/python/.gitkeep similarity index 100% rename from src/sqlbuild/playground_templates/loader_waffle_shop/hooks/python/.gitkeep rename to src/sqlbuild/playground_templates/loader_waffle_shop/sql/hooks/python/.gitkeep diff --git a/src/sqlbuild/playground_templates/loader_waffle_shop/hooks/sql/.gitkeep b/src/sqlbuild/playground_templates/loader_waffle_shop/sql/hooks/sql/.gitkeep similarity index 100% rename from src/sqlbuild/playground_templates/loader_waffle_shop/hooks/sql/.gitkeep rename to src/sqlbuild/playground_templates/loader_waffle_shop/sql/hooks/sql/.gitkeep diff --git a/src/sqlbuild/playground_templates/loader_waffle_shop/models/customer_revenue.sql b/src/sqlbuild/playground_templates/loader_waffle_shop/sql/models/customer_revenue.sql similarity index 100% rename from src/sqlbuild/playground_templates/loader_waffle_shop/models/customer_revenue.sql rename to src/sqlbuild/playground_templates/loader_waffle_shop/sql/models/customer_revenue.sql diff --git a/src/sqlbuild/playground_templates/loader_waffle_shop/models/fact_waffle_orders.sql b/src/sqlbuild/playground_templates/loader_waffle_shop/sql/models/fact_waffle_orders.sql similarity index 100% rename from src/sqlbuild/playground_templates/loader_waffle_shop/models/fact_waffle_orders.sql rename to src/sqlbuild/playground_templates/loader_waffle_shop/sql/models/fact_waffle_orders.sql diff --git a/src/sqlbuild/playground_templates/loader_waffle_shop/sources/raw.yml b/src/sqlbuild/playground_templates/loader_waffle_shop/sql/sources/raw.yml similarity index 100% rename from src/sqlbuild/playground_templates/loader_waffle_shop/sources/raw.yml rename to src/sqlbuild/playground_templates/loader_waffle_shop/sql/sources/raw.yml diff --git a/src/sqlbuild/playground_templates/python_nodes/python/assets/orders_inputs.py.txt b/src/sqlbuild/playground_templates/python_nodes/python/assets/orders_inputs.py.txt deleted file mode 100644 index 8dfae170f2..0000000000 --- a/src/sqlbuild/playground_templates/python_nodes/python/assets/orders_inputs.py.txt +++ /dev/null @@ -1,28 +0,0 @@ -"""Upstream asset examples for the Python nodes playground.""" - -from sqlbuild.assets import SkipMode, asset - - -@asset(tags=["python", "ingress"], group="ingress") -def prepare_raw_orders(ctx): - """Prepare a tiny in-memory order extract before the loader runs.""" - - rows = [ - {"order_id": 1, "customer_id": 10, "amount_cents": 1200, "load_batch": 1}, - {"order_id": 2, "customer_id": 20, "amount_cents": 800, "load_batch": 1}, - ] - return ctx.result(payload={"rows": rows}, metadata={"row_count": len(rows)}) - - -@asset(tags=["python", "optional"], group="exports") -def optional_partner_feed(ctx): - """Soft-skip an optional upstream without blocking sibling fan-in.""" - - return ctx.skip(reason="partner feed is not configured", mode=SkipMode.SOFT) - - -@asset(tags=["python", "optional"], group="exports") -def export_window(ctx): - """Successful sibling that lets downstream fan-in continue.""" - - return ctx.result(payload={"window": "daily"}) diff --git a/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/export_window/asset.py.txt b/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/export_window/asset.py.txt new file mode 100644 index 0000000000..6fe0337efa --- /dev/null +++ b/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/export_window/asset.py.txt @@ -0,0 +1,10 @@ +"""An upstream asset that names the export window.""" + +from sqlbuild.assets import asset + + +@asset(tags=["python", "optional"], group="exports") +def export_window(ctx): + """Successful sibling that lets downstream fan-in continue.""" + + return ctx.result(payload={"window": "daily"}) diff --git a/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/optional_partner_feed/asset.py.txt b/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/optional_partner_feed/asset.py.txt new file mode 100644 index 0000000000..1887ae94e1 --- /dev/null +++ b/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/optional_partner_feed/asset.py.txt @@ -0,0 +1,10 @@ +"""An optional upstream asset that soft-skips.""" + +from sqlbuild.assets import SkipMode, asset + + +@asset(tags=["python", "optional"], group="exports") +def optional_partner_feed(ctx): + """Soft-skip an optional upstream without blocking sibling fan-in.""" + + return ctx.skip(reason="partner feed is not configured", mode=SkipMode.SOFT) diff --git a/src/sqlbuild/playground_templates/python_nodes/python/assets/orders_export.py.txt b/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/orders_export/asset.py.txt similarity index 85% rename from src/sqlbuild/playground_templates/python_nodes/python/assets/orders_export.py.txt rename to src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/orders_export/asset.py.txt index 1280ac3c9c..e0c603ccc2 100644 --- a/src/sqlbuild/playground_templates/python_nodes/python/assets/orders_export.py.txt +++ b/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/orders_export/asset.py.txt @@ -3,7 +3,8 @@ from sqlbuild.assets import asset from sqlbuild.refs import model -from python.assets.orders_inputs import export_window, optional_partner_feed +from python.nodes.assets.export_window.asset import export_window +from python.nodes.assets.optional_partner_feed.asset import optional_partner_feed @asset( diff --git a/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/prepare_raw_orders/asset.py.txt b/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/prepare_raw_orders/asset.py.txt new file mode 100644 index 0000000000..f2d639140e --- /dev/null +++ b/src/sqlbuild/playground_templates/python_nodes/python/nodes/assets/prepare_raw_orders/asset.py.txt @@ -0,0 +1,14 @@ +"""An upstream asset that prepares a tiny order extract for the loader.""" + +from sqlbuild.assets import asset + + +@asset(tags=["python", "ingress"], group="ingress") +def prepare_raw_orders(ctx): + """Prepare a tiny in-memory order extract before the loader runs.""" + + rows = [ + {"order_id": 1, "customer_id": 10, "amount_cents": 1200, "load_batch": 1}, + {"order_id": 2, "customer_id": 20, "amount_cents": 800, "load_batch": 1}, + ] + return ctx.result(payload={"rows": rows}, metadata={"row_count": len(rows)}) diff --git a/src/sqlbuild/playground_templates/python_nodes/python/checks/orders_export.py.txt b/src/sqlbuild/playground_templates/python_nodes/python/nodes/checks/orders_export/checks.py.txt similarity index 91% rename from src/sqlbuild/playground_templates/python_nodes/python/checks/orders_export.py.txt rename to src/sqlbuild/playground_templates/python_nodes/python/nodes/checks/orders_export/checks.py.txt index cc4cd581d9..8521638be1 100644 --- a/src/sqlbuild/playground_templates/python_nodes/python/checks/orders_export.py.txt +++ b/src/sqlbuild/playground_templates/python_nodes/python/nodes/checks/orders_export/checks.py.txt @@ -2,7 +2,7 @@ from sqlbuild.checks import check -from python.assets.orders_export import orders_export +from python.nodes.assets.orders_export.asset import orders_export @check(depends_on=orders_export, tags=["quality"], group="exports") diff --git a/src/sqlbuild/playground_templates/python_nodes/python/loaders/orders.py.txt b/src/sqlbuild/playground_templates/python_nodes/python/nodes/loaders/orders/loader.py.txt similarity index 88% rename from src/sqlbuild/playground_templates/python_nodes/python/loaders/orders.py.txt rename to src/sqlbuild/playground_templates/python_nodes/python/nodes/loaders/orders/loader.py.txt index f65022bfd1..6bcc706829 100644 --- a/src/sqlbuild/playground_templates/python_nodes/python/loaders/orders.py.txt +++ b/src/sqlbuild/playground_templates/python_nodes/python/nodes/loaders/orders/loader.py.txt @@ -1,7 +1,7 @@ """Loader examples for the Python nodes playground.""" from sqlbuild.loaders import loader -from python.assets.orders_inputs import prepare_raw_orders +from python.nodes.assets.prepare_raw_orders.asset import prepare_raw_orders @loader(depends_on=(prepare_raw_orders,)) diff --git a/src/sqlbuild/playground_templates/python_nodes/hooks/python/.gitkeep b/src/sqlbuild/playground_templates/python_nodes/sql/hooks/python/.gitkeep similarity index 100% rename from src/sqlbuild/playground_templates/python_nodes/hooks/python/.gitkeep rename to src/sqlbuild/playground_templates/python_nodes/sql/hooks/python/.gitkeep diff --git a/src/sqlbuild/playground_templates/python_nodes/hooks/sql/.gitkeep b/src/sqlbuild/playground_templates/python_nodes/sql/hooks/sql/.gitkeep similarity index 100% rename from src/sqlbuild/playground_templates/python_nodes/hooks/sql/.gitkeep rename to src/sqlbuild/playground_templates/python_nodes/sql/hooks/sql/.gitkeep diff --git a/src/sqlbuild/playground_templates/python_nodes/models/fact_orders.sql b/src/sqlbuild/playground_templates/python_nodes/sql/models/fact_orders.sql similarity index 100% rename from src/sqlbuild/playground_templates/python_nodes/models/fact_orders.sql rename to src/sqlbuild/playground_templates/python_nodes/sql/models/fact_orders.sql diff --git a/src/sqlbuild/playground_templates/python_nodes/sources/raw.yml b/src/sqlbuild/playground_templates/python_nodes/sql/sources/raw.yml similarity index 100% rename from src/sqlbuild/playground_templates/python_nodes/sources/raw.yml rename to src/sqlbuild/playground_templates/python_nodes/sql/sources/raw.yml diff --git a/src/sqlbuild/playground_templates/waffle_shop/README.md b/src/sqlbuild/playground_templates/waffle_shop/README.md index a0246bea43..1e66c322eb 100644 --- a/src/sqlbuild/playground_templates/waffle_shop/README.md +++ b/src/sqlbuild/playground_templates/waffle_shop/README.md @@ -45,8 +45,8 @@ sqb lineage fact_orders ### Try semantic compilation `sqb compile` checks the enforced source schemas offline. Change `o.quantity` to `o.qty` in -`models/marts/fact_orders.sql` to see an unknown-column error (B002). Add -`WHERE ordered_at > 5` to `models/staging/stg_orders.sql` to see DuckDB's timestamp/integer +`sql/models/marts/fact_orders.sql` to see an unknown-column error (B002). Add +`WHERE ordered_at > 5` to `sql/models/staging/stg_orders.sql` to see DuckDB's timestamp/integer comparison error (B217). Restore each edit after trying it; downstream models and SQL tests may also report the consequences of a changed output column. diff --git a/src/sqlbuild/playground_templates/waffle_shop/materializations/partition_tracked.py.txt b/src/sqlbuild/playground_templates/waffle_shop/python/materializations/partition_tracked.py.txt similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/materializations/partition_tracked.py.txt rename to src/sqlbuild/playground_templates/waffle_shop/python/materializations/partition_tracked.py.txt diff --git a/tests/e2e/fixtures/waffle_shop/python/loaders/waffle_sources.py b/src/sqlbuild/playground_templates/waffle_shop/python/nodes/loaders/waffle_sources/loaders.py.txt similarity index 71% rename from tests/e2e/fixtures/waffle_shop/python/loaders/waffle_sources.py rename to src/sqlbuild/playground_templates/waffle_shop/python/nodes/loaders/waffle_sources/loaders.py.txt index 5c240440ca..bfd39fdea1 100644 --- a/tests/e2e/fixtures/waffle_shop/python/loaders/waffle_sources.py +++ b/src/sqlbuild/playground_templates/waffle_shop/python/nodes/loaders/waffle_sources/loaders.py.txt @@ -1,8 +1,10 @@ from collections.abc import Iterator from datetime import datetime +from sqlbuild.factories import factory from sqlbuild.loaders import loader + CUSTOMERS: list[dict[str, object]] = [ { "id": 1, @@ -55,23 +57,26 @@ ] -@loader -def raw_customers(ctx: object) -> list[dict[str, object]]: - """Test loader raw_customers.""" - _ = ctx - return CUSTOMERS + +@factory +def waffle_sources_loaders() -> list[object]: + @loader + def raw__customers(ctx: object) -> list[dict[str, object]]: + _ = ctx + return CUSTOMERS + + @loader + def raw__orders(ctx: object) -> Iterator[dict[str, object]]: + _ = ctx + for order_id, customer_id, waffle_type_id, quantity, ordered_at, status in ORDERS: + yield { + "id": order_id, + "customer_id": customer_id, + "waffle_type_id": waffle_type_id, + "quantity": quantity, + "ordered_at": ordered_at, + "status": status, + } -@loader -def raw_orders(ctx: object) -> Iterator[dict[str, object]]: - """Test loader raw_orders.""" - _ = ctx - for order_id, customer_id, waffle_type_id, quantity, ordered_at, status in ORDERS: - yield { - "id": order_id, - "customer_id": customer_id, - "waffle_type_id": waffle_type_id, - "quantity": quantity, - "ordered_at": ordered_at, - "status": status, - } + return [raw__customers, raw__orders] diff --git a/src/sqlbuild/playground_templates/waffle_shop/functions/sql/table_fn__customer_orders.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/functions/sql/table_fn__customer_orders.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/functions/sql/table_fn__customer_orders.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/functions/sql/table_fn__customer_orders.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/functions/sql/udf__is_completed_order.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/functions/sql/udf__is_completed_order.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/functions/sql/udf__is_completed_order.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/functions/sql/udf__is_completed_order.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/hooks/python/.gitkeep b/src/sqlbuild/playground_templates/waffle_shop/sql/hooks/python/.gitkeep similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/hooks/python/.gitkeep rename to src/sqlbuild/playground_templates/waffle_shop/sql/hooks/python/.gitkeep diff --git a/src/sqlbuild/playground_templates/waffle_shop/hooks/sql/.gitkeep b/src/sqlbuild/playground_templates/waffle_shop/sql/hooks/sql/.gitkeep similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/hooks/sql/.gitkeep rename to src/sqlbuild/playground_templates/waffle_shop/sql/hooks/sql/.gitkeep diff --git a/src/sqlbuild/playground_templates/waffle_shop/macros/python/currency.py.txt b/src/sqlbuild/playground_templates/waffle_shop/sql/macros/python/currency.py.txt similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/macros/python/currency.py.txt rename to src/sqlbuild/playground_templates/waffle_shop/sql/macros/python/currency.py.txt diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/intermediate/customer_status_snapshot.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/intermediate/customer_status_snapshot.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/intermediate/customer_status_snapshot.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/intermediate/customer_status_snapshot.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/intermediate/order_status_index.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/intermediate/order_status_index.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/intermediate/order_status_index.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/intermediate/order_status_index.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/_sqlbuild/_macros/python/currency.py.txt b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/_sqlbuild/_macros/python/currency.py.txt similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/_sqlbuild/_macros/python/currency.py.txt rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/_sqlbuild/_macros/python/currency.py.txt diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/_sqlbuild/_macros/python/datetime.py.txt b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/_sqlbuild/_macros/python/datetime.py.txt similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/_sqlbuild/_macros/python/datetime.py.txt rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/_sqlbuild/_macros/python/datetime.py.txt diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/daily_activity_rollup.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/daily_activity_rollup.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/daily_activity_rollup.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/daily_activity_rollup.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/daily_order_partitioned.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/daily_order_partitioned.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/daily_order_partitioned.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/daily_order_partitioned.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/daily_revenue.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/daily_revenue.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/daily_revenue.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/daily_revenue.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/dim_customers.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/dim_customers.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/dim_customers.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/dim_customers.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/fact_orders.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/fact_orders.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/fact_orders.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/fact_orders.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/hourly_activity_with_daily_context.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/hourly_activity_with_daily_context.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/hourly_activity_with_daily_context.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/hourly_activity_with_daily_context.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/marts/hourly_order_activity.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/hourly_order_activity.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/marts/hourly_order_activity.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/marts/hourly_order_activity.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/staging/stg_customers.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/staging/stg_customers.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/staging/stg_customers.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/staging/stg_customers.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/staging/stg_orders.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/staging/stg_orders.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/staging/stg_orders.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/staging/stg_orders.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/models/staging/stg_payments.sql b/src/sqlbuild/playground_templates/waffle_shop/sql/models/staging/stg_payments.sql similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/models/staging/stg_payments.sql rename to src/sqlbuild/playground_templates/waffle_shop/sql/models/staging/stg_payments.sql diff --git a/src/sqlbuild/playground_templates/waffle_shop/seeds/lookups.yml b/src/sqlbuild/playground_templates/waffle_shop/sql/seeds/lookups.yml similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/seeds/lookups.yml rename to src/sqlbuild/playground_templates/waffle_shop/sql/seeds/lookups.yml diff --git a/src/sqlbuild/playground_templates/waffle_shop/seeds/waffle_types.csv b/src/sqlbuild/playground_templates/waffle_shop/sql/seeds/waffle_types.csv similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/seeds/waffle_types.csv rename to src/sqlbuild/playground_templates/waffle_shop/sql/seeds/waffle_types.csv diff --git a/src/sqlbuild/playground_templates/waffle_shop/sources/raw.yml b/src/sqlbuild/playground_templates/waffle_shop/sql/sources/raw.yml similarity index 100% rename from src/sqlbuild/playground_templates/waffle_shop/sources/raw.yml rename to src/sqlbuild/playground_templates/waffle_shop/sql/sources/raw.yml diff --git a/src/sqlbuild/provider/_helpers/injection.py b/src/sqlbuild/provider/_helpers/injection.py index 4718700410..03f400ba04 100644 --- a/src/sqlbuild/provider/_helpers/injection.py +++ b/src/sqlbuild/provider/_helpers/injection.py @@ -146,6 +146,6 @@ def _provider_alias_import_message( f"{provider_annotation.__name__} imported as " f"'{provider_annotation.__module__}', but provider '{parameter_name}' was discovered as " f"{provider_class.__module__}.{provider_class.__name__}. Import project providers using " - "the project-root providers package path, for example: " - "from providers.my_provider import MyProvider" + "the project path of the providers package, for example: " + "from python.providers.my_provider.provider import MyProvider" ) diff --git a/src/sqlbuild/provider/classes/session.py b/src/sqlbuild/provider/classes/session.py index 79a4897d6d..59b50d9060 100644 --- a/src/sqlbuild/provider/classes/session.py +++ b/src/sqlbuild/provider/classes/session.py @@ -120,6 +120,7 @@ def close(self, *, force: bool = False) -> None: return self._is_closed = True errors: list[str] = [] + failures: list[str] = [] for name in reversed(self._setup_names): provider: Provider = self._providers[name] try: @@ -129,8 +130,14 @@ def close(self, *, force: bool = False) -> None: f"Provider '{name}' ({provider.__class__.__name__}) failed during " f"teardown: {error}" ) + failures.append( + f"'{name}' ({provider.__class__.__name__}) raised " + f"{error.__class__.__name__}" + ) if errors: - raise ProviderTeardownError("\n".join(errors)) + teardown_error: ProviderTeardownError = ProviderTeardownError("\n".join(errors)) + teardown_error.failures = tuple(failures) + raise teardown_error def _instantiate(self, *, name: str) -> Provider: """Read a deferred provider's settings from the environment on its first use.""" diff --git a/src/sqlbuild/provider/exceptions.py b/src/sqlbuild/provider/exceptions.py index 1dcda8b297..2c7941e391 100644 --- a/src/sqlbuild/provider/exceptions.py +++ b/src/sqlbuild/provider/exceptions.py @@ -14,7 +14,9 @@ class ProviderSetupError(RuntimeError): class ProviderTeardownError(RuntimeError): - """Raised when provider teardown fails.""" + """Raised when provider teardown fails; ``failures`` names each provider and error type.""" + + failures: tuple[str, ...] = () class ProviderInjectionError(RuntimeError): diff --git a/src/sqlbuild/python_nodes/_helpers/dependency_normalization.py b/src/sqlbuild/python_nodes/_helpers/dependency_normalization.py index 2ada3b7eff..c4d1466311 100644 --- a/src/sqlbuild/python_nodes/_helpers/dependency_normalization.py +++ b/src/sqlbuild/python_nodes/_helpers/dependency_normalization.py @@ -18,6 +18,7 @@ def normalize_python_node_dependencies( def normalize_loader_dependencies( - value: tuple[Callable[..., object], ...] | list[Callable[..., object]], -) -> tuple[Callable[..., object], ...]: + value: tuple[Callable[..., object] | NodeSetRef, ...] + | list[Callable[..., object] | NodeSetRef], +) -> tuple[Callable[..., object] | NodeSetRef, ...]: return tuple(value) diff --git a/src/sqlbuild/python_nodes/_helpers/loader_authoring.py b/src/sqlbuild/python_nodes/_helpers/loader_authoring.py index a69d729e8f..2249320438 100644 --- a/src/sqlbuild/python_nodes/_helpers/loader_authoring.py +++ b/src/sqlbuild/python_nodes/_helpers/loader_authoring.py @@ -8,7 +8,7 @@ from sqlbuild._native import SourceWriteStrategy as SourceWriteStrategy from sqlbuild.python_nodes.main._apply_loader import apply_loader from sqlbuild.python_nodes.main.read_loader_definition import read_loader_definition -from sqlbuild.python_nodes.models import LoaderDefinition +from sqlbuild.python_nodes.models import LoaderDefinition, NodeSetRef from sqlbuild.python_nodes.types import LoaderColumnSpec @@ -16,7 +16,8 @@ def loader( function: Callable[..., object] | None = None, *, name: str | None = None, - depends_on: tuple[Callable[..., object], ...] | list[Callable[..., object]] = (), + depends_on: tuple[Callable[..., object] | NodeSetRef, ...] + | list[Callable[..., object] | NodeSetRef] = (), destination: str | None = None, write_strategy: str | None = None, cursor_column: str | None = None, diff --git a/src/sqlbuild/python_nodes/main/_apply_loader.py b/src/sqlbuild/python_nodes/main/_apply_loader.py index 67367a9a9e..f559b48316 100644 --- a/src/sqlbuild/python_nodes/main/_apply_loader.py +++ b/src/sqlbuild/python_nodes/main/_apply_loader.py @@ -14,7 +14,7 @@ normalize_unique_key, normalize_write_strategy, ) -from sqlbuild.python_nodes.models import LoaderDefinition +from sqlbuild.python_nodes.models import LoaderDefinition, NodeSetRef from sqlbuild.python_nodes.types import LoaderColumnSpec @@ -22,7 +22,8 @@ def apply_loader( *, function: Callable[..., object] | None = None, name: str | None = None, - depends_on: tuple[Callable[..., object], ...] | list[Callable[..., object]] = (), + depends_on: tuple[Callable[..., object] | NodeSetRef, ...] + | list[Callable[..., object] | NodeSetRef] = (), destination: str | None = None, write_strategy: str | None = None, cursor_column: str | None = None, @@ -33,7 +34,9 @@ def apply_loader( ) -> Callable[..., object] | Callable[[Callable[..., object]], Callable[..., object]]: """Apply SQLBuild loader metadata to a Python function.""" - normalized_deps: tuple[Callable[..., object], ...] = normalize_loader_dependencies(depends_on) + normalized_deps: tuple[Callable[..., object] | NodeSetRef, ...] = normalize_loader_dependencies( + depends_on + ) def decorate(inner: Callable[..., object]) -> Callable[..., object]: inner_function: Any = cast(Any, inner) diff --git a/src/sqlbuild/python_nodes/models.py b/src/sqlbuild/python_nodes/models.py index 2e2522bc28..d3b8a7431d 100644 --- a/src/sqlbuild/python_nodes/models.py +++ b/src/sqlbuild/python_nodes/models.py @@ -103,7 +103,7 @@ class LoaderDefinition: """Metadata attached to a decorated source loader function.""" name: str - depends_on: tuple[Callable[..., object] | SqlResourceRef, ...] = () + depends_on: tuple[Callable[..., object] | SqlResourceRef | NodeSetRef, ...] = () destination: str | None = None write_strategy: SourceWriteStrategy | None = None cursor_column: str | None = None diff --git a/src/sqlbuild/runtime/event_exporting/README.md b/src/sqlbuild/runtime/event_exporting/README.md index db6a7a4aad..067dc8a337 100644 --- a/src/sqlbuild/runtime/event_exporting/README.md +++ b/src/sqlbuild/runtime/event_exporting/README.md @@ -15,7 +15,7 @@ are dropped. This bounds concurrently hung threads to the number of exporters, b terminate those daemon threads or undo destination side effects if they eventually return. Shutdown stops acceptance, drains only until the shared deadline (CLI commands use -`sinks.lifecycle.shutdown_timeout`, default two seconds), accounts queued and unattempted +`event_sinks.lifecycle.shutdown_timeout`, default two seconds), accounts queued and unattempted deliveries as dropped, terminates the event dispatcher, and returns without waiting for timed-out invocation threads. Concurrent shutdown callers receive the same cached final accounting snapshot. The shared provider session is retained while any invocation remains live. Teardown runs exactly @@ -37,8 +37,8 @@ it returns. and `error`. Omitted declaration filters opt into all kinds from `debug` upward. Options are validated and frozen when the function is decorated. -Project config can only narrow that opt-in. `[sinks.lifecycle]` supplies global `event_kinds` and -`min_severity`; `[sinks.lifecycle.named.]` can narrow one exporter further. Effective +Project config can only narrow that opt-in. `[event_sinks.lifecycle]` supplies global `event_kinds` and +`min_severity`; `[event_sinks.lifecycle.named.]` can narrow one exporter further. Effective kinds are the intersection of declaration, global, and named sets. Effective minimum severity is the strictest of those three values. Unknown names, kinds, and severities fail before execution. @@ -73,10 +73,10 @@ dropped. Failure and health diagnostics use only exporter name, catalogued kind/ type, counts, and queue dimensions. They bypass lifecycle publication and exporter enqueue, contain no event payload or destination/provider details, and reporter failures remain isolated. -Startup first imports public Python modules under `sinks/` and collects decorated +Startup first imports public Python modules under `python/event_sinks/` and collects decorated declarations without discovering providers. If those modules contain only helpers, SQLBuild does not import project providers or construct exporter queue, dispatcher, or notification threads. Normal command-owned project discovery remains responsible for providers needed by nodes and hooks. The project declaration, configuration, delivery, security, and failure contract is documented at -[sqlbuild.com/docs/concepts/observability/sinks](https://sqlbuild.com/docs/concepts/observability/sinks/). +[sqlbuild.com/docs/concepts/observability/event-sinks](https://sqlbuild.com/docs/concepts/observability/event-sinks/). diff --git a/src/sqlbuild/runtime/event_exporting/main/command_output_sink.py b/src/sqlbuild/runtime/event_exporting/main/command_output_event_sink.py similarity index 95% rename from src/sqlbuild/runtime/event_exporting/main/command_output_sink.py rename to src/sqlbuild/runtime/event_exporting/main/command_output_event_sink.py index 8c684ba100..11602d7436 100644 --- a/src/sqlbuild/runtime/event_exporting/main/command_output_sink.py +++ b/src/sqlbuild/runtime/event_exporting/main/command_output_event_sink.py @@ -9,11 +9,11 @@ from sqlbuild.python_nodes.main.attach_definition import attach_definition from sqlbuild.runtime.event_exporting.constants import COMMAND_OUTPUT_SINK_ATTRIBUTE from sqlbuild.runtime.event_exporting.exceptions import EventExporterInputError -from sqlbuild.runtime.output_capture.models import CommandOutputSinkDefinition +from sqlbuild.runtime.output_capture.models import CommandOutputEventSinkDefinition from sqlbuild.runtime.output_capture.types import CommandOutputStream -def command_output_sink( +def command_output_event_sink( function: Callable[..., object] | None = None, *, name: str | None = None, @@ -27,7 +27,7 @@ def decorate(inner: Callable[..., object]) -> Callable[..., object]: return attach_definition( function=inner, attribute_name=COMMAND_OUTPUT_SINK_ATTRIBUTE, - definition=CommandOutputSinkDefinition( + definition=CommandOutputEventSinkDefinition( name=resolved_name, streams=resolved_streams, ), diff --git a/src/sqlbuild/runtime/event_exporting/main/get_command_output_sink_definition.py b/src/sqlbuild/runtime/event_exporting/main/get_command_output_event_sink_definition.py similarity index 76% rename from src/sqlbuild/runtime/event_exporting/main/get_command_output_sink_definition.py rename to src/sqlbuild/runtime/event_exporting/main/get_command_output_event_sink_definition.py index 7cfbf7ef1e..e9a843b974 100644 --- a/src/sqlbuild/runtime/event_exporting/main/get_command_output_sink_definition.py +++ b/src/sqlbuild/runtime/event_exporting/main/get_command_output_event_sink_definition.py @@ -4,16 +4,16 @@ from sqlbuild.python_nodes.main.read_attached_definition import read_attached_definition from sqlbuild.runtime.event_exporting.constants import COMMAND_OUTPUT_SINK_ATTRIBUTE -from sqlbuild.runtime.output_capture.models import CommandOutputSinkDefinition +from sqlbuild.runtime.output_capture.models import CommandOutputEventSinkDefinition -def get_command_output_sink_definition( +def get_command_output_event_sink_definition( function: Callable[..., object], -) -> CommandOutputSinkDefinition | None: +) -> CommandOutputEventSinkDefinition | None: """Return command-output sink metadata attached to a function.""" return read_attached_definition( function=function, attribute_name=COMMAND_OUTPUT_SINK_ATTRIBUTE, - definition_type=CommandOutputSinkDefinition, + definition_type=CommandOutputEventSinkDefinition, ) diff --git a/src/sqlbuild/runtime/observability/README.md b/src/sqlbuild/runtime/observability/README.md index 5534d64d6f..7aea4e7ebe 100644 --- a/src/sqlbuild/runtime/observability/README.md +++ b/src/sqlbuild/runtime/observability/README.md @@ -20,7 +20,8 @@ JSON-compatible `payload` object. The v1 event catalog is: -- Invocation: `invocation_started`, `invocation_completed`, `invocation_failed` +- Invocation: `invocation_started`, `invocation_completed`, `invocation_failed`; schema version 2 adds + `invocation_phase`, one per finished preparation step - Run: `run_started`, `run_completed`, `run_failed` - Resource attempt: `resource_attempt_started`, `resource_attempt_completed`, `resource_attempt_failed`, `resource_attempt_skipped` diff --git a/src/sqlbuild/runtime/output_capture/models.py b/src/sqlbuild/runtime/output_capture/models.py index f371b82625..931c204361 100644 --- a/src/sqlbuild/runtime/output_capture/models.py +++ b/src/sqlbuild/runtime/output_capture/models.py @@ -81,7 +81,7 @@ class OutputCaptureContext: @dataclass(frozen=True) -class CommandOutputSinkDefinition: +class CommandOutputEventSinkDefinition: """Immutable metadata attached to a command-output sink function.""" name: str diff --git a/tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/local_only.sql b/tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/local_only.sql similarity index 100% rename from tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/local_only.sql rename to tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/local_only.sql diff --git a/tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/marts/deprecated_orders.sql b/tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/marts/deprecated_orders.sql similarity index 100% rename from tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/marts/deprecated_orders.sql rename to tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/marts/deprecated_orders.sql diff --git a/tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/marts/downstream_orders.sql b/tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/marts/downstream_orders.sql similarity index 100% rename from tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/marts/downstream_orders.sql rename to tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/marts/downstream_orders.sql diff --git a/tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/marts/event_time_orders.sql b/tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/marts/event_time_orders.sql similarity index 100% rename from tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/marts/event_time_orders.sql rename to tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/marts/event_time_orders.sql diff --git a/tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/marts/mart_orders.sql b/tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/marts/mart_orders.sql similarity index 100% rename from tests/e2e/fixtures/dbt_interop/sqlbuild_project/models/marts/mart_orders.sql rename to tests/e2e/fixtures/dbt_interop/sqlbuild_project/sql/models/marts/mart_orders.sql diff --git a/tests/e2e/fixtures/source_loader_strategies/python/loaders/strategy_sources.py b/tests/e2e/fixtures/source_loader_strategies/python/loaders/strategy_sources.py deleted file mode 100644 index 00846041ce..0000000000 --- a/tests/e2e/fixtures/source_loader_strategies/python/loaders/strategy_sources.py +++ /dev/null @@ -1,94 +0,0 @@ -from datetime import datetime -from typing import Any - -from sqlbuild.loaders import loader - - -@loader -def raw_countries(ctx: object) -> list[dict[str, object]]: - """Test loader raw_countries.""" - _ = ctx - return [ - {"country_id": 1, "country_code": "US", "country_name": "United States"}, - {"country_id": 2, "country_code": "CA", "country_name": "Canada"}, - ] - - -@loader -def raw_webhook_events(ctx: object) -> list[dict[str, object]]: - """Test loader raw_webhook_events.""" - _ = ctx - return [ - {"event_id": 101, "event_name": "signup"}, - {"event_id": 102, "event_name": "checkout"}, - ] - - -@loader -def raw_order_events(ctx: Any) -> list[dict[str, object]]: - """Test loader raw_order_events.""" - if ctx.current_cursor_value is None: - return [ - { - "event_id": 201, - "event_at": datetime(2026, 5, 1, 0, 0, 0), - "amount_cents": 1000, - }, - { - "event_id": 202, - "event_at": datetime(2026, 5, 1, 1, 0, 0), - "amount_cents": 2000, - }, - ] - return [ - { - "event_id": 202, - "event_at": datetime(2026, 5, 1, 1, 0, 0), - "amount_cents": 2500, - }, - { - "event_id": 203, - "event_at": datetime(2026, 5, 1, 2, 0, 0), - "amount_cents": 3000, - }, - ] - - -@loader -def raw_customers(ctx: Any) -> list[dict[str, object]]: - """Test loader raw_customers.""" - if ctx.current_cursor_value is None: - return [ - { - "customer_id": 1, - "plan_name": "basic", - "updated_at": datetime(2026, 5, 1, 0, 0, 0), - }, - { - "customer_id": 2, - "plan_name": "trial", - "updated_at": datetime(2026, 5, 1, 0, 0, 0), - }, - ] - return [ - { - "customer_id": 1, - "plan_name": "pro", - "updated_at": datetime(2026, 5, 2, 0, 0, 0), - }, - { - "customer_id": 3, - "plan_name": "enterprise", - "updated_at": datetime(2026, 5, 2, 0, 0, 0), - }, - ] - - -@loader -def raw_loader_status(ctx: Any) -> None: - """Test loader raw_loader_status.""" - ctx.execute_sql(f"DROP TABLE IF EXISTS {ctx.destination}") - ctx.execute_sql( - f"CREATE TABLE {ctx.destination} AS " - "SELECT 1 AS status_id, 'loaded' AS status_name, 'self_managed' AS loaded_by" - ) diff --git a/tests/e2e/fixtures/source_loader_strategies/python/nodes/loaders/strategy_sources/loaders.py b/tests/e2e/fixtures/source_loader_strategies/python/nodes/loaders/strategy_sources/loaders.py new file mode 100644 index 0000000000..58056f1cfa --- /dev/null +++ b/tests/e2e/fixtures/source_loader_strategies/python/nodes/loaders/strategy_sources/loaders.py @@ -0,0 +1,95 @@ +from datetime import datetime +from typing import Any + +from sqlbuild.factories import factory +from sqlbuild.loaders import loader + + +@factory +def strategy_sources_loaders() -> list[object]: + @loader + def raw_countries(ctx: object) -> list[dict[str, object]]: + """Test loader raw_countries.""" + _ = ctx + return [ + {"country_id": 1, "country_code": "US", "country_name": "United States"}, + {"country_id": 2, "country_code": "CA", "country_name": "Canada"}, + ] + + @loader + def raw_webhook_events(ctx: object) -> list[dict[str, object]]: + """Test loader raw_webhook_events.""" + _ = ctx + return [ + {"event_id": 101, "event_name": "signup"}, + {"event_id": 102, "event_name": "checkout"}, + ] + + @loader + def raw_order_events(ctx: Any) -> list[dict[str, object]]: + """Test loader raw_order_events.""" + if ctx.current_cursor_value is None: + return [ + { + "event_id": 201, + "event_at": datetime(2026, 5, 1, 0, 0, 0), + "amount_cents": 1000, + }, + { + "event_id": 202, + "event_at": datetime(2026, 5, 1, 1, 0, 0), + "amount_cents": 2000, + }, + ] + return [ + { + "event_id": 202, + "event_at": datetime(2026, 5, 1, 1, 0, 0), + "amount_cents": 2500, + }, + { + "event_id": 203, + "event_at": datetime(2026, 5, 1, 2, 0, 0), + "amount_cents": 3000, + }, + ] + + @loader + def raw_customers(ctx: Any) -> list[dict[str, object]]: + """Test loader raw_customers.""" + if ctx.current_cursor_value is None: + return [ + { + "customer_id": 1, + "plan_name": "basic", + "updated_at": datetime(2026, 5, 1, 0, 0, 0), + }, + { + "customer_id": 2, + "plan_name": "trial", + "updated_at": datetime(2026, 5, 1, 0, 0, 0), + }, + ] + return [ + { + "customer_id": 1, + "plan_name": "pro", + "updated_at": datetime(2026, 5, 2, 0, 0, 0), + }, + { + "customer_id": 3, + "plan_name": "enterprise", + "updated_at": datetime(2026, 5, 2, 0, 0, 0), + }, + ] + + @loader + def raw_loader_status(ctx: Any) -> None: + """Test loader raw_loader_status.""" + ctx.execute_sql(f"DROP TABLE IF EXISTS {ctx.destination}") + ctx.execute_sql( + f"CREATE TABLE {ctx.destination} AS " + "SELECT 1 AS status_id, 'loaded' AS status_name, 'self_managed' AS loaded_by" + ) + + return [raw_countries, raw_webhook_events, raw_order_events, raw_customers, raw_loader_status] diff --git a/tests/e2e/fixtures/source_loader_strategies/sources/raw.yml b/tests/e2e/fixtures/source_loader_strategies/sql/sources/raw.yml similarity index 100% rename from tests/e2e/fixtures/source_loader_strategies/sources/raw.yml rename to tests/e2e/fixtures/source_loader_strategies/sql/sources/raw.yml diff --git a/tests/e2e/fixtures/waffle_shop/materializations/partition_tracked.py b/tests/e2e/fixtures/waffle_shop/python/materializations/partition_tracked.py similarity index 100% rename from tests/e2e/fixtures/waffle_shop/materializations/partition_tracked.py rename to tests/e2e/fixtures/waffle_shop/python/materializations/partition_tracked.py diff --git a/website/examples/waffle-shop/python/loaders/waffle_sources.py b/tests/e2e/fixtures/waffle_shop/python/nodes/loaders/waffle_sources/loaders.py similarity index 69% rename from website/examples/waffle-shop/python/loaders/waffle_sources.py rename to tests/e2e/fixtures/waffle_shop/python/nodes/loaders/waffle_sources/loaders.py index b9267ec2b1..3833d28854 100644 --- a/website/examples/waffle-shop/python/loaders/waffle_sources.py +++ b/tests/e2e/fixtures/waffle_shop/python/nodes/loaders/waffle_sources/loaders.py @@ -1,6 +1,7 @@ from collections.abc import Iterator from datetime import datetime +from sqlbuild.factories import factory from sqlbuild.loaders import loader CUSTOMERS: list[dict[str, object]] = [ @@ -55,21 +56,26 @@ ] -@loader -def raw__customers(ctx: object) -> list[dict[str, object]]: - _ = ctx - return CUSTOMERS +@factory +def waffle_sources_loaders() -> list[object]: + @loader + def raw_customers(ctx: object) -> list[dict[str, object]]: + """Test loader raw_customers.""" + _ = ctx + return CUSTOMERS + @loader + def raw_orders(ctx: object) -> Iterator[dict[str, object]]: + """Test loader raw_orders.""" + _ = ctx + for order_id, customer_id, waffle_type_id, quantity, ordered_at, status in ORDERS: + yield { + "id": order_id, + "customer_id": customer_id, + "waffle_type_id": waffle_type_id, + "quantity": quantity, + "ordered_at": ordered_at, + "status": status, + } -@loader -def raw__orders(ctx: object) -> Iterator[dict[str, object]]: - _ = ctx - for order_id, customer_id, waffle_type_id, quantity, ordered_at, status in ORDERS: - yield { - "id": order_id, - "customer_id": customer_id, - "waffle_type_id": waffle_type_id, - "quantity": quantity, - "ordered_at": ordered_at, - "status": status, - } + return [raw_customers, raw_orders] diff --git a/tests/e2e/fixtures/waffle_shop/functions/python/is_completed_order_py.py b/tests/e2e/fixtures/waffle_shop/sql/functions/python/is_completed_order_py.py similarity index 100% rename from tests/e2e/fixtures/waffle_shop/functions/python/is_completed_order_py.py rename to tests/e2e/fixtures/waffle_shop/sql/functions/python/is_completed_order_py.py diff --git a/tests/e2e/fixtures/waffle_shop/functions/sql/customer_orders.sql b/tests/e2e/fixtures/waffle_shop/sql/functions/sql/customer_orders.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/functions/sql/customer_orders.sql rename to tests/e2e/fixtures/waffle_shop/sql/functions/sql/customer_orders.sql diff --git a/tests/e2e/fixtures/waffle_shop/functions/sql/is_completed_order.sql b/tests/e2e/fixtures/waffle_shop/sql/functions/sql/is_completed_order.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/functions/sql/is_completed_order.sql rename to tests/e2e/fixtures/waffle_shop/sql/functions/sql/is_completed_order.sql diff --git a/tests/e2e/fixtures/waffle_shop/macros/python/currency.py b/tests/e2e/fixtures/waffle_shop/sql/macros/python/currency.py similarity index 100% rename from tests/e2e/fixtures/waffle_shop/macros/python/currency.py rename to tests/e2e/fixtures/waffle_shop/sql/macros/python/currency.py diff --git a/tests/e2e/fixtures/waffle_shop/models/intermediate/customer_status_snapshot.sql b/tests/e2e/fixtures/waffle_shop/sql/models/intermediate/customer_status_snapshot.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/intermediate/customer_status_snapshot.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/intermediate/customer_status_snapshot.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/intermediate/order_status_index.sql b/tests/e2e/fixtures/waffle_shop/sql/models/intermediate/order_status_index.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/intermediate/order_status_index.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/intermediate/order_status_index.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/_macros/python/time.py b/tests/e2e/fixtures/waffle_shop/sql/models/marts/_macros/python/time.py similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/_macros/python/time.py rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/_macros/python/time.py diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql b/tests/e2e/fixtures/waffle_shop/sql/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/daily_activity_rollup.sql b/tests/e2e/fixtures/waffle_shop/sql/models/marts/daily_activity_rollup.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/daily_activity_rollup.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/daily_activity_rollup.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/daily_order_partitioned.sql b/tests/e2e/fixtures/waffle_shop/sql/models/marts/daily_order_partitioned.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/daily_order_partitioned.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/daily_order_partitioned.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/daily_revenue.sql b/tests/e2e/fixtures/waffle_shop/sql/models/marts/daily_revenue.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/daily_revenue.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/daily_revenue.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/dim_customers.sql b/tests/e2e/fixtures/waffle_shop/sql/models/marts/dim_customers.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/dim_customers.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/dim_customers.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/fact_orders.sql b/tests/e2e/fixtures/waffle_shop/sql/models/marts/fact_orders.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/fact_orders.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/fact_orders.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/hourly_activity_with_daily_context.sql b/tests/e2e/fixtures/waffle_shop/sql/models/marts/hourly_activity_with_daily_context.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/hourly_activity_with_daily_context.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/hourly_activity_with_daily_context.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/hourly_order_activity.sql b/tests/e2e/fixtures/waffle_shop/sql/models/marts/hourly_order_activity.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/hourly_order_activity.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/hourly_order_activity.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/marts/scenario_order_prices.sql b/tests/e2e/fixtures/waffle_shop/sql/models/marts/scenario_order_prices.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/marts/scenario_order_prices.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/marts/scenario_order_prices.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/staging/stg_customers.sql b/tests/e2e/fixtures/waffle_shop/sql/models/staging/stg_customers.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/staging/stg_customers.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/staging/stg_customers.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/staging/stg_orders.sql b/tests/e2e/fixtures/waffle_shop/sql/models/staging/stg_orders.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/staging/stg_orders.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/staging/stg_orders.sql diff --git a/tests/e2e/fixtures/waffle_shop/models/staging/stg_payments.sql b/tests/e2e/fixtures/waffle_shop/sql/models/staging/stg_payments.sql similarity index 100% rename from tests/e2e/fixtures/waffle_shop/models/staging/stg_payments.sql rename to tests/e2e/fixtures/waffle_shop/sql/models/staging/stg_payments.sql diff --git a/tests/e2e/fixtures/waffle_shop/seeds/lookups.yml b/tests/e2e/fixtures/waffle_shop/sql/seeds/lookups.yml similarity index 100% rename from tests/e2e/fixtures/waffle_shop/seeds/lookups.yml rename to tests/e2e/fixtures/waffle_shop/sql/seeds/lookups.yml diff --git a/tests/e2e/fixtures/waffle_shop/seeds/waffle_types.csv b/tests/e2e/fixtures/waffle_shop/sql/seeds/waffle_types.csv similarity index 100% rename from tests/e2e/fixtures/waffle_shop/seeds/waffle_types.csv rename to tests/e2e/fixtures/waffle_shop/sql/seeds/waffle_types.csv diff --git a/tests/e2e/fixtures/waffle_shop/sources/raw.yml b/tests/e2e/fixtures/waffle_shop/sql/sources/raw.yml similarity index 100% rename from tests/e2e/fixtures/waffle_shop/sources/raw.yml rename to tests/e2e/fixtures/waffle_shop/sql/sources/raw.yml diff --git a/tests/e2e/scripts/compile_performance_ratio/helpers.py b/tests/e2e/scripts/compile_performance_ratio/helpers.py index 7a3b7f1acf..b716cb411e 100644 --- a/tests/e2e/scripts/compile_performance_ratio/helpers.py +++ b/tests/e2e/scripts/compile_performance_ratio/helpers.py @@ -11,9 +11,11 @@ def write_benchmark_project(*, kind: str, project_dir: Path, models: int) -> None: del models - (project_dir / "models").mkdir(parents=True) - (project_dir / "sqlbuild_project.toml").write_text('name = "orders"\\nadapter = "duckdb"\\n') - (project_dir / "models" / "base_marker.sql").write_text( + (project_dir / "sql" / "models").mkdir(parents=True) + (project_dir / "sqlbuild_project.toml").write_text( + 'name = "orders"\\nadapter = "duckdb"\\nextra_paths = ["base_marker.txt"]\\n' + ) + (project_dir / "sql" / "models" / "base_marker.sql").write_text( 'MODEL (description "Base marker");\\n\\nSELECT 1 AS id\\n' ) (project_dir / "base_marker.txt").write_text(kind) diff --git a/tests/e2e/scripts/compiler_differential/helpers.py b/tests/e2e/scripts/compiler_differential/helpers.py index e61f44bd82..7bb49e093d 100644 --- a/tests/e2e/scripts/compiler_differential/helpers.py +++ b/tests/e2e/scripts/compiler_differential/helpers.py @@ -12,7 +12,7 @@ 'name = "broken_orders"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "broken_orders.duckdb"\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( 'MODEL (\n description "Order totals",\n);\n\nSELECT * FROM __ref("nope")\n' ), } diff --git a/tests/e2e/scripts/planner_differential/test_planner_differential.py b/tests/e2e/scripts/planner_differential/test_planner_differential.py index a5772cc81a..29fab7de49 100644 --- a/tests/e2e/scripts/planner_differential/test_planner_differential.py +++ b/tests/e2e/scripts/planner_differential/test_planner_differential.py @@ -27,7 +27,7 @@ expected_clean_line="Planner differential passed: 1 projects matched the baseline", expected_difference_line=" - step edit-query: plan_json", expected_diff_line='+ "exit_code": 0,', - expected_note="edited models/daily_revenue.sql", + expected_note="edited sql/models/daily_revenue.sql", ), ], ids=lambda case: case.description, diff --git a/tests/e2e/scripts/release_performance/helpers.py b/tests/e2e/scripts/release_performance/helpers.py index 4ac62a6c50..ca00ffd536 100644 --- a/tests/e2e/scripts/release_performance/helpers.py +++ b/tests/e2e/scripts/release_performance/helpers.py @@ -5,7 +5,7 @@ import shutil from pathlib import Path -BASELINE_MARKER: str = "BASELINE_MARKER" +BASELINE_MARKER: str = ".BASELINE_MARKER" _MARKING_WRAPPER: str = """ _unmarked_write_pristine_projects = write_pristine_projects @@ -16,7 +16,7 @@ def write_pristine_projects(*, root: Path, inspection_models: int, build_models: root=root, inspection_models=inspection_models, build_models=build_models ) for project in pristine.iterdir(): - (project / "BASELINE_MARKER").write_text("baseline", encoding="utf-8") + (project / ".BASELINE_MARKER").write_text("baseline", encoding="utf-8") return pristine """ _DENSE_MARKING_WRAPPER: str = """ @@ -26,7 +26,7 @@ def write_pristine_projects(*, root: Path, inspection_models: int, build_models: def write_dense_compile_project(*, project_dir: Path, model_count: int) -> None: _unmarked_write_dense_compile_project(project_dir=project_dir, model_count=model_count) - (project_dir / "BASELINE_MARKER").write_text("baseline", encoding="utf-8") + (project_dir / ".BASELINE_MARKER").write_text("baseline", encoding="utf-8") """ diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/adapters/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/adapters/helpers.py index 2954fd46dc..c3fbba9716 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/adapters/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/adapters/helpers.py @@ -18,7 +18,7 @@ def prepare_project_with_local_adapter(*, tmp_path: Path) -> Path: "[connection]\n" 'database = "local.duckdb"\n' ), - "adapters/warehouse/duckdb_plus.py": ( + "python/adapters/warehouse/duckdb_plus.py": ( "from sqlbuild.adapter.contract.models import QueryResult\n" "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n\n" "class DuckDbPlusAdapter(DuckDbAdapter):\n" @@ -47,7 +47,7 @@ def prepare_project_with_rendering_adapter(*, tmp_path: Path) -> Path: "[connection]\n" 'database = "local.duckdb"\n' ), - "adapters/duckdb_marked.py": ( + "python/adapters/duckdb_marked.py": ( "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n\n" "class DuckDbMarkedAdapter(DuckDbAdapter):\n" " adapter_name = 'duckdb_marked'\n\n" @@ -58,7 +58,7 @@ def prepare_project_with_rendering_adapter(*, tmp_path: Path) -> Path: " 'SELECT 1 AS marked',\n" " )\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders", materialized table);\n\n' "SELECT 1 AS order_id, 'shipped' AS status\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/audit/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/audit/helpers.py index a9d24c3e5b..b3c36dfde4 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/audit/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/audit/helpers.py @@ -17,6 +17,7 @@ query_duckdb, run_sqb, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files ORDER_COLUMNS: tuple[str, ...] = tuple(f"order_attribute_{index:02d}" for index in range(12)) @@ -44,7 +45,7 @@ def delivery_model_files() -> dict[str, str]: columns: str = "\n".join(f" {name} (audits [not_null])," for name in ORDER_COLUMNS) selected: str = ",\n ".join(f"1 AS {name}" for name in ORDER_COLUMNS) return { - "models/customers.sql": dedent( + "sql/models/customers.sql": dedent( """ MODEL (description "Test model customers.", materialized table, @@ -56,7 +57,7 @@ def delivery_model_files() -> dict[str, str]: SELECT 1 AS customer_id """ ).lstrip(), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n materialized table,\n columns (\n" f"{columns}\n" " ),\n);\n\n" @@ -75,7 +76,7 @@ def recording_sink_source(*, event_kinds: str, delay_seconds: float) -> str: import time from pathlib import Path - from sqlbuild.sinks import ( + from sqlbuild.event_sinks import ( LifecycleEvent, LifecycleEventKind, lifecycle_event_sink, @@ -102,7 +103,11 @@ def slow_once_sink_source(*, slow_call: int) -> str: import time from pathlib import Path - from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink, lifecycle_event_to_json + from sqlbuild.event_sinks import ( + LifecycleEvent, + lifecycle_event_sink, + lifecycle_event_to_json, + ) CALLS: list[int] = [] @@ -155,7 +160,7 @@ def audit_meta_project_files( database = "audit_meta.duckdb" """ ).lstrip(), - "audits/generic/valid_order_rate.sql": dedent( + "sql/audits/generic/valid_order_rate.sql": dedent( """ AUDIT ( evaluation measurement, @@ -172,11 +177,13 @@ def audit_meta_project_files( ); """ ).lstrip(), - "audits/generic/expression_is_true.sql": ( + "sql/audits/generic/expression_is_true.sql": ( "AUDIT ();\n\nSELECT * FROM @relation WHERE NOT (@expression)\n" ), - "python/factories/order_quality.py": dedent( - """ + **node_module_files( + "python/nodes/factories/order_quality.py", + dedent( + """ from sqlbuild.audits import AuditCase, AuditSeverity, audit_factory @@ -192,8 +199,9 @@ def order_quality(): ) ] """ - ).lstrip(), - "models/orders.sql": ( + ).lstrip(), + ), + "sql/models/orders.sql": ( "MODEL (\n" ' description "Test model orders.",\n' " materialized table,\n" @@ -229,7 +237,7 @@ def prepare_audit_meta_project(*, tmp_path: Path, measurement_options: str) -> P project_name="audit_meta", repo_files={ **audit_meta_project_files(measurement_options=measurement_options), - "sinks/orders_events.py": recording_sink_source( + "python/event_sinks/orders_events.py": recording_sink_source( event_kinds="{LifecycleEventKind.AUDIT}", delay_seconds=0 ), }, @@ -315,7 +323,7 @@ def plan_reasons(project_dir: Path) -> dict[str, str]: } -GENERIC_AUDIT_PATH: str = "audits/generic/unique_within_group.sql" +GENERIC_AUDIT_PATH: str = "sql/audits/generic/unique_within_group.sql" def generic_audit_project_files(*, arguments: str) -> dict[str, str]: @@ -332,7 +340,7 @@ def generic_audit_project_files(*, arguments: str) -> dict[str, str]: "FROM @relation\nWHERE @column IS NOT NULL\nGROUP BY @group_columns\n" "HAVING COUNT(DISTINCT @column) > 1\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n materialized table,\n columns (\n" f" status (audits [unique_within_group ({arguments})]),\n ),\n);\n\n" "SELECT 1 AS order_id, 'open' AS status, 'web' AS channel\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit.py b/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit.py index 49d27c8d39..b2de22c1cf 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit.py @@ -142,7 +142,7 @@ def test_given_failing_audit_when_running_audit_then_exit_code_is_nonzero( tmp_path: Path, ) -> None: project_dir: Path = prepare_waffle_shop(tmp_path) - model_path: Path = project_dir / "models" / "marts" / "daily_order_partitioned.sql" + model_path: Path = project_dir / "sql" / "models" / "marts" / "daily_order_partitioned.sql" original_model: str = model_path.read_text(encoding="utf-8") assert 'expression "waffles_ordered > 0"' in original_model model_path.write_text( @@ -183,7 +183,7 @@ def test_given_attached_audit_reads_sibling_model_when_building_and_auditing_the tmp_path: Path, ) -> None: project_dir: Path = prepare_waffle_shop(tmp_path) - model_path: Path = project_dir / "models" / "staging" / "stg_orders.sql" + model_path: Path = project_dir / "sql" / "models" / "staging" / "stg_orders.sql" model_sql: str = model_path.read_text(encoding="utf-8") model_path.write_text( model_sql.replace( @@ -195,6 +195,7 @@ def test_given_attached_audit_reads_sibling_model_when_building_and_auditing_the ) audit_path: Path = ( project_dir + / "sql" / "models" / "staging" / "_sqlbuild" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit_event_delivery.py b/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit_event_delivery.py index 58189b2797..e49e9c6fee 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit_event_delivery.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit_event_delivery.py @@ -35,7 +35,7 @@ r"(?P\d+) of (?P\d+) events dropped, (?P\d+) failed " r"\(sink 'slow_orders_events'\)\. " r"Check sink health: a sink call slower than 1s drops that sink's events until it returns; " - r"events still queued at exit need a longer sinks\.lifecycle\.shutdown_timeout\." + r"events still queued at exit need a longer event_sinks\.lifecycle\.shutdown_timeout\." ) @@ -69,7 +69,7 @@ def test_given_many_audits_when_running_then_audit_completed_events_arrive_durin repo_files={ "sqlbuild_project.toml": delivery_project_toml(lifecycle_config=""), **delivery_model_files(), - "sinks/orders_events.py": recording_sink_source( + "python/event_sinks/orders_events.py": recording_sink_source( event_kinds="{LifecycleEventKind.AUDIT, LifecycleEventKind.RESOURCE}", delay_seconds=0, ), @@ -136,11 +136,11 @@ def test_given_slow_sink_and_zero_drain_when_auditing_then_warns_with_counts_and repo_files={ "sqlbuild_project.toml": delivery_project_toml( lifecycle_config=( - f'\n[sinks.lifecycle]\nshutdown_timeout = "{test_case.shutdown_timeout}"\n' + f'\n[event_sinks.lifecycle]\nshutdown_timeout = "{test_case.shutdown_timeout}"\n' ) ), **delivery_model_files(), - "sinks/orders_events.py": recording_sink_source( + "python/event_sinks/orders_events.py": recording_sink_source( event_kinds="{LifecycleEventKind.AUDIT}", delay_seconds=0.4 ), }, @@ -191,11 +191,11 @@ def test_given_slow_sink_and_raised_drain_when_auditing_then_delivers_all_withou repo_files={ "sqlbuild_project.toml": delivery_project_toml( lifecycle_config=( - f'\n[sinks.lifecycle]\nshutdown_timeout = "{test_case.shutdown_timeout}"\n' + f'\n[event_sinks.lifecycle]\nshutdown_timeout = "{test_case.shutdown_timeout}"\n' ) ), **delivery_model_files(), - "sinks/orders_events.py": recording_sink_source( + "python/event_sinks/orders_events.py": recording_sink_source( event_kinds="{LifecycleEventKind.AUDIT}", delay_seconds=0.4 ), }, @@ -225,17 +225,17 @@ def test_given_slow_sink_and_raised_drain_when_auditing_then_delivers_all_withou InvalidDrainTimeoutE2ETestCase( "negative duration", '"-5s"', - "sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m'", + "event_sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m'", ), InvalidDrainTimeoutE2ETestCase( "bare number", "5", - "sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m'", + "event_sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m'", ), InvalidDrainTimeoutE2ETestCase( "above upper bound", '"1h"', - "sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m'", + "event_sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m'", ), ), ids=lambda case: case.description, @@ -250,11 +250,11 @@ def test_given_invalid_drain_timeout_when_auditing_then_fails_with_config_error( repo_files={ "sqlbuild_project.toml": delivery_project_toml( lifecycle_config=( - f"\n[sinks.lifecycle]\nshutdown_timeout = {test_case.shutdown_timeout_toml}\n" + f"\n[event_sinks.lifecycle]\nshutdown_timeout = {test_case.shutdown_timeout_toml}\n" ) ), **delivery_model_files(), - "sinks/orders_events.py": recording_sink_source( + "python/event_sinks/orders_events.py": recording_sink_source( event_kinds="{LifecycleEventKind.AUDIT}", delay_seconds=0 ), }, @@ -297,7 +297,9 @@ def test_given_sink_slow_once_when_building_then_later_and_outcome_events_still_ repo_files={ "sqlbuild_project.toml": delivery_project_toml(lifecycle_config=""), **delivery_model_files(), - "sinks/orders_events.py": slow_once_sink_source(slow_call=test_case.slow_call), + "python/event_sinks/orders_events.py": slow_once_sink_source( + slow_call=test_case.slow_call + ), }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit_meta.py b/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit_meta.py index 9244bc4d7a..a47003d628 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit_meta.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_audit_meta.py @@ -137,7 +137,7 @@ def test_given_meta_only_change_when_rebuilding_then_outcomes_and_reruns_match_d ) assert first.returncode == 0, first.stdout + first.stderr baselines[variant] = stored_audit_identities(project_dir) - model_path: Path = project_dir / "models" / "orders.sql" + model_path: Path = project_dir / "sql" / "models" / "orders.sql" model_path.write_text( model_path.read_text(encoding="utf-8").replace( test_case.original_header_fragment, fragment @@ -170,7 +170,7 @@ def test_given_meta_only_change_when_rebuilding_then_outcomes_and_reruns_match_d ( InvalidAuditMetaE2ETestCase( "factory meta with a date", - "python/factories/order_quality.py", + "python/nodes/factories/order_quality.py", _INVALID_FACTORY, ( "AuditCase 'positive_amount' meta must map string keys to JSON values", @@ -179,7 +179,7 @@ def test_given_meta_only_change_when_rebuilding_then_outcomes_and_reruns_match_d ), InvalidAuditMetaE2ETestCase( "header meta that is not a mapping", - "models/orders.sql", + "sql/models/orders.sql", _INVALID_HEADER, ("'meta' must be a mapping of JSON values",), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_generic_audit_arguments.py b/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_generic_audit_arguments.py index 91a4bb02e1..4cdee6ba2a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_generic_audit_arguments.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/audit/test_generic_audit_arguments.py @@ -25,7 +25,7 @@ description="an argument the audit never reads names itself for removal", arguments='group_columns "channel", where_condition "channel = \'web\'"', expected_message=( - "models/orders.sql audit 'unique_within_group' passes argument " + "sql/models/orders.sql audit 'unique_within_group' passes argument " "'where_condition', which the audit's SQL in " f"{GENERIC_AUDIT_PATH} never uses; remove 'where_condition' from the attachment" ), @@ -63,7 +63,7 @@ def test_given_unused_generic_audit_argument_when_compiling_then_compile_fails( arguments='group_columns "channel"', detached_column=" (type VARCHAR)", expected_relative_path=( - "target/compiled/audits/generic/orders/unique_within_group__status.sql" + "target/compiled/sql/audits/generic/orders/unique_within_group__status.sql" ), expected_sql=( "SELECT channel, COUNT(DISTINCT status) AS distinct_count\n" @@ -90,7 +90,7 @@ def test_given_attached_generic_audit_when_compiling_then_rendered_sql_is_writte command=("--no-color", "compile"), project_dir=project_dir ) rendered: str = audit_file.read_text(encoding="utf-8") - model_path: Path = project_dir / "models/orders.sql" + model_path: Path = project_dir / "sql/models/orders.sql" _ = model_path.write_text( model_path.read_text(encoding="utf-8").replace( f" (audits [unique_within_group ({test_case.arguments})])", @@ -107,4 +107,4 @@ def test_given_attached_generic_audit_when_compiling_then_rendered_sql_is_writte assert rendered == test_case.expected_sql assert second.returncode == 0, second.stdout + second.stderr assert not audit_file.exists() - assert (project_dir / "target/compiled/models/orders.sql").is_file() + assert (project_dir / "target/compiled/sql/models/orders.sql").is_file() diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/helpers.py index dd37a3407e..3aced5f99a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/helpers.py @@ -255,7 +255,7 @@ def prepare_bigquery_diff_project(*, tmp_path: Path) -> tuple[Path, str, str]: build_bigquery_local_config(location=location), encoding="utf-8", ) - models_dir: Path = project_dir / "models" / "staging" + models_dir: Path = project_dir / "sql" / "models" / "staging" models_dir.mkdir(parents=True, exist_ok=True) (models_dir / "stg_orders.sql").write_text( "MODEL (description 'Test model stg_orders.',\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/test_bigquery.py b/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/test_bigquery.py index b78d64c4f1..aaecf53a42 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/test_bigquery.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/test_bigquery.py @@ -72,6 +72,7 @@ build_bigquery_connection_config, build_unique_dataset_name, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.dbt @@ -168,15 +169,15 @@ def test_given_python_result_when_running_check_on_bigquery_then_persists_node_r project_name="bigquery_node_results", dataset_name=dataset_name, ), - "python/tasks/results.py": ( + "python/nodes/tasks/results/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_result(ctx):\n" " '''Test task produce_result.'''\n return ctx.result(payload={'value': 42}, metadata={'source': 'bigquery'})\n" ), - "python/checks/results.py": ( + "python/nodes/checks/results/checks.py": ( "from sqlbuild.checks import check\n" - "from python.tasks.results import produce_result\n\n" + "from python.nodes.tasks.results.asset import produce_result\n\n" "@check(depends_on=produce_result)\n" "def check_produce_result(ctx):\n" " '''Test check check_produce_result.'''\n return ctx.result_of(node_function=produce_result).payload['value'] == 42\n" @@ -251,13 +252,13 @@ def test_given_physical_source_without_freshness_when_running_on_bigquery_then_u project_name="bigquery_freshness_metadata", dataset_name=dataset_name, ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" f" schema: {dataset_name}\n" " table: raw_orders\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __source("raw_orders")\n' ), }, @@ -533,7 +534,7 @@ def test_given_source_deferral_env_when_building_on_bigquery_then_reads_prod_and prod_dataset_name=prod_dataset_name, ), "sqlbuild_local.toml": build_bigquery_local_config(location=location), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -544,13 +545,13 @@ def test_given_source_deferral_env_when_building_on_bigquery_then_reads_prod_and " - name: status\n" " type: STRING\n" ), - "python/loaders/raw_orders.py": ( + "python/nodes/loaders/raw_orders/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 7, 'status': 'loaded-dev'}]\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT order_id, status FROM __source("raw_orders")' ), }, @@ -738,7 +739,7 @@ def test_given_snapshot_project_when_building_on_bigquery_then_scd2_history_is_v expected_historical_check_rows=test_case.expected_historical_check_rows, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="blocked", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -762,7 +763,7 @@ def test_given_snapshot_project_when_building_on_bigquery_then_scd2_history_is_v expected_rows=test_case.expected_current_rows_after_initial_build, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="pro", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -839,16 +840,16 @@ def test_given_existing_snapshot_targets_when_building_on_bigquery_then_apply_sq ) assert initial_result.returncode == 0, initial_result.stdout + initial_result.stderr - (project_dir / "models" / "current_check_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_check_customers.sql").write_text( build_current_check_customers_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "current_delete_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_delete_customers.sql").write_text( build_current_delete_customers_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "historical_timestamp_extracts.sql").write_text( + (project_dir / "sql" / "models" / "historical_timestamp_extracts.sql").write_text( build_historical_timestamp_extracts_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "historical_check_daily.sql").write_text( + (project_dir / "sql" / "models" / "historical_check_daily.sql").write_text( build_historical_check_daily_model_sql(changed=True), encoding="utf-8" ) @@ -959,7 +960,7 @@ def test_given_waffle_shop_when_running_full_build_on_bigquery_then_expected_tab ), ) assert daily_revenue_rows == test_case.expected_daily_revenue_rows - run_dir: Path = project_dir / "target" / "run" / "models" + run_dir: Path = project_dir / "target" / "run" / "sql" / "models" hourly_sql: str = (run_dir / "marts" / "hourly_order_activity.sql").read_text( encoding="utf-8" ) @@ -1121,14 +1122,17 @@ def test_given_loader_schema_evolution_project_when_loading_twice_on_bigquery_th " - name: load_seq\n" " type: INTEGER\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n if ctx.current_cursor_value is None:\n" - " return [{'event_id': 1, 'load_seq': 1}]\n" - " return [{'event_id': 2, 'load_seq': 2, 'note': 'late-note'}]\n" - ), + node_files={ + **node_module_files( + "python/nodes/loaders/source_rows.py", + "from sqlbuild.loaders import loader\n\n" + "@loader\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n if ctx.current_cursor_value is None:\n" + " return [{'event_id': 1, 'load_seq': 1}]\n" + " return [{'event_id': 2, 'load_seq': 2, 'note': 'late-note'}]\n", + ) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -1200,22 +1204,25 @@ def test_given_chained_loader_project_when_loading_on_bigquery_then_runs_loader_ " - name: status\n" " type: VARCHAR\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " cursor = ctx.query(\n" - " f'SELECT event_id FROM {events.destination} ORDER BY event_id'\n" - " )\n" - " rows = cursor.fetchall()\n" - " return [{'event_id': row[0], 'status': 'loaded'} for row in rows]\n" - ), + node_files={ + **node_module_files( + "python/nodes/loaders/source_rows.py", + "from sqlbuild.loaders import loader\n\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" + " cursor = ctx.query(\n" + " f'SELECT event_id FROM {events.destination} ORDER BY event_id'\n" + " )\n" + " rows = cursor.fetchall()\n" + " return [{'event_id': row[0], 'status': 'loaded'} for row in rows]\n", + ) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -1378,7 +1385,9 @@ def test_given_intermediate_strategy_project_when_loading_twice_on_bigquery_then " - name: amount\n" " type: INTEGER\n" ), - loader_py=test_case.loader_py, + node_files={ + **node_module_files("python/nodes/loaders/source_rows.py", test_case.loader_py) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -1531,7 +1540,9 @@ def test_given_bigquery_waffle_shop_model_when_building_then_portable_sql_succee assert result.returncode == test_case.expected_return_code, result.stdout + result.stderr compiled_files: tuple[Path, ...] = tuple( - (project_dir / "target" / "run" / "models").glob(f"**/{test_case.model_name}.sql") + (project_dir / "target" / "run" / "sql" / "models").glob( + f"**/{test_case.model_name}.sql" + ) ) assert len(compiled_files) == 1 assert test_case.expected_sql_fragment in compiled_files[0].read_text(encoding="utf-8") @@ -1589,7 +1600,7 @@ def test_given_bigquery_invalid_model_when_building_then_underlying_error_is_pre project_dir: Path dataset_name: str project_dir, dataset_name = prepare_bigquery_waffle_shop(tmp_path=tmp_path) - broken_model: Path = project_dir / "models" / "marts" / "bigquery_broken_model.sql" + broken_model: Path = project_dir / "sql" / "models" / "marts" / "bigquery_broken_model.sql" broken_model.write_text( "MODEL (description 'Test model bigquery_broken_model.', materialized table);\n\nSELECT missing_column FROM UNNEST([STRUCT(1 AS id)])", encoding="utf-8", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py index 27d3545fdf..64a77f056b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py @@ -29,6 +29,22 @@ run_sqb, ) from tests.integration.src.sqlbuild.compiler.compiled_project.helpers import duckshop_orchestration +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files + +RAW_DATA_SCRIPT: str = "seed_raw_data.sql" + + +def take_raw_data_sql(project_dir: Path) -> str: + """Remove the fixture's raw data script from the project and return its SQL. + + The script loads source rows before the first build; it is not part of the project, so it + leaves the project before SQLBuild reads it. + """ + + script: Path = project_dir / RAW_DATA_SCRIPT + sql: str = script.read_text(encoding="utf-8") + script.unlink() + return sql def run_replay_command( @@ -66,7 +82,7 @@ def capped_microbatch_project_files( """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -76,7 +92,7 @@ def capped_microbatch_project_files( """ ).strip() + "\n", - "models/capped_events.sql": dedent( + "sql/models/capped_events.sql": dedent( f""" MODEL (description "Test model capped_events.", materialized incremental, @@ -104,7 +120,7 @@ def capped_microbatch_project_files( """ ).strip() + "\n", - "models/downstream_events.sql": dedent( + "sql/models/downstream_events.sql": dedent( """ MODEL (description "Test model downstream_events.", materialized view); SELECT id, event_time @@ -119,7 +135,7 @@ def capped_watermark_consumer_project_files(*, limit_action: str) -> dict[str, s """Build an invalid project whose watermark consumer reads a capped producer.""" repo_files: dict[str, str] = capped_microbatch_project_files(limit_action=limit_action) - repo_files["models/downstream_events.sql"] = ( + repo_files["sql/models/downstream_events.sql"] = ( dedent( """ MODEL (description "Test model downstream_events.", @@ -151,7 +167,7 @@ def capped_filter_join_consumer_project_files(*, limit_action: str) -> dict[str, """Build a project whose microbatch consumer filters a capped producer and joins its source.""" repo_files: dict[str, str] = capped_microbatch_project_files(limit_action=limit_action) - repo_files["models/downstream_events.sql"] = ( + repo_files["sql/models/downstream_events.sql"] = ( dedent( """ MODEL (description "Test model downstream_events.", @@ -216,8 +232,8 @@ def prepare_defer_clone_project( """ ).strip() + "\n", - "models/upstream.sql": upstream_sql, - "models/downstream.sql": downstream_sql, + "sql/models/upstream.sql": upstream_sql, + "sql/models/downstream.sql": downstream_sql, }, ) @@ -245,7 +261,7 @@ def assert_defer_clone_build_case(*, tmp_path: Path, test_case: DeferCloneBuildE ), encoding="utf-8", ) - (project_dir / "models" / "upstream.sql").write_text( + (project_dir / "sql" / "models" / "upstream.sql").write_text( test_case.changed_upstream_sql, encoding="utf-8", ) @@ -299,7 +315,7 @@ def prepare_build_test_audit_flag_project(*, tmp_path: Path, project_name: str) """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -321,8 +337,10 @@ def prepare_build_test_audit_flag_project(*, tmp_path: Path, project_name: str) """ ).strip() + "\n", - "python/checks/orders.py": dedent( - """ + **node_module_files( + "python/nodes/checks/orders.py", + dedent( + """ from sqlbuild.checks import check from sqlbuild.refs import model @@ -332,7 +350,8 @@ def check_orders_exist(ctx): '''Test check check_orders_exist.''' return ctx.pass_() """ - ).lstrip(), + ).lstrip(), + ), }, ) @@ -482,8 +501,8 @@ def prepare_replay_microbatch_project( database_name=database_name, settings_toml=("\n[settings]\nconcurrency = 3\nmicrobatch_concurrency = true\n"), ), - "sources/raw.yml": raw_events_source_yml(), - "models/orders.sql": timestamp_microbatch_model_sql( + "sql/sources/raw.yml": raw_events_source_yml(), + "sql/models/orders.sql": timestamp_microbatch_model_sql( value_expression="CAST(payload AS INTEGER)", batch_concurrency=3, replay_policy=replay_policy, @@ -501,11 +520,11 @@ def dropped_incremental_project_files(*, incremental_strategy: str) -> dict[str, 'name = "dropped_orders"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "dropped_orders.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " materialized incremental,\n" f" incremental_strategy {incremental_strategy},\n" @@ -529,35 +548,35 @@ def dropped_incremental_project_files(*, incremental_strategy: str) -> dict[str, ) _GATE_TARGET_FILES: dict[str, dict[str, str]] = { "model": { - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', " "materialized table, audits [code_check (severity error)]);\n\n" "SELECT '{code}' AS code\n" ), - "models/order_summary.sql": ( + "sql/models/order_summary.sql": ( 'MODEL (description "Test model order_summary.", ' 'materialized table);\n\nSELECT code FROM __ref("orders")\n' ), }, "source": { - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" " audits:\n - code_check:\n severity: error\n" ), - "models/staged_orders.sql": ( + "sql/models/staged_orders.sql": ( 'MODEL (description "Test model staged_orders.", ' 'materialized table);\n\nSELECT code FROM __source("raw_orders")\n' ), }, "seed": { - "seeds/order_codes.yml": ( + "sql/seeds/order_codes.yml": ( "seeds:\n - name: order_codes\n description: Test seed order_codes.\n" " columns:\n - name: code\n" " type: VARCHAR\n audits:\n - code_check:\n severity: error\n" ), - "seeds/order_codes.csv": "code\n{code}\n", - "models/coded_orders.sql": ( + "sql/seeds/order_codes.csv": "code\n{code}\n", + "sql/models/coded_orders.sql": ( 'MODEL (description "Test model coded_orders.", ' 'materialized table);\n\nSELECT code FROM __seed("order_codes")\n' ), @@ -580,8 +599,8 @@ def prepare_attached_audit_gate_project( 'name = "gate_shop"\nadapter = "duckdb"\n\n' f'[connection]\ndatabase = "{ATTACHED_AUDIT_GATE_DATABASE}"\n' ), - "audits/generic/code_check.sql": _GATE_AUDIT_TEMPLATE.format(read=read), - "models/valid_codes.sql": ( + "sql/audits/generic/code_check.sql": _GATE_AUDIT_TEMPLATE.format(read=read), + "sql/models/valid_codes.sql": ( "MODEL (description 'Test model valid_codes.', " "materialized table);\n\n" "WITH valid(code) AS (VALUES ('A'), ('B'))\nSELECT code FROM valid\n" @@ -616,23 +635,23 @@ def prepare_nested_source_gate_project(*, tmp_path: Path, raw_code: str) -> Path 'name = "gate_shop"\nadapter = "duckdb"\n\n' f'[connection]\ndatabase = "{ATTACHED_AUDIT_GATE_DATABASE}"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_codes\n description: Test source raw_codes.\n" " schema: main\n table: raw_codes\n" " audits:\n - source_check:\n severity: error\n" ), - "audits/generic/source_check.sql": _GATE_AUDIT_TEMPLATE.format( + "sql/audits/generic/source_check.sql": _GATE_AUDIT_TEMPLATE.format( read='__ref("valid_codes")' ), - "audits/generic/order_check.sql": _GATE_AUDIT_TEMPLATE.format( + "sql/audits/generic/order_check.sql": _GATE_AUDIT_TEMPLATE.format( read='__source("raw_codes")' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', " "materialized table, audits [order_check (severity error)]);\n\n" "SELECT 'A' AS code\n" ), - "models/valid_codes.sql": ( + "sql/models/valid_codes.sql": ( "MODEL (description 'Test model valid_codes.', materialized table);\n\n" "WITH valid(code) AS (VALUES ('A'), ('B'))\nSELECT code FROM valid\n" ), @@ -675,37 +694,37 @@ def build_asset_names(stdout: str) -> tuple[str, ...]: ) _AUDIT_ERROR_TARGET_FILES: dict[str, dict[str, str]] = { "source": { - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" " audits:\n - broken_check:\n severity: {severity}\n" ), - "audits/generic/broken_check.sql": _BROKEN_AUDIT, - "models/staged_orders.sql": ( + "sql/audits/generic/broken_check.sql": _BROKEN_AUDIT, + "sql/models/staged_orders.sql": ( 'MODEL (description "Test model staged_orders.", ' 'materialized table);\n\nSELECT code FROM __source("raw_orders")\n' ), }, "seed": { - "seeds/order_codes.yml": ( + "sql/seeds/order_codes.yml": ( "seeds:\n - name: order_codes\n description: Test seed order_codes.\n" " columns:\n - name: code\n" " type: VARCHAR\n audits:\n - broken_check:\n" " severity: {severity}\n" ), - "seeds/order_codes.csv": "code\nA\n", - "audits/generic/broken_check.sql": _BROKEN_AUDIT, - "models/coded_orders.sql": ( + "sql/seeds/order_codes.csv": "code\nA\n", + "sql/audits/generic/broken_check.sql": _BROKEN_AUDIT, + "sql/models/coded_orders.sql": ( 'MODEL (description "Test model coded_orders.", ' 'materialized table);\n\nSELECT code FROM __seed("order_codes")\n' ), }, "end": { - "models/orders.sql": "MODEL (description 'Test model orders.', " + "sql/models/orders.sql": "MODEL (description 'Test model orders.', " "materialized table);\n\nSELECT 'A' AS code\n", - "models/customers.sql": "MODEL (description 'Test model customers.', " + "sql/models/customers.sql": "MODEL (description 'Test model customers.', " "materialized table);\n\nSELECT 'A' AS code\n", - "audits/singular/broken_check.sql": ( + "sql/audits/singular/broken_check.sql": ( "AUDIT (severity {severity});\n\n" 'SELECT o.code FROM __ref("orders") o JOIN __ref("customers") c USING (code)\n' "JOIN main.missing_lookup m USING (code)\n" @@ -762,13 +781,13 @@ def prepare_audit_read_plan_project(*, tmp_path: Path) -> Path: 'name = "plan_shop"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "plan_shop.duckdb"\n' ), - "seeds/waffle_types.yml": ( + "sql/seeds/waffle_types.yml": ( "seeds:\n - name: waffle_types\n description: Test seed waffle_types.\n" " columns:\n" " - name: waffle_type_id\n type: INTEGER\n" ), - "seeds/waffle_types.csv": "waffle_type_id\n1\n", - "models/stg_orders.sql": ( + "sql/seeds/waffle_types.csv": "waffle_type_id\n1\n", + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.'," "\n materialized table,\n columns (\n waffle_type_id (\n" ' audits [relationships (to __seed("waffle_types"), field waffle_type_id)],\n' @@ -778,9 +797,9 @@ def prepare_audit_read_plan_project(*, tmp_path: Path) -> Path: ) -EXPLICIT_REFERENCE_MODELS: str = "models/sales" -EXPLICIT_REFERENCE_MACRO_PATH: str = "models/sales/_sqlbuild/_macros/python/unions.py" -EXPLICIT_REFERENCE_HOOK_PATH: str = "models/sales/_sqlbuild/_hooks/python/lookups.py" +EXPLICIT_REFERENCE_MODELS: str = "sql/models/sales" +EXPLICIT_REFERENCE_MACRO_PATH: str = "sql/models/sales/_sqlbuild/_macros/python/unions.py" +EXPLICIT_REFERENCE_HOOK_PATH: str = "sql/models/sales/_sqlbuild/_hooks/python/lookups.py" EXPLICIT_REFERENCE_MACROS: str = ( "def union_all(relations):\n" " return ' UNION ALL '.join(\n" @@ -892,7 +911,7 @@ def python_node_selection_project_files(*, orders_sql: str) -> dict[str, str]: 'name = "order_nodes"\nadapter = "duckdb"\n\n' f'[connection]\ndatabase = "{PYTHON_NODE_SELECTION_DATABASE}"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" @@ -900,28 +919,31 @@ def python_node_selection_project_files(*, orders_sql: str) -> dict[str, str]: " managed: true\n write_strategy: table\n" " columns:\n - name: customer_id\n type: INTEGER\n" ), - "python/loaders/customers.py": ( + "python/nodes/loaders/customers/loader.py": ( "from sqlbuild.loaders import loader\n\n\n" "@loader\ndef raw_customers(ctx):\n" " '''Test loader raw_customers.'''\n" " return [{'customer_id': 99}]\n" ), - "python/tasks/counts.py": ( + **node_module_files( + "python/nodes/tasks/counts.py", "from sqlbuild.refs import model, source\nfrom sqlbuild.assets import asset\n\n\n" - + task_nodes + + task_nodes, ), - "python/assets/extracts.py": ( + **node_module_files( + "python/nodes/assets/extracts.py", "from sqlbuild.assets import asset\nfrom sqlbuild.refs import model, source\n\n\n" - + asset_nodes + + asset_nodes, ), - "models/orders.sql": orders_sql, - "models/order_summary.sql": ( + "sql/models/orders.sql": orders_sql, + "sql/models/order_summary.sql": ( 'MODEL (description "Test model order_summary.", ' 'materialized table);\nSELECT count(*) AS order_count FROM __ref("orders")\n' ), **duckshop_orchestration("python_node_jobs"), - "python/tasks/reports.py": ( - "from python.tasks.counts import count_orders\nfrom sqlbuild.assets import asset\n\n\n" + "python/nodes/tasks/reports/asset.py": ( + "from python.nodes.tasks.counts import count_orders\n" + "from sqlbuild.assets import asset\n\n\n" "@asset(depends_on=count_orders)\n" "def report_order_count(ctx):\n" " '''Test task report_order_count.'''\n" @@ -968,7 +990,7 @@ def prepare_empty_cursor_inputs_project(*, tmp_path: Path, models: dict[str, str project_name="empty_cursor_inputs", repo_files={ "sqlbuild_project.toml": _EMPTY_CURSOR_PROJECT_TOML, - "sources/raw.yml": _EMPTY_CURSOR_SOURCES_YML, + "sql/sources/raw.yml": _EMPTY_CURSOR_SOURCES_YML, **models, }, ) @@ -1011,12 +1033,14 @@ def prepare_emptied_cursor_project( """Build a model over loaded payments, then empty the source and write the next model SQL.""" project_dir: Path = prepare_empty_cursor_inputs_project( - tmp_path=tmp_path, models={"models/daily_revenue.sql": model_sql} + tmp_path=tmp_path, models={"sql/models/daily_revenue.sql": model_sql} ) load_empty_cursor_payments(project_dir=project_dir) build_empty_cursor_project(project_dir=project_dir) execute_empty_cursor_sql(project_dir=project_dir, sql="DELETE FROM main.raw_payments") - (project_dir / "models" / "daily_revenue.sql").write_text(changed_model_sql, encoding="utf-8") + (project_dir / "sql" / "models" / "daily_revenue.sql").write_text( + changed_model_sql, encoding="utf-8" + ) return project_dir @@ -1024,7 +1048,7 @@ def prepare_waiting_on_empty_input_project(*, tmp_path: Path, model_sql: str) -> """Build over payments and refunds, then empty refunds while new payments arrive.""" project_dir: Path = prepare_empty_cursor_inputs_project( - tmp_path=tmp_path, models={"models/daily_revenue.sql": model_sql} + tmp_path=tmp_path, models={"sql/models/daily_revenue.sql": model_sql} ) execute_empty_cursor_sql( project_dir=project_dir, @@ -1060,7 +1084,7 @@ def prepare_same_run_empty_inputs_project( build_empty_cursor_project(project_dir=project_dir) execute_empty_cursor_sql(project_dir=project_dir, sql=emptying_sql) view_path: Path - for view_path in sorted((project_dir / "models").glob("stg_*.sql")): + for view_path in sorted((project_dir / "sql" / "models").glob("stg_*.sql")): view_path.write_text( view_path.read_text(encoding="utf-8").replace( "amount_cents FROM", "amount_cents * 1 AS amount_cents FROM" @@ -1122,7 +1146,7 @@ def dynamic_category_project(*, tmp_path: Path, name_pattern_entry: str) -> Path 'select = ["SQBRMODEL102", "SQBRCONTRACT101", "SQBRCONTRACT105", ' '"SQBRCONTRACT106"]\n' ), - "models/stg_order_amounts.sql": ( + "sql/models/stg_order_amounts.sql": ( "MODEL (description 'Test model stg_order_amounts.',\n" " materialized table,\n" " columns (\n" @@ -1141,7 +1165,7 @@ def dynamic_category_project(*, tmp_path: Path, name_pattern_entry: str) -> Path "SELECT CAST(2 AS INTEGER), CAST('books' AS VARCHAR), " "CAST(7.00 AS DECIMAL(12,2))\n" ), - "models/customer_category_amounts.sql": ( + "sql/models/customer_category_amounts.sql": ( "MODEL (description 'Test model customer_category_amounts.',\n" " materialized table,\n" " columns (customer_id (type INTEGER)),\n" @@ -1171,8 +1195,8 @@ def seed_audit_files(status_values: tuple[str, ...]) -> dict[str, str]: 'name = "seed_audit_rows"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' '[connection]\ndatabase = "seed_audits.duckdb"\n\n[targets.dev]\nschema = "dev"\n' ), - "seeds/order_statuses.csv": "status_id,status\n1,placed\n2,shipped\n", - "seeds/order_statuses.yml": ( + "sql/seeds/order_statuses.csv": "status_id,status\n1,placed\n2,shipped\n", + "sql/seeds/order_statuses.yml": ( "seeds:\n" " - name: order_statuses\n" " description: Order statuses.\n" @@ -1220,8 +1244,8 @@ def target_concurrency_project_files( f"{target_concurrency}" ), "sqlbuild_local.toml": local_settings, - "seeds/products.csv": "product_id\n1\n2\n", - "seeds/products.yml": ( + "sql/seeds/products.csv": "product_id\n1\n2\n", + "sql/seeds/products.yml": ( "seeds:\n" " - name: products\n" " description: Products.\n" @@ -1229,7 +1253,7 @@ def target_concurrency_project_files( " - name: product_id\n" " type: INTEGER\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n\nSELECT 1 AS order_id\n" ), } @@ -1254,14 +1278,14 @@ def target_concurrency_microbatch_files() -> dict[str, str]: 'schema = "main"\n' "concurrency = 3\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_events\n" " description: Raw events.\n" " schema: main\n" " table: raw_events\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders.",\n' " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -1362,8 +1386,8 @@ def prepare_changed_project(*, tmp_path: Path, warehouse: ChangedWarehouse) -> P """The DuckShop changed-builds edge case on `warehouse`, with its raw tables loaded.""" files: dict[str, str] = { - str(path.relative_to(CHANGED_BUILDS_FIXTURE)): path.read_text(encoding="utf-8") - for path in sorted(CHANGED_BUILDS_FIXTURE.glob("*/*")) + path.relative_to(CHANGED_BUILDS_FIXTURE).as_posix(): path.read_text(encoding="utf-8") + for path in sorted(CHANGED_BUILDS_FIXTURE.glob("sql/*/*")) } project_dir: Path = prepare_inline_project( tmp_path=tmp_path, @@ -1419,7 +1443,7 @@ def kill_changed_build_mid_write( ) -> tuple[frozenset[str], list[tuple[object, ...]]]: """Kill a build while a slow model writes; return what it finished and the slow model's rows.""" - slow_model: Path = project_dir / "models/order_weights.sql" + slow_model: Path = project_dir / "sql/models/order_weights.sql" slow_model.write_text( _CHANGED_SLOW_MODEL.format(scan=warehouse.slow_scan_cte), encoding="utf-8" ) @@ -1470,7 +1494,7 @@ def changed_build_steps(warehouse: ChangedWarehouse) -> tuple[ChangedBuildStep, "a definition change", (), { - "models/stg_customers.sql": ( + "sql/models/stg_customers.sql": ( 'MODEL (description "Staged customers.", materialized table);\n' 'SELECT customer_id FROM __source("raw_customers") WHERE customer_id > 0\n' ) @@ -1505,8 +1529,8 @@ def changed_build_steps(warehouse: ChangedWarehouse) -> tuple[ChangedBuildStep, ROUND_TRIP_FIXTURE: Path = Path("benchmarks/duckshop/edge_cases/loaders/round_trip") _TWO_GATE_LOADER: str = ( "from sqlbuild.loaders import loader\n\n" - "from python.tasks.ranking import rank_orders\n" - "from python.tasks.scoring import score_orders\n\n\n" + "from python.nodes.tasks.ranking import rank_orders\n" + "from python.nodes.tasks.scoring.asset import score_orders\n\n\n" "@loader(depends_on=[score_orders, rank_orders])\n" "def partner_scores(ctx):\n" ' """Load the scores the partner returned."""\n' @@ -1525,10 +1549,10 @@ def round_trip_project_files(*, project_settings: str, task_body: str) -> dict[s [*project.rglob("*.py"), *project.rglob("*.sql"), *project.rglob("*.yml")] ) } - assert SCORING_TASK in files["python/tasks/scoring.py"] - files["python/tasks/scoring.py"] = files["python/tasks/scoring.py"].replace( - SCORING_TASK, task_body - ) + assert SCORING_TASK in files["python/nodes/tasks/scoring/asset.py"] + files["python/nodes/tasks/scoring/asset.py"] = files[ + "python/nodes/tasks/scoring/asset.py" + ].replace(SCORING_TASK, task_body) return { "sqlbuild_project.toml": ( 'name = "partner_scoring"\n' @@ -1562,7 +1586,7 @@ def round_trip_variant(variant: str, files: dict[str, str]) -> dict[str, str]: def scoring_task_files(body: str) -> dict[str, str]: """The round trip's score task with `body`, keyed by where it goes in the project.""" - path: str = "python/tasks/scoring.py" + path: str = "python/nodes/tasks/scoring/asset.py" return { path: round_trip_project_files(project_settings=ALLOW_ROUND_TRIPS, task_body=body)[path] } @@ -1572,14 +1596,15 @@ def ranking_task_files(body: str) -> dict[str, str]: """A second task gating the partner loader, with `body`, and the loader depending on both.""" return { - "python/tasks/ranking.py": ( + **node_module_files( + "python/nodes/tasks/ranking.py", "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n\n" '@asset(depends_on=model("orders"))\n' "def rank_orders(ctx):\n" - ' """Rank the orders for the partner."""\n' + body + ' """Rank the orders for the partner."""\n' + body, ), - "python/loaders/partner.py": _TWO_GATE_LOADER, + "python/nodes/loaders/partner/loader.py": _TWO_GATE_LOADER, } @@ -1620,25 +1645,25 @@ def build_round_trip_project( ) # A table whose final audit fails, and a model that reads it. STAGED_AUDIT_FILES: dict[str, str] = { - "audits/generic/expression_is_true.sql": _EXPRESSION_AUDIT, - "models/daily.sql": ( + "sql/audits/generic/expression_is_true.sql": _EXPRESSION_AUDIT, + "sql/models/daily.sql": ( "MODEL (description 'Daily totals.', materialized table, audits [expression_is_true " '(name "total_is_negative", expression "total_cents < 0", severity error)]);\n\n' "SELECT 1 AS day, 300 AS total_cents\n" ), - "models/daily_summary.sql": ( + "sql/models/daily_summary.sql": ( "MODEL (description 'Reads daily.', materialized table);\n\n" 'SELECT day FROM __ref("daily")\n' ), } # An incremental model whose delta audit fails, over one row it already holds. INCREMENTAL_AUDIT_FILES: dict[str, str] = { - "audits/generic/expression_is_true.sql": _EXPRESSION_AUDIT, - "sources/raw.yml": ( + "sql/audits/generic/expression_is_true.sql": _EXPRESSION_AUDIT, + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" " schema: main\n table: raw_orders\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized incremental, incremental_strategy merge, " 'unique_key [id], audits [expression_is_true (name "amount_is_negative", ' 'expression "amount_cents < 0", severity error, run_scope delta_and_final)]);\n\n' @@ -1650,14 +1675,14 @@ def build_round_trip_project( ) # A source whose audit fails, and a model that reads it. SOURCE_AUDIT_FILES: dict[str, str] = { - "audits/generic/expression_is_true.sql": _EXPRESSION_AUDIT, - "sources/raw.yml": ( + "sql/audits/generic/expression_is_true.sql": _EXPRESSION_AUDIT, + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" " schema: main\n table: raw_orders\n audits:\n" " - expression_is_true:\n name: raw_amount_is_negative\n" ' expression: "amount_cents < 0"\n severity: error\n' ), - "models/order_count.sql": ( + "sql/models/order_count.sql": ( "MODEL (description 'Reads raw orders.', materialized table);\n\n" 'SELECT count(*) AS order_count FROM __source("raw_orders")\n' ), @@ -1728,7 +1753,7 @@ def node_result_project(*, tmp_path: Path, target_lines: str, files: dict[str, s '[connection]\ndatabase = "dev.duckdb"\n\n' f'[defaults]\ndatabase = "dev"\nschema = "mart"\n\n[targets.dev]\n{target_lines}' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n\n" 'SELECT order_id FROM __source("raw_orders")\n' ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/no_tests_no_audits/test_build_no_tests_no_audits.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/no_tests_no_audits/test_build_no_tests_no_audits.py index 2652952160..775ab5d829 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/no_tests_no_audits/test_build_no_tests_no_audits.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/no_tests_no_audits/test_build_no_tests_no_audits.py @@ -66,7 +66,7 @@ def test_given_project_with_python_hooks_when_running_run_then_hooks_execute( """ ).strip() + "\n", - "hooks/python/lifecycle.py": dedent( + "sql/hooks/python/lifecycle.py": dedent( """ from sqlbuild.hooks import HookContext, hook @@ -85,7 +85,7 @@ def log_hook(ctx: HookContext): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -151,7 +151,9 @@ def test_given_waffle_shop_project_when_running_run_then_warehouse_state_matches ) assert result.returncode == test_case.expected_exit_code, result.stdout + result.stderr - run_sql_path: Path = project_dir / "target" / "run" / "models" / "marts" / "fact_orders.sql" + run_sql_path: Path = ( + project_dir / "target" / "run" / "sql" / "models" / "marts" / "fact_orders.sql" + ) assert run_sql_path.exists() run_sql: str = run_sql_path.read_text(encoding="utf-8") assert "CREATE OR REPLACE TABLE main.fact_orders__staging AS" in run_sql @@ -196,12 +198,13 @@ def test_given_factory_generated_nodes_when_running_commands_then_lifecycle_succ project_name="factory_nodes_project", repo_files={ "sqlbuild_project.toml": ( + 'extra_paths = ["prepare_marker.txt", "loader_marker.txt", "asset_marker.txt"]\n' 'name = "factory_nodes_project"\n' 'adapter = "duckdb"\n\n' "[connection]\n" 'database = "factory_nodes_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -210,10 +213,11 @@ def test_given_factory_generated_nodes_when_running_commands_then_lifecycle_succ " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "python/factories/generated.py": """ + "python/nodes/factories/generated/factory.py": """ from pathlib import Path from sqlbuild.assets import asset from sqlbuild.checks import check @@ -222,7 +226,7 @@ def test_given_factory_generated_nodes_when_running_commands_then_lifecycle_succ from sqlbuild.assets import asset -PROJECT_DIR = Path(__file__).parents[2] +PROJECT_DIR = Path(__file__).parents[4] @factory @@ -357,20 +361,34 @@ def test_given_existing_intermediate_target_when_running_source_only_then_reuses "[connection]\n" 'database = "run_existing_intermediate_project.duckdb"\n' ), - "python/loaders/raw.py": ( - "from sqlbuild.loaders import loader\n\n" + "python/nodes/loaders/raw/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" "@loader(write_strategy='table', columns=[\n" " {'name': 'event_id', 'type': 'INTEGER'},\n" "])\n" "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}]\n\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/raw/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw.fetch_events.loader import fetch_events\n" + "\n" + "\n" "@loader(depends_on=[fetch_events])\n" "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS " "SELECT event_id FROM {events.destination}')\n" ), - "sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", + "python/nodes/loaders/raw/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + "sql/sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", }, ) setup_result: subprocess.CompletedProcess[str] = run_sqb( @@ -419,12 +437,13 @@ def test_given_task_selector_when_running_run_then_task_executes( "[connection]\n" 'database = "python_run_project.duckdb"\n' ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from pathlib import Path\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_orders(ctx):\n" - " '''Test task prepare_orders.'''\n Path(__file__).parents[2].joinpath('task_marker.txt').write_text('ran')\n" + " '''Test task prepare_orders.'''\n " + "Path(__file__).parents[4].joinpath('task_marker.txt').write_text('ran')\n" " return ctx.result(payload={'status': 'ok'})\n" ), }, @@ -469,17 +488,19 @@ def test_given_asset_selector_when_running_run_then_asset_executes( project_name="python_asset_run_project", repo_files={ "sqlbuild_project.toml": ( + 'extra_paths = ["asset_marker.txt"]\n' 'name = "python_asset_run_project"\n' 'adapter = "duckdb"\n\n' "[connection]\n" 'database = "python_asset_run_project.duckdb"\n' ), - "python/assets/orders.py": ( + "python/nodes/assets/orders/asset.py": ( "from pathlib import Path\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepared_orders(ctx):\n" - " '''Test asset prepared_orders.'''\n Path(__file__).parents[2].joinpath('asset_marker.txt').write_text('ran')\n" + " '''Test asset prepared_orders.'''\n " + "Path(__file__).parents[4].joinpath('asset_marker.txt').write_text('ran')\n" " return ctx.result(payload={'status': 'ok'}, materialized=True)\n" ), }, @@ -530,7 +551,7 @@ def test_given_task_selector_with_json_output_when_running_run_then_json_include "[connection]\n" 'database = "python_run_json_project.duckdb"\n' ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_orders(ctx):\n" @@ -601,7 +622,7 @@ def test_given_failing_task_selector_when_running_run_then_command_fails( "[connection]\n" 'database = "python_failed_run_project.duckdb"\n' ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def fail_orders(ctx):\n" @@ -670,26 +691,28 @@ def test_given_task_loader_source_model_chain_when_running_model_then_task_runs_ "[connection]\n" 'database = "python_loader_run_project.duckdb"\n' ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from pathlib import Path\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_orders(ctx):\n" - " '''Test task prepare_orders.'''\n Path(__file__).parents[2].joinpath('orders_ready.txt').write_text('ready')\n" + " '''Test task prepare_orders.'''\n " + "Path(__file__).parents[4].joinpath('orders_ready.txt').write_text('ready')\n" " return ctx.result(metadata={'prepared': True})\n" ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from pathlib import Path\n" "from sqlbuild.loaders import loader\n" - "from python.tasks.orders import prepare_orders\n\n" + "from python.nodes.tasks.orders.asset import prepare_orders\n\n" "@loader(depends_on=(prepare_orders,))\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n marker = Path(__file__).parents[2].joinpath('orders_ready.txt')\n" + " '''Test loader raw_orders.'''\n marker = " + "Path(__file__).parents[4].joinpath('orders_ready.txt')\n" " if not marker.exists():\n" " raise RuntimeError('orders were not prepared')\n" " return [{'order_id': 1, 'amount_cents': 100}]\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -700,7 +723,7 @@ def test_given_task_loader_source_model_chain_when_running_model_then_task_runs_ " - name: amount_cents\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.', materialized table);\n\n" 'SELECT order_id, amount_cents FROM __source("raw_orders")\n' ), @@ -748,7 +771,7 @@ def test_given_model_and_task_selector_when_running_run_then_task_can_read_built "[connection]\n" 'database = "python_model_task_run_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id, 100 AS amount_cents\n" @@ -758,19 +781,20 @@ def test_given_model_and_task_selector_when_running_run_then_task_can_read_built " - name: amount_cents\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.', materialized table);\n\n" 'SELECT order_id, amount_cents FROM __source("raw_orders")\n' ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from pathlib import Path\n" "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('fact_orders'))\n" "def summarize_orders(ctx):\n" - " '''Test task summarize_orders.'''\n orders = ctx.relation(model('fact_orders'))\n" + " '''Test task summarize_orders.'''\n orders = " + "ctx.relation(model('fact_orders'))\n" " rows = ctx.query(f'SELECT COUNT(*) FROM {orders}').fetchall()[0][0]\n" - " Path(__file__).parents[2].joinpath('summary.txt').write_text(str(rows))\n" + " Path(__file__).parents[4].joinpath('summary.txt').write_text(str(rows))\n" " return ctx.result(metadata={'rows': rows})\n" ), }, @@ -823,7 +847,7 @@ def test_given_asset_depends_on_terminal_model_when_running_run_then_asset_reads "[connection]\n" 'database = "python_model_asset_run_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -831,18 +855,20 @@ def test_given_asset_depends_on_terminal_model_when_running_run_then_asset_reads " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "python/assets/orders.py": ( + "python/nodes/assets/orders/asset.py": ( "from pathlib import Path\n" "from sqlbuild.assets import asset\n" "from sqlbuild.refs import model\n\n" "@asset(depends_on=model('fact_orders'))\n" "def export_fact_orders(ctx):\n" - " '''Test asset export_fact_orders.'''\n orders = ctx.relation(model('fact_orders'))\n" + " '''Test asset export_fact_orders.'''\n orders = " + "ctx.relation(model('fact_orders'))\n" " rows = ctx.query(f'SELECT COUNT(*) FROM {orders}').fetchall()[0][0]\n" - " Path(__file__).parents[2].joinpath('export.txt').write_text(str(rows))\n" + " Path(__file__).parents[4].joinpath('export.txt').write_text(str(rows))\n" " return ctx.result(metadata={'rows': rows}, materialized=True)\n" ), }, @@ -895,29 +921,31 @@ def test_given_task_asset_task_chain_when_running_final_task_then_chain_executes "[connection]\n" 'database = "python_task_asset_task_run_project.duckdb"\n' ), - "python/tasks/fetch_orders.py": ( + "python/nodes/tasks/fetch_orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def fetch_orders(ctx):\n" " '''Test task fetch_orders.'''\n return ctx.result(payload={'rows': 1})\n" ), - "python/tasks/notify_orders.py": ( + "python/nodes/tasks/notify_orders/asset.py": ( "from pathlib import Path\n" - "from python.assets.orders import publish_orders\n" + "from python.nodes.assets.orders.asset import publish_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=publish_orders)\n" "def notify_orders(ctx):\n" - " '''Test task notify_orders.'''\n metadata = ctx.result_of(node_function=publish_orders).metadata\n" - " output = Path(__file__).parents[2].joinpath('notify.txt')\n" + " '''Test task notify_orders.'''\n metadata = " + "ctx.result_of(node_function=publish_orders).metadata\n" + " output = Path(__file__).parents[4].joinpath('notify.txt')\n" " output.write_text(str(metadata['published']))\n" " return ctx.result()\n" ), - "python/assets/orders.py": ( + "python/nodes/assets/orders/asset.py": ( "from sqlbuild.assets import asset\n" - "from python.tasks.fetch_orders import fetch_orders\n\n" + "from python.nodes.tasks.fetch_orders.asset import fetch_orders\n\n" "@asset(depends_on=fetch_orders)\n" "def publish_orders(ctx):\n" - " '''Test asset publish_orders.'''\n payload = ctx.result_of(node_function=fetch_orders).payload\n" + " '''Test asset publish_orders.'''\n payload = " + "ctx.result_of(node_function=fetch_orders).payload\n" " return ctx.result(payload=payload, metadata={'published': True})\n" ), }, @@ -960,13 +988,14 @@ def test_given_source_task_asset_selection_when_running_run_then_task_reads_load "[connection]\n" 'database = "python_source_task_asset_run_project.duckdb"\n' ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n return [{'order_id': 1, 'amount_cents': 100}]\n" + " '''Test loader raw_orders.'''\n return [{'order_id': 1, " + "'amount_cents': 100}]\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -977,21 +1006,23 @@ def test_given_source_task_asset_selection_when_running_run_then_task_reads_load " - name: amount_cents\n" " type: INTEGER\n" ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.refs import source\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=source('raw_orders'))\n" "def summarize_loaded_orders(ctx):\n" - " '''Test task summarize_loaded_orders.'''\n orders = ctx.relation(source('raw_orders'))\n" + " '''Test task summarize_loaded_orders.'''\n orders = " + "ctx.relation(source('raw_orders'))\n" " rows = ctx.query(f'SELECT COUNT(*) FROM {orders}').fetchall()[0][0]\n" " return ctx.result(payload={'rows': rows}, metadata={'rows': rows})\n" ), - "python/assets/orders.py": ( + "python/nodes/assets/orders/asset.py": ( "from sqlbuild.assets import asset\n" - "from python.tasks.orders import summarize_loaded_orders\n\n" + "from python.nodes.tasks.orders.asset import summarize_loaded_orders\n\n" "@asset(depends_on=summarize_loaded_orders)\n" "def publish_loaded_orders(ctx):\n" - " '''Test asset publish_loaded_orders.'''\n payload = ctx.result_of(node_function=summarize_loaded_orders).payload\n" + " '''Test asset publish_loaded_orders.'''\n payload = " + "ctx.result_of(node_function=summarize_loaded_orders).payload\n" " return ctx.result(payload=payload, materialized=False)\n" ), }, @@ -1047,17 +1078,18 @@ def test_given_skip_and_asset_selection_with_json_when_running_run_then_json_rec "[connection]\n" 'database = "python_json_fields_run_project.duckdb"\n' ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def optional_orders(ctx):\n" " '''Test task optional_orders.'''\n return ctx.skip(reason='no files')\n\n" ), - "python/assets/orders.py": ( + "python/nodes/assets/orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def observed_orders(ctx):\n" - " '''Test asset observed_orders.'''\n return ctx.result(metadata={'uri': 's3://orders'}, materialized=False)\n" + " '''Test asset observed_orders.'''\n return " + "ctx.result(metadata={'uri': 's3://orders'}, materialized=False)\n" ), }, ) @@ -1125,7 +1157,7 @@ def test_given_independent_python_and_sql_selectors_when_running_run_then_all_br "[connection]\n" 'database = "python_independent_run_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -1133,21 +1165,35 @@ def test_given_independent_python_and_sql_selectors_when_running_run_then_all_br " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT order_id FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT order_id FROM __source("raw_orders")\n' ), - "python/tasks/branches.py": ( + "python/nodes/tasks/branches/branch_a/asset.py": ( "from pathlib import Path\n" - "from sqlbuild.assets import asset\n\n" + "from sqlbuild.assets import asset\n" + "\n" + "\n" "@asset\n" "def branch_a(ctx):\n" - " '''Test task branch_a.'''\n Path(__file__).parents[2].joinpath('branch_a.txt').write_text('a')\n" - " return ctx.result()\n\n" + " '''Test task branch_a.'''\n" + " Path(__file__).parents[5].joinpath('branch_a.txt').write_text('a')\n" + " return ctx.result()\n" + ), + "python/nodes/tasks/branches/branch_b/asset.py": ( + "from pathlib import Path\n" + "from sqlbuild.assets import asset\n" + "\n" + "\n" "@asset\n" "def branch_b(ctx):\n" - " '''Test task branch_b.'''\n Path(__file__).parents[2].joinpath('branch_b.txt').write_text('b')\n" + " '''Test task branch_b.'''\n" + " Path(__file__).parents[5].joinpath('branch_b.txt').write_text('b')\n" " return ctx.result()\n" ), + "python/nodes/tasks/branches/__init__.py": ( + "from .branch_a.asset import branch_a\nfrom .branch_b.asset import branch_b\n" + ), }, ) @@ -1197,7 +1243,7 @@ def test_given_task_depends_on_model_when_running_run_then_task_runs_before_down "[connection]\n" 'database = "python_read_side_run_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id, 100 AS amount_cents\n" @@ -1207,18 +1253,21 @@ def test_given_task_depends_on_model_when_running_run_then_task_runs_before_down " - name: amount_cents\n" " type: INTEGER\n" ), - "models/stg_orders.sql": ( - 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/stg_orders.sql": ( + 'MODEL (description "Test model stg_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __ref("stg_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __ref("stg_orders")\n' ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('stg_orders'))\n" "def profile_stg_orders(ctx):\n" - " '''Test task profile_stg_orders.'''\n orders = ctx.relation(model('stg_orders'))\n" + " '''Test task profile_stg_orders.'''\n orders = " + "ctx.relation(model('stg_orders'))\n" " rows = ctx.query(f'SELECT COUNT(*) FROM {orders}').fetchall()[0][0]\n" " return ctx.result(payload={'rows': rows})\n" ), @@ -1272,13 +1321,14 @@ def test_given_task_depends_on_source_when_running_run_then_task_runs_after_sour "[connection]\n" 'database = "python_read_side_source_run_project.duckdb"\n' ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n return [{'order_id': 1, 'amount_cents': 100}]\n" + " '''Test loader raw_orders.'''\n return [{'order_id': 1, " + "'amount_cents': 100}]\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -1289,12 +1339,13 @@ def test_given_task_depends_on_source_when_running_run_then_task_runs_after_sour " - name: amount_cents\n" " type: INTEGER\n" ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from sqlbuild.refs import source\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=source('raw_orders'))\n" "def profile_raw_orders(ctx):\n" - " '''Test task profile_raw_orders.'''\n orders = ctx.relation(source('raw_orders'))\n" + " '''Test task profile_raw_orders.'''\n orders = " + "ctx.relation(source('raw_orders'))\n" " rows = ctx.query(f'SELECT COUNT(*) FROM {orders}').fetchall()[0][0]\n" " return ctx.result(payload={'rows': rows})\n" ), @@ -1348,7 +1399,7 @@ def test_given_sql_ready_task_fails_when_running_run_then_footer_json_and_exit_f "[connection]\n" 'database = "python_read_side_failure_run_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -1356,18 +1407,21 @@ def test_given_sql_ready_task_fails_when_running_run_then_footer_json_and_exit_f " - name: order_id\n" " type: INTEGER\n" ), - "models/stg_orders.sql": ( - 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/stg_orders.sql": ( + 'MODEL (description "Test model stg_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __ref("stg_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __ref("stg_orders")\n' ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('stg_orders'))\n" "def fail_after_stg_orders(ctx):\n" - " '''Test task fail_after_stg_orders.'''\n raise RuntimeError('profile failed')\n" + " '''Test task fail_after_stg_orders.'''\n raise " + "RuntimeError('profile failed')\n" ), }, ) @@ -1428,13 +1482,13 @@ def test_given_task_depends_on_terminal_loader_when_running_run_then_command_rej "[connection]\n" 'database = "python_boundary_run_project.duckdb"\n' ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 1}]\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -1442,8 +1496,8 @@ def test_given_task_depends_on_terminal_loader_when_running_run_then_command_rej " - name: order_id\n" " type: INTEGER\n" ), - "python/tasks/orders.py": ( - "from python.loaders.orders import raw_orders\n" + "python/nodes/tasks/orders/asset.py": ( + "from python.nodes.loaders.orders.loader import raw_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=raw_orders)\n" "def summarize_orders(ctx):\n" @@ -1496,7 +1550,7 @@ def test_given_task_asset_depend_on_intermediate_loader_when_running_run_then_lo "[connection]\n" 'database = "python_intermediate_loader_run_project.duckdb"\n' ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader(\n" " destination='stage_orders',\n" @@ -1507,22 +1561,25 @@ def test_given_task_asset_depend_on_intermediate_loader_when_running_run_then_lo " ],\n" ")\n" "def stage_orders(ctx):\n" - " '''Test loader stage_orders.'''\n return [{'order_id': 1, 'amount_cents': 100}]\n" + " '''Test loader stage_orders.'''\n return [{'order_id': 1, " + "'amount_cents': 100}]\n" ), - "python/tasks/orders.py": ( - "from python.loaders.orders import stage_orders\n" + "python/nodes/tasks/orders/asset.py": ( + "from python.nodes.loaders.orders.loader import stage_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=stage_orders)\n" "def summarize_stage_orders(ctx):\n" - " '''Test task summarize_stage_orders.'''\n rows = ctx.query('SELECT COUNT(*) FROM stage_orders').fetchall()[0][0]\n" + " '''Test task summarize_stage_orders.'''\n rows = " + "ctx.query('SELECT COUNT(*) FROM stage_orders').fetchall()[0][0]\n" " return ctx.result(payload={'rows': rows}, metadata={'rows': rows})\n" ), - "python/assets/orders.py": ( + "python/nodes/assets/orders/asset.py": ( "from sqlbuild.assets import asset\n" - "from python.tasks.orders import summarize_stage_orders\n\n" + "from python.nodes.tasks.orders.asset import summarize_stage_orders\n\n" "@asset(depends_on=summarize_stage_orders)\n" "def publish_stage_orders(ctx):\n" - " '''Test asset publish_stage_orders.'''\n payload = ctx.result_of(node_function=summarize_stage_orders).payload\n" + " '''Test asset publish_stage_orders.'''\n payload = " + "ctx.result_of(node_function=summarize_stage_orders).payload\n" " return ctx.result(payload=payload, materialized=True)\n" ), }, @@ -1577,7 +1634,7 @@ def test_given_loader_task_loader_chain_when_running_model_then_ingress_orders_c "[connection]\n" 'database = "python_loader_task_loader_run_project.duckdb"\n' ), - "python/loaders/window.py": ( + "python/nodes/loaders/window/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader(\n" " destination='window_orders',\n" @@ -1587,28 +1644,31 @@ def test_given_loader_task_loader_chain_when_running_model_then_ingress_orders_c "def load_window_orders(ctx):\n" " '''Test loader load_window_orders.'''\n return [{'order_id': 1}]\n" ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from pathlib import Path\n" - "from python.loaders.window import load_window_orders\n" + "from python.nodes.loaders.window.loader import load_window_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=load_window_orders)\n" "def prepare_raw_orders(ctx):\n" - " '''Test task prepare_raw_orders.'''\n rows = ctx.query('SELECT COUNT(*) FROM window_orders').fetchall()[0][0]\n" - " Path(__file__).parents[2].joinpath('prepared.txt').write_text(str(rows))\n" + " '''Test task prepare_raw_orders.'''\n rows = ctx.query('SELECT " + "COUNT(*) FROM window_orders').fetchall()[0][0]\n" + " Path(__file__).parents[4].joinpath('prepared.txt').write_text(str(rows))\n" " return ctx.result(metadata={'rows': rows})\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from pathlib import Path\n" - "from python.tasks.orders import prepare_raw_orders\n" + "from python.nodes.tasks.orders.asset import prepare_raw_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(prepare_raw_orders,))\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n marker = Path(__file__).parents[2].joinpath('prepared.txt')\n" + " '''Test loader raw_orders.'''\n marker = " + "Path(__file__).parents[4].joinpath('prepared.txt')\n" " if marker.read_text() != '1':\n" " raise RuntimeError('window orders were not prepared')\n" " return [{'order_id': 1}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -1617,8 +1677,9 @@ def test_given_loader_task_loader_chain_when_running_model_then_ingress_orders_c " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), }, ) @@ -1663,35 +1724,38 @@ def test_given_task_asset_loader_chain_when_running_model_then_ingress_orders_ch "[connection]\n" 'database = "python_task_asset_loader_run_project.duckdb"\n' ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def fetch_orders(ctx):\n" - " '''Test task fetch_orders.'''\n return ctx.result(payload={'order_id': 1})\n" + " '''Test task fetch_orders.'''\n return " + "ctx.result(payload={'order_id': 1})\n" ), - "python/assets/orders.py": ( + "python/nodes/assets/orders/asset.py": ( "from pathlib import Path\n" - "from python.tasks.orders import fetch_orders\n" + "from python.nodes.tasks.orders.asset import fetch_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=fetch_orders)\n" "def publish_orders(ctx):\n" - " '''Test asset publish_orders.'''\n payload = ctx.result_of(node_function=fetch_orders).payload\n" - " marker = Path(__file__).parents[2].joinpath('asset_ready.txt')\n" + " '''Test asset publish_orders.'''\n payload = " + "ctx.result_of(node_function=fetch_orders).payload\n" + " marker = Path(__file__).parents[4].joinpath('asset_ready.txt')\n" " marker.write_text(str(payload['order_id']))\n" " return ctx.result(payload=payload, materialized=True)\n" ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from pathlib import Path\n" - "from python.assets.orders import publish_orders\n" + "from python.nodes.assets.orders.asset import publish_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(publish_orders,))\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n marker = Path(__file__).parents[2].joinpath('asset_ready.txt')\n" + " '''Test loader raw_orders.'''\n marker = " + "Path(__file__).parents[4].joinpath('asset_ready.txt')\n" " if marker.read_text() != '1':\n" " raise RuntimeError('asset was not ready')\n" " return [{'order_id': 1}]\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -1700,8 +1764,9 @@ def test_given_task_asset_loader_chain_when_running_model_then_ingress_orders_ch " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), }, ) @@ -1746,7 +1811,7 @@ def test_given_loader_asset_loader_chain_when_running_model_then_ingress_orders_ "[connection]\n" 'database = "python_loader_asset_loader_run_project.duckdb"\n' ), - "python/loaders/window.py": ( + "python/nodes/loaders/window/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader(\n" " destination='window_orders',\n" @@ -1756,28 +1821,31 @@ def test_given_loader_asset_loader_chain_when_running_model_then_ingress_orders_ "def load_window_orders(ctx):\n" " '''Test loader load_window_orders.'''\n return [{'order_id': 1}]\n" ), - "python/assets/orders.py": ( + "python/nodes/assets/orders/asset.py": ( "from pathlib import Path\n" - "from python.loaders.window import load_window_orders\n" + "from python.nodes.loaders.window.loader import load_window_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=load_window_orders)\n" "def prepare_asset_orders(ctx):\n" - " '''Test asset prepare_asset_orders.'''\n rows = ctx.query('SELECT COUNT(*) FROM window_orders').fetchall()[0][0]\n" - " Path(__file__).parents[2].joinpath('asset_ready.txt').write_text(str(rows))\n" + " '''Test asset prepare_asset_orders.'''\n rows = " + "ctx.query('SELECT COUNT(*) FROM window_orders').fetchall()[0][0]\n" + " Path(__file__).parents[4].joinpath('asset_ready.txt').write_text(str(rows))\n" " return ctx.result(metadata={'rows': rows}, materialized=True)\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from pathlib import Path\n" - "from python.assets.orders import prepare_asset_orders\n" + "from python.nodes.assets.orders.asset import prepare_asset_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(prepare_asset_orders,))\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n marker = Path(__file__).parents[2].joinpath('asset_ready.txt')\n" + " '''Test loader raw_orders.'''\n marker = " + "Path(__file__).parents[4].joinpath('asset_ready.txt')\n" " if marker.read_text() != '1':\n" " raise RuntimeError('asset orders were not prepared')\n" " return [{'order_id': 1}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -1786,8 +1854,9 @@ def test_given_loader_asset_loader_chain_when_running_model_then_ingress_orders_ " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), }, ) @@ -1832,7 +1901,7 @@ def test_given_loader_loader_chain_when_running_model_then_ingress_orders_chain( "[connection]\n" 'database = "python_loader_loader_run_project.duckdb"\n' ), - "python/loaders/window.py": ( + "python/nodes/loaders/window/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader(\n" " destination='window_orders',\n" @@ -1842,15 +1911,17 @@ def test_given_loader_loader_chain_when_running_model_then_ingress_orders_chain( "def load_window_orders(ctx):\n" " '''Test loader load_window_orders.'''\n return [{'order_id': 1}]\n" ), - "python/loaders/raw.py": ( - "from python.loaders.window import load_window_orders\n" + "python/nodes/loaders/raw/loader.py": ( + "from python.nodes.loaders.window.loader import load_window_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(load_window_orders,))\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n rows = ctx.query('SELECT COUNT(*) FROM window_orders').fetchall()[0][0]\n" + " '''Test loader raw_orders.'''\n rows = ctx.query('SELECT " + "COUNT(*) FROM window_orders').fetchall()[0][0]\n" " return [{'order_id': rows}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -1859,8 +1930,9 @@ def test_given_loader_loader_chain_when_running_model_then_ingress_orders_chain( " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), }, ) @@ -1905,7 +1977,7 @@ def test_given_loader_task_asset_loader_model_task_asset_task_spine_when_running "[connection]\n" 'database = "python_sql_python_spine_run_project.duckdb"\n' ), - "python/loaders/window.py": ( + "python/nodes/loaders/window/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader(\n" " destination='window_orders',\n" @@ -1915,35 +1987,39 @@ def test_given_loader_task_asset_loader_model_task_asset_task_spine_when_running "def load_window_orders(ctx):\n" " '''Test loader load_window_orders.'''\n return [{'order_id': 7}]\n" ), - "python/tasks/prepare.py": ( - "from python.loaders.window import load_window_orders\n" + "python/nodes/tasks/prepare/asset.py": ( + "from python.nodes.loaders.window.loader import load_window_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=load_window_orders)\n" "def prepare_orders(ctx):\n" - " '''Test task prepare_orders.'''\n rows = ctx.query('SELECT order_id FROM window_orders').fetchall()\n" + " '''Test task prepare_orders.'''\n rows = ctx.query('SELECT " + "order_id FROM window_orders').fetchall()\n" " return ctx.result(payload={'order_id': rows[0][0]})\n" ), - "python/assets/prepare.py": ( + "python/nodes/assets/prepare/asset.py": ( "from pathlib import Path\n" - "from python.tasks.prepare import prepare_orders\n" + "from python.nodes.tasks.prepare.asset import prepare_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=prepare_orders)\n" "def publish_prepared_orders(ctx):\n" - " '''Test asset publish_prepared_orders.'''\n payload = ctx.result_of(node_function=prepare_orders).payload\n" - " marker = Path(__file__).parents[2].joinpath('prepared_order_id.txt')\n" + " '''Test asset publish_prepared_orders.'''\n payload = " + "ctx.result_of(node_function=prepare_orders).payload\n" + " marker = Path(__file__).parents[4].joinpath('prepared_order_id.txt')\n" " marker.write_text(str(payload['order_id']))\n" " return ctx.result(payload=payload, materialized=True)\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from pathlib import Path\n" - "from python.assets.prepare import publish_prepared_orders\n" + "from python.nodes.assets.prepare.asset import publish_prepared_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(publish_prepared_orders,))\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n marker = Path(__file__).parents[2].joinpath('prepared_order_id.txt')\n" + " '''Test loader raw_orders.'''\n marker = " + "Path(__file__).parents[4].joinpath('prepared_order_id.txt')\n" " return [{'order_id': int(marker.read_text())}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -1952,34 +2028,38 @@ def test_given_loader_task_asset_loader_model_task_asset_task_spine_when_running " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('fact_orders'))\n" "def profile_fact_orders(ctx):\n" - " '''Test task profile_fact_orders.'''\n orders = ctx.relation(model('fact_orders'))\n" + " '''Test task profile_fact_orders.'''\n orders = " + "ctx.relation(model('fact_orders'))\n" " order_id = ctx.query(f'SELECT order_id FROM {orders}').fetchall()[0][0]\n" " return ctx.result(payload={'order_id': order_id}, metadata={'rows': 1})\n" ), - "python/assets/export.py": ( - "from python.tasks.profile import profile_fact_orders\n" + "python/nodes/assets/export/asset.py": ( + "from python.nodes.tasks.profile.asset import profile_fact_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=profile_fact_orders)\n" "def export_fact_orders(ctx):\n" - " '''Test asset export_fact_orders.'''\n payload = ctx.result_of(node_function=profile_fact_orders).payload\n" + " '''Test asset export_fact_orders.'''\n payload = " + "ctx.result_of(node_function=profile_fact_orders).payload\n" " return ctx.result(payload=payload, metadata={'exported': True})\n" ), - "python/tasks/notify.py": ( + "python/nodes/tasks/notify/asset.py": ( "from pathlib import Path\n" - "from python.assets.export import export_fact_orders\n" + "from python.nodes.assets.export.asset import export_fact_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=export_fact_orders)\n" "def notify_fact_orders(ctx):\n" - " '''Test task notify_fact_orders.'''\n payload = ctx.result_of(node_function=export_fact_orders).payload\n" - " output = Path(__file__).parents[2].joinpath('notify.txt')\n" + " '''Test task notify_fact_orders.'''\n payload = " + "ctx.result_of(node_function=export_fact_orders).payload\n" + " output = Path(__file__).parents[4].joinpath('notify.txt')\n" " output.write_text(str(payload['order_id']))\n" " return ctx.result(metadata={'notified': True})\n" ), @@ -2049,7 +2129,7 @@ def test_given_source_task_loader_chain_when_running_run_then_command_rejects_bo "[connection]\n" 'database = "python_source_task_loader_boundary_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -2057,15 +2137,15 @@ def test_given_source_task_loader_chain_when_running_run_then_command_rejects_bo " - name: order_id\n" " type: INTEGER\n" ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.refs import source\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=source('raw_orders'))\n" "def prepare_orders(ctx):\n" " '''Test task prepare_orders.'''\n return ctx.result()\n" ), - "python/loaders/orders.py": ( - "from python.tasks.orders import prepare_orders\n" + "python/nodes/loaders/orders/loader.py": ( + "from python.nodes.tasks.orders.asset import prepare_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(\n" " destination='stage_orders',\n" @@ -2125,7 +2205,7 @@ def test_given_model_task_loader_chain_when_running_run_then_command_rejects_bou "[connection]\n" 'database = "python_model_task_loader_boundary_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -2133,18 +2213,19 @@ def test_given_model_task_loader_chain_when_running_run_then_command_rejects_bou " - name: order_id\n" " type: INTEGER\n" ), - "models/stg_orders.sql": ( - 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/stg_orders.sql": ( + 'MODEL (description "Test model stg_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('stg_orders'))\n" "def prepare_orders(ctx):\n" " '''Test task prepare_orders.'''\n return ctx.result()\n" ), - "python/loaders/orders.py": ( - "from python.tasks.orders import prepare_orders\n" + "python/nodes/loaders/orders/loader.py": ( + "from python.nodes.tasks.orders.asset import prepare_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(\n" " destination='stage_orders',\n" @@ -2230,27 +2311,27 @@ def test_given_check_selector_when_running_build_then_check_needs_its_checked_no "[connection]\n" 'database = "python_check_run_project.duckdb"\n' ), - "python/checks/orders.py": ( - "from python.tasks.orders import prepare_orders\n" + "python/nodes/checks/orders/checks.py": ( + "from python.nodes.tasks.orders.asset import prepare_orders\n" "from sqlbuild.checks import check\n\n" "@check(depends_on=prepare_orders)\n" "def check_orders_export(ctx):\n" " '''Test check check_orders_export.'''\n return ctx.pass_()\n" ), - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_orders(ctx):\n" " '''Test task prepare_orders.'''\n return ctx.result()\n" ), - "python/checks/events.py": ( + "python/nodes/checks/events/checks.py": ( "from sqlbuild.checks import check\n" "from sqlbuild.refs import source\n\n" "@check(depends_on=source('raw_events'))\n" "def check_raw_events(ctx):\n" " '''Test check check_raw_events.'''\n return ctx.pass_()\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_events\n description: Test source raw_events.\n" ), }, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/helpers.py index eb609edd8d..b3e1152eac 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/helpers.py @@ -75,7 +75,7 @@ 'SELECT\n id,\n event_date\nFROM __ref("upstream_v")\n' "WHERE\n event_date >= __cursor_start()::DATE\n" ) -_ADJUST_FUNCTION_PATH: str = "functions/sql/udf__adjust_amount.sql" +_ADJUST_FUNCTION_PATH: str = "sql/functions/sql/udf__adjust_amount.sql" def _upstream_view_sql(*, upstream: str) -> str: @@ -90,11 +90,11 @@ def build_event_project(*, tmp_path: Path, extra_files: dict[str, str]) -> Path: files: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "seeds/seeds.yml": _EVENTS_SEED_YML, - "seeds/events.csv": _EVENTS_CSV, - "models/upstream.sql": _UPSTREAM_SQL, - "models/upstream_v.sql": _upstream_view_sql(upstream="upstream"), - "models/downstream_mb.sql": _DOWNSTREAM_MB_SQL, + "sql/seeds/seeds.yml": _EVENTS_SEED_YML, + "sql/seeds/events.csv": _EVENTS_CSV, + "sql/models/upstream.sql": _UPSTREAM_SQL, + "sql/models/upstream_v.sql": _upstream_view_sql(upstream="upstream"), + "sql/models/downstream_mb.sql": _DOWNSTREAM_MB_SQL, **extra_files, } project_dir: Path = prepare_inline_project( @@ -107,7 +107,7 @@ def build_event_project(*, tmp_path: Path, extra_files: dict[str, str]) -> Path: def merge_downstream_files(*, extra_config: str) -> dict[str, str]: """Return a merge model whose SQL reads its interval through cursor intrinsics.""" - return {"models/downstream.sql": _DOWNSTREAM_MERGE_SQL.format(extra_config=extra_config)} + return {"sql/models/downstream.sql": _DOWNSTREAM_MERGE_SQL.format(extra_config=extra_config)} def mark_first_day(*, project_dir: Path, relations: tuple[str, ...]) -> None: @@ -124,7 +124,7 @@ def mark_first_day(*, project_dir: Path, relations: tuple[str, ...]) -> None: def insert_table_between_upstream_and_view(*, project_dir: Path) -> None: """Add a new table between the upstream table and its view.""" - (project_dir / "models/upstream_new.sql").write_text( + (project_dir / "sql/models/upstream_new.sql").write_text( "MODEL (description 'Test model upstream_new.',\n materialized table,\n);\n\n" 'SELECT\n id,\n event_date\nFROM __ref("upstream")\n', encoding="utf-8", @@ -135,8 +135,8 @@ def insert_table_between_upstream_and_view(*, project_dir: Path) -> None: def rename_upstream_with_migrate_from(*, project_dir: Path, extra_sql: str) -> None: """Rename the upstream table by hand, declaring migrate_from, optionally changing its SQL.""" - (project_dir / "models/upstream.sql").unlink() - (project_dir / "models/upstream_renamed.sql").write_text( + (project_dir / "sql/models/upstream.sql").unlink() + (project_dir / "sql/models/upstream_renamed.sql").write_text( _UPSTREAM_SQL.replace( " materialized table,\n", " materialized table,\n migrate_from upstream,\n" ) @@ -154,12 +154,12 @@ def rename_upstream_with_cli(*, project_dir: Path, extra_sql: str) -> None: project_dir=project_dir, ) assert result.returncode == 0, result.stdout + result.stderr - renamed_path: Path = project_dir / "models/upstream_renamed.sql" + renamed_path: Path = project_dir / "sql/models/upstream_renamed.sql" renamed_path.write_text(renamed_path.read_text(encoding="utf-8") + extra_sql, encoding="utf-8") def _write_upstream_view(*, project_dir: Path, upstream: str) -> None: - (project_dir / "models/upstream_v.sql").write_text( + (project_dir / "sql/models/upstream_v.sql").write_text( _upstream_view_sql(upstream=upstream), encoding="utf-8" ) @@ -169,7 +169,7 @@ def build_function_project(*, tmp_path: Path, caller_config: str) -> Path: files: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "seeds/seeds.yml": ( + "sql/seeds/seeds.yml": ( "seeds:\n" "- name: orders\n description: Test seed orders.\n" " columns:\n" @@ -180,14 +180,14 @@ def build_function_project(*, tmp_path: Path, caller_config: str) -> Path: " - name: amount\n" " type: INTEGER\n" ), - "seeds/orders.csv": ( + "sql/seeds/orders.csv": ( "id,ordered_at,amount\n1,2026-09-01,10\n2,2026-09-02,20\n3,2026-09-03,30\n" ), _ADJUST_FUNCTION_PATH: ( "FUNCTION (description 'Test function.'," "\n arguments (amount INTEGER),\n returns INTEGER,\n);\n\namount + 1\n" ), - "models/order_amounts.sql": ( + "sql/models/order_amounts.sql": ( "MODEL (description 'Test model order_amounts.',\n" " materialized incremental,\n" " incremental_strategy merge,\n" @@ -202,7 +202,7 @@ def build_function_project(*, tmp_path: Path, caller_config: str) -> Path: ' __udf("udf__adjust_amount")(amount) AS adjusted_amount\n' 'FROM __seed("orders")\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Test model order_totals.',\n" " materialized incremental,\n" " incremental_strategy merge,\n" @@ -233,7 +233,7 @@ def direct_reference_merge_files() -> dict[str, str]: """Return a protected full-replay merge model that reads the upstream table directly.""" return { - "models/down_merge.sql": ( + "sql/models/down_merge.sql": ( "MODEL (description 'Test model down_merge.',\n" " materialized incremental,\n" " incremental_strategy merge,\n" @@ -253,7 +253,7 @@ def direct_reference_merge_files() -> dict[str, str]: def edit_direct_reference_merge(*, project_dir: Path) -> None: """Make a real query edit to the direct-reference merge model.""" - path: Path = project_dir / "models/down_merge.sql" + path: Path = project_dir / "sql/models/down_merge.sql" path.write_text( path.read_text(encoding="utf-8").replace( " event_date\nFROM", " event_date,\n id * 2 AS doubled_id\nFROM" @@ -270,11 +270,11 @@ def build_star_project(*, tmp_path: Path, downstream_config: str) -> Path: project_name="star_projection", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/up.sql": ( + "sql/models/up.sql": ( "MODEL (description 'Test model up.',\n materialized table,\n);\n\n" "SELECT 1 AS id, DATE '2026-09-01' AS event_date\n" ), - "models/down.sql": ( + "sql/models/down.sql": ( "MODEL (description 'Test model down.',\n" " materialized incremental,\n" " incremental_strategy append,\n" @@ -292,7 +292,7 @@ def build_star_project(*, tmp_path: Path, downstream_config: str) -> Path: def add_upstream_column(*, project_dir: Path) -> None: """Add a column to the star project's upstream table.""" - path: Path = project_dir / "models/up.sql" + path: Path = project_dir / "sql/models/up.sql" path.write_text( path.read_text(encoding="utf-8").replace( "AS event_date", "AS event_date, 'web' AS channel" @@ -309,7 +309,7 @@ def add_upstream_column(*, project_dir: Path) -> None: def declare_downstream_column_type(*, project_dir: Path) -> None: """Change the declared type of the star downstream's id column in its own contract.""" - path: Path = project_dir / "models/down.sql" + path: Path = project_dir / "sql/models/down.sql" path.write_text( path.read_text(encoding="utf-8").replace("id (type INTEGER)", "id (type BIGINT)"), encoding="utf-8", @@ -319,7 +319,7 @@ def declare_downstream_column_type(*, project_dir: Path) -> None: def remove_downstream_declared_column(*, project_dir: Path) -> None: """Remove event_date from the star downstream's own contract and select list.""" - path: Path = project_dir / "models/down.sql" + path: Path = project_dir / "sql/models/down.sql" path.write_text( path.read_text(encoding="utf-8") .replace(" event_date (type DATE),\n", "") @@ -332,11 +332,11 @@ def udf_reference_merge_files() -> dict[str, str]: """Return a protected full-replay merge model that reads the upstream through a UDF.""" return { - "functions/sql/udf__plus_one.sql": ( + "sql/functions/sql/udf__plus_one.sql": ( "FUNCTION (description 'Test function udf__plus_one.'," "\n arguments (value INTEGER),\n returns INTEGER,\n);\n\nvalue + 1\n" ), - "models/down_merge.sql": ( + "sql/models/down_merge.sql": ( "MODEL (description 'Test model down_merge.',\n" " materialized incremental,\n" " incremental_strategy merge,\n" @@ -360,7 +360,7 @@ def incremental_upstream_files() -> dict[str, str]: """Return an incremental upstream so a rename moves its data instead of renaming it.""" return { - "models/upstream.sql": ( + "sql/models/upstream.sql": ( "MODEL (description 'Test model upstream.',\n" " materialized incremental,\n" " incremental_strategy merge,\n" @@ -388,7 +388,7 @@ def build_selected(*, project_dir: Path, selector: str) -> None: def remove_migrate_from(*, project_dir: Path) -> None: """Drop the migrate_from declaration from the renamed upstream model.""" - path: Path = project_dir / "models/upstream_renamed.sql" + path: Path = project_dir / "sql/models/upstream_renamed.sql" path.write_text( path.read_text(encoding="utf-8").replace(" migrate_from upstream,\n", ""), encoding="utf-8", @@ -398,7 +398,7 @@ def remove_migrate_from(*, project_dir: Path) -> None: def drop_upstream_column(*, project_dir: Path) -> None: """Drop the event_date column from the star project's upstream table.""" - (project_dir / "models/up.sql").write_text( + (project_dir / "sql/models/up.sql").write_text( "MODEL (description 'Test model up.',\n materialized table,\n);\n\nSELECT 1 AS id\n", encoding="utf-8", ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_append_cursor_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_append_cursor_build.py index e9cd889830..ba68dc4436 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_append_cursor_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_append_cursor_build.py @@ -29,8 +29,8 @@ """ ).strip() + "\n", - "seeds/raw_orders.csv": "id,ordered_at\n1,2026-01-01 00:00:00\n2,2026-01-01 01:00:00\n", - "seeds/raw_orders.yml": dedent( + "sql/seeds/raw_orders.csv": "id,ordered_at\n1,2026-01-01 00:00:00\n2,2026-01-01 01:00:00\n", + "sql/seeds/raw_orders.yml": dedent( """ seeds: - name: raw_orders @@ -43,7 +43,7 @@ """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Orders by timestamp cursor.", materialized incremental, @@ -58,7 +58,7 @@ """ ).strip() + "\n", - "models/order_ids.sql": dedent( + "sql/models/order_ids.sql": dedent( """ MODEL (description "Orders by integer cursor.", materialized incremental, @@ -105,7 +105,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -115,7 +115,7 @@ """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -202,7 +202,7 @@ def test_given_append_cursor_project_when_rerunning_build_then_boundary_behavior second_result.stdout + second_result.stderr ) - runtime_sql: str = (project_dir / "target" / "run" / "models" / "orders.sql").read_text( + runtime_sql: str = (project_dir / "target" / "run" / "sql" / "models" / "orders.sql").read_text( encoding="utf-8" ) assert test_case.expected_runtime_sql_fragment in runtime_sql @@ -233,7 +233,7 @@ def test_given_append_cursor_project_when_rerunning_build_then_boundary_behavior """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -243,7 +243,7 @@ def test_given_append_cursor_project_when_rerunning_build_then_boundary_behavior """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -308,7 +308,7 @@ def test_given_append_cursor_project_when_rerunning_build_then_boundary_behavior """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -318,7 +318,7 @@ def test_given_append_cursor_project_when_rerunning_build_then_boundary_behavior """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -390,7 +390,7 @@ def test_given_timestamp_cursor_start_override_when_building_then_lower_bound_is result: object = run_sqb(command=test_case.command, project_dir=project_dir) assert result.returncode == test_case.expected_exit_code, result.stdout + result.stderr - runtime_sql: str = (project_dir / "target" / "run" / "models" / "orders.sql").read_text( + runtime_sql: str = (project_dir / "target" / "run" / "sql" / "models" / "orders.sql").read_text( encoding="utf-8" ) assert test_case.expected_runtime_sql_fragment in runtime_sql diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_audit_factory_failures.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_audit_factory_failures.py index 259e54c649..3be35ac8fa 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_audit_factory_failures.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_audit_factory_failures.py @@ -40,15 +40,15 @@ def test_given_failing_factory_audit_when_building_then_existing_table_is_untouc [defaults] materialized = "table" """, - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", audit_factories [order_quality]); SELECT 2 AS id, -10 AS amount """, - "audits/generic/expression_is_true.sql": """ + "sql/audits/generic/expression_is_true.sql": """ AUDIT (); SELECT * FROM __ref("@model") WHERE NOT (@expression) """, - "python/factories/quality.py": """ + "python/nodes/factories/quality.py": """ from sqlbuild.audits import AuditCase, AuditSeverity, audit_factory @audit_factory diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_audit_failures.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_audit_failures.py index 30e4ba2ce0..72eacd15dd 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_audit_failures.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_audit_failures.py @@ -13,7 +13,10 @@ MeasurementAuditCliE2ETestCase, StandaloneAuditRowE2ETestCase, ) -from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import seed_audit_files +from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import ( + seed_audit_files, + take_raw_data_sql, +) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( prepare_inline_project, run_sqb, @@ -61,7 +64,7 @@ """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -81,7 +84,7 @@ """ ).strip() + "\n", - "audits/generic/expression_is_true.sql": dedent( + "sql/audits/generic/expression_is_true.sql": dedent( """ AUDIT (); @@ -135,7 +138,7 @@ """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -155,7 +158,7 @@ """ ).strip() + "\n", - "audits/generic/expression_is_true.sql": dedent( + "sql/audits/generic/expression_is_true.sql": dedent( """ AUDIT (); @@ -188,7 +191,7 @@ def test_given_audit_failure_projects_when_running_build_then_cli_reports_failur import duckdb connection: duckdb.DuckDBPyConnection = duckdb.connect(str(db_path)) - connection.execute((project_dir / "seed_raw_data.sql").read_text(encoding="utf-8")) + connection.execute(take_raw_data_sql(project_dir)) connection.close() result: subprocess.CompletedProcess[str] = run_sqb( @@ -211,11 +214,11 @@ def test_given_audit_failure_projects_when_running_build_then_cli_reports_failur 'name = "measurement_build"\nadapter = "duckdb"\n' '[connection]\ndatabase = "measurement.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table, audits [row_rate (" "thresholds (error (below 90)))]) ; SELECT 1 AS order_id" ), - "audits/generic/row_rate.sql": ( + "sql/audits/generic/row_rate.sql": ( "AUDIT (evaluation measurement, value rate); " "MEASURE (SELECT 80.0 AS rate FROM @relation LIMIT 1);" ), @@ -231,13 +234,13 @@ def test_given_audit_failure_projects_when_running_build_then_cli_reports_failur 'name = "measurement_audit"\nadapter = "duckdb"\n' '[connection]\ndatabase = "measurement.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table); SELECT 1 AS order_id" ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Test model customers.', materialized table); SELECT 1 AS order_id" ), - "audits/singular/rate.sql": ( + "sql/audits/singular/rate.sql": ( "AUDIT (evaluation measurement, value rate, " "thresholds (error (below 90))); " 'MEASURE (SELECT 80.0 AS rate FROM __ref("orders") ' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_build.py index b1dc964223..8760d47e54 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_build.py @@ -38,18 +38,19 @@ run_sqb, table_exists, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _TARGET_CONFIG_RECORDER: str = ( "import dataclasses, json\n" "from pathlib import Path\n\n" "def record(ctx, node):\n" " line = {'node': node, **dataclasses.asdict(ctx.target_config)}\n" - " with Path(__file__).parents[1].joinpath('target_config.jsonl').open('a') as out:\n" + " with Path(__file__).parents[2].joinpath('target_config.jsonl').open('a') as out:\n" " out.write(json.dumps(line) + '\\n')\n" ) _TARGET_PROBE_SINK: str = ( - "from providers.target_probe import TargetProbe\n" - "from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink\n\n" + "from python.providers.target_probe import TargetProbe\n" + "from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink\n\n" "@lifecycle_event_sink\n" "def probe_events(event: LifecycleEvent, target_probe: TargetProbe) -> None:\n" " del event, target_probe\n" @@ -63,10 +64,12 @@ description="selected downstream clones missing upstream boundary from prod", project_name="defer_clone_build", initial_upstream_sql=( - "MODEL (description 'Test model.', materialized table);\n\nSELECT 1 AS id, 'prod_version' AS label\n" + "MODEL (description 'Test model.', materialized table);\n\nSELECT 1 AS " + "id, 'prod_version' AS label\n" ), changed_upstream_sql=( - "MODEL (description 'Test model.', materialized table);\n\nSELECT 1 AS id, 'dev_version' AS label\n" + "MODEL (description 'Test model.', materialized table);\n\nSELECT 1 AS " + "id, 'dev_version' AS label\n" ), downstream_sql=( "MODEL (description 'Test model.', materialized table);\n\n" @@ -151,9 +154,9 @@ def test_given_changed_unselected_upstream_when_building_leaf_then_warns_and_noo "[connection]\n" f'database = "{test_case.project_name}.duckdb"\n' ), - "models/a.sql": "MODEL (description 'Test model a.', materialized table);\n\nselect 1 as id\n", - "models/b.sql": "MODEL (description 'Test model b.', materialized table);\n\nselect 1 as id\n", - "models/c.sql": ( + "sql/models/a.sql": "MODEL (description 'Test model a.', materialized table);\n\nselect 1 as id\n", + "sql/models/b.sql": "MODEL (description 'Test model b.', materialized table);\n\nselect 1 as id\n", + "sql/models/c.sql": ( "MODEL (description 'Test model c.', materialized table);\n\n" 'select id from __ref("a") union all select id from __ref("b")\n' ), @@ -164,11 +167,11 @@ def test_given_changed_unselected_upstream_when_building_leaf_then_warns_and_noo command=test_case.initial_command, project_dir=project_dir, ) - (project_dir / "models" / "a.sql").write_text( + (project_dir / "sql" / "models" / "a.sql").write_text( "MODEL (description 'Test model a.', materialized table);\n\nselect 10 as id\n", encoding="utf-8", ) - (project_dir / "models" / "b.sql").write_text( + (project_dir / "sql" / "models" / "b.sql").write_text( "MODEL (description 'Test model b.', materialized table);\n\nselect 2 as id\n", encoding="utf-8", ) @@ -226,11 +229,13 @@ def test_given_direct_function_dependency_when_building_then_persists_function_h "[connection]\n" 'database = "warehouse.duckdb"\n' ), - "functions/sql/is_large_order.sql": ( - "FUNCTION (description 'Test function is_large_order.', arguments (amount INTEGER), returns BOOLEAN);\n\namount > 100\n" + "sql/functions/sql/is_large_order.sql": ( + "FUNCTION (description 'Test function is_large_order.', arguments " + "(amount INTEGER), returns BOOLEAN);\n\namount > 100\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT __udf("is_large_order")(150) AS is_large\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT __udf("is_large_order")(150) AS is_large\n' ), }, ) @@ -286,7 +291,7 @@ def test_given_source_freshness_changes_during_build_when_appending_then_persist "[connection]\n" 'database = "warehouse.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -295,8 +300,9 @@ def test_given_source_freshness_changes_during_build_when_appending_then_persist " type: integer\n" " query: SELECT data_version FROM freshness_control\n" ), - "models/orders.sql": ( - 'MODEL (description "Test model orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/orders.sql": ( + 'MODEL (description "Test model orders.", materialized table);\n\nSELECT ' + '* FROM __source("raw_orders")\n' ), }, ) @@ -315,7 +321,7 @@ def test_given_source_freshness_changes_during_build_when_appending_then_persist db_path=project_dir / "warehouse.duckdb", sql="UPDATE freshness_control SET data_version = 1", ) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( ( "MODEL (description 'Test model orders.', materialized table, " 'post_hooks [inline_sql("UPDATE freshness_control SET data_version = 2")]);\n\n' @@ -376,7 +382,7 @@ def test_given_independent_source_branch_failure_when_building_then_appends_succ "[connection]\n" 'database = "warehouse.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -391,11 +397,13 @@ def test_given_independent_source_branch_failure_when_building_then_appends_succ " type: integer\n" " query: SELECT 1 AS data_version\n" ), - "models/orders.sql": ( - 'MODEL (description "Test model orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/orders.sql": ( + 'MODEL (description "Test model orders.", materialized table);\n\nSELECT ' + '* FROM __source("raw_orders")\n' ), - "models/payments.sql": ( - 'MODEL (description "Test model payments.", materialized table);\n\nSELECT * FROM __source("raw_payments")\n' + "sql/models/payments.sql": ( + 'MODEL (description "Test model payments.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_payments")\n' ), }, ) @@ -413,7 +421,7 @@ def test_given_independent_source_branch_failure_when_building_then_appends_succ assert first_changes_only_result.returncode == 0, ( first_changes_only_result.stdout + first_changes_only_result.stderr ) - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources" / "raw.yml").write_text( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -429,8 +437,9 @@ def test_given_independent_source_branch_failure_when_building_then_appends_succ " query: SELECT 2 AS data_version\n", encoding="utf-8", ) - (project_dir / "models" / "payments.sql").write_text( - "MODEL (description 'Test model payments.', materialized table);\n\nSELECT CAST('bad' AS INTEGER) AS payment_id\n", + (project_dir / "sql" / "models" / "payments.sql").write_text( + "MODEL (description 'Test model payments.', materialized table);\n\nSELECT " + "CAST('bad' AS INTEGER) AS payment_id\n", encoding="utf-8", ) execution_json_path: Path = project_dir / "target" / "failed-build.json" @@ -498,20 +507,23 @@ def test_given_source_freshness_error_when_building_then_blocks_only_affected_br "[connection]\n" 'database = "warehouse.duckdb"\n' ), - "sources/raw.yml": build_freshness_error_branch_source_yml( + "sql/sources/raw.yml": build_freshness_error_branch_source_yml( order_id=1, customer_id=1, order_freshness_query="SELECT CURRENT_TIMESTAMP AS data_version", customer_freshness_query="SELECT CURRENT_TIMESTAMP AS data_version", ), - "models/stg_orders.sql": ( - 'MODEL (description "Test model stg_orders.", materialized view);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/stg_orders.sql": ( + 'MODEL (description "Test model stg_orders.", materialized ' + 'view);\n\nSELECT * FROM __source("raw_orders")\n' ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __ref("stg_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __ref("stg_orders")\n' ), - "models/dim_customers.sql": ( - 'MODEL (description "Test model dim_customers.", materialized table);\n\nSELECT * FROM __source("raw_customers")\n' + "sql/models/dim_customers.sql": ( + 'MODEL (description "Test model dim_customers.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_customers")\n' ), }, ) @@ -522,7 +534,7 @@ def test_given_source_freshness_error_when_building_then_blocks_only_affected_br assert initial_build_result.returncode == 0, ( initial_build_result.stdout + initial_build_result.stderr ) - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources" / "raw.yml").write_text( build_freshness_error_branch_source_yml( order_id=2, customer_id=2, @@ -583,7 +595,7 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "warehouse.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -598,7 +610,7 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap " type: integer\n" " query: SELECT 1 AS data_version\n" ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.', materialized table);\n\n" 'SELECT o.order_id, p.payment_id FROM __source("raw_orders") o ' 'JOIN __source("raw_payments") p USING (order_id)\n' @@ -619,7 +631,7 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap assert first_changes_only_result.returncode == 0, ( first_changes_only_result.stdout + first_changes_only_result.stderr ) - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources" / "raw.yml").write_text( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -635,8 +647,9 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap " query: SELECT 2 AS data_version\n", encoding="utf-8", ) - (project_dir / "models" / "fact_orders.sql").write_text( - "MODEL (description 'Test model fact_orders.', materialized table);\n\nSELECT CAST('bad' AS INTEGER) AS order_id\n", + (project_dir / "sql" / "models" / "fact_orders.sql").write_text( + "MODEL (description 'Test model fact_orders.', materialized table);\n\nSELECT " + "CAST('bad' AS INTEGER) AS order_id\n", encoding="utf-8", ) @@ -675,20 +688,22 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "python_build_ingress_failure_project.duckdb"\n' ), - "python/tasks/prepare.py": ( + "python/nodes/tasks/prepare/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_orders(ctx):\n" - " '''Test task prepare_orders.'''\n raise RuntimeError('prepare failed')\n" + " '''Test task prepare_orders.'''\n raise " + "RuntimeError('prepare failed')\n" ), - "python/loaders/raw.py": ( - "from python.tasks.prepare import prepare_orders\n" + "python/nodes/loaders/raw/loader.py": ( + "from python.nodes.tasks.prepare.asset import prepare_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(prepare_orders,))\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 1}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -697,8 +712,9 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), }, expected_exit_code=1, @@ -721,21 +737,23 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "python_build_ingress_skip_project.duckdb"\n' ), - "python/tasks/prepare.py": ( + "python/nodes/tasks/prepare/asset.py": ( "from sqlbuild.compiler.python_nodes.types import SkipMode\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_orders(ctx):\n" - " '''Test task prepare_orders.'''\n return ctx.skip(reason='no input', mode=SkipMode.HARD)\n" + " '''Test task prepare_orders.'''\n return " + "ctx.skip(reason='no input', mode=SkipMode.HARD)\n" ), - "python/loaders/raw.py": ( - "from python.tasks.prepare import prepare_orders\n" + "python/nodes/loaders/raw/loader.py": ( + "from python.nodes.tasks.prepare.asset import prepare_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(prepare_orders,))\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 1}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -744,8 +762,9 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), }, expected_exit_code=0, @@ -768,11 +787,12 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "python_build_non_json_result_project.duckdb"\n' ), - "python/tasks/bad.py": ( + "python/nodes/tasks/bad/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_bad_result(ctx):\n" - " '''Test task produce_bad_result.'''\n return ctx.result(payload={'bad': {'a', 'b'}})\n" + " '''Test task produce_bad_result.'''\n return " + "ctx.result(payload={'bad': {'a', 'b'}})\n" ), }, expected_exit_code=1, @@ -792,11 +812,12 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "python_build_non_json_metadata_project.duckdb"\n' ), - "python/tasks/bad.py": ( + "python/nodes/tasks/bad/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_bad_metadata(ctx):\n" - " '''Test task produce_bad_metadata.'''\n return ctx.result(payload={}, metadata={'bad': {'a', 'b'}})\n" + " '''Test task produce_bad_metadata.'''\n return " + "ctx.result(payload={}, metadata={'bad': {'a', 'b'}})\n" ), }, expected_exit_code=1, @@ -816,7 +837,7 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "python_build_read_side_failure_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -824,15 +845,17 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('fact_orders'))\n" "def fail_after_fact(ctx):\n" - " '''Test task fail_after_fact.'''\n raise RuntimeError('profile failed')\n" + " '''Test task fail_after_fact.'''\n raise " + "RuntimeError('profile failed')\n" ), }, expected_exit_code=1, @@ -855,7 +878,7 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "python_build_read_side_hard_skip_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -863,16 +886,18 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from sqlbuild.compiler.python_nodes.types import SkipMode\n" "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('fact_orders'))\n" "def skip_after_fact(ctx):\n" - " '''Test task skip_after_fact.'''\n return ctx.skip(reason='no profile needed', mode=SkipMode.HARD)\n" + " '''Test task skip_after_fact.'''\n return " + "ctx.skip(reason='no profile needed', mode=SkipMode.HARD)\n" ), }, expected_exit_code=0, @@ -895,7 +920,7 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "python_build_read_side_soft_skip_project.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" @@ -903,16 +928,18 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from sqlbuild.compiler.python_nodes.types import SkipMode\n" "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('fact_orders'))\n" "def soft_skip_after_fact(ctx):\n" - " '''Test task soft_skip_after_fact.'''\n return ctx.skip(reason='optional profile skipped', mode=SkipMode.SOFT)\n" + " '''Test task soft_skip_after_fact.'''\n return " + "ctx.skip(reason='optional profile skipped', mode=SkipMode.SOFT)\n" ), }, expected_exit_code=0, @@ -935,23 +962,25 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "python_build_no_python_project.duckdb"\n' ), - "python/tasks/prepare.py": ( + "python/nodes/tasks/prepare/asset.py": ( "from pathlib import Path\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_orders(ctx):\n" - " '''Test task prepare_orders.'''\n marker = Path(__file__).parents[2].joinpath('prepared.txt')\n" + " '''Test task prepare_orders.'''\n marker = " + "Path(__file__).parents[4].joinpath('prepared.txt')\n" " marker.write_text('prepared')\n" " return ctx.result(payload={'order_id': 3})\n" ), - "python/loaders/raw.py": ( - "from python.tasks.prepare import prepare_orders\n" + "python/nodes/loaders/raw/loader.py": ( + "from python.nodes.tasks.prepare.asset import prepare_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(prepare_orders,))\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 3}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -960,16 +989,18 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from pathlib import Path\n" "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('fact_orders'))\n" "def profile_fact(ctx):\n" - " '''Test task profile_fact.'''\n marker = Path(__file__).parents[2].joinpath('profile.txt')\n" + " '''Test task profile_fact.'''\n marker = " + "Path(__file__).parents[4].joinpath('profile.txt')\n" " marker.write_text('profiled')\n" " return ctx.result()\n" ), @@ -994,13 +1025,14 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap "[connection]\n" 'database = "python_build_source_relation_project.duckdb"\n' ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 5}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -1009,15 +1041,16 @@ def test_given_shared_downstream_failure_when_building_then_blocks_all_source_ap " - name: order_id\n" " type: INTEGER\n" ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from pathlib import Path\n" "from sqlbuild.refs import source\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=source('raw_orders'))\n" "def profile_raw_orders(ctx):\n" - " '''Test task profile_raw_orders.'''\n relation = ctx.relation(source('raw_orders'))\n" + " '''Test task profile_raw_orders.'''\n relation = " + "ctx.relation(source('raw_orders'))\n" " value = ctx.query(f'SELECT order_id FROM {relation}').fetchall()[0][0]\n" - " marker = Path(__file__).parents[2].joinpath('source_profile.txt')\n" + " marker = Path(__file__).parents[4].joinpath('source_profile.txt')\n" " marker.write_text(str(value))\n" " return ctx.result(metadata={'source_order_id': value})\n" ), @@ -1082,20 +1115,34 @@ def test_given_python_lifecycle_edge_case_when_building_then_direct_build_harden "[connection]\n" 'database = "direct_build_missing_intermediate_project.duckdb"\n' ), - "python/loaders/raw.py": ( - "from sqlbuild.loaders import loader\n\n" + "python/nodes/loaders/raw/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" "@loader(write_strategy='table', columns=[\n" " {'name': 'event_id', 'type': 'INTEGER'},\n" "])\n" "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}]\n\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/raw/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw.fetch_events.loader import fetch_events\n" + "\n" + "\n" "@loader(depends_on=[fetch_events])\n" "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS " - "SELECT event_id FROM {events.destination}')\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} " + "AS SELECT event_id FROM {events.destination}')\n" + ), + "python/nodes/loaders/raw/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" ), - "sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", + "sql/sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", }, expected_exit_code=1, expected_output_fragments=("requires intermediate loader 'fetch_events'",), @@ -1111,23 +1158,25 @@ def test_given_python_lifecycle_edge_case_when_building_then_direct_build_harden "[connection]\n" 'database = "direct_build_no_python_source_only_project.duckdb"\n' ), - "python/tasks/prepare.py": ( + "python/nodes/tasks/prepare/asset.py": ( "from pathlib import Path\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_events(ctx):\n" - " '''Test task prepare_events.'''\n marker = Path(__file__).parents[2].joinpath('prepared.txt')\n" + " '''Test task prepare_events.'''\n marker = " + "Path(__file__).parents[4].joinpath('prepared.txt')\n" " marker.write_text('prepared')\n" " return ctx.result()\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from sqlbuild.loaders import loader\n" - "from python.tasks.prepare import prepare_events\n\n" + "from python.nodes.tasks.prepare.asset import prepare_events\n\n" "@loader(depends_on=[prepare_events])\n" "def raw_events(ctx):\n" " '''Test loader raw_events.'''\n return [{'event_id': 1}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_events\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_events\n description: Test source raw_events.\n" " managed: true\n" @@ -1188,20 +1237,34 @@ def test_given_direct_source_only_build_when_loader_has_ingress_then_enforces_so "[connection]\n" 'database = "direct_build_existing_intermediate_project.duckdb"\n' ), - "python/loaders/raw.py": ( - "from sqlbuild.loaders import loader\n\n" + "python/nodes/loaders/raw/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" "@loader(write_strategy='table', columns=[\n" " {'name': 'event_id', 'type': 'INTEGER'},\n" "])\n" "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}]\n\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/raw/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw.fetch_events.loader import fetch_events\n" + "\n" + "\n" "@loader(depends_on=[fetch_events])\n" "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS " - "SELECT event_id FROM {events.destination}')\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} " + "AS SELECT event_id FROM {events.destination}')\n" ), - "sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", + "python/nodes/loaders/raw/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + "sql/sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", }, expected_exit_code=0, expected_output_fragments=("source raw_events",), @@ -1255,11 +1318,12 @@ def test_given_existing_intermediate_target_when_building_source_only_then_reuse "[connection]\n" 'database = "python_build_json_project.duckdb"\n' ), - "python/assets/orders.py": ( + "python/nodes/assets/orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def observed_orders(ctx):\n" - " '''Test asset observed_orders.'''\n return ctx.result(metadata={'uri': 's3://orders'}, materialized=False)\n" + " '''Test asset observed_orders.'''\n return " + "ctx.result(metadata={'uri': 's3://orders'}, materialized=False)\n" ), }, expected_exit_code=0, @@ -1360,7 +1424,7 @@ def test_given_python_sql_python_spine_when_building_then_orders_python_around_s "[connection]\n" 'database = "python_sql_python_spine_build_project.duckdb"\n' ), - "python/loaders/window.py": ( + "python/nodes/loaders/window/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader(\n" " destination='window_orders',\n" @@ -1370,35 +1434,39 @@ def test_given_python_sql_python_spine_when_building_then_orders_python_around_s "def load_window_orders(ctx):\n" " '''Test loader load_window_orders.'''\n return [{'order_id': 7}]\n" ), - "python/tasks/prepare.py": ( - "from python.loaders.window import load_window_orders\n" + "python/nodes/tasks/prepare/asset.py": ( + "from python.nodes.loaders.window.loader import load_window_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=load_window_orders)\n" "def prepare_orders(ctx):\n" - " '''Test task prepare_orders.'''\n rows = ctx.query('SELECT order_id FROM window_orders').fetchall()\n" + " '''Test task prepare_orders.'''\n rows = ctx.query('SELECT " + "order_id FROM window_orders').fetchall()\n" " return ctx.result(payload={'order_id': rows[0][0]})\n" ), - "python/assets/prepare.py": ( + "python/nodes/assets/prepare/asset.py": ( "from pathlib import Path\n" - "from python.tasks.prepare import prepare_orders\n" + "from python.nodes.tasks.prepare.asset import prepare_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=prepare_orders)\n" "def publish_prepared_orders(ctx):\n" - " '''Test asset publish_prepared_orders.'''\n payload = ctx.result_of(node_function=prepare_orders).payload\n" - " marker = Path(__file__).parents[2].joinpath('prepared_order_id.txt')\n" + " '''Test asset publish_prepared_orders.'''\n payload = " + "ctx.result_of(node_function=prepare_orders).payload\n" + " marker = Path(__file__).parents[4].joinpath('prepared_order_id.txt')\n" " marker.write_text(str(payload['order_id']))\n" " return ctx.result(payload=payload, materialized=True)\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from pathlib import Path\n" - "from python.assets.prepare import publish_prepared_orders\n" + "from python.nodes.assets.prepare.asset import publish_prepared_orders\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(publish_prepared_orders,))\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n marker = Path(__file__).parents[2].joinpath('prepared_order_id.txt')\n" + " '''Test loader raw_orders.'''\n marker = " + "Path(__file__).parents[4].joinpath('prepared_order_id.txt')\n" " return [{'order_id': int(marker.read_text())}]\n" ), - "sources/raw.yml": ( + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -1407,34 +1475,38 @@ def test_given_python_sql_python_spine_when_building_then_orders_python_around_s " - name: order_id\n" " type: INTEGER\n" ), - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT * FROM __source("raw_orders")\n' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "python/tasks/profile.py": ( + "python/nodes/tasks/profile/asset.py": ( "from sqlbuild.refs import model\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=model('fact_orders'))\n" "def profile_fact_orders(ctx):\n" - " '''Test task profile_fact_orders.'''\n relation = ctx.relation(model('fact_orders'))\n" + " '''Test task profile_fact_orders.'''\n relation = " + "ctx.relation(model('fact_orders'))\n" " order_id = ctx.query(f'SELECT order_id FROM {relation}').fetchall()[0][0]\n" " return ctx.result(payload={'order_id': order_id}, metadata={'rows': 1})\n" ), - "python/assets/export.py": ( - "from python.tasks.profile import profile_fact_orders\n" + "python/nodes/assets/export/asset.py": ( + "from python.nodes.tasks.profile.asset import profile_fact_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=profile_fact_orders)\n" "def export_fact_orders(ctx):\n" - " '''Test asset export_fact_orders.'''\n payload = ctx.result_of(node_function=profile_fact_orders).payload\n" + " '''Test asset export_fact_orders.'''\n payload = " + "ctx.result_of(node_function=profile_fact_orders).payload\n" " return ctx.result(payload=payload, metadata={'exported': True})\n" ), - "python/tasks/notify.py": ( + "python/nodes/tasks/notify/asset.py": ( "from pathlib import Path\n" - "from python.assets.export import export_fact_orders\n" + "from python.nodes.assets.export.asset import export_fact_orders\n" "from sqlbuild.assets import asset\n\n" "@asset(depends_on=export_fact_orders)\n" "def notify_fact_orders(ctx):\n" - " '''Test task notify_fact_orders.'''\n payload = ctx.result_of(node_function=export_fact_orders).payload\n" - " output = Path(__file__).parents[2].joinpath('notify.txt')\n" + " '''Test task notify_fact_orders.'''\n payload = " + "ctx.result_of(node_function=export_fact_orders).payload\n" + " output = Path(__file__).parents[4].joinpath('notify.txt')\n" " output.write_text(str(payload['order_id']))\n" " return ctx.result(metadata={'notified': True})\n" ), @@ -1511,16 +1583,18 @@ def test_given_prior_python_task_result_when_later_task_reads_result_then_uses_p project_name="python_persisted_result_project", repo_files={ "sqlbuild_project.toml": ( + 'extra_paths = ["consumed.txt"]\n' 'name = "python_persisted_result_project"\n' 'adapter = "duckdb"\n\n' "[connection]\n" 'database = "python_persisted_result_project.duckdb"\n' ), - "python/tasks/produce.py": ( + "python/nodes/tasks/produce/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_result(ctx):\n" - " '''Test task produce_result.'''\n return ctx.result(payload={'value': 42}, metadata={'source': 'first'})\n" + " '''Test task produce_result.'''\n return " + "ctx.result(payload={'value': 42}, metadata={'source': 'first'})\n" ), }, ) @@ -1534,12 +1608,13 @@ def test_given_prior_python_task_result_when_later_task_reads_result_then_uses_p sql="SELECT run_id FROM _sqlbuild_node_results WHERE node_name = 'produce_result'", ) first_run_id: str = str(first_run_rows[0][0]) - (project_dir / "python" / "tasks" / "produce.py").write_text( + (project_dir / "python" / "nodes" / "tasks" / "produce" / "asset.py").write_text( ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_result(ctx):\n" - " '''Test task produce_result.'''\n return ctx.result(payload={'value': 84}, metadata={'source': 'second'})\n" + " '''Test task produce_result.'''\n return " + "ctx.result(payload={'value': 84}, metadata={'source': 'second'})\n" ), encoding="utf-8", ) @@ -1547,12 +1622,13 @@ def test_given_prior_python_task_result_when_later_task_reads_result_then_uses_p command=("--no-color", "build", "--select", "produce_result"), project_dir=project_dir, ) - (project_dir / "python" / "tasks" / "produce.py").write_text( + (project_dir / "python" / "nodes" / "tasks" / "produce" / "asset.py").write_text( ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_result(ctx):\n" - " '''Test task produce_result.'''\n raise RuntimeError('producer failed after previous success')\n" + " '''Test task produce_result.'''\n raise RuntimeError('producer " + "failed after previous success')\n" ), encoding="utf-8", ) @@ -1568,19 +1644,22 @@ def test_given_prior_python_task_result_when_later_task_reads_result_then_uses_p ), ) failed_run_id: str = str(failed_run_rows[0][0]) - (project_dir / "python" / "tasks" / "consume.py").write_text( + consume_dir: Path = project_dir / "python" / "nodes" / "tasks" / "consume" + consume_dir.mkdir(parents=True) + (consume_dir / "asset.py").write_text( ( "from pathlib import Path\n" - "from python.tasks.produce import produce_result\n" + "from python.nodes.tasks.produce.asset import produce_result\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def consume_result(ctx):\n" - " '''Test task consume_result.'''\n latest = ctx.result_of(node_function=produce_result)\n" + " '''Test task consume_result.'''\n latest = " + "ctx.result_of(node_function=produce_result)\n" f" first = ctx.result_of(node_function=produce_result, run_id='{first_run_id}')\n" f" failed = ctx.result_of(node_function=produce_result, run_id='{failed_run_id}')\n" " history = ctx.results_of(node_function=produce_result, limit=2)\n" " values = ','.join(str(item.payload['value']) for item in history)\n" - " output = Path(__file__).parents[2].joinpath('consumed.txt')\n" + " output = Path(__file__).parents[4].joinpath('consumed.txt')\n" " output.write_text(\n" " f\"{latest.payload['value']}:{first.payload['value']}:\"\n" ' f"{failed.status}:{failed.payload is None}:{values}:"\n' @@ -1659,13 +1738,13 @@ def test_given_prior_loader_result_when_later_task_reads_result_then_uses_loader "[connection]\n" 'database = "python_persisted_loader_result_project.duckdb"\n' ), - "python/loaders/events.py": ( + "python/nodes/loaders/events/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_events(ctx):\n" " '''Test loader raw_events.'''\n return [{'event_id': 1}]\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_events\n description: Test source raw_events.\n" " managed: true\n" @@ -1674,17 +1753,19 @@ def test_given_prior_loader_result_when_later_task_reads_result_then_uses_loader " - name: event_id\n" " type: INTEGER\n" ), - "models/fact_events.sql": ( - 'MODEL (description "Test model fact_events.", materialized table);\n\nSELECT * FROM __source("raw_events")\n' + "sql/models/fact_events.sql": ( + 'MODEL (description "Test model fact_events.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_events")\n' ), - "python/tasks/consume.py": ( + "python/nodes/tasks/consume/asset.py": ( "from pathlib import Path\n" - "from python.loaders.events import raw_events\n" + "from python.nodes.loaders.events.loader import raw_events\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def consume_loader_result(ctx):\n" - " '''Test task consume_loader_result.'''\n result = ctx.result_of(node_function=raw_events)\n" - " output = Path(__file__).parents[2].joinpath('loader_result.txt')\n" + " '''Test task consume_loader_result.'''\n result = " + "ctx.result_of(node_function=raw_events)\n" + " output = Path(__file__).parents[4].joinpath('loader_result.txt')\n" " output.write_text(\n" " f\"{result.metadata['loader_name']}:{result.metadata['source_name']}:\"\n" " f\"{result.metadata['rows_loaded']}\"\n" @@ -1728,13 +1809,13 @@ def test_given_prior_loader_result_when_later_task_reads_result_then_uses_loader "[connection]\n" 'database = "python_failed_loader_result_project.duckdb"\n' ), - "python/loaders/events.py": ( + "python/nodes/loaders/events/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_events(ctx):\n" " '''Test loader raw_events.'''\n raise RuntimeError('loader failed')\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_events\n description: Test source raw_events.\n" " managed: true\n" @@ -1743,8 +1824,9 @@ def test_given_prior_loader_result_when_later_task_reads_result_then_uses_loader " - name: event_id\n" " type: INTEGER\n" ), - "models/fact_events.sql": ( - 'MODEL (description "Test model fact_events.", materialized table);\n\nSELECT * FROM __source("raw_events")\n' + "sql/models/fact_events.sql": ( + 'MODEL (description "Test model fact_events.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_events")\n' ), }, command=("--no-color", "build", "--select", "fact_events"), @@ -1761,21 +1843,22 @@ def test_given_prior_loader_result_when_later_task_reads_result_then_uses_loader "[connection]\n" 'database = "python_skipped_loader_result_project.duckdb"\n' ), - "python/tasks/prepare.py": ( + "python/nodes/tasks/prepare/asset.py": ( "from sqlbuild.compiler.python_nodes.types import SkipMode\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_events(ctx):\n" - " '''Test task prepare_events.'''\n return ctx.skip(reason='no input', mode=SkipMode.HARD)\n" + " '''Test task prepare_events.'''\n return " + "ctx.skip(reason='no input', mode=SkipMode.HARD)\n" ), - "python/loaders/events.py": ( - "from python.tasks.prepare import prepare_events\n" + "python/nodes/loaders/events/loader.py": ( + "from python.nodes.tasks.prepare.asset import prepare_events\n" "from sqlbuild.loaders import loader\n\n" "@loader(depends_on=(prepare_events,))\n" "def raw_events(ctx):\n" " '''Test loader raw_events.'''\n return [{'event_id': 1}]\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_events\n description: Test source raw_events.\n" " managed: true\n" @@ -1784,8 +1867,9 @@ def test_given_prior_loader_result_when_later_task_reads_result_then_uses_loader " - name: event_id\n" " type: INTEGER\n" ), - "models/fact_events.sql": ( - 'MODEL (description "Test model fact_events.", materialized table);\n\nSELECT * FROM __source("raw_events")\n' + "sql/models/fact_events.sql": ( + 'MODEL (description "Test model fact_events.", materialized ' + 'table);\n\nSELECT * FROM __source("raw_events")\n' ), }, command=("--no-color", "build", "--select", "+fact_events"), @@ -1855,7 +1939,7 @@ def test_given_loader_status_result_when_building_then_persists_loader_status_ro "database_preserved": False, "schema_preserved": False, }, - extra_files=(("sinks/events.py", _TARGET_PROBE_SINK),), + extra_files=(("python/event_sinks/events.py", _TARGET_PROBE_SINK),), ), PythonTargetConfigBuildE2ETestCase( description="loader_schema falls back to the target schema", @@ -1882,6 +1966,7 @@ def test_given_local_target_override_when_running_python_then_every_context_sees project_name="python_target_config_project", repo_files={ "sqlbuild_project.toml": ( + 'extra_paths = ["target_config.jsonl"]\n' 'name = "python_target_config_project"\n' 'adapter = "duckdb"\n' 'default_target = "dev"\n\n' @@ -1889,18 +1974,18 @@ def test_given_local_target_override_when_running_python_then_every_context_sees 'database = "python_target_config_project.duckdb"\n\n' "[targets.dev]\n" + test_case.project_target_lines ), - "python/recorder.py": _TARGET_CONFIG_RECORDER, - "providers/target_probe.py": ( - "from python.recorder import record\n" + **node_module_files("python/nodes/recorder.py", _TARGET_CONFIG_RECORDER), + "python/providers/target_probe.py": ( + "from python.nodes.recorder import record\n" "from sqlbuild.providers import Provider\n\n" "class TargetProbe(Provider):\n" " '''Test provider TargetProbe.'''\n\n" " def setup(self, ctx):\n" " record(ctx, 'provider')\n" ), - "python/tasks/configured.py": ( - "from providers.target_probe import TargetProbe\n" - "from python.recorder import record\n" + "python/nodes/tasks/configured/asset.py": ( + "from python.providers.target_probe import TargetProbe\n" + "from python.nodes.recorder import record\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def configured_task(ctx, target_probe: TargetProbe):\n" @@ -1908,9 +1993,9 @@ def test_given_local_target_override_when_running_python_then_every_context_sees " record(ctx, 'asset')\n" " return ctx.result()\n" ), - "python/loaders/raw.py": ( - "from providers.target_probe import TargetProbe\n" - "from python.recorder import record\n" + "python/nodes/loaders/raw/loader.py": ( + "from python.providers.target_probe import TargetProbe\n" + "from python.nodes.recorder import record\n" "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx, target_probe: TargetProbe):\n" @@ -1918,10 +2003,11 @@ def test_given_local_target_override_when_running_python_then_every_context_sees " record(ctx, 'loader')\n" " return [{'order_id': 1}]\n" ), - "python/checks/configured.py": ( - "from providers.target_probe import TargetProbe\n" - "from python.recorder import record\n" - "from python.tasks.configured import configured_task\n" + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "python/nodes/checks/configured/checks.py": ( + "from python.providers.target_probe import TargetProbe\n" + "from python.nodes.recorder import record\n" + "from python.nodes.tasks.configured.asset import configured_task\n" "from sqlbuild.checks import check\n\n" "@check(depends_on=configured_task)\n" "def configured_check(ctx, target_probe: TargetProbe):\n" @@ -1929,7 +2015,7 @@ def test_given_local_target_override_when_running_python_then_every_context_sees " record(ctx, 'check')\n" " return ctx.pass_(message='recorded')\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -2010,6 +2096,7 @@ def test_given_unresolvable_target_when_running_with_a_sink_then_only_target_fre project_name="unresolved_target_project", repo_files={ "sqlbuild_project.toml": ( + 'extra_paths = ["setups.jsonl"]\n' 'name = "unresolved_target_project"\n' 'adapter = "duckdb"\n' 'default_target = "dev"\n\n' @@ -2017,11 +2104,11 @@ def test_given_unresolvable_target_when_running_with_a_sink_then_only_target_fre 'connection = "warehouse"\n' 'schema = "dev"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\n" "SELECT 1 AS order_id\n" ), - "providers/target_probe.py": ( + "python/providers/target_probe.py": ( "import json\n" "from pathlib import Path\n" "from sqlbuild.providers import Provider\n\n" @@ -2029,10 +2116,11 @@ def test_given_unresolvable_target_when_running_with_a_sink_then_only_target_fre ' """Test provider TargetProbe."""\n\n' " def setup(self, ctx):\n" " line = None if ctx is None else ctx.target_config.name\n" - " with Path(__file__).parents[1].joinpath('setups.jsonl').open('a') as out:\n" + " with " + "Path(__file__).parents[2].joinpath('setups.jsonl').open('a') as out:\n" " out.write(json.dumps(line) + '\\n')\n" ), - "sinks/events.py": _TARGET_PROBE_SINK, + "python/event_sinks/events.py": _TARGET_PROBE_SINK, "setups.jsonl": "", }, ) @@ -2071,6 +2159,7 @@ def test_given_ctx_templated_target_schema_when_running_then_python_sees_no_load project_name="ctx_target_project", repo_files={ "sqlbuild_project.toml": ( + 'extra_paths = ["target_config.jsonl"]\n' 'name = "ctx_target_project"\n' 'adapter = "duckdb"\n' 'default_target = "dev"\n\n' @@ -2079,10 +2168,10 @@ def test_given_ctx_templated_target_schema_when_running_then_python_sees_no_load "[targets.dev]\n" f'schema = "{test_case.target_schema}"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS order_id\n", - "python/recorder.py": _TARGET_CONFIG_RECORDER, - "python/loaders/raw.py": ( - "from python.recorder import record\n" + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS order_id\n", + **node_module_files("python/nodes/recorder.py", _TARGET_CONFIG_RECORDER), + "python/nodes/loaders/raw/loader.py": ( + "from python.nodes.recorder import record\n" "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" @@ -2090,8 +2179,9 @@ def test_given_ctx_templated_target_schema_when_running_then_python_sees_no_load " record(ctx, 'loader')\n" " return [{'order_id': 1}]\n" ), - "python/tasks/configured.py": ( - "from python.recorder import record\n" + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_orders\n", + "python/nodes/tasks/configured/asset.py": ( + "from python.nodes.recorder import record\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def configured_task(ctx):\n" @@ -2099,7 +2189,7 @@ def test_given_ctx_templated_target_schema_when_running_then_python_sees_no_load " record(ctx, 'asset')\n" " return ctx.result()\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -2178,20 +2268,22 @@ def test_given_same_node_results_in_multiple_targets_when_reading_then_uses_acti "[targets.prod]\n" 'schema = "prod"\n' ), - "python/tasks/produce.py": ( + "python/nodes/tasks/produce/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_result(ctx):\n" - " '''Test task produce_result.'''\n return ctx.result(payload={'target': ctx.target})\n" + " '''Test task produce_result.'''\n return " + "ctx.result(payload={'target': ctx.target})\n" ), - "python/tasks/consume.py": ( + "python/nodes/tasks/consume/asset.py": ( "from pathlib import Path\n" - "from python.tasks.produce import produce_result\n" + "from python.nodes.tasks.produce.asset import produce_result\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def consume_result(ctx):\n" - " '''Test task consume_result.'''\n result = ctx.result_of(node_function=produce_result)\n" - " output = Path(__file__).parents[2].joinpath('target_result.txt')\n" + " '''Test task consume_result.'''\n result = " + "ctx.result_of(node_function=produce_result)\n" + " output = Path(__file__).parents[4].joinpath('target_result.txt')\n" " output.write_text(str(result.payload['target']))\n" " return ctx.result()\n" ), @@ -2319,7 +2411,9 @@ def test_given_waffle_shop_project_when_running_build_then_warehouse_state_match ) assert result.returncode == test_case.expected_exit_code, result.stdout + result.stderr - run_sql_path: Path = project_dir / "target" / "run" / "models" / "marts" / "fact_orders.sql" + run_sql_path: Path = ( + project_dir / "target" / "run" / "sql" / "models" / "marts" / "fact_orders.sql" + ) assert run_sql_path.exists() run_sql: str = run_sql_path.read_text(encoding="utf-8") assert "CREATE OR REPLACE TABLE main.fact_orders__staging AS" in run_sql diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_capped_microbatch_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_capped_microbatch_build.py index 14512d3b2e..a2ceb999f0 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_capped_microbatch_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_capped_microbatch_build.py @@ -54,10 +54,10 @@ def test_given_monthly_producer_with_midmonth_max_when_building_capped_daily_con """ ).strip() + "\n", - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_meetings\n description: Test source raw_meetings.\n schema: main\n table: raw_meetings\n" ), - "models/monthly_meetings.sql": dedent( + "sql/models/monthly_meetings.sql": dedent( """ MODEL (description "Test model monthly_meetings.", materialized incremental, @@ -78,7 +78,7 @@ def test_given_monthly_producer_with_midmonth_max_when_building_capped_daily_con """ ).strip() + "\n", - "models/daily_suffix.sql": dedent( + "sql/models/daily_suffix.sql": dedent( """ MODEL (description "Test model daily_suffix.", materialized incremental, @@ -301,9 +301,9 @@ def test_given_cap_from_end_watermark_jump_when_rebuilding_then_producer_leaves_ tmp_path: Path, test_case: CappedMicrobatchScenarioE2ETestCase ) -> None: project_files: dict[str, str] = capped_microbatch_project_files(limit_action="cap_from_end") - project_files["models/capped_events.sql"] = project_files["models/capped_events.sql"].replace( - "cursor_end '2026-01-06'", "cursor_end '2026-01-12'" - ) + project_files["sql/models/capped_events.sql"] = project_files[ + "sql/models/capped_events.sql" + ].replace("cursor_end '2026-01-06'", "cursor_end '2026-01-12'") project_dir: Path = prepare_inline_project( tmp_path=tmp_path, project_name="cap_from_end_watermark_jump", @@ -377,7 +377,7 @@ def test_given_any_watermarks_and_consumer_end_when_capped_winner_is_later_then_ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_late @@ -391,7 +391,7 @@ def test_given_any_watermarks_and_consumer_end_when_capped_winner_is_later_then_ """ ).strip() + "\n", - "models/capped_late.sql": dedent( + "sql/models/capped_late.sql": dedent( """ MODEL (description "Test model capped_late.", materialized incremental, @@ -418,14 +418,14 @@ def test_given_any_watermarks_and_consumer_end_when_capped_winner_is_later_then_ """ ).strip() + "\n", - "models/uncapped_early.sql": dedent( + "sql/models/uncapped_early.sql": dedent( """ MODEL (description "Test model uncapped_early.", materialized table); SELECT id, event_time FROM __source("raw_early") """ ).strip() + "\n", - "models/any_consumer.sql": dedent( + "sql/models/any_consumer.sql": dedent( """ MODEL (description "Test model any_consumer.", materialized incremental, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_changed_builds.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_changed_builds.py index 20fedd7e7a..fbaab7934b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_changed_builds.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_changed_builds.py @@ -147,7 +147,7 @@ def test_given_an_unqualified_name_matching_two_relations_when_building_with_cha ) -> None: project_dir: Path = prepare_changed_project(tmp_path=tmp_path, warehouse=test_case.warehouse) add_changed_overlay(project_dir, CHANGED_BUILDS_UNQUALIFIED_FIXTURE) - customers_model: Path = project_dir / "models/customers.sql" + customers_model: Path = project_dir / "sql/models/customers.sql" run_changed_build(project_dir, ("--select", "+customers")) run_changed_build(project_dir, ("--changed",)) nothing_changed: frozenset[str] = run_changed_build(project_dir, ("--changed",)) @@ -251,7 +251,7 @@ def test_given_scheduled_jobs_when_building_with_changed_then_a_change_stops_at_ project_dir / warehouse.warehouse_file, "INSERT INTO raw.orders VALUES (2, 1, 2)" ) new_data: frozenset[str] = run_changed_build(project_dir, ("--changed",)) - (project_dir / "models/stg_orders.sql").write_text(STG_ORDERS_REDEFINED, encoding="utf-8") + (project_dir / "sql/models/stg_orders.sql").write_text(STG_ORDERS_REDEFINED, encoding="utf-8") plan: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "plan", "--changed"), project_dir=project_dir ) @@ -300,8 +300,8 @@ def test_given_two_jobs_each_holding_a_redefined_upstream_when_building_changed_ project_dir: Path = prepare_changed_project(tmp_path=tmp_path, warehouse=warehouse) add_changed_overlay(project_dir, CHANGED_BUILDS_TWO_UP_FIXTURE) first: frozenset[str] = run_changed_build(project_dir, (CHANGED_ANY,)) - (project_dir / "models/stg_orders.sql").write_text(STG_ORDERS_REDEFINED, encoding="utf-8") - (project_dir / "models/stg_customers.sql").write_text( + (project_dir / "sql/models/stg_orders.sql").write_text(STG_ORDERS_REDEFINED, encoding="utf-8") + (project_dir / "sql/models/stg_customers.sql").write_text( 'MODEL (description "Staged customers.", materialized table);\n' 'SELECT customer_id FROM __source("raw_customers") WHERE customer_id > 0\n', encoding="utf-8", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_compile_json_behavior.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_compile_json_behavior.py index 19954834f1..e2b796efb7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_compile_json_behavior.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_compile_json_behavior.py @@ -162,7 +162,7 @@ def test_given_waffle_shop_when_running_compile_json_then_it_reports_offline_que "type": "sql", "statement": "SELECT 1", "name": "select_value", - "relative_path": "hooks/sql/select_value.sql", + "relative_path": "sql/hooks/sql/select_value.sql", "definition_sql": "SELECT @value", "kwargs": {"value": 1}, "description": "Test hook select_value.", @@ -190,14 +190,14 @@ def test_given_model_with_hooks_when_running_compile_json_then_it_reports_hook_m "[connection]\n" 'database = "compile_json_hooks_project.duckdb"\n' ), - "hooks/python/notify.py": ( + "sql/hooks/python/notify.py": ( "from sqlbuild.hooks import hook\n\n" "@hook\n" "def notify(ctx, message):\n" " '''Test hook notify.'''\n ctx.log.info(message)\n" ), - "hooks/sql/select_value.sql": "HOOK (description 'Test hook select_value.');\n\nSELECT @value\n", - "models/orders.sql": ( + "sql/hooks/sql/select_value.sql": "HOOK (description 'Test hook select_value.');\n\nSELECT @value\n", + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " materialized table,\n" ' pre_hooks [sql("select_value", value: 1), ' @@ -233,11 +233,11 @@ def test_given_model_with_hooks_when_running_compile_json_then_it_reports_hook_m assert hooks_by_name["select_value"] == { "type": "sql", "name": "select_value", - "relative_path": "hooks/sql/select_value.sql", + "relative_path": "sql/hooks/sql/select_value.sql", "description": "Test hook select_value.", "sql": "SELECT @value", } - assert hooks_by_name["notify"]["relative_path"] == "hooks/python/notify.py" + assert hooks_by_name["notify"]["relative_path"] == "sql/hooks/python/notify.py" assert hooks_by_name["notify"]["definition_hash"] assert hooks_by_name["notify"]["version_hash"] @@ -249,7 +249,7 @@ def test_given_model_with_hooks_when_running_compile_json_then_it_reports_hook_m description="unknown materialization stops compile", repo_files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.', materialized tablex);\n\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized tablex);\n\nSELECT 1 AS order_id\n", }, expected_code="P001", expected_message_fragment="unknown materialization 'tablex'", @@ -259,7 +259,7 @@ def test_given_model_with_hooks_when_running_compile_json_then_it_reports_hook_m description="unknown on_schema_change stops compile with help", repo_files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n materialized incremental,\n incremental_strategy append,\n" " on_schema_change append_columns,\n);\n\nSELECT 1 AS order_id\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_concurrent_microbatch_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_concurrent_microbatch_build.py index be98fffbb3..41d83c92de 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_concurrent_microbatch_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_concurrent_microbatch_build.py @@ -49,7 +49,7 @@ def test_given_project_capability_disabled_when_batch_concurrency_exceeds_one_th """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -72,7 +72,7 @@ def test_given_project_capability_disabled_when_batch_concurrency_exceeds_one_th """ ).strip() + "\n", - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_events\n description: Test source raw_events.\n schema: main\n table: raw_events\n" ), }, @@ -116,7 +116,7 @@ def test_given_opt_in_concurrent_microbatch_when_building_twice_then_records_all """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -126,7 +126,7 @@ def test_given_opt_in_concurrent_microbatch_when_building_twice_then_records_all """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -242,7 +242,7 @@ def test_given_later_batches_succeed_when_one_batch_fails_then_next_run_preserve """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -252,7 +252,7 @@ def test_given_later_batches_succeed_when_one_batch_fails_then_next_run_preserve """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -309,22 +309,30 @@ def test_given_later_batches_succeed_when_one_batch_fails_then_next_run_preserve "(7, '2026-01-01 06:30:00', '7')" ) connection.close() + completion_events_sql: str = ( + "SELECT event_id, partition_start FROM main._sqlbuild_microbatches " + "WHERE record_type = 'partition_completion'" + ) + initial_completion_ids: set[str] = { + row[0] for row in query_duckdb(db_path=db_path, sql=completion_events_sql) + } failed: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir ) assert failed.returncode != 0 - assert ( - query_duckdb( - db_path=db_path, - sql=( - "SELECT COUNT(*) FROM main._sqlbuild_microbatches " - "WHERE record_type = 'partition_completion' " - "AND partition_start >= '2026-01-01T03:00:00'" - ), - )[0][0] - == 2 + completion_starts: dict[str, str] = dict( + query_duckdb(db_path=db_path, sql=completion_events_sql) + ) + failed_run_completion_starts: set[str] = set( + map(completion_starts.__getitem__, completion_starts.keys() - initial_completion_ids) ) + # The failing 02:00 batch records no completion. Its 03:00 sibling is handed to a worker + # before the coordinator runs 04:00 itself, and sibling failures are only examined after + # 04:00 finishes, so both always complete. Whether 05:00 and 06:00 also start before the + # failure is seen depends on runner timing. + assert "2026-01-01T02:00:00" not in failed_run_completion_starts + assert {"2026-01-01T03:00:00", "2026-01-01T04:00:00"} <= failed_run_completion_starts connection = duckdb.connect(str(db_path)) connection.execute("UPDATE raw_events SET payload = '3' WHERE id = 3") @@ -400,7 +408,7 @@ def test_given_microbatch_history_is_lost_when_reconciling_then_policy_is_applie """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -410,7 +418,7 @@ def test_given_microbatch_history_is_lost_when_reconciling_then_policy_is_applie """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -510,7 +518,7 @@ def test_given_bounded_replay_on_change_when_model_changes_then_requirement_is_d """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -520,7 +528,7 @@ def test_given_bounded_replay_on_change_when_model_changes_then_requirement_is_d """ ).strip() + "\n", - "models/orders.sql": replay_microbatch_model_sql( + "sql/models/orders.sql": replay_microbatch_model_sql( value_expression="CAST(payload AS INTEGER)" ), }, @@ -546,7 +554,7 @@ def test_given_bounded_replay_on_change_when_model_changes_then_requirement_is_d ) assert initial.returncode == 0, initial.stdout + initial.stderr - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( replay_microbatch_model_sql(value_expression="CAST(payload AS INTEGER) + 1"), encoding="utf-8", ) @@ -610,7 +618,7 @@ def test_given_full_replay_fails_when_retried_then_original_requirement_is_reuse """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -620,7 +628,7 @@ def test_given_full_replay_fails_when_retried_then_original_requirement_is_reuse """ ).strip() + "\n", - "models/orders.sql": replay_microbatch_model_sql( + "sql/models/orders.sql": replay_microbatch_model_sql( value_expression="CAST(payload AS INTEGER)", replay_policy="full" ), }, @@ -644,7 +652,7 @@ def test_given_full_replay_fails_when_retried_then_original_requirement_is_reuse ) assert initial.returncode == 0, initial.stdout + initial.stderr - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( replay_microbatch_model_sql( value_expression="CAST(payload AS INTEGER) + 1", replay_policy="full" ), @@ -701,7 +709,7 @@ def test_given_version_hash_returns_when_replaying_then_new_transition_gets_new_ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -711,7 +719,7 @@ def test_given_version_hash_returns_when_replaying_then_new_transition_gets_new_ """ ).strip() + "\n", - "models/orders.sql": replay_microbatch_model_sql( + "sql/models/orders.sql": replay_microbatch_model_sql( value_expression="CAST(payload AS INTEGER)" ), }, @@ -731,7 +739,7 @@ def test_given_version_hash_returns_when_replaying_then_new_transition_gets_new_ ) connection.close() - model_path: Path = project_dir / "models" / "orders.sql" + model_path: Path = project_dir / "sql" / "models" / "orders.sql" f1_sql: str = replay_microbatch_model_sql(value_expression="CAST(payload AS INTEGER)") f2_sql: str = replay_microbatch_model_sql(value_expression="CAST(payload AS INTEGER) + 1") initial: subprocess.CompletedProcess[str] = run_sqb( @@ -792,7 +800,7 @@ def test_given_historical_backfill_when_normal_run_resumes_then_gap_to_normal_fl """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -802,7 +810,7 @@ def test_given_historical_backfill_when_normal_run_resumes_then_gap_to_normal_fl """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -901,7 +909,7 @@ def test_given_no_new_cursor_work_when_history_is_lost_then_reconciliation_still """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -911,7 +919,7 @@ def test_given_no_new_cursor_work_when_history_is_lost_then_reconciliation_still """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_observations.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_observations.py index bab2d7366a..0a13749912 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_observations.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_observations.py @@ -33,8 +33,8 @@ """ ).strip() + "\n", - "seeds/raw_orders.csv": "id,ordered_at\n1,2026-01-01 00:00:00\n2,2026-01-01 01:00:00\n", - "seeds/raw_orders.yml": dedent( + "sql/seeds/raw_orders.csv": "id,ordered_at\n1,2026-01-01 00:00:00\n2,2026-01-01 01:00:00\n", + "sql/seeds/raw_orders.yml": dedent( """ seeds: - name: raw_orders @@ -47,7 +47,7 @@ """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Orders by timestamp cursor.", materialized incremental, @@ -62,7 +62,7 @@ """ ).strip() + "\n", - "models/order_ids.sql": dedent( + "sql/models/order_ids.sql": dedent( """ MODEL (description "Orders by integer cursor.", materialized incremental, @@ -75,7 +75,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_refunds @@ -91,7 +91,7 @@ """ ).strip() + "\n", - "models/refunds.sql": dedent( + "sql/models/refunds.sql": dedent( """ MODEL (description "Refunds.", materialized table); @@ -99,7 +99,7 @@ """ ).strip() + "\n", - "models/order_count.sql": dedent( + "sql/models/order_count.sql": dedent( """ MODEL (description "Order count without a cursor.", materialized table); @@ -222,7 +222,7 @@ def test_given_wrong_cursor_observation_when_planning_and_building_then_live_max database: Path = project_dir / "observations.duckdb" first: subprocess.CompletedProcess[str] = run_sqb(command=("build",), project_dir=project_dir) assert first.returncode == 0, first.stderr - seed: Path = project_dir / "seeds/raw_orders.csv" + seed: Path = project_dir / "sql/seeds/raw_orders.csv" seed.write_text(seed.read_text() + test_case.added_seed_rows) honest: subprocess.CompletedProcess[str] = run_sqb(command=("plan",), project_dir=project_dir) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_runtime_failures.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_runtime_failures.py index 559fae9c2b..686f2f36f7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_runtime_failures.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_runtime_failures.py @@ -11,6 +11,7 @@ from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import ( CliFailureBuildE2ETestCase, ) +from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import take_raw_data_sql from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( prepare_inline_project, run_sqb, @@ -35,11 +36,11 @@ "CREATE TABLE main.customer_status_snapshot " "(customer_id INTEGER, last_ordered_at TIMESTAMP);\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized view);\n\n" "SELECT id AS order_id, ordered_at FROM main.raw_orders\n" ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.',\n" " materialized table,\n" " contract enforced,\n" @@ -50,7 +51,7 @@ ");\n\n" 'SELECT order_id, ordered_at FROM __ref("stg_orders")\n' ), - "models/customer_status_snapshot.sql": dedent( + "sql/models/customer_status_snapshot.sql": dedent( """ MODEL (description "Test model customer_status_snapshot.", materialized incremental, @@ -73,7 +74,7 @@ command=("--no-color", "build", "--select", "+customer_status_snapshot"), expected_exit_code=1, expected_stderr_fragments=( - "error[B300]: [B300] models/customer_status_snapshot.sql:9:17: cursor_inputs " + "error[B300]: [B300] sql/models/customer_status_snapshot.sql:9:17: cursor_inputs " "fact_orders references unknown column 'missing_column'", ), verification_sql="SELECT COUNT(*) FROM main.customer_status_snapshot", @@ -92,7 +93,7 @@ "seed_raw_data.sql": ( "CREATE TABLE main.raw_orders (id INTEGER, ordered_at TIMESTAMP);\n" ), - "models/customer_status_snapshot.sql": dedent( + "sql/models/customer_status_snapshot.sql": dedent( """ MODEL (description "Test model customer_status_snapshot.", materialized incremental, @@ -133,12 +134,12 @@ def test_given_cursor_runtime_failure_projects_when_running_build_then_cli_fails project_name="cursor_runtime_project", repo_files=test_case.repo_files, ) - seed_file: Path = project_dir / "seed_raw_data.sql" + raw_data_sql: str = take_raw_data_sql(project_dir) import duckdb db_path: Path = project_dir / "cursor_runtime.duckdb" connection: duckdb.DuckDBPyConnection = duckdb.connect(str(db_path)) - connection.execute(seed_file.read_text(encoding="utf-8")) + connection.execute(raw_data_sql) connection.close() pre_command: tuple[str, ...] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_defer_migration_origin.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_defer_migration_origin.py index 7c567d49b9..f436da04b9 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_defer_migration_origin.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_defer_migration_origin.py @@ -25,15 +25,15 @@ '[targets.dev]\nschema = "dev"\n\n' '[targets.prod]\nschema = "preserve"\n' ), - "models/order_ledger.sql": ( + "sql/models/order_ledger.sql": ( 'MODEL (description "Test model order_ledger.", materialized table, ' "schema prod, migrate_from order_history);\n\nSELECT 1 AS order_id\n" ), - "models/order_report.sql": ( + "sql/models/order_report.sql": ( 'MODEL (description "Test model order_report.", materialized table, schema prod);\n\n' 'SELECT order_id FROM __ref("order_ledger")\n' ), - "models/order_archive.sql": ( + "sql/models/order_archive.sql": ( 'MODEL (description "Test model order_archive.", materialized table, schema sales);\n\n' "SELECT 1 AS order_id\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_discovered_nodes.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_discovered_nodes.py index 3c4c749ece..926afde250 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_discovered_nodes.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_discovered_nodes.py @@ -14,6 +14,7 @@ from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb _PROJECT: str = ( + 'extra_paths = ["runs.txt"]\n' 'name = "discovered"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' '[connection]\ndatabase = "discovered.duckdb"\n\n[targets.dev]\nschema = "dev"\n' ) @@ -37,7 +38,7 @@ def plan() -> Discovered: @asset(for_each=plan, depends_on=model("orders")) def run_step(ctx: AssetContext, step: str) -> None: """Run one step.""" - with (Path(__file__).parents[2] / "runs.txt").open("a") as runs: + with (Path(__file__).parents[4] / "runs.txt").open("a") as runs: runs.write(f"{ctx.discovered.item}:{step}:{ctx.discovered.tags['release']}\\n") ''' @@ -111,8 +112,8 @@ def test_given_a_for_each_asset_when_planning_or_building_outside_a_location_the project_name="discovered", repo_files={ "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "python/plan/nodes.py": _NODES, + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/nodes/plan/nodes/asset.py": _NODES, }, ) runs_file: Path = project_dir / "runs.txt" @@ -149,8 +150,8 @@ def test_given_a_for_each_asset_when_compiling_then_the_dag_shows_the_placeholde project_name="discovered", repo_files={ "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "python/plan/nodes.py": _NODES, + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/nodes/plan/nodes/asset.py": _NODES, }, ) dag: Path = project_dir / "target" / "sqlbuild_dag.json" @@ -197,8 +198,8 @@ def test_given_a_set_without_items_when_discovering_for_a_command_then_it_stops_ project_name="discovered", repo_files={ "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "python/plan/nodes.py": nodes, + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/nodes/plan/nodes/asset.py": nodes, }, ) result: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_duckdb_attach.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_duckdb_attach.py index 0798368e7e..e8b7bc5f03 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_duckdb_attach.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_duckdb_attach.py @@ -53,22 +53,22 @@ def test_given_attached_duckdb_file_when_building_then_models_land_in_it( project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML.format(attach_path=test_case.attach_path), - "models/archived_orders.sql": ( + "sql/models/archived_orders.sql": ( "MODEL (description 'Test model archived_orders.', materialized table, " "database archive, schema main);\nSELECT 1 AS order_id\n" ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Test model customers.', materialized table);\n" "SELECT 1 AS customer_id\n" ), - "models/order_ids.sql": ( + "sql/models/order_ids.sql": ( "MODEL (description 'Test model order_ids.', materialized table);\n" 'SELECT o.order_id FROM __ref("archived_orders") AS o\n' ), }, ) home: Path = tmp_path / "home" - home.mkdir() + home.mkdir(parents=True) built: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build", "--concurrency", str(test_case.concurrency)), project_dir=project_dir, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_duckdb_storage_key.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_duckdb_storage_key.py index 7af693c641..dfe12f4c14 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_duckdb_storage_key.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_duckdb_storage_key.py @@ -44,7 +44,7 @@ def test_given_storage_key_in_connection_when_building_then_warehouse_keeps_defa 'name = "storage_key"\nadapter = "duckdb"\n\n' f'[connection]\ndatabase = "warehouse.duckdb"\n{test_case.connection_key} = "latest"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_empty_cursor_inputs.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_empty_cursor_inputs.py index 873f07bcc4..f584dd5962 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_empty_cursor_inputs.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_empty_cursor_inputs.py @@ -102,8 +102,8 @@ ) _LOADED_REVENUE_ROWS: tuple[tuple[object, ...], ...] = (("2026-04-01", 1200), ("2026-04-02", 1650)) _EMPTIED_MODELS: dict[str, str] = { - "models/daily_revenue.sql": _DAILY_REVENUE_SQL, - "models/revenue_summary.sql": _REVENUE_SUMMARY_SQL, + "sql/models/daily_revenue.sql": _DAILY_REVENUE_SQL, + "sql/models/revenue_summary.sql": _REVENUE_SUMMARY_SQL, } _ALIASED_REPLAY_SQL: str = dedent( """ @@ -170,21 +170,21 @@ """ ).lstrip() _SAME_RUN_MODELS: dict[str, str] = { - "models/stg_payments.sql": dedent( + "sql/models/stg_payments.sql": dedent( """ MODEL (description "Payments staged for reporting", materialized view); SELECT payment_id, paid_at, amount_cents FROM __source("raw_payments") """ ).lstrip(), - "models/stg_refunds.sql": dedent( + "sql/models/stg_refunds.sql": dedent( """ MODEL (description "Refunds staged for reporting", materialized view); SELECT refund_id, refunded_at, amount_cents FROM __source("raw_refunds") """ ).lstrip(), - "models/daily_revenue.sql": dedent( + "sql/models/daily_revenue.sql": dedent( """ MODEL ( description "Daily revenue net of refunds, from staged inputs", @@ -208,7 +208,7 @@ "DELETE FROM main.raw_refunds; " "INSERT INTO main.raw_payments VALUES (2, '2026-04-02 10:00:00', 1650)" ) -_NO_INPUTS_MODELS: dict[str, str] = {"models/finance/daily_revenue.sql": _NO_INPUTS_SQL} +_NO_INPUTS_MODELS: dict[str, str] = {"sql/models/finance/daily_revenue.sql": _NO_INPUTS_SQL} @pytest.mark.parametrize( @@ -236,7 +236,7 @@ def test_given_empty_source_when_building_first_then_creates_empty_table_and_nex tmp_path: Path, ) -> None: project_dir: Path = prepare_empty_cursor_inputs_project( - tmp_path=tmp_path, models={"models/daily_revenue.sql": test_case.model_sql} + tmp_path=tmp_path, models={"sql/models/daily_revenue.sql": test_case.model_sql} ) first: subprocess.CompletedProcess[str] = run_empty_cursor_command( @@ -369,7 +369,7 @@ def test_given_emptied_source_when_planning_json_then_reports_no_input_rows( tmp_path: Path, ) -> None: project_dir: Path = prepare_empty_cursor_inputs_project( - tmp_path=tmp_path, models={"models/daily_revenue.sql": _DAILY_REVENUE_SQL} + tmp_path=tmp_path, models={"sql/models/daily_revenue.sql": _DAILY_REVENUE_SQL} ) load_empty_cursor_payments(project_dir=project_dir) build_empty_cursor_project(project_dir=project_dir) @@ -399,7 +399,7 @@ def test_given_emptied_source_when_planning_json_then_reports_no_input_rows( expected_output_fragments=( "error[P011]: incremental model 'daily_revenue' reads no inputs, so builds " "after the first cannot work out their cursor window", - "--> models/finance/daily_revenue.sql:5:3", + "--> sql/models/finance/daily_revenue.sql:5:3", "cursor revenue_date,", "^^^^^^^^^^^^^^^^^^^", "help: read the data through __ref(), __source() or __seed() so its cursor can " @@ -468,7 +468,7 @@ def test_given_cursor_model_without_inputs_when_compiling_json_then_locates_curs assert test_case.expected_json_location is not None line, column, end_column = test_case.expected_json_location assert diagnostic["location"] == { - "path": "models/finance/daily_revenue.sql", + "path": "sql/models/finance/daily_revenue.sql", "line": line, "column": column, "end_line": line, @@ -495,7 +495,7 @@ def test_given_failing_incremental_build_when_building_then_delta_relation_is_ke tmp_path: Path, ) -> None: project_dir: Path = prepare_empty_cursor_inputs_project( - tmp_path=tmp_path, models={"models/daily_revenue.sql": _DAILY_REVENUE_SQL} + tmp_path=tmp_path, models={"sql/models/daily_revenue.sql": _DAILY_REVENUE_SQL} ) load_empty_cursor_payments(project_dir=project_dir) build_empty_cursor_project(project_dir=project_dir) @@ -742,14 +742,14 @@ def test_given_empty_input_built_in_same_run_when_building_then_labels_it_by_pro project_dir: Path = prepare_empty_cursor_inputs_project( tmp_path=tmp_path, models={ - "models/stg_payments.sql": _STG_PAYMENTS_SQL, - "models/daily_revenue.sql": _STAGED_REVENUE_SQL, + "sql/models/stg_payments.sql": _STG_PAYMENTS_SQL, + "sql/models/daily_revenue.sql": _STAGED_REVENUE_SQL, }, ) load_empty_cursor_payments(project_dir=project_dir) build_empty_cursor_project(project_dir=project_dir) execute_empty_cursor_sql(project_dir=project_dir, sql="DELETE FROM main.raw_payments") - (project_dir / "models" / "stg_payments.sql").write_text( + (project_dir / "sql" / "models" / "stg_payments.sql").write_text( test_case.changed_upstream_sql, encoding="utf-8" ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_enum_contract.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_enum_contract.py index 3a3bd5c27d..811ebdd47b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_enum_contract.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_enum_contract.py @@ -44,8 +44,8 @@ def test_given_enum_typed_contract_when_value_is_invalid_then_build_fails_audit( """ ).strip() + "\n", - "models/_enums/fulfillment_method.sql": "ENUM (name fulfillment_method, members [DELIVERY, PICKUP]);\n", - "models/orders.sql": dedent( + "sql/models/_enums/fulfillment_method.sql": "ENUM (name fulfillment_method, members [DELIVERY, PICKUP]);\n", + "sql/models/orders.sql": dedent( f""" MODEL (description "Test model orders.", materialized table, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_execution_limits.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_execution_limits.py index 9af51c2bcc..a055790dd8 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_execution_limits.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_execution_limits.py @@ -51,8 +51,8 @@ def test_given_target_model_limit_when_building_then_effective_policy_controls_e max_models = 1 remediation = "Automated tools must request approval before changing this policy." """.strip(), - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id\n", - "models/order_items.sql": "MODEL (description 'Test model order_items.', materialized table);\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id\n", + "sql/models/order_items.sql": "MODEL (description 'Test model order_items.', materialized table);\n\nSELECT 1 AS id\n", }, ) @@ -112,8 +112,8 @@ def test_given_local_model_limit_override_when_building_then_local_policy_is_app [targets.dev.execution_limits] max_models = 2 """.strip(), - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id\n", - "models/order_items.sql": "MODEL (description 'Test model order_items.', materialized table);\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id\n", + "sql/models/order_items.sql": "MODEL (description 'Test model order_items.', materialized table);\n\nSELECT 1 AS id\n", }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_explicit_references.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_explicit_references.py index 1d8b7ef2a2..d52d2fc7aa 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_explicit_references.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_explicit_references.py @@ -35,6 +35,7 @@ run_sqb, table_exists, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _EMITTING_MACROS: str = ( EXPLICIT_REFERENCE_MACROS @@ -45,7 +46,7 @@ "def customers_base():\n return 'SELECT * FROM __ref(\"stg_customers\")'\n" ) _UNDECLARED_HOOKS: str = EXPLICIT_REFERENCE_HOOKS + ' ctx.relation(model("all_orders"))\n' -_AUDITS: str = "models/sales/_sqlbuild" +_AUDITS: str = "sql/models/sales/_sqlbuild" _AUDIT_READING: str = ( "AUDIT ();\nSELECT s.order_id FROM @relation s\n" 'LEFT JOIN __ref("{read}") a USING (order_id) WHERE a.order_id IS NULL\n' @@ -76,10 +77,10 @@ _COUNTRY_SEED_FILES: dict[str, str] = { - "seeds/countries.yml": ( + "sql/seeds/countries.yml": ( "seeds:\n - name: countries\n description: Test seed countries.\n columns:\n - name: code\n type: VARCHAR\n" ), - "seeds/countries.csv": "code\nGB\nFR\n", + "sql/seeds/countries.csv": "code\nGB\nFR\n", } _SEED_TASK: str = ( "from sqlbuild.refs import seed\n" @@ -161,8 +162,8 @@ def test_given_python_seed_and_model_dependencies_when_building_then_graph_selec repo_files=explicit_reference_project_files( overrides={ **_COUNTRY_SEED_FILES, - "python/tasks/countries.py": _SEED_TASK, - "python/checks/orders.py": _MODEL_CHECK, + "python/nodes/tasks/countries/asset.py": _SEED_TASK, + "python/nodes/checks/orders/checks.py": _MODEL_CHECK, } ), ) @@ -284,7 +285,7 @@ def test_given_both_way_selector_when_building_then_it_expands_from_the_selected tmp_path=tmp_path, project_name="explicit_refs", repo_files=explicit_reference_project_files( - overrides={"python/tasks/exports.py": _SIBLING_TASKS} + overrides={**node_module_files("python/nodes/tasks/exports.py", _SIBLING_TASKS)} ), ) @@ -366,7 +367,7 @@ def test_given_typed_macro_references_and_hook_reads_when_building_then_graph_an expected_output_fragments=( "error[P006]: model:hidden depends on model:stg_orders_eu through macro " "orders_base()", - "--> models/sales/_sqlbuild/_macros/python/unions.py", + "--> sql/models/sales/_sqlbuild/_macros/python/unions.py", '@py.orders_base(__ref("stg_orders_eu"))', "[references]\n enforce_explicit = false", ), @@ -382,31 +383,34 @@ def test_given_typed_macro_references_and_hook_reads_when_building_then_graph_an ), ExplicitReferenceFailureE2ETestCase( description="literal SQL naming a project relation fails compile", - overrides={"python/tasks/export.py": _LITERAL_TASK}, + overrides={"python/nodes/tasks/export/asset.py": _LITERAL_TASK}, command=("--no-color", "compile"), expected_exit_code=1, expected_output_fragments=( "error[P008]: asset:export_orders names model:stg_customers as 'stg_customers'", - "--> python/tasks/export.py:8", + "--> python/nodes/tasks/export/asset.py:8", "[references]\n enforce_explicit = false", ), ), ExplicitReferenceFailureE2ETestCase( description="check literal SQL naming an undeclared model fails compile", - overrides={"python/checks/orders.py": _LITERAL_CHECK}, + overrides={"python/nodes/checks/orders/checks.py": _LITERAL_CHECK}, command=("--no-color", "compile"), expected_exit_code=1, expected_output_fragments=( "error[P008]: check:orders_present names model:stg_customers as 'stg_customers'", - "--> python/checks/orders.py:9", + "--> python/nodes/checks/orders/checks.py:9", 'declare it with depends_on=model("stg_customers")', ), ), ExplicitReferenceFailureE2ETestCase( description="loader literal SQL naming a source fails compile with ctx.source help", overrides={ - "sources/raw.yml": _RAW_SOURCES, - "python/loaders/raw.py": explicit_reference_literal_loader(table="raw_regions"), + "sql/sources/raw.yml": _RAW_SOURCES, + **node_module_files( + "python/nodes/loaders/raw.py", + explicit_reference_literal_loader(table="raw_regions"), + ), }, command=("--no-color", "compile"), expected_exit_code=1, @@ -418,8 +422,11 @@ def test_given_typed_macro_references_and_hook_reads_when_building_then_graph_an ExplicitReferenceFailureE2ETestCase( description="loader literal SQL naming a model fails compile", overrides={ - "sources/raw.yml": _RAW_SOURCES, - "python/loaders/raw.py": explicit_reference_literal_loader(table="stg_customers"), + "sql/sources/raw.yml": _RAW_SOURCES, + **node_module_files( + "python/nodes/loaders/raw.py", + explicit_reference_literal_loader(table="stg_customers"), + ), }, command=("--no-color", "compile"), expected_exit_code=1, @@ -455,7 +462,7 @@ def test_given_implicit_reference_when_running_command_then_it_fails_with_guidan [ ExplicitReferenceRuntimeWarningE2ETestCase( description="run-time hard-coded name warns while the build succeeds", - overrides={"python/tasks/export.py": _RUNTIME_TASK}, + overrides={"python/nodes/tasks/export/asset.py": _RUNTIME_TASK}, enforce_explicit=True, expected_exit_code=0, expected_warning_fragments=( @@ -466,11 +473,12 @@ def test_given_implicit_reference_when_running_command_then_it_fails_with_guidan ExplicitReferenceRuntimeWarningE2ETestCase( description="enforcement disabled allows every implicit reference", overrides={ - "python/tasks/export.py": _RUNTIME_TASK, + "python/nodes/tasks/export/asset.py": _RUNTIME_TASK, EXPLICIT_REFERENCE_MACRO_PATH: _EMITTING_MACROS, f"{EXPLICIT_REFERENCE_MODELS}/hidden.sql": _EMITTING_MODEL, - "python/tasks/literal.py": _LITERAL_TASK.replace( - "export_orders", "count_customers" + **node_module_files( + "python/nodes/tasks/literal.py", + _LITERAL_TASK.replace("export_orders", "count_customers"), ), }, enforce_explicit=False, @@ -521,7 +529,7 @@ def test_given_runtime_hard_coded_relation_when_building_then_it_warns_without_f [ ExplicitReferenceRuntimeWarningE2ETestCase( description="check naming an undeclared model at run time warns and passes", - overrides={"python/checks/orders.py": _RUNTIME_CHECK}, + overrides={"python/nodes/checks/orders/checks.py": _RUNTIME_CHECK}, enforce_explicit=True, expected_exit_code=0, expected_warning_fragments=( @@ -569,12 +577,12 @@ def test_given_check_runtime_hard_coded_relation_when_building_then_it_warns_wit description="two ref-emitting macros and a hard-coded task name all report at once", overrides={ EXPLICIT_REFERENCE_MACRO_PATH: _EMITTING_MACROS, - "models/sales/_sqlbuild/_macros/python/customers.py": _SECOND_EMITTING_MACROS, + "sql/models/sales/_sqlbuild/_macros/python/customers.py": _SECOND_EMITTING_MACROS, f"{EXPLICIT_REFERENCE_MODELS}/hidden.sql": _EMITTING_MODEL, f"{EXPLICIT_REFERENCE_MODELS}/hidden_customers.sql": ( "MODEL (description 'Test model hidden_customers.', materialized table);\n@py.customers_base()\n" ), - "python/tasks/export.py": _LITERAL_TASK, + "python/nodes/tasks/export/asset.py": _LITERAL_TASK, }, expected_output_fragments=( "error[P006]: model:hidden depends on model:stg_orders_eu through macro " @@ -627,11 +635,11 @@ def test_given_check_runtime_hard_coded_relation_when_building_then_it_warns_wit expected_output_fragments=( "error[P004]: Singular audit 'one_customers'", "error[P004]: Singular audit 'one_orders'", - "--> models/sales/_sqlbuild/audits/singular/one_orders.sql", + "--> sql/models/sales/_sqlbuild/audits/singular/one_orders.sql", "error[P005]: Audit 'a_check' on model 'orders_a' reads model 'orders_a_summary'", "error[P005]: Audit 'b_check' on model 'customers_b' reads model " "'customers_b_summary'", - "--> models/sales/_sqlbuild/_audits/generic/a_check.sql", + "--> sql/models/sales/_sqlbuild/_audits/generic/a_check.sql", "4 errors", ), expected_json_diagnostics=( @@ -647,8 +655,8 @@ def test_given_check_runtime_hard_coded_relation_when_building_then_it_warns_wit CollectedCompileDiagnosticsE2ETestCase( description="every declaration placement error reports on its own", overrides={ - "audits/generic/eu_check.sql": _NULL_AUDIT, - "audits/generic/us_check.sql": _NULL_AUDIT, + "sql/audits/generic/eu_check.sql": _NULL_AUDIT, + "sql/audits/generic/us_check.sql": _NULL_AUDIT, f"{_AUDITS}/audits/generic/unused_check.sql": _NULL_AUDIT, f"{EXPLICIT_REFERENCE_MODELS}/stg_orders_eu.sql": ( "MODEL (description 'Test model stg_orders_eu.', materialized table, audits [eu_check]);\n" @@ -663,7 +671,7 @@ def test_given_check_runtime_hard_coded_relation_when_building_then_it_warns_wit "error[S010]: Unused inherited declaration 'audit:unused_check'", "error[S024]: Declaration 'audit:eu_check'", "error[S024]: Declaration 'audit:us_check'", - "--> audits/generic/eu_check.sql", + "--> sql/audits/generic/eu_check.sql", "3 errors", ), expected_json_diagnostics=( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_expression_sources.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_expression_sources.py index 99addcdb95..7720b20f88 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_expression_sources.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_expression_sources.py @@ -38,7 +38,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -63,7 +63,7 @@ """ ).strip() + "\n", - "models/fact_orders.sql": dedent( + "sql/models/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table); @@ -127,9 +127,9 @@ def test_given_expression_source_when_building_then_inline_source_sql_is_used( actual_rows: list[tuple[object, ...]] = query_duckdb(db_path=db_path, sql=query) assert tuple(tuple(row) for row in actual_rows) == expected_rows - runtime_sql: str = (project_dir / "target" / "run" / "models" / "fact_orders.sql").read_text( - encoding="utf-8" - ) + runtime_sql: str = ( + project_dir / "target" / "run" / "sql" / "models" / "fact_orders.sql" + ).read_text(encoding="utf-8") fragment: str for fragment in test_case.expected_runtime_fragments: assert fragment in runtime_sql diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_lifecycle_commands.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_lifecycle_commands.py index d71e77b767..5b0065a97a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_lifecycle_commands.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_lifecycle_commands.py @@ -29,8 +29,8 @@ "[targets.dev]\n" 'schema = "dev"\n' ), - "seeds/order_statuses.csv": "status_id,status\n1,placed\n", - "seeds/order_statuses.yml": ( + "sql/seeds/order_statuses.csv": "status_id,status\n1,placed\n", + "sql/seeds/order_statuses.yml": ( "seeds:\n" " - name: order_statuses\n" " description: Order statuses.\n" @@ -41,7 +41,7 @@ " - name: status\n" " type: VARCHAR\n" ), - "models/statuses.sql": ( + "sql/models/statuses.sql": ( "MODEL (description 'Statuses.', materialized table, " "columns (status_id (audits [not_null])));\n\n" 'SELECT status_id FROM __seed("order_statuses")\n' @@ -57,7 +57,7 @@ "sqlbuild_project.toml": _UNREACHABLE_WAREHOUSE_FILES["sqlbuild_project.toml"] .replace('adapter = "duckdb"', 'adapter = "duckdb_forbidden"') .replace("missing_directory/nested/orders.duckdb", "orders.duckdb"), - "adapters/duckdb_forbidden.py": ( + "python/adapters/duckdb_forbidden.py": ( "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n\n" "class Forbidden(Exception):\n" " code = 403\n\n\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_loader_watermark_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_loader_watermark_build.py index 5e81489ccf..0611a0306e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_loader_watermark_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_loader_watermark_build.py @@ -44,6 +44,7 @@ def test_given_managed_loader_watermark_when_reloaded_then_incremental_consumes_ repo_files={ "sqlbuild_project.toml": dedent( """ + extra_paths = ["maximum.txt"] name = "loader_watermark_build" adapter = "duckdb" @@ -55,16 +56,16 @@ def test_given_managed_loader_watermark_when_reloaded_then_incremental_consumes_ """ ).strip() + "\n", - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from pathlib import Path\n" "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n maximum = int(Path(__file__).parents[2].joinpath('maximum.txt').read_text())\n" + " '''Test loader raw_orders.'''\n maximum = int(Path(__file__).parents[4].joinpath('maximum.txt').read_text())\n" " return [{'id': value, 'amount': value * 100} " "for value in range(1, maximum + 1)]\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -75,7 +76,7 @@ def test_given_managed_loader_watermark_when_reloaded_then_incremental_consumes_ " - name: amount\n" " type: INTEGER\n" ), - "models/raw_orders_incremental.sql": dedent( + "sql/models/raw_orders_incremental.sql": dedent( """ MODEL (description "Test model raw_orders_incremental.", materialized incremental, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_manifest_artifact_gating.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_manifest_artifact_gating.py index 3e6c5c4d3f..a666a86abc 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_manifest_artifact_gating.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_manifest_artifact_gating.py @@ -40,7 +40,7 @@ def test_given_direct_project_when_building_then_manifest_requires_compile_manif "[connection]\n" 'database = "warehouse.duckdb"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id\n", }, ) manifest_path: Path = project_dir / "target" / "manifest.json" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_materialization_type_change.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_materialization_type_change.py index d1bb294f8f..2bdccf137e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_materialization_type_change.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_materialization_type_change.py @@ -22,7 +22,7 @@ _PROJECT_TOML: str = ( 'name = "orders"\nadapter = "duckdb"\n[connection]\ndatabase = "orders.duckdb"\n' ) -_MODEL_PATH: str = "models/order_totals.sql" +_MODEL_PATH: str = "sql/models/order_totals.sql" _SNAPSHOT_PROJECT_TOML: str = ( 'name = "customers"\nadapter = "duckdb"\n[connection]\ndatabase = "customers.duckdb"\n' '[snapshots]\ncurrent_state_full_refresh = "allow"\n' @@ -117,7 +117,7 @@ def test_given_view_model_when_switched_and_fully_refreshed_then_each_refresh_re project_name="customers_project", repo_files={ "sqlbuild_project.toml": _SNAPSHOT_PROJECT_TOML, - "sources/raw.yml": _RAW_CUSTOMERS_YML, + "sql/sources/raw.yml": _RAW_CUSTOMERS_YML, }, ) import duckdb @@ -128,7 +128,7 @@ def test_given_view_model_when_switched_and_fully_refreshed_then_each_refresh_re "SELECT 1 AS customer_id, 'basic' AS plan, TIMESTAMP '2024-01-01' AS updated_at" ) connection.close() - model_path: Path = project_dir / "models/customer_snapshot.sql" + model_path: Path = project_dir / "sql/models/customer_snapshot.sql" model_path.parent.mkdir(parents=True, exist_ok=True) _ = model_path.write_text( "MODEL (description 'Customer snapshot.', materialized view);\n\n" + _CUSTOMER_SNAPSHOT_SQL, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_aware_cursor_date_input.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_aware_cursor_date_input.py index 0fce894f98..e218da5b82 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_aware_cursor_date_input.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_aware_cursor_date_input.py @@ -27,7 +27,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -42,7 +42,7 @@ """ ).strip() + "\n", - "models/events.sql": dedent( + "sql/models/events.sql": dedent( """ MODEL ( description "Events (web, store or phone); one row per event.", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_batch_progress.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_batch_progress.py index fbc81f53d2..307b09dd80 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_batch_progress.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_batch_progress.py @@ -22,11 +22,11 @@ _DATABASE: str = "warehouse.duckdb" _PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": f'name = "batch_progress"\nadapter = "duckdb"\n\n[connection]\ndatabase = "{_DATABASE}"\n', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/daily_orders.sql": dedent( + "sql/models/daily_orders.sql": dedent( """ MODEL (description "Test model daily_orders.", materialized incremental, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_direct_lifecycle.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_direct_lifecycle.py index 5bd9329e48..af24bc1cdc 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_direct_lifecycle.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_direct_lifecycle.py @@ -55,8 +55,8 @@ def test_given_serial_microbatch_when_building_then_state_table_is_not_used( database_name="serial.duckdb", settings_toml=test_case.settings_toml, ), - "sources/raw.yml": raw_events_source_yml(), - "models/orders.sql": timestamp_microbatch_model_sql( + "sql/sources/raw.yml": raw_events_source_yml(), + "sql/models/orders.sql": timestamp_microbatch_model_sql( value_expression="payload", batch_concurrency=1, replay_policy="forward", @@ -130,8 +130,8 @@ def test_given_integer_cursor_maximum_when_building_then_half_open_batches_inclu database_name="integer_maximum.duckdb", settings_toml=("\n[settings]\nconcurrency = 3\nmicrobatch_concurrency = true\n"), ), - "sources/raw.yml": raw_events_source_yml(), - "models/orders.sql": ( + "sql/sources/raw.yml": raw_events_source_yml(), + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -213,8 +213,8 @@ def test_given_concurrent_ceiling_when_first_run_and_full_refresh_then_target_bo database_name="bootstrap.duckdb", settings_toml=("\n[settings]\nconcurrency = 3\nmicrobatch_concurrency = true\n"), ), - "sources/raw.yml": raw_events_source_yml(), - "models/orders.sql": timestamp_microbatch_model_sql( + "sql/sources/raw.yml": raw_events_source_yml(), + "sql/models/orders.sql": timestamp_microbatch_model_sql( value_expression="payload", batch_concurrency=3, replay_policy="forward", @@ -299,8 +299,8 @@ def test_given_recreated_target_when_building_then_old_completion_generation_is_ database_name="recreated.duckdb", settings_toml="\n[settings]\nmicrobatch_concurrency = true\n", ), - "sources/raw.yml": raw_events_source_yml(), - "models/orders.sql": timestamp_microbatch_model_sql( + "sql/sources/raw.yml": raw_events_source_yml(), + "sql/models/orders.sql": timestamp_microbatch_model_sql( value_expression="payload", batch_concurrency=2, replay_policy="forward", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_failure_windows.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_failure_windows.py index 46aa758a33..0b61f25e66 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_failure_windows.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_failure_windows.py @@ -55,13 +55,13 @@ def test_given_completion_write_failure_during_rebuild_when_retried_then_live_ta 'adapter = "duckdb"', 'adapter = "failing_microbatch_state_duckdb"', ), - "sources/raw.yml": raw_events_source_yml(), - "models/orders.sql": timestamp_microbatch_model_sql( + "sql/sources/raw.yml": raw_events_source_yml(), + "sql/models/orders.sql": timestamp_microbatch_model_sql( value_expression="payload", batch_concurrency=3, replay_policy="forward", ), - "adapters/failing_microbatch_state_duckdb.py": ( + "python/adapters/failing_microbatch_state_duckdb.py": ( "import os\n" "from typing import Any\n" "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n" @@ -170,8 +170,8 @@ def test_given_concurrent_delta_audit_failure_when_fixed_then_rejected_partition database_name="delta_audit_failure.duckdb", settings_toml=("\n[settings]\nconcurrency = 3\nmicrobatch_concurrency = true\n"), ), - "sources/raw.yml": raw_events_source_yml(), - "models/orders.sql": timestamp_microbatch_model_sql( + "sql/sources/raw.yml": raw_events_source_yml(), + "sql/models/orders.sql": timestamp_microbatch_model_sql( value_expression="CAST(payload AS INTEGER)", batch_concurrency=3, replay_policy="forward", @@ -181,7 +181,7 @@ def test_given_concurrent_delta_audit_failure_when_fixed_then_rejected_partition "run_scope delta_and_final,)]," ), ), - "audits/generic/expression_is_true.sql": _AUDIT_SQL, + "sql/audits/generic/expression_is_true.sql": _AUDIT_SQL, }, ) db_path: Path = project_dir / "delta_audit_failure.duckdb" @@ -281,9 +281,9 @@ def test_given_concurrent_batches_when_audit_and_hooks_wrap_model_then_aggregate database_name="aggregate_hooks.duckdb", settings_toml=("\n[settings]\nconcurrency = 3\nmicrobatch_concurrency = true\n"), ), - "sources/raw.yml": raw_events_source_yml(), - "models/orders.sql": model_sql, - "audits/generic/expression_is_true.sql": _AUDIT_SQL, + "sql/sources/raw.yml": raw_events_source_yml(), + "sql/models/orders.sql": model_sql, + "sql/audits/generic/expression_is_true.sql": _AUDIT_SQL, }, ) db_path: Path = project_dir / "aggregate_hooks.duckdb" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_replay_backfill_lifecycle.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_replay_backfill_lifecycle.py index d6ec40454b..df27a132c4 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_replay_backfill_lifecycle.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_replay_backfill_lifecycle.py @@ -219,7 +219,7 @@ def test_given_partial_bounded_replay_and_later_upstream_progress_when_retried_t batch_concurrency=3, replay_policy="bounded-4h", ) - (project_dir / "models" / "orders.sql").write_text(f2_sql, encoding="utf-8") + (project_dir / "sql" / "models" / "orders.sql").write_text(f2_sql, encoding="utf-8") partial: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir ) @@ -312,7 +312,7 @@ def test_given_all_failed_f2_and_f3_when_code_returns_to_f2_then_old_requirement batch_concurrency=3, replay_policy="bounded-2h", ) - model_path: Path = project_dir / "models" / "orders.sql" + model_path: Path = project_dir / "sql" / "models" / "orders.sql" model_path.write_text(f2_sql, encoding="utf-8") failed_f2: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir @@ -378,7 +378,7 @@ def test_given_pending_replay_when_model_is_only_reformatted_then_replay_still_c batch_concurrency=3, replay_policy="bounded-4h", ) - model_path: Path = project_dir / "models" / "orders.sql" + model_path: Path = project_dir / "sql" / "models" / "orders.sql" model_path.write_text(f2_sql, encoding="utf-8") partial: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_mixed_timestamp_grain_replay.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_mixed_timestamp_grain_replay.py index 57fe340b2d..673d32dee1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_mixed_timestamp_grain_replay.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_mixed_timestamp_grain_replay.py @@ -11,6 +11,7 @@ from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import ( MixedTimestampGrainBuildE2ETestCase, ) +from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import take_raw_data_sql from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( prepare_inline_project, query_duckdb, @@ -67,7 +68,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -77,7 +78,7 @@ """ ).strip() + "\n", - "models/staging/stg_orders.sql": dedent( + "sql/models/staging/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized view); @@ -90,7 +91,7 @@ """ ).strip() + "\n", - "models/marts/fact_orders.sql": dedent( + "sql/models/marts/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table); @@ -99,7 +100,7 @@ """ ).strip() + "\n", - "models/marts/hourly_order_activity.sql": dedent( + "sql/models/marts/hourly_order_activity.sql": dedent( """ MODEL (description "Test model hourly_order_activity.", materialized incremental, @@ -126,7 +127,7 @@ """ ).strip() + "\n", - "models/marts/daily_activity_rollup.sql": dedent( + "sql/models/marts/daily_activity_rollup.sql": dedent( """ MODEL (description "Test model daily_activity_rollup.", materialized incremental, @@ -153,7 +154,7 @@ """ ).strip() + "\n", - "models/marts/hourly_activity_with_daily_context.sql": dedent( + "sql/models/marts/hourly_activity_with_daily_context.sql": dedent( """ MODEL (description "Test model hourly_activity_with_daily_context.", materialized incremental, @@ -207,7 +208,7 @@ def test_given_known_current_upstream_when_rerunning_then_cli_uses_consumer_grai import duckdb connection: duckdb.DuckDBPyConnection = duckdb.connect(str(db_path)) - connection.execute((project_dir / "seed_raw_data.sql").read_text(encoding="utf-8")) + connection.execute(take_raw_data_sql(project_dir)) connection.close() initial_result: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_model_backed_cursor_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_model_backed_cursor_build.py index 0975748e5b..5e20fdac53 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_model_backed_cursor_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_model_backed_cursor_build.py @@ -10,6 +10,7 @@ from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import ( ModelBackedCursorBuildE2ETestCase, ) +from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import take_raw_data_sql from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( prepare_inline_project, query_duckdb, @@ -55,7 +56,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -65,7 +66,7 @@ """ ).strip() + "\n", - "models/staging/stg_orders.sql": dedent( + "sql/models/staging/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized view @@ -82,7 +83,7 @@ """ ).strip() + "\n", - "models/marts/fact_orders.sql": dedent( + "sql/models/marts/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table @@ -99,7 +100,7 @@ """ ).strip() + "\n", - "models/intermediate/order_status_index.sql": dedent( + "sql/models/intermediate/order_status_index.sql": dedent( """ MODEL (description "Test model order_status_index.", materialized incremental, @@ -123,7 +124,7 @@ """ ).strip() + "\n", - "models/marts/hourly_order_activity.sql": dedent( + "sql/models/marts/hourly_order_activity.sql": dedent( """ MODEL (description "Test model hourly_order_activity.", materialized incremental, @@ -153,7 +154,7 @@ """ ).strip() + "\n", - "models/marts/fact_orders_view.sql": dedent( + "sql/models/marts/fact_orders_view.sql": dedent( """ MODEL (description "Test model fact_orders_view.", materialized view @@ -213,7 +214,7 @@ def test_given_inline_project_when_building_model_backed_cursor_models_then_it_s import duckdb connection: duckdb.DuckDBPyConnection = duckdb.connect(str(db_path)) - connection.execute((project_dir / "seed_raw_data.sql").read_text(encoding="utf-8")) + connection.execute(take_raw_data_sql(project_dir)) connection.close() result: object = run_sqb(command=test_case.command, project_dir=project_dir) @@ -231,8 +232,14 @@ def test_given_inline_project_when_building_model_backed_cursor_models_then_it_s assert tuple(tuple(row) for row in actual_rows) == expected_rows runtime_sql_paths: tuple[Path, ...] = ( - project_dir / "target" / "run" / "models" / "intermediate" / "order_status_index.sql", - project_dir / "target" / "run" / "models" / "marts" / "hourly_order_activity.sql", + project_dir + / "target" + / "run" + / "sql" + / "models" + / "intermediate" + / "order_status_index.sql", + project_dir / "target" / "run" / "sql" / "models" / "marts" / "hourly_order_activity.sql", ) runtime_sql_path: Path for runtime_sql_path in runtime_sql_paths: @@ -245,7 +252,7 @@ def test_given_inline_project_when_building_model_backed_cursor_models_then_it_s connection.execute("DELETE FROM raw_orders") connection.close() normal_incremental_path: Path = ( - project_dir / "models" / "intermediate" / "order_status_index.sql" + project_dir / "sql" / "models" / "intermediate" / "order_status_index.sql" ) normal_incremental_sql: str = normal_incremental_path.read_text(encoding="utf-8") normal_incremental_path.write_text( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_model_config_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_model_config_build.py index ec9627fe60..4022320ce8 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_model_config_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_model_config_build.py @@ -22,8 +22,8 @@ ) _MART_SCHEMA_ENV_VAR: str = "SQB_MART_SCHEMA" -_INCREMENTAL_MODEL: str = "models/marts/orders_incremental.sql" -_SNAPSHOT_MODEL: str = "models/marts/order_history.sql" +_INCREMENTAL_MODEL: str = "sql/models/marts/orders_incremental.sql" +_SNAPSHOT_MODEL: str = "sql/models/marts/order_history.sql" _PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' @@ -34,12 +34,12 @@ 'schema = "${coalesce(ENV:SQB_MART_SCHEMA, \'marts\')}"\ntags = ["marts"]\n\n' '[path_defaults."staging/*"]\nschema = "staging"\n' ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( 'MODEL (description "Staged orders.");\n\n' "WITH t(order_id, amount, status) AS (VALUES (1, 10, 'placed'), (2, 20, 'shipped'))\n" "SELECT * FROM t\n" ), - "models/marts/order_totals.sql": ( + "sql/models/marts/order_totals.sql": ( 'MODEL (\n description "Order totals for ${CTX:run.target}.",\n' ' alias "${CTX:model.name}_v2",\n tags ["daily"],\n);\n\n' 'SELECT status, SUM(amount) AS total_amount\nFROM __ref("stg_orders")\nGROUP BY status\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_no_load_sources.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_no_load_sources.py index 50529a3f9f..874b1021a8 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_no_load_sources.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_no_load_sources.py @@ -71,17 +71,17 @@ def test_given_loaded_source_when_building_without_loading_then_only_its_audits_ '[connection]\ndatabase = "warehouse.duckdb"\n\n' '[defaults]\nmaterialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n write_strategy: append\n columns:\n" " - name: order_id\n type: INTEGER\n audits: [not_null]\n" ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n\n" "@loader()\ndef raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 1}]\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n" 'SELECT r.order_id FROM __source("raw_orders") AS r\n' ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_node_result_location.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_node_result_location.py index a1a2b0267d..e058349b3c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_node_result_location.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_node_result_location.py @@ -26,6 +26,7 @@ query_duckdb, run_sqb, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _EDGE_CASES: Path = Path("benchmarks/duckshop/edge_cases/loaders") _LOADER: str = ( @@ -41,7 +42,7 @@ " return ctx.result(payload={'announced': True})\n" ) _CHECK: str = ( - "from python.tasks.announce import announce_orders\nfrom sqlbuild.checks import check\n\n\n" + "from python.nodes.tasks.announce.asset import announce_orders\nfrom sqlbuild.checks import check\n\n\n" "@check(depends_on=announce_orders)\n" "def check_orders_announced(ctx):\n" ' """The task announced the orders."""\n' @@ -49,7 +50,7 @@ " return ctx.pass_(message='announced') if announced else ctx.fail(message='silent')\n" ) _COPYING_LOADER: str = ( - "from python.loaders.orders import raw_orders\nfrom sqlbuild.loaders import loader\n\n\n" + "from python.nodes.loaders.orders.loader import raw_orders\nfrom sqlbuild.loaders import loader\n\n\n" "@loader\n" "def raw_order_copies(ctx) -> list[dict[str, object]]:\n" ' """One order when the orders loader has a result to read, none otherwise."""\n' @@ -103,14 +104,14 @@ def test_given_target_location_when_building_and_loading_then_node_results_stay_ tmp_path=tmp_path, target_lines=test_case.target_lines, files={ - "sources/raw.yml": node_result_source_yml(test_case.source_location), - "sources/copies.yml": node_result_source_yml(test_case.source_location).replace( + "sql/sources/raw.yml": node_result_source_yml(test_case.source_location), + "sql/sources/copies.yml": node_result_source_yml(test_case.source_location).replace( "raw_orders", "raw_order_copies" ), - "python/loaders/orders.py": _LOADER, - "python/loaders/copies.py": _COPYING_LOADER, - "python/tasks/announce.py": _TASK, - "python/checks/orders.py": _CHECK, + "python/nodes/loaders/orders/loader.py": _LOADER, + "python/nodes/loaders/copies/loader.py": _COPYING_LOADER, + "python/nodes/tasks/announce/asset.py": _TASK, + "python/nodes/checks/orders/checks.py": _CHECK, }, ) @@ -166,14 +167,18 @@ def test_given_target_location_when_building_and_loading_then_node_results_stay_ PreservedTargetRefusalE2ETestCase( description="a task under a preserved schema needs a loader schema", python_files={ - "python/tasks/announce.py": _TASK.replace('depends_on=source("raw_orders")', "") + "python/nodes/tasks/announce/asset.py": _TASK.replace( + 'depends_on=source("raw_orders")', "" + ) }, expected_error="error[S105]: Target 'dev' keeps each model's own schema", ), PreservedTargetRefusalE2ETestCase( description="a loader schema whose var resolves to empty is no loader schema", python_files={ - "python/tasks/announce.py": _TASK.replace('depends_on=source("raw_orders")', "") + "python/nodes/tasks/announce/asset.py": _TASK.replace( + 'depends_on=source("raw_orders")', "" + ) }, expected_error="error[S105]: Target 'dev' keeps each model's own schema", target_lines='loader_schema = "${results_schema}"\n\n[vars]\nresults_schema = ""\n', @@ -181,7 +186,9 @@ def test_given_target_location_when_building_and_loading_then_node_results_stay_ PreservedTargetRefusalE2ETestCase( description="a loader schema that resolves only inside a model is no loader schema", python_files={ - "python/tasks/announce.py": _TASK.replace('depends_on=source("raw_orders")', "") + "python/nodes/tasks/announce/asset.py": _TASK.replace( + 'depends_on=source("raw_orders")', "" + ) }, expected_error="error[S105]: Target 'dev' keeps each model's own schema", target_lines='loader_schema = "raw_${CTX:model.name}"\n', @@ -202,7 +209,7 @@ def test_given_preserved_schema_without_loader_schema_when_compiling_then_python '[defaults]\nschema = "mart"\n\n[targets.dev]\nschema = "preserve"\n' + test_case.target_lines ), - "models/orders.sql": "MODEL (description 'Orders.');\n\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Orders.');\n\nSELECT 1 AS order_id\n", } | test_case.python_files, ) @@ -244,9 +251,9 @@ def test_given_two_builds_when_planning_then_python_nodes_are_not_new( tmp_path=tmp_path, target_lines=test_case.target_lines, files={ - "sources/raw.yml": node_result_source_yml(" schema: raw\n"), - "python/loaders/orders.py": _LOADER, - "python/tasks/announce.py": _TASK, + "sql/sources/raw.yml": node_result_source_yml(" schema: raw\n"), + "python/nodes/loaders/orders/loader.py": _LOADER, + "python/nodes/tasks/announce/asset.py": _TASK, }, ) for _ in range(2): @@ -282,14 +289,14 @@ def test_given_older_named_schema_results_when_planning_preserved_target_then_lo tmp_path=tmp_path, target_lines=test_case.earlier_target_lines, files={ - "sources/raw.yml": node_result_source_yml(" schema: raw\n"), - "python/loaders/orders.py": _LOADER, - "python/tasks/announce.py": _TASK, - "models/staged_orders.sql": ( + "sql/sources/raw.yml": node_result_source_yml(" schema: raw\n"), + "python/nodes/loaders/orders/loader.py": _LOADER, + "python/nodes/tasks/announce/asset.py": _TASK, + "sql/models/staged_orders.sql": ( "MODEL (description 'Staged orders.', schema \"staging\");\n\n" "SELECT 1 AS order_id\n" ), - "models/raw_order_ids.sql": ( + "sql/models/raw_order_ids.sql": ( "MODEL (description 'Order ids beside the raw data.', schema \"raw\");\n\n" "SELECT 1 AS order_id\n" ), @@ -303,7 +310,7 @@ def test_given_older_named_schema_results_when_planning_preserved_target_then_lo config.write_text( config.read_text().replace(test_case.earlier_target_lines, test_case.target_lines) ) - task: Path = project_dir / "python/tasks/announce.py" + task: Path = project_dir / "python/nodes/tasks/announce/asset.py" task.write_text(task.read_text().replace("'announced': True", "'announced': 1")) for _ in range(2): build: subprocess.CompletedProcess[str] = run_sqb( @@ -344,8 +351,10 @@ def test_given_results_in_the_adapter_default_when_one_loader_rebuilds_then_both 'name = "orders"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' '[connection]\ndatabase = "dev.duckdb"\n\n[targets.dev]\n' ), - "sources/events.yml": (_EDGE_CASES / "loader_results.yml").read_text(), - "python/loaders/events.py": (_EDGE_CASES / "loader_results.py").read_text(), + "sql/sources/events.yml": (_EDGE_CASES / "loader_results.yml").read_text(), + **node_module_files( + "python/nodes/loaders/events.py", (_EDGE_CASES / "loader_results.py").read_text() + ), }, ) db_path: Path = project_dir / "dev.duckdb" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_plan_command_surface.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_plan_command_surface.py index 34de9c9fd4..de2d9be22b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_plan_command_surface.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_plan_command_surface.py @@ -18,7 +18,7 @@ [ PlanCommandBuildE2ETestCase( description="plan select no-color scopes to marts", - command=("--no-color", "plan", "--select", "path:models/marts"), + command=("--no-color", "plan", "--select", "path:sql/models/marts"), expected_exit_code=0, expected_stdout_fragments=( "Plan ready 10 selected", @@ -37,7 +37,7 @@ "--no-color", "plan", "--select", - "/models/marts", + "/sql/models/marts", "--exclude", "hourly_order_activity", ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_check_outcomes.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_check_outcomes.py index ebe2b25d60..0bc7e18211 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_check_outcomes.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_check_outcomes.py @@ -11,6 +11,7 @@ PythonCheckBuildE2ETestCase, ) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -58,15 +59,16 @@ def test_given_python_check_when_building_then_completion_line_reports_its_outco 'name = "python_check_outcomes"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "warehouse.duckdb"\n\n[defaults]\nmaterialized = "table"\n' ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.');\nSELECT 1 AS order_id\n" ), - "python/checks/orders.py": ( + **node_module_files( + "python/nodes/checks/orders.py", "from sqlbuild.checks import check\nfrom sqlbuild.refs import model\n\n\n" f"{test_case.check_decorator}\n" "def orders_checked(ctx):\n" " '''Test check orders_checked.'''\n" - f" {test_case.check_body}\n" + f" {test_case.check_body}\n", ), }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_hooks.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_hooks.py index 88f6db4280..b81edcb008 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_hooks.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_hooks.py @@ -16,6 +16,7 @@ PythonHooksLifecycleMatrixBuildE2ETestCase, SnapshotPythonHooksBuildE2ETestCase, ) +from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import take_raw_data_sql from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( execute_duckdb, prepare_inline_project, @@ -67,7 +68,7 @@ def test_given_python_pre_hook_returns_skip_when_building_then_model_and_downstr """ ).strip() + "\n", - "hooks/python/skips.py": dedent( + "sql/hooks/python/skips.py": dedent( """ from sqlbuild.hooks import hook @@ -79,7 +80,7 @@ def skip_model(ctx): """ ).strip() + "\n", - "models/upstream_orders.sql": dedent( + "sql/models/upstream_orders.sql": dedent( """ MODEL (description "Test model upstream_orders.", materialized table, @@ -90,7 +91,7 @@ def skip_model(ctx): """ ).strip() + "\n", - "models/downstream_orders.sql": dedent( + "sql/models/downstream_orders.sql": dedent( """ MODEL (description "Test model downstream_orders.", materialized table); @@ -152,7 +153,7 @@ def test_given_python_post_hook_skip_when_building_then_keeps_relation_and_skips """ ).strip() + "\n", - "hooks/python/skips.py": dedent( + "sql/hooks/python/skips.py": dedent( """ from sqlbuild.hooks import hook @@ -164,7 +165,7 @@ def skip_downstream(ctx): """ ).strip() + "\n", - "models/upstream_orders.sql": dedent( + "sql/models/upstream_orders.sql": dedent( """ MODEL (description "Test model upstream_orders.", materialized table, @@ -175,7 +176,7 @@ def skip_downstream(ctx): """ ).strip() + "\n", - "models/downstream_orders.sql": dedent( + "sql/models/downstream_orders.sql": dedent( """ MODEL (description "Test model downstream_orders.", materialized table); @@ -240,7 +241,7 @@ def test_given_project_with_python_hooks_when_building_then_hooks_execute( """ ).strip() + "\n", - "hooks/python/lifecycle.py": dedent( + "sql/hooks/python/lifecycle.py": dedent( """ from sqlbuild.hooks import hook @@ -265,7 +266,7 @@ def record_hook_completion(ctx, phase): """ ).strip() + "\n", - "hooks/sql/select_one.sql": dedent( + "sql/hooks/sql/select_one.sql": dedent( """ HOOK (description "Execute a parameterized SQL payload"); @@ -274,7 +275,7 @@ def record_hook_completion(ctx, phase): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -426,7 +427,7 @@ def test_given_python_hooks_lifecycle_matrix_when_building_then_all_materializat """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -440,7 +441,7 @@ def test_given_python_hooks_lifecycle_matrix_when_building_then_all_materializat """ ).strip() + "\n", - "hooks/python/lifecycle.py": dedent( + "sql/hooks/python/lifecycle.py": dedent( """ from sqlbuild.hooks import hook @@ -455,7 +456,7 @@ def log_hook(ctx): """ ).strip() + "\n", - "materializations/copy_table.py": dedent( + "python/materializations/copy_table.py": dedent( """ from sqlbuild.executor.custom.models import ( MaterializationContext, @@ -469,7 +470,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: """ ).strip() + "\n", - "models/staging/stg_orders.sql": dedent( + "sql/models/staging/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized view, @@ -488,7 +489,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: """ ).strip() + "\n", - "models/marts/fact_orders.sql": dedent( + "sql/models/marts/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table, @@ -507,7 +508,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: """ ).strip() + "\n", - "models/intermediate/order_status_index.sql": dedent( + "sql/models/intermediate/order_status_index.sql": dedent( """ MODEL (description "Test model order_status_index.", materialized incremental, @@ -531,7 +532,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: """ ).strip() + "\n", - "models/marts/hourly_order_activity.sql": dedent( + "sql/models/marts/hourly_order_activity.sql": dedent( """ MODEL (description "Test model hourly_order_activity.", materialized incremental, @@ -560,7 +561,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: """ ).strip() + "\n", - "models/snapshots/customer_snapshot.sql": dedent( + "sql/models/snapshots/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -576,7 +577,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: """ ).strip() + "\n", - "models/custom/custom_orders.sql": dedent( + "sql/models/custom/custom_orders.sql": dedent( """ MODEL (description "Test model custom_orders.", materialized copy_table, @@ -594,7 +595,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: db_path: Path = project_dir / "python_hooks_lifecycle_matrix_project.duckdb" execute_duckdb( db_path=db_path, - sql=(project_dir / "seed_raw_data.sql").read_text(encoding="utf-8"), + sql=take_raw_data_sql(project_dir), ) result: subprocess.CompletedProcess[str] = run_sqb( @@ -652,7 +653,7 @@ def test_given_python_post_hook_failure_when_building_graph_then_downstream_is_b """ ).strip() + "\n", - "hooks/python/lifecycle.py": dedent( + "sql/hooks/python/lifecycle.py": dedent( """ from sqlbuild.hooks import hook @@ -664,7 +665,7 @@ def fail_hook(ctx, message): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -675,7 +676,7 @@ def fail_hook(ctx, message): """ ).strip() + "\n", - "models/downstream_orders.sql": dedent( + "sql/models/downstream_orders.sql": dedent( """ MODEL (description "Test model downstream_orders.", materialized table); @@ -724,7 +725,7 @@ def fail_hook(ctx, message): ), expected_present_tables=(), expected_absent_tables=("orders",), - hook_files={"hooks/python/lifecycle.py": _FAIL_HOOK_SOURCE}, + hook_files={"sql/hooks/python/lifecycle.py": _FAIL_HOOK_SOURCE}, ), PythonHookFailureBuildE2ETestCase( description="pre hook failure shows failing SQL hook row", @@ -770,7 +771,7 @@ def test_given_pre_hook_failure_when_building_then_cli_shows_failing_hook_row( ).strip() + "\n", **test_case.hook_files, - "models/orders.sql": test_case.model_sql, + "sql/models/orders.sql": test_case.model_sql, }, ) @@ -823,14 +824,14 @@ def test_given_long_python_hook_name_when_building_then_cli_truncates_label_at_c """ ).strip() + "\n", - "hooks/python/lifecycle.py": ( + "sql/hooks/python/lifecycle.py": ( "from sqlbuild.hooks import hook\n\n\n" "@hook\n" "def publish_customer_metadata_to_external_catalog_after_successful_" "materialization(ctx):\n" ' """Test hook publish_customer_metadata_to_external_catalog_after_successful_materialization."""\n ctx.log.info("long hook ran")\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " materialized table,\n" ' pre_hooks [python("publish_customer_metadata_to_external_catalog_after_' @@ -883,7 +884,7 @@ def test_given_snapshot_with_python_hooks_when_building_then_hooks_execute( """ ).strip() + "\n", - "hooks/python/snapshot_hooks.py": dedent( + "sql/hooks/python/snapshot_hooks.py": dedent( """ from sqlbuild.hooks import hook @@ -908,7 +909,7 @@ def log_snapshot_hook(ctx): """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_node_identity.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_node_identity.py index 6644a71605..0f13afc047 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_node_identity.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_node_identity.py @@ -18,9 +18,12 @@ query_duckdb, run_sqb, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files -_LOADERS_PATH: str = "python/loaders/orders.py" -_ASSETS_PATH: str = "python/assets/exports.py" +_LOADERS_MODULE: str = "python/nodes/loaders/orders.py" +_ASSETS_MODULE: str = "python/nodes/assets/exports.py" +_LOADERS_PATH: str = "python/nodes/loaders/orders/staged_orders/loader.py" +_ASSETS_PATH: str = "python/nodes/assets/exports/export_orders/asset.py" _ORIGINAL_COLUMNS: str = 'LoaderColumnSpec(name="order_id", type="INTEGER")' _ORIGINAL_RETRY: str = "RetryPolicy(max_attempts=2, retry_on=RuntimeError)" @@ -68,8 +71,10 @@ def test_given_built_python_nodes_when_editing_decorator_inputs_then_identity_tr """ ).strip() + "\n", - _LOADERS_PATH: dedent( - f""" + **node_module_files( + _LOADERS_MODULE, + dedent( + f""" from sqlbuild.loaders import LoaderColumnSpec, loader STAGED_ORDER_COLUMNS = [{_ORIGINAL_COLUMNS}] @@ -88,8 +93,9 @@ def raw_orders(ctx): rows = ctx.query(f"SELECT order_id FROM {{staged}}") return [{{"order_id": row[0]}} for row in rows] """ - ).lstrip(), - "sources/raw.yml": dedent( + ).lstrip(), + ), + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -101,8 +107,10 @@ def raw_orders(ctx): type: INTEGER """ ).lstrip(), - _ASSETS_PATH: dedent( - f""" + **node_module_files( + _ASSETS_MODULE, + dedent( + f""" from sqlbuild.assets import asset from sqlbuild.retries import RetryPolicy @@ -114,7 +122,8 @@ def export_orders(ctx): '''Test asset export_orders.''' return None """ - ).lstrip(), + ).lstrip(), + ), }, ) first_build: subprocess.CompletedProcess[str] = run_sqb( @@ -155,7 +164,7 @@ def export_orders(ctx): [ PythonHelperPackageIdentityE2ETestCase( description="relative-import helper edit changes the dependent task identity", - edited_path="python/helpers/clean.py", + edited_path="python/nodes/helpers/clean.py", original_text="value.strip().lower()", edited_text="value.strip().upper()", expected_identity_status="changed", @@ -182,20 +191,25 @@ def test_given_helper_package_with_relative_imports_when_editing_helper_then_tas """ ).strip() + "\n", - "python/helpers/__init__.py": "", - "python/helpers/values.py": 'STATUS = "shipped"\n', - "python/helpers/clean.py": dedent( - """ + "python/nodes/helpers/__init__.py": "", + "python/nodes/helpers/values.py": 'STATUS = "shipped"\n', + **node_module_files( + "python/nodes/helpers/clean.py", + dedent( + """ from .values import STATUS def normalize_status(value): return f"{value.strip().lower()}:{STATUS}" """ - ).lstrip(), - "python/orders.py": dedent( - """ - import python.helpers.clean + ).lstrip(), + ), + **node_module_files( + "python/nodes/orders.py", + dedent( + """ + import python.nodes.helpers.clean from sqlbuild.assets import asset @@ -203,10 +217,11 @@ def normalize_status(value): def orders(ctx): '''Test task orders.''' return ctx.result( - payload={"status": python.helpers.clean.normalize_status(" Shipped ")} + payload={"status": python.nodes.helpers.clean.normalize_status(" Shipped ")} ) """ - ).lstrip(), + ).lstrip(), + ), }, ) first_build: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_source_deferral.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_source_deferral.py index fa8c3e8437..cb7d424f9f 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_source_deferral.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_source_deferral.py @@ -27,15 +27,15 @@ '[targets.dev]\nschema = "dev"\nloader_schema = "raw_dev"\ndefer_sources_to = "prod"\n\n' '[targets.prod]\nschema = "prod"\nloader_schema = "raw_prod"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n managed: true\n write_strategy: table\n" " columns:\n - name: order_id\n type: INTEGER\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from sqlbuild.loaders import loader\n\n\n" "@loader\ndef raw_orders(ctx):\n '''Test loader raw_orders.'''\n return [{'order_id': 9}]\n" ), - "models/sales/_sqlbuild/_hooks/python/count.py": ( + "sql/models/sales/_sqlbuild/_hooks/python/count.py": ( "from sqlbuild.hooks import hook\nfrom sqlbuild.refs import source\n\n\n" '@hook(reads=source("raw_orders"))\n' "def count_raw(ctx):\n" @@ -43,14 +43,14 @@ ' ctx.execute_sql(f"CREATE OR REPLACE TABLE main.hook_counts AS ' 'SELECT count(*) AS n FROM {raw}")\n' ), - "models/sales/order_count.sql": ( + "sql/models/sales/order_count.sql": ( 'MODEL (description "Test model order_count.", materialized table, post_hooks [python("count_raw")]);\n' 'SELECT count(*) AS n FROM __source("raw_orders")\n' ), - "models/sales/order_marker.sql": ( + "sql/models/sales/order_marker.sql": ( 'MODEL (description "Test model order_marker.", materialized table, post_hooks [python("count_raw")]);\nSELECT 1 AS n\n' ), - "python/tasks/count.py": ( + "python/nodes/tasks/count/asset.py": ( "from sqlbuild.refs import source\nfrom sqlbuild.assets import asset\n\n\n" '@asset(depends_on=source("raw_orders"))\n' "def count_task(ctx):\n" @@ -58,7 +58,7 @@ ' ctx.execute_sql(f"CREATE OR REPLACE TABLE main.task_counts AS ' 'SELECT count(*) AS n FROM {raw}")\n' ), - "python/checks/count.py": ( + "python/nodes/checks/count/checks.py": ( "from sqlbuild.checks import check\nfrom sqlbuild.refs import source\n\n\n" '@check(depends_on=source("raw_orders"))\n' "def two_raw_orders(ctx):\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_change_tracking.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_change_tracking.py index 9e5516efd8..73e1e30e96 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_change_tracking.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_change_tracking.py @@ -13,6 +13,7 @@ from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import ( QueryChangeTrackingBuildE2ETestCase, ) +from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import take_raw_data_sql from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( execute_duckdb, prepare_inline_project, @@ -35,7 +36,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -45,7 +46,7 @@ """ ).strip() + "\n", - "models/stg_orders.sql": dedent( + "sql/models/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders."); @@ -53,7 +54,7 @@ """ ).strip() + "\n", - "models/fact_orders.sql": dedent( + "sql/models/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders."); @@ -98,7 +99,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -108,7 +109,7 @@ """ ).strip() + "\n", - "models/staging/stg_orders.sql": dedent( + "sql/models/staging/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized view @@ -123,7 +124,7 @@ """ ).strip() + "\n", - "models/marts/fact_orders.sql": dedent( + "sql/models/marts/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table @@ -162,7 +163,7 @@ def test_given_unchanged_project_when_planning_after_build_then_models_are_not_q import duckdb connection: duckdb.DuckDBPyConnection = duckdb.connect(str(db_path)) - connection.execute((project_dir / "seed_raw_data.sql").read_text(encoding="utf-8")) + connection.execute(take_raw_data_sql(project_dir)) connection.close() build_result: subprocess.CompletedProcess[str] = run_sqb( @@ -276,7 +277,7 @@ def test_given_hashes_from_older_fingerprint_scheme_when_rebuilding_then_only_ed db_path=db_path, sql="UPDATE main._sqlbuild_fingerprints SET definition_hash = 'older-scheme-' || node_name", ) - edited_model: Path = project_dir / "models" / "fact_orders.sql" + edited_model: Path = project_dir / "sql" / "models" / "fact_orders.sql" edited_model.write_text( edited_model.read_text(encoding="utf-8").replace("line_total_cents", "total_cents"), encoding="utf-8", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_fingerprint_changes.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_fingerprint_changes.py index fd2b83ab95..cf70492b9b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_fingerprint_changes.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_fingerprint_changes.py @@ -25,18 +25,18 @@ '[connection]\ndatabase = "fingerprint.duckdb"\n\n' '[defaults]\nmaterialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n schema: main\n table: raw_orders\n" ), - "functions/sql/is_large_order.sql": ( + "sql/functions/sql/is_large_order.sql": ( "FUNCTION (description 'Test function is_large_order.', arguments (amount_cents INTEGER), returns BOOLEAN);\n\namount_cents > 100\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\n" "SELECT id AS order_id, amount_cents, 'web order' AS channel\n" 'FROM __source("raw_orders")\n' ), - "models/large_orders.sql": ( + "sql/models/large_orders.sql": ( "MODEL (description 'Test model large_orders.', materialized table);\n\n" "SELECT order_id, is_large_order(amount_cents) AS is_large\n" 'FROM __ref("stg_orders")\n' @@ -64,8 +64,12 @@ QueryFingerprintEditE2ETestCase( description="comment and keyword case edits are unchanged", edits=( - ("models/stg_orders.sql", "SELECT id", "-- Staged orders.\nselect id"), - ("functions/sql/is_large_order.sql", "amount_cents > 100", "amount_cents > 100"), + ("sql/models/stg_orders.sql", "SELECT id", "-- Staged orders.\nselect id"), + ( + "sql/functions/sql/is_large_order.sql", + "amount_cents > 100", + "amount_cents > 100", + ), ), format_flags=("--check",), expected_format_summary="3 files checked, 3 changed", @@ -73,14 +77,14 @@ ), QueryFingerprintEditE2ETestCase( description="whitespace inside a string literal is a query change", - edits=(("models/stg_orders.sql", "'web order'", "'web order'"),), + edits=(("sql/models/stg_orders.sql", "'web order'", "'web order'"),), format_flags=("--check",), expected_format_summary="3 files checked, 2 changed", expected_reasons={"stg_orders": "query_changed"}, ), QueryFingerprintEditE2ETestCase( description="identifier case is a query change", - edits=(("models/large_orders.sql", "AS is_large", "AS Is_Large"),), + edits=(("sql/models/large_orders.sql", "AS is_large", "AS Is_Large"),), format_flags=("--check",), expected_format_summary="3 files checked, 2 changed", expected_reasons={"stg_orders": "no_change", "large_orders": "query_changed"}, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_propagation.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_propagation.py index a8136a594a..4274846555 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_propagation.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_query_propagation.py @@ -12,6 +12,7 @@ from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import ( QueryPropagationBuildE2ETestCase, ) +from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import take_raw_data_sql from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( prepare_inline_project, query_duckdb, @@ -52,7 +53,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -62,7 +63,7 @@ """ ).strip() + "\n", - "models/staging/stg_orders.sql": dedent( + "sql/models/staging/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized view); @@ -70,7 +71,7 @@ """ ).strip() + "\n", - "models/marts/fact_orders.sql": dedent( + "sql/models/marts/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table); @@ -79,7 +80,7 @@ """ ).strip() + "\n", - "models/marts/hourly_order_activity.sql": dedent( + "sql/models/marts/hourly_order_activity.sql": dedent( """ MODEL (description "Test model hourly_order_activity.", materialized incremental, @@ -105,7 +106,7 @@ """ ).strip() + "\n", - "models/marts/daily_activity_rollup.sql": dedent( + "sql/models/marts/daily_activity_rollup.sql": dedent( """ MODEL (description "Test model daily_activity_rollup.", materialized incremental, @@ -135,7 +136,7 @@ }, initial_build_command=("--no-color", "build"), plan_command=("plan", "--json"), - mutation_file="models/marts/hourly_order_activity.sql", + mutation_file="sql/models/marts/hourly_order_activity.sql", before_text="SUM(line_total_cents) AS revenue_cents", after_text="SUM(line_total_cents) + 0 AS revenue_cents", expected_exit_code=0, @@ -176,7 +177,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -186,7 +187,7 @@ """ ).strip() + "\n", - "functions/sql/is_high_value_order.sql": dedent( + "sql/functions/sql/is_high_value_order.sql": dedent( """ FUNCTION (description "Test function is_high_value_order.", arguments (amount_cents INTEGER), @@ -197,7 +198,7 @@ """ ).strip() + "\n", - "models/fact_orders.sql": dedent( + "sql/models/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized incremental, @@ -222,7 +223,7 @@ }, initial_build_command=("--no-color", "build"), plan_command=("plan", "--json"), - mutation_file="functions/sql/is_high_value_order.sql", + mutation_file="sql/functions/sql/is_high_value_order.sql", before_text="amount_cents > 100", after_text="amount_cents >= 100", expected_exit_code=0, @@ -260,7 +261,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -270,7 +271,7 @@ """ ).strip() + "\n", - "models/staging/stg_orders.sql": dedent( + "sql/models/staging/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized view); @@ -278,7 +279,7 @@ """ ).strip() + "\n", - "models/marts/fact_orders.sql": dedent( + "sql/models/marts/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table); @@ -287,7 +288,7 @@ """ ).strip() + "\n", - "models/marts/hourly_order_activity.sql": dedent( + "sql/models/marts/hourly_order_activity.sql": dedent( """ MODEL (description "Test model hourly_order_activity.", materialized incremental, @@ -314,7 +315,7 @@ """ ).strip() + "\n", - "models/marts/daily_activity_rollup.sql": dedent( + "sql/models/marts/daily_activity_rollup.sql": dedent( """ MODEL (description "Test model daily_activity_rollup.", materialized incremental, @@ -344,7 +345,7 @@ }, initial_build_command=("--no-color", "build"), plan_command=("plan", "--json"), - mutation_file="models/marts/hourly_order_activity.sql", + mutation_file="sql/models/marts/hourly_order_activity.sql", before_text="SUM(line_total_cents) AS revenue_cents", after_text="SUM(line_total_cents) + 0 AS revenue_cents", expected_exit_code=0, @@ -376,7 +377,7 @@ def test_given_changed_upstream_when_planning_then_downstream_reason_matches_pol import duckdb connection: duckdb.DuckDBPyConnection = duckdb.connect(str(db_path)) - connection.execute((project_dir / "seed_raw_data.sql").read_text(encoding="utf-8")) + connection.execute(take_raw_data_sql(project_dir)) connection.close() initial_result: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_quoted_mixed_case_columns.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_quoted_mixed_case_columns.py index d74ce1b65b..d32155f427 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_quoted_mixed_case_columns.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_quoted_mixed_case_columns.py @@ -25,19 +25,19 @@ "sqlbuild_project.toml": ( 'name = "partner_feed"\nadapter = "duckdb"\n\n[connection]\ndatabase = "partner_feed.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_listings\n description: Partner listings in quoted camelCase.\n" " schema: main\n table: raw_listings\n columns:\n" " - name: '\"listingId\"'\n type: VARCHAR\n" " - name: '\"unitPriceMinor\"'\n type: BIGINT\n" ), - "models/stg_listings.sql": ( + "sql/models/stg_listings.sql": ( "MODEL (description 'Listings renamed to snake case.', materialized table);\n\n" 'SELECT s."listingId" AS listing_id, s."unitPriceMinor" AS unit_price_minor\n' 'FROM __source("raw_listings") AS s\n' ), - "models/listing_export.sql": ( + "sql/models/listing_export.sql": ( "MODEL (\n description 'Listings in the partner feed format.',\n materialized table,\n" " columns (\n" ' "listingId" (type VARCHAR, nullable false, audits [not_null, unique]),\n' @@ -136,7 +136,7 @@ def test_given_enforced_contract_on_quoted_alias_when_building_then_contract_and project_name="partner_feed", repo_files={ **_PROJECT_FILES, - "models/listing_export.sql": ( + "sql/models/listing_export.sql": ( "MODEL (\n description 'Listings in the partner feed format.',\n" " materialized table,\n contract enforced,\n" f" columns ({test_case.declared_name} (type VARCHAR),),\n);\n\n" @@ -188,20 +188,20 @@ def test_given_quoted_configured_columns_when_building_twice_then_snapshot_and_b project_name="partner_feed", repo_files={ "sqlbuild_project.toml": _PROJECT_FILES["sqlbuild_project.toml"], - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_listings\n description: Partner listings.\n" " schema: main\n table: raw_listings\n" " - name: raw_listing_events\n description: Partner listing events.\n" " schema: main\n table: raw_listing_events\n" ), - "models/listing_history.sql": ( + "sql/models/listing_history.sql": ( "MODEL (\n description 'Listing price history.',\n materialized snapshot,\n" f" unique_key [{test_case.unique_key}],\n snapshot_strategy timestamp,\n" " updated_at '\"updatedAt\"',\n);\n\n" 'SELECT "listingId", "unitPriceMinor", "updatedAt" FROM __source("raw_listings")\n' ), - "models/listing_activity.sql": ( + "sql/models/listing_activity.sql": ( "MODEL (\n description 'Listing events by hour.',\n materialized incremental,\n" " incremental_strategy delete_insert,\n incremental_mode microbatch,\n" " microbatch_strategy watermark,\n cursor_watermark_mode all,\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_remove_column_semantics.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_remove_column_semantics.py index 12bfbf338a..ad00e80553 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_remove_column_semantics.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_remove_column_semantics.py @@ -22,7 +22,7 @@ description=( "remove column mutation reports query_changed for non-enforced output change" ), - mutate_file="models/intermediate/order_status_index.sql", + mutate_file="sql/models/intermediate/order_status_index.sql", before_text=" ordered_at,\n", after_text="", command=( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_replay_on_change_full_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_replay_on_change_full_build.py index a59402a92c..57b920c1d6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_replay_on_change_full_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_replay_on_change_full_build.py @@ -37,7 +37,7 @@ database = "replay.duckdb" """ ).lstrip(), - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -46,8 +46,8 @@ table: raw_orders """ ).lstrip(), - "models/order_regions.sql": "MODEL (description 'Test model order_regions.', materialized table);\n\nSELECT 1 AS region_id\n", - "models/stg_orders.sql": dedent( + "sql/models/order_regions.sql": "MODEL (description 'Test model order_regions.', materialized table);\n\nSELECT 1 AS region_id\n", + "sql/models/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized incremental, @@ -172,7 +172,7 @@ ReplayFullRebuildE2ETestCase( description="planner_resolved_model_backed_input_with_added_unlisted_ref", target_table="daily_orders", - changed_model_path="models/daily_orders.sql", + changed_model_path="sql/models/daily_orders.sql", changed_model_sql=_DAILY_ORDERS_WITH_UNLISTED_REF_SQL, rebuild_command=("--select", "daily_orders"), expected_plan_fragments=( @@ -186,7 +186,7 @@ ReplayFullRebuildE2ETestCase( description="runtime_owned_bounds_when_upstream_incremental_runs_in_same_build", target_table="daily_orders", - changed_model_path="models/daily_orders.sql", + changed_model_path="sql/models/daily_orders.sql", changed_model_sql=_DAILY_ORDERS_WITH_UNLISTED_REF_SQL, rebuild_command=(), expected_plan_fragments=( @@ -198,7 +198,7 @@ ReplayFullRebuildE2ETestCase( description="query_change_without_cursor_inputs", target_table="source_orders", - changed_model_path="models/source_orders.sql", + changed_model_path="sql/models/source_orders.sql", changed_model_sql=_SOURCE_ORDERS_SQL.format(revision=2), rebuild_command=("--select", "source_orders"), expected_plan_fragments=( @@ -210,7 +210,7 @@ ReplayFullRebuildE2ETestCase( description="microbatch_model", target_table="microbatch_orders", - changed_model_path="models/microbatch_orders.sql", + changed_model_path="sql/models/microbatch_orders.sql", changed_model_sql=_MICROBATCH_ORDERS_SQL.format(revision=2), rebuild_command=("--select", "microbatch_orders"), expected_plan_fragments=( @@ -231,9 +231,9 @@ def test_given_existing_incremental_when_replay_on_change_full_rebuilds_then_his project_name="replay_full_project", repo_files={ **_BASE_FILES, - "models/daily_orders.sql": _DAILY_ORDERS_SQL, - "models/source_orders.sql": _SOURCE_ORDERS_SQL.format(revision=1), - "models/microbatch_orders.sql": _MICROBATCH_ORDERS_SQL.format(revision=1), + "sql/models/daily_orders.sql": _DAILY_ORDERS_SQL, + "sql/models/source_orders.sql": _SOURCE_ORDERS_SQL.format(revision=1), + "sql/models/microbatch_orders.sql": _MICROBATCH_ORDERS_SQL.format(revision=1), }, ) db_path: Path = project_dir / "replay.duckdb" @@ -263,9 +263,9 @@ def test_given_existing_incremental_when_replay_on_change_full_rebuilds_then_his project_name="fresh_replay_project", repo_files={ **_BASE_FILES, - "models/daily_orders.sql": _DAILY_ORDERS_SQL, - "models/source_orders.sql": _SOURCE_ORDERS_SQL.format(revision=1), - "models/microbatch_orders.sql": _MICROBATCH_ORDERS_SQL.format(revision=1), + "sql/models/daily_orders.sql": _DAILY_ORDERS_SQL, + "sql/models/source_orders.sql": _SOURCE_ORDERS_SQL.format(revision=1), + "sql/models/microbatch_orders.sql": _MICROBATCH_ORDERS_SQL.format(revision=1), test_case.changed_model_path: test_case.changed_model_sql, }, ) @@ -323,14 +323,14 @@ def test_given_window_limited_run_when_building_existing_incremental_then_only_w project_name="replay_window_project", repo_files={ **_BASE_FILES, - "models/windowed_orders.sql": _WINDOWED_ORDERS_SQL.format(revision=1), + "sql/models/windowed_orders.sql": _WINDOWED_ORDERS_SQL.format(revision=1), }, ) db_path: Path = project_dir / "replay.duckdb" execute_duckdb(db_path=db_path, sql=_SOURCE_ROWS_SQL) run_replay_command(command=("build",), project_dir=project_dir) - (project_dir / "models" / "windowed_orders.sql").write_text( + (project_dir / "sql" / "models" / "windowed_orders.sql").write_text( test_case.changed_model_sql, encoding="utf-8" ) execute_duckdb(db_path=db_path, sql=test_case.source_mutation_sql) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_reusable_model_schemas.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_reusable_model_schemas.py index 16e872ba43..e7025f7198 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_reusable_model_schemas.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_reusable_model_schemas.py @@ -43,7 +43,7 @@ def test_given_reusable_inherited_schemas_when_building_then_all_materialization """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -53,7 +53,7 @@ def test_given_reusable_inherited_schemas_when_building_then_all_materialization """ ).strip() + "\n", - "schemas/events/base.sql": dedent( + "sql/schemas/events/base.sql": dedent( """ SCHEMA (description "Test schema.", name event, @@ -65,7 +65,7 @@ def test_given_reusable_inherited_schemas_when_building_then_all_materialization """ ).strip() + "\n", - "schemas/events/sourced.sql": dedent( + "sql/schemas/events/sourced.sql": dedent( """ SCHEMA (description "Test schema.", name sourced_event, @@ -77,7 +77,7 @@ def test_given_reusable_inherited_schemas_when_building_then_all_materialization """ ).strip() + "\n", - "models/stg_events.sql": dedent( + "sql/models/stg_events.sql": dedent( """ MODEL ( materialized view, @@ -92,7 +92,7 @@ def test_given_reusable_inherited_schemas_when_building_then_all_materialization """ ).strip() + "\n", - "models/event_table.sql": dedent( + "sql/models/event_table.sql": dedent( """ MODEL ( materialized table, @@ -108,7 +108,7 @@ def test_given_reusable_inherited_schemas_when_building_then_all_materialization """ ).strip() + "\n", - "models/event_incremental.sql": dedent( + "sql/models/event_incremental.sql": dedent( """ MODEL ( materialized incremental, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_runtime_artifact_preservation.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_runtime_artifact_preservation.py index 23b64d7332..9f736269d6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_runtime_artifact_preservation.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_runtime_artifact_preservation.py @@ -23,22 +23,22 @@ RuntimeArtifactPreservationBuildE2ETestCase( description="full build then selected rerun preserves existing runtime artifacts", initial_command=("--no-color", "build"), - rerun_command=("--no-color", "build", "--select", "/models/marts"), + rerun_command=("--no-color", "build", "--select", "/sql/models/marts"), expected_runtime_paths=( - "target/run/models/staging/stg_orders.sql", - "target/run/models/intermediate/customer_status_snapshot.sql", - "target/run/models/marts/hourly_order_activity.sql", - "target/run/models/marts/hourly_activity_with_daily_context.sql", - "target/run/functions/sql/is_completed_order.sql", - "target/run/functions/python/is_completed_order_py.sql", + "target/run/sql/models/staging/stg_orders.sql", + "target/run/sql/models/intermediate/customer_status_snapshot.sql", + "target/run/sql/models/marts/hourly_order_activity.sql", + "target/run/sql/models/marts/hourly_activity_with_daily_context.sql", + "target/run/sql/functions/sql/is_completed_order.sql", + "target/run/sql/functions/python/is_completed_order_py.sql", ), expected_exit_code=0, expected_compiler_cache_count=1, expected_local_history=False, expected_compiled_paths=( - "target/compiled/models/marts/fact_orders.sql", - "target/compiled/functions/sql/is_completed_order.sql", - "target/compiled/functions/python/is_completed_order_py.sql", + "target/compiled/sql/models/marts/fact_orders.sql", + "target/compiled/sql/functions/sql/is_completed_order.sql", + "target/compiled/sql/functions/python/is_completed_order_py.sql", ), ) ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_schema_backfill_behavior.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_schema_backfill_behavior.py index 5a35f0df47..e912e4c1f7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_schema_backfill_behavior.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_schema_backfill_behavior.py @@ -22,10 +22,10 @@ [ SchemaBackfillBuildE2ETestCase( description="add column mutation reports bounded schema backfill", - mutate_model_file="models/intermediate/order_status_index.sql", + mutate_model_file="sql/models/intermediate/order_status_index.sql", model_before_text="on_schema_change append_new_columns", model_after_text="on_schema_change append_new_columns", - mutate_schema_file="models/intermediate/order_status_index.sql", + mutate_schema_file="sql/models/intermediate/order_status_index.sql", schema_before_text=" columns (\n order_id (audits [not_null, unique]),\n ),", schema_after_text=( " columns (\n" @@ -43,10 +43,10 @@ ), SchemaBackfillBuildE2ETestCase( description="add column mutation with on_schema_change fail reports error warning", - mutate_model_file="models/intermediate/order_status_index.sql", + mutate_model_file="sql/models/intermediate/order_status_index.sql", model_before_text="on_schema_change append_new_columns", model_after_text="on_schema_change fail", - mutate_schema_file="models/intermediate/order_status_index.sql", + mutate_schema_file="sql/models/intermediate/order_status_index.sql", schema_before_text=" columns (\n order_id (audits [not_null, unique]),\n ),", schema_after_text=( " columns (\n" @@ -66,10 +66,10 @@ ), SchemaBackfillBuildE2ETestCase( description="add column mutation with on_schema_change ignore reports info warning", - mutate_model_file="models/intermediate/order_status_index.sql", + mutate_model_file="sql/models/intermediate/order_status_index.sql", model_before_text="on_schema_change append_new_columns", model_after_text="on_schema_change ignore", - mutate_schema_file="models/intermediate/order_status_index.sql", + mutate_schema_file="sql/models/intermediate/order_status_index.sql", schema_before_text=" columns (\n order_id (audits [not_null, unique]),\n ),", schema_after_text=( " columns (\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_scoped_declarations.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_scoped_declarations.py index 3f23f0de51..9fa52c430d 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_scoped_declarations.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_scoped_declarations.py @@ -37,24 +37,24 @@ "sqlbuild_project.toml": ( 'name = "scoped_shop"\nadapter = "duckdb"\n\n[connection]\ndatabase = "scoped_shop.duckdb"\n' ), - "models/marts/daily/orders.sql": _MART_MODEL, - "models/marts/weekly/orders_weekly.sql": _MART_MODEL, - "models/marts/_sqlbuild/schemas/order_shape.sql": ( + "sql/models/marts/daily/orders.sql": _MART_MODEL, + "sql/models/marts/weekly/orders_weekly.sql": _MART_MODEL, + "sql/models/marts/_sqlbuild/schemas/order_shape.sql": ( "SCHEMA (description 'Test schema.', name order_shape, columns (order_id (type INTEGER, nullable false)));\n" ), - "models/marts/_sqlbuild/audits/generic/order_check.sql": ( + "sql/models/marts/_sqlbuild/audits/generic/order_check.sql": ( 'AUDIT ();\n\nSELECT order_id FROM __ref("@model") WHERE order_id IS NULL\n' ), - "models/marts/_sqlbuild/audits/singular/orders_match_weekly.sql": ( + "sql/models/marts/_sqlbuild/audits/singular/orders_match_weekly.sql": ( 'AUDIT (name "orders_match_weekly", severity error);\n\n' 'SELECT d.order_id FROM __ref("orders") d\n' 'LEFT JOIN __ref("orders_weekly") w USING (order_id)\n' "WHERE w.order_id IS NULL\n" ), - "models/marts/_sqlbuild/hooks/sql/record_start.sql": ( + "sql/models/marts/_sqlbuild/hooks/sql/record_start.sql": ( "HOOK (description 'Test hook record_start.');\n\nINSERT INTO main.hook_log VALUES ('sql')\n" ), - "models/marts/_sqlbuild/hooks/python/lifecycle.py": ( + "sql/models/marts/_sqlbuild/hooks/python/lifecycle.py": ( "from sqlbuild.hooks import hook\n\n\n" "@hook\n" "def record_finish(ctx):\n" @@ -128,12 +128,12 @@ def test_given_scoped_declarations_when_building_then_schema_hooks_and_audits_ap [ ScopedDeclarationScopeE2ETestCase( description="scope report lists scoped schema, hooks, and generic audit as used", - target="models/marts/daily/orders.sql", + target="sql/models/marts/daily/orders.sql", expected_fragments=( - "audit:order_check models/marts/_sqlbuild/audits/generic/order_check.sql", - "python_hook:record_finish models/marts/_sqlbuild/hooks/python/lifecycle.py", - "schema:order_shape models/marts/_sqlbuild/schemas/order_shape.sql", - "sql_hook:record_start models/marts/_sqlbuild/hooks/sql/record_start.sql", + "audit:order_check sql/models/marts/_sqlbuild/audits/generic/order_check.sql", + "python_hook:record_finish sql/models/marts/_sqlbuild/hooks/python/lifecycle.py", + "schema:order_shape sql/models/marts/_sqlbuild/schemas/order_shape.sql", + "sql_hook:record_start sql/models/marts/_sqlbuild/hooks/sql/record_start.sql", ), ) ], @@ -189,9 +189,9 @@ def test_given_seed_audit_when_building_then_it_runs_after_load_and_gates_depend 'name = "seed_audit_shop"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "seed_audit_shop.duckdb"\n' ), - "seeds/order_codes.yml": _SEED_YAML, - "seeds/order_codes.csv": test_case.seed_csv, - "models/coded_orders.sql": ( + "sql/seeds/order_codes.yml": _SEED_YAML, + "sql/seeds/order_codes.csv": test_case.seed_csv, + "sql/models/coded_orders.sql": ( 'MODEL (description "Test model coded_orders.", materialized table);\n\nSELECT order_id, label FROM __seed("order_codes")\n' ), }, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_seed_watermark_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_seed_watermark_build.py index f8fda505f0..4b56e1306a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_seed_watermark_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_seed_watermark_build.py @@ -55,7 +55,7 @@ def test_given_seed_watermark_when_seed_changes_then_incremental_consumes_new_hi """ ).strip() + "\n", - "seeds/schema.yml": ( + "sql/seeds/schema.yml": ( "seeds:\n" " - name: order_events\n description: Test seed order_events.\n" " columns:\n" @@ -64,8 +64,8 @@ def test_given_seed_watermark_when_seed_changes_then_incremental_consumes_new_hi " - name: amount\n" " type: INTEGER\n" ), - "seeds/order_events.csv": test_case.initial_seed, - "models/order_events_incremental.sql": dedent( + "sql/seeds/order_events.csv": test_case.initial_seed, + "sql/models/order_events_incremental.sql": dedent( """ MODEL (description "Test model order_events_incremental.", materialized incremental, @@ -101,7 +101,7 @@ def test_given_seed_watermark_when_seed_changes_then_incremental_consumes_new_hi assert plan_result.returncode == 0, plan_result.stdout + plan_result.stderr assert test_case.expected_plan_bounds in plan_result.stdout, plan_result.stdout - (project_dir / "seeds" / "order_events.csv").write_text( + (project_dir / "sql" / "seeds" / "order_events.csv").write_text( test_case.changed_seed, encoding="utf-8" ) changed_result: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_selector_surface.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_selector_surface.py index 69ec9e5be0..ab5053a929 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_selector_surface.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_selector_surface.py @@ -23,7 +23,7 @@ [ SelectorSurfaceBuildE2ETestCase( description="slash path selector works on build", - command=("--no-color", "build", "--select", "/models/marts"), + command=("--no-color", "build", "--select", "/sql/models/marts"), expected_exit_code=0, expected_stdout_fragments=( "Plan ready 10 selected", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_snapshot_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_snapshot_build.py index cac6c592c4..020d175108 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_snapshot_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_snapshot_build.py @@ -99,7 +99,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -109,7 +109,7 @@ """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -123,7 +123,7 @@ """ ).strip() + "\n", - "models/current_customer_plans.sql": dedent( + "sql/models/current_customer_plans.sql": dedent( """ MODEL (description "Test model current_customer_plans.", materialized table); @@ -286,7 +286,7 @@ def test_given_snapshot_selector_when_excluding_downstream_then_only_snapshot_bu """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -296,7 +296,7 @@ def test_given_snapshot_selector_when_excluding_downstream_then_only_snapshot_bu """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -387,7 +387,7 @@ def test_given_snapshot_hooks_when_building_then_hooks_execute_and_history_is_va """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_current_customers @@ -409,7 +409,7 @@ def test_given_snapshot_hooks_when_building_then_hooks_execute_and_history_is_va """ ).strip() + "\n", - "models/current_hard_delete_snapshot.sql": dedent( + "sql/models/current_hard_delete_snapshot.sql": dedent( """ MODEL (description "Test model current_hard_delete_snapshot.", materialized snapshot, @@ -424,7 +424,7 @@ def test_given_snapshot_hooks_when_building_then_hooks_execute_and_history_is_va """ ).strip() + "\n", - "models/historical_out_of_order_snapshot.sql": dedent( + "sql/models/historical_out_of_order_snapshot.sql": dedent( """ MODEL (description "Test model historical_out_of_order_snapshot.", materialized snapshot, @@ -440,7 +440,7 @@ def test_given_snapshot_hooks_when_building_then_hooks_execute_and_history_is_va """ ).strip() + "\n", - "models/initial_updated_at_snapshot.sql": dedent( + "sql/models/initial_updated_at_snapshot.sql": dedent( """ MODEL (description "Test model initial_updated_at_snapshot.", materialized snapshot, @@ -455,7 +455,7 @@ def test_given_snapshot_hooks_when_building_then_hooks_execute_and_history_is_va """ ).strip() + "\n", - "models/audited_customer_snapshot.sql": dedent( + "sql/models/audited_customer_snapshot.sql": dedent( """ MODEL (description "Test model audited_customer_snapshot.", materialized snapshot, @@ -477,7 +477,7 @@ def test_given_snapshot_hooks_when_building_then_hooks_execute_and_history_is_va """ ).strip() + "\n", - "audits/generic/expression_is_true.sql": dedent( + "sql/audits/generic/expression_is_true.sql": dedent( """ AUDIT (); @@ -674,7 +674,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -684,7 +684,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -748,7 +748,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -758,7 +758,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -828,7 +828,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -838,7 +838,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -858,7 +858,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "audits/generic/expression_is_true.sql": dedent( + "sql/audits/generic/expression_is_true.sql": dedent( """ AUDIT (); @@ -923,7 +923,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -933,7 +933,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -955,7 +955,7 @@ def test_given_advanced_snapshot_edges_when_building_then_history_remains_valid( """ ).strip() + "\n", - "audits/generic/expression_is_true.sql": dedent( + "sql/audits/generic/expression_is_true.sql": dedent( """ AUDIT (); @@ -1098,7 +1098,7 @@ def test_given_snapshot_failure_when_building_then_history_remains_consistent( """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_current_timestamp_customers @@ -1120,7 +1120,7 @@ def test_given_snapshot_failure_when_building_then_history_remains_consistent( """ ).strip() + "\n", - "models/customer_plan_timestamp_snapshot.sql": dedent( + "sql/models/customer_plan_timestamp_snapshot.sql": dedent( """ MODEL (description "Test model customer_plan_timestamp_snapshot.", materialized snapshot, @@ -1134,7 +1134,7 @@ def test_given_snapshot_failure_when_building_then_history_remains_consistent( """ ).strip() + "\n", - "models/customer_status_check_snapshot.sql": dedent( + "sql/models/customer_status_check_snapshot.sql": dedent( """ MODEL (description "Test model customer_status_check_snapshot.", materialized snapshot, @@ -1148,7 +1148,7 @@ def test_given_snapshot_failure_when_building_then_history_remains_consistent( """ ).strip() + "\n", - "models/customer_plan_historical_snapshot.sql": dedent( + "sql/models/customer_plan_historical_snapshot.sql": dedent( """ MODEL (description "Test model customer_plan_historical_snapshot.", materialized snapshot, @@ -1164,7 +1164,7 @@ def test_given_snapshot_failure_when_building_then_history_remains_consistent( """ ).strip() + "\n", - "models/customer_plan_change_records_snapshot.sql": dedent( + "sql/models/customer_plan_change_records_snapshot.sql": dedent( """ MODEL (description "Test model customer_plan_change_records_snapshot.", materialized snapshot, @@ -1524,10 +1524,15 @@ def test_given_shallow_waffle_shop_snapshots_when_sources_change_then_cli_reruns "customer_plan_change_records_snapshot", ): compiled_path: Path = ( - project_dir / "target" / "compiled" / "models" / (f"{snapshot_artifact_name}.sql") + project_dir + / "target" + / "compiled" + / "sql" + / "models" + / (f"{snapshot_artifact_name}.sql") ) run_path: Path = ( - project_dir / "target" / "run" / "models" / (f"{snapshot_artifact_name}.sql") + project_dir / "target" / "run" / "sql" / "models" / (f"{snapshot_artifact_name}.sql") ) assert compiled_path.exists(), f"expected compiled snapshot artifact: {compiled_path}" assert run_path.exists(), f"expected run snapshot artifact: {run_path}" @@ -1570,7 +1575,7 @@ def test_given_shallow_waffle_shop_snapshots_when_sources_change_then_cli_reruns """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_regions @@ -1592,7 +1597,7 @@ def test_given_shallow_waffle_shop_snapshots_when_sources_change_then_cli_reruns """ ).strip() + "\n", - "models/customer_region_custom_snapshot.sql": dedent( + "sql/models/customer_region_custom_snapshot.sql": dedent( """ MODEL (description "Test model customer_region_custom_snapshot.", materialized snapshot, @@ -1608,7 +1613,7 @@ def test_given_shallow_waffle_shop_snapshots_when_sources_change_then_cli_reruns """ ).strip() + "\n", - "models/customer_hard_delete_snapshot.sql": dedent( + "sql/models/customer_hard_delete_snapshot.sql": dedent( """ MODEL (description "Test model customer_hard_delete_snapshot.", materialized snapshot, @@ -1623,7 +1628,7 @@ def test_given_shallow_waffle_shop_snapshots_when_sources_change_then_cli_reruns """ ).strip() + "\n", - "models/customer_status_historical_check_snapshot.sql": dedent( + "sql/models/customer_status_historical_check_snapshot.sql": dedent( """ MODEL (description "Test model customer_status_historical_check_snapshot.", materialized snapshot, @@ -1638,7 +1643,7 @@ def test_given_shallow_waffle_shop_snapshots_when_sources_change_then_cli_reruns """ ).strip() + "\n", - "models/customer_status_historical_check_hard_delete_snapshot.sql": dedent( + "sql/models/customer_status_historical_check_hard_delete_snapshot.sql": dedent( """ MODEL (description "Test model customer_status_historical_check_hard_delete_snapshot.", materialized snapshot, @@ -2014,7 +2019,7 @@ def test_given_shallow_waffle_shop_snapshot_edges_when_sources_change_then_cli_t """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_membership_observations @@ -2028,7 +2033,7 @@ def test_given_shallow_waffle_shop_snapshot_edges_when_sources_change_then_cli_t """ ).strip() + "\n", - "models/membership_incremental_snapshot.sql": dedent( + "sql/models/membership_incremental_snapshot.sql": dedent( """ MODEL (description "Test model membership_incremental_snapshot.", materialized snapshot, @@ -2044,7 +2049,7 @@ def test_given_shallow_waffle_shop_snapshot_edges_when_sources_change_then_cli_t """ ).strip() + "\n", - "models/membership_full_history_snapshot.sql": dedent( + "sql/models/membership_full_history_snapshot.sql": dedent( """ MODEL (description "Test model membership_full_history_snapshot.", materialized snapshot, @@ -2127,7 +2132,7 @@ def test_given_shallow_waffle_shop_snapshot_edges_when_sources_change_then_cli_t """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_membership_observations @@ -2141,7 +2146,7 @@ def test_given_shallow_waffle_shop_snapshot_edges_when_sources_change_then_cli_t """ ).strip() + "\n", - "models/membership_incremental_snapshot.sql": dedent( + "sql/models/membership_incremental_snapshot.sql": dedent( """ MODEL (description "Test model membership_incremental_snapshot.", materialized snapshot, @@ -2158,7 +2163,7 @@ def test_given_shallow_waffle_shop_snapshot_edges_when_sources_change_then_cli_t """ ).strip() + "\n", - "models/membership_full_history_snapshot.sql": dedent( + "sql/models/membership_full_history_snapshot.sql": dedent( """ MODEL (description "Test model membership_full_history_snapshot.", materialized snapshot, @@ -2307,7 +2312,7 @@ def test_given_hard_deleted_key_when_it_reappears_unchanged_then_snapshot_opens_ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -2317,7 +2322,7 @@ def test_given_hard_deleted_key_when_it_reappears_unchanged_then_snapshot_opens_ """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -2385,7 +2390,7 @@ def test_given_hard_deleted_key_when_it_reappears_unchanged_then_snapshot_opens_ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -2395,7 +2400,7 @@ def test_given_hard_deleted_key_when_it_reappears_unchanged_then_snapshot_opens_ """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -2510,7 +2515,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -2520,7 +2525,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -2565,7 +2570,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -2575,7 +2580,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -2625,7 +2630,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -2635,7 +2640,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -2685,7 +2690,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -2695,7 +2700,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -2736,7 +2741,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -2746,7 +2751,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -2790,7 +2795,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -2800,7 +2805,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -2824,7 +2829,7 @@ def test_given_timestamp_snapshot_project_when_rerunning_build_then_tracks_histo command=("--no-color", "build"), expected_exit_code=1, expected_output_fragments=( - "error[B300]: [B300] models/customer_snapshot.sql:3:15:", + "error[B300]: [B300] sql/models/customer_snapshot.sql:3:15:", "unique_key references unknown column 'customer_id'", ), ), @@ -2873,7 +2878,7 @@ def test_given_duplicate_timestamp_snapshot_source_when_building_then_cli_report """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -2883,7 +2888,7 @@ def test_given_duplicate_timestamp_snapshot_source_when_building_then_cli_report """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -2992,7 +2997,7 @@ def test_given_snapshot_dml_failure_when_building_then_target_history_is_unchang """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -3002,7 +3007,7 @@ def test_given_snapshot_dml_failure_when_building_then_target_history_is_unchang """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3067,7 +3072,7 @@ def test_given_snapshot_dml_failure_when_building_then_target_history_is_unchang """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -3077,7 +3082,7 @@ def test_given_snapshot_dml_failure_when_building_then_target_history_is_unchang """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3131,7 +3136,7 @@ def test_given_snapshot_dml_failure_when_building_then_target_history_is_unchang """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -3141,7 +3146,7 @@ def test_given_snapshot_dml_failure_when_building_then_target_history_is_unchang """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3195,7 +3200,7 @@ def test_given_snapshot_dml_failure_when_building_then_target_history_is_unchang """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -3205,7 +3210,7 @@ def test_given_snapshot_dml_failure_when_building_then_target_history_is_unchang """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3319,7 +3324,7 @@ def test_given_check_snapshot_project_when_rerunning_build_then_tracks_checked_c """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_daily @@ -3329,7 +3334,7 @@ def test_given_check_snapshot_project_when_rerunning_build_then_tracks_checked_c """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3398,7 +3403,7 @@ def test_given_check_snapshot_project_when_rerunning_build_then_tracks_checked_c """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_daily @@ -3408,7 +3413,7 @@ def test_given_check_snapshot_project_when_rerunning_build_then_tracks_checked_c """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3476,7 +3481,7 @@ def test_given_check_snapshot_project_when_rerunning_build_then_tracks_checked_c """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_daily @@ -3486,7 +3491,7 @@ def test_given_check_snapshot_project_when_rerunning_build_then_tracks_checked_c """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3602,7 +3607,7 @@ def test_given_historical_check_snapshot_project_when_rerunning_build_then_track """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_extracts @@ -3612,7 +3617,7 @@ def test_given_historical_check_snapshot_project_when_rerunning_build_then_track """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3682,7 +3687,7 @@ def test_given_historical_check_snapshot_project_when_rerunning_build_then_track """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_extracts @@ -3692,7 +3697,7 @@ def test_given_historical_check_snapshot_project_when_rerunning_build_then_track """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3814,7 +3819,7 @@ def test_given_historical_timestamp_snapshot_project_when_rerunning_build_then_t """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_changes @@ -3824,7 +3829,7 @@ def test_given_historical_timestamp_snapshot_project_when_rerunning_build_then_t """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3941,7 +3946,7 @@ def test_given_historical_timestamp_changes_project_when_rerunning_build_then_tr """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -3951,7 +3956,7 @@ def test_given_historical_timestamp_changes_project_when_rerunning_build_then_tr """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -3992,7 +3997,7 @@ def test_given_historical_timestamp_changes_project_when_rerunning_build_then_tr """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -4002,7 +4007,7 @@ def test_given_historical_timestamp_changes_project_when_rerunning_build_then_tr """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4075,7 +4080,7 @@ def test_given_missing_check_snapshot_output_column_when_building_then_cli_repor """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -4085,7 +4090,7 @@ def test_given_missing_check_snapshot_output_column_when_building_then_cli_repor """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4128,7 +4133,7 @@ def test_given_missing_check_snapshot_output_column_when_building_then_cli_repor """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -4138,7 +4143,7 @@ def test_given_missing_check_snapshot_output_column_when_building_then_cli_repor """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4225,7 +4230,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -4235,7 +4240,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4291,7 +4296,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -4301,7 +4306,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4353,7 +4358,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_daily @@ -4363,7 +4368,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4432,7 +4437,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_daily @@ -4442,7 +4447,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4511,7 +4516,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_extracts @@ -4521,7 +4526,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4596,7 +4601,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_extracts @@ -4606,7 +4611,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4680,7 +4685,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_changes @@ -4690,7 +4695,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4765,7 +4770,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_changes @@ -4775,7 +4780,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4849,7 +4854,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_daily @@ -4859,7 +4864,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, @@ -4934,7 +4939,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customer_extracts @@ -4944,7 +4949,7 @@ def test_given_snapshot_full_refresh_default_deny_when_building_then_cli_reports """ ).strip() + "\n", - "models/customer_snapshot.sql": dedent( + "sql/models/customer_snapshot.sql": dedent( """ MODEL (description "Test model customer_snapshot.", materialized snapshot, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_snapshot_validity_columns.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_snapshot_validity_columns.py index 7bba63162b..e2d2b062f2 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_snapshot_validity_columns.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_snapshot_validity_columns.py @@ -58,8 +58,8 @@ def test_given_built_snapshot_when_building_again_then_validity_columns_are_not_ project_name="customers_project", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/customers.sql": _CUSTOMERS_SQL, - "models/customer_history.sql": ( + "sql/models/customers.sql": _CUSTOMERS_SQL, + "sql/models/customer_history.sql": ( "MODEL (\n description 'Customer history.',\n materialized snapshot,\n" " unique_key [customer_id],\n snapshot_strategy timestamp,\n" f" updated_at updated_at,\n{test_case.validity_config});\n\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_source_end_audits.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_source_end_audits.py index 025baf3948..8d63be8726 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_source_end_audits.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_source_end_audits.py @@ -17,12 +17,12 @@ 'name = "source_end_audits"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "warehouse.duckdb"\n\n[defaults]\nmaterialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_refunds\n description: Test source raw_refunds.\n" " schema: main\n table: raw_refunds\n columns:\n" " - name: refund_id\n type: INTEGER\n audits: [not_null]\n" ), - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", } diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_sql_hook_identity.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_sql_hook_identity.py index 380a026955..6d53748ae5 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_sql_hook_identity.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_sql_hook_identity.py @@ -14,7 +14,7 @@ ) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb -_HOOK_PATH: str = "hooks/sql/record_order_access.sql" +_HOOK_PATH: str = "sql/hooks/sql/record_order_access.sql" _HOOK_CONTENTS: str = ( dedent( """ @@ -42,7 +42,7 @@ SqlHookIdentityBuildE2ETestCase( description="hook file move keeps the model unchanged", removed_hook_path=_HOOK_PATH, - added_hook_path="hooks/sql/audit/record_order_access.sql", + added_hook_path="sql/hooks/sql/audit/record_order_access.sql", added_hook_contents=_HOOK_CONTENTS, expected_reason="no_change", ), @@ -75,7 +75,7 @@ def test_given_built_model_with_sql_hook_when_editing_hook_then_plans_expected_r ).strip() + "\n", _HOOK_PATH: _HOOK_CONTENTS, - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_sql_hook_reads.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_sql_hook_reads.py index cf6c489808..a51bd24f7c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_sql_hook_reads.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_sql_hook_reads.py @@ -21,7 +21,7 @@ ) _DATABASE: str = "warehouse.duckdb" -_MODELS: str = "models/sales" +_MODELS: str = "sql/models/sales" _PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": ( 'name = "sql_hook_reads"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' @@ -29,11 +29,11 @@ '[targets.dev]\nschema = "dev"\nloader_schema = "raw_dev"\ndefer_sources_to = "prod"\n\n' '[targets.prod]\nschema = "prod"\nloader_schema = "raw_prod"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n managed: true\n write_strategy: table\n" " columns:\n - name: order_id\n type: INTEGER\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from sqlbuild.loaders import loader\n\n\n" "@loader\ndef raw_orders(ctx):\n '''Test loader raw_orders.'''\n return [{'order_id': 9}]\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_table_function_dependency.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_table_function_dependency.py index 608578127b..e9891fd3fa 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_table_function_dependency.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_table_function_dependency.py @@ -47,7 +47,7 @@ def test_given_model_table_function_dependency_when_building_then_creates_and_co """ ).strip() + "\n", - "functions/sql/customer_orders.sql": dedent( + "sql/functions/sql/customer_orders.sql": dedent( """ FUNCTION (description "Test function customer_orders.", arguments (customer_id INTEGER), @@ -61,7 +61,7 @@ def test_given_model_table_function_dependency_when_building_then_creates_and_co """ ).strip() + "\n", - "models/customer_order_summary.sql": dedent( + "sql/models/customer_order_summary.sql": dedent( f""" MODEL (description "Test model customer_order_summary.", materialized table diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_template_expressions.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_template_expressions.py index 9190a6d1c5..d2abb46cba 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_template_expressions.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_template_expressions.py @@ -56,7 +56,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -66,7 +66,7 @@ """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", cursor ordered_at, @@ -189,7 +189,7 @@ def test_given_template_expression_project_when_building_then_config_expressions second_result.stdout + second_result.stderr ) - runtime_sql: str = (project_dir / "target" / "run" / "models" / "orders.sql").read_text( + runtime_sql: str = (project_dir / "target" / "run" / "sql" / "models" / "orders.sql").read_text( encoding="utf-8" ) assert test_case.expected_runtime_sql_fragment in runtime_sql diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_terminal_failure.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_terminal_failure.py index 5e01acbc9c..7e74e4f788 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_terminal_failure.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_terminal_failure.py @@ -35,7 +35,7 @@ command=("build",), model_replacements=( ( - "models/marts/daily_revenue.sql", + "sql/models/marts/daily_revenue.sql", '__ref("stg_payments")', '__ref("missing_payments")', ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_unbuilt_dependencies.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_unbuilt_dependencies.py index 3339c39b67..e748932a4c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_unbuilt_dependencies.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_unbuilt_dependencies.py @@ -18,11 +18,11 @@ 'name = "unbuilt_dependencies"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "warehouse.duckdb"\n\n[defaults]\nmaterialized = "table"\n' ), - "models/broken_orders.sql": ( + "sql/models/broken_orders.sql": ( "MODEL (description 'Test model broken_orders.');\n" "SELECT CAST('not a number' AS INTEGER) AS order_id\n" ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Test model customers.');\nSELECT 1 AS customer_id\n" ), } @@ -43,7 +43,7 @@ description="end-of-build audit over a failed model is skipped", repo_files={ **_BASE_FILES, - "audits/singular/orders_have_customers.sql": ( + "sql/audits/singular/orders_have_customers.sql": ( "AUDIT ();\n" 'SELECT o.order_id FROM __ref("broken_orders") AS o\n' 'LEFT JOIN __ref("customers") AS c ON c.customer_id = o.order_id\n' @@ -64,7 +64,7 @@ description="full refresh on a fresh warehouse skips the audit over a failed model", repo_files={ **_BASE_FILES, - "audits/singular/orders_have_customers.sql": ( + "sql/audits/singular/orders_have_customers.sql": ( "AUDIT ();\n" 'SELECT o.order_id FROM __ref("broken_orders") AS o\n' 'LEFT JOIN __ref("customers") AS c ON c.customer_id = o.order_id\n' @@ -83,13 +83,13 @@ description="test calling a skipped table function is skipped", repo_files={ **_BASE_FILES, - "functions/sql/customer_orders.sql": ( + "sql/functions/sql/customer_orders.sql": ( 'FUNCTION (description "Test function customer_orders.",\n' " arguments (p_customer_id INTEGER), returns table (order_id INTEGER));\n" 'SELECT o.order_id FROM __ref("broken_orders") AS o\n' "WHERE o.order_id = p_customer_id\n" ), - "models/summary.sql": ( + "sql/models/summary.sql": ( "MODEL (description 'Test model summary.');\n" "SELECT c.customer_id, f.order_id\n" 'FROM __ref("customers") AS c\n' @@ -146,10 +146,10 @@ def test_given_hook_skipped_existing_model_when_rebuilding_then_its_end_audits_r project_name="unbuilt_dependencies", repo_files={ "sqlbuild_project.toml": _BASE_FILES["sqlbuild_project.toml"], - "models/customers.sql": "MODEL (description 'Test model customers.');\n" + "sql/models/customers.sql": "MODEL (description 'Test model customers.');\n" + _CUSTOMERS_SQL, - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", - "audits/singular/customers_exist.sql": ( + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", + "sql/audits/singular/customers_exist.sql": ( "AUDIT ();\n" 'SELECT o.order_id FROM __ref("orders") AS o\n' 'LEFT JOIN __ref("customers") AS c ON c.customer_id = o.order_id\n' @@ -161,9 +161,9 @@ def test_given_hook_skipped_existing_model_when_rebuilding_then_its_end_audits_r command=("--no-color", "build"), project_dir=project_dir ) assert first.returncode == 0, first.stdout + first.stderr - (project_dir / "hooks/python").mkdir(parents=True) - _ = (project_dir / "hooks/python/skips.py").write_text(_HOOK_FILE) - _ = (project_dir / "models/customers.sql").write_text(test_case.hooked_model) + (project_dir / "sql/hooks/python").mkdir(parents=True) + _ = (project_dir / "sql/hooks/python/skips.py").write_text(_HOOK_FILE) + _ = (project_dir / "sql/models/customers.sql").write_text(test_case.hooked_model) rebuilt: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_validation_failures.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_validation_failures.py index bb75213809..daa20b9c10 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_validation_failures.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_validation_failures.py @@ -11,6 +11,7 @@ from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import ( CliFailureBuildE2ETestCase, ) +from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import take_raw_data_sql from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( prepare_inline_project, run_sqb, @@ -34,7 +35,7 @@ ).strip() + "\n", "seed_raw_data.sql": "", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -85,7 +86,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -95,7 +96,7 @@ """ ).strip() + "\n", - "models/staging/stg_orders.sql": dedent( + "sql/models/staging/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized view); @@ -106,7 +107,7 @@ """ ).strip() + "\n", - "models/marts/fact_orders.sql": dedent( + "sql/models/marts/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table); @@ -114,7 +115,7 @@ """ ).strip() + "\n", - "models/marts/customer_status_snapshot.sql": dedent( + "sql/models/marts/customer_status_snapshot.sql": dedent( """ MODEL (description "Test model customer_status_snapshot.", materialized incremental, @@ -154,7 +155,7 @@ ).strip() + "\n", "seed_raw_data.sql": "", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -163,7 +164,7 @@ """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table); @@ -193,12 +194,12 @@ def test_given_invalid_cli_project_when_running_build_then_it_fails_clearly( project_name="validation_project", repo_files=test_case.repo_files, ) - seed_file: Path = project_dir / "seed_raw_data.sql" + raw_data_sql: str = take_raw_data_sql(project_dir) import duckdb db_path: Path = project_dir / "validation.duckdb" connection: duckdb.DuckDBPyConnection = duckdb.connect(str(db_path)) - connection.execute(seed_file.read_text(encoding="utf-8")) + connection.execute(raw_data_sql) connection.close() result: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_warehouse_round_trips.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_warehouse_round_trips.py index aa2b9c67e4..9164db4291 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_warehouse_round_trips.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_warehouse_round_trips.py @@ -236,8 +236,8 @@ def test_given_a_round_trip_that_cannot_complete_when_building_then_its_readers_ extra_files=round_trip_variant( "transitive_gate", { - "python/tasks/packaging.py": "packaging.py", - "python/loaders/partner.py": "partner.py", + "python/nodes/tasks/packaging/asset.py": "packaging.py", + "python/nodes/loaders/partner/loader.py": "partner.py", }, ), expected_output_fragments=( @@ -253,10 +253,10 @@ def test_given_a_round_trip_that_cannot_complete_when_building_then_its_readers_ extra_files=round_trip_variant( "ingress_gate", { - "python/tasks/rates.py": "rates_task.py", - "python/loaders/rates.py": "rates_loader.py", - "sources/rates.yml": "rates.yml", - "python/loaders/partner.py": "partner.py", + "python/nodes/tasks/rates/asset.py": "rates_task.py", + "python/nodes/loaders/rates/loader.py": "rates_loader.py", + "sql/sources/rates.yml": "rates.yml", + "python/nodes/loaders/partner/loader.py": "partner.py", }, ), expected_output_fragments=( @@ -287,8 +287,11 @@ def test_given_a_built_round_trip_when_rebuilding_then_the_decision_follows_the_ ), ) project_dir: Path = database.parent - (project_dir / "models" / "orders.sql").write_text(test_case.orders_sql, encoding="utf-8") + (project_dir / "sql" / "models" / "orders.sql").write_text( + test_case.orders_sql, encoding="utf-8" + ) for relative, text in test_case.extra_files.items(): + (project_dir / relative).parent.mkdir(parents=True, exist_ok=True) (project_dir / relative).write_text(text, encoding="utf-8") result: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/check/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/check/helpers.py index 0c01ab6572..d5cfa4af91 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/check/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/check/helpers.py @@ -23,24 +23,31 @@ def prepare_python_check_project(*, tmp_path: Path) -> Path: [connection] database = "python_check_project.duckdb" """, - "python/tasks/orders.py": """ + "python/nodes/tasks/orders/export_orders/asset.py": ( + "from sqlbuild.assets import asset\n" + "\n" + "\n" + "@asset()\n" + "def export_orders(ctx):\n" + " '''Test task export_orders.'''\n" + ' return ctx.result(payload={"rows": 3}, metadata={"rows": 3})\n' + ), + "python/nodes/tasks/orders/export_customers/asset.py": ( + "from sqlbuild.assets import asset\n" + "\n" + "\n" + "@asset()\n" + "def export_customers(ctx):\n" + " '''Test task export_customers.'''\n" + ' return ctx.result(payload={"rows": 2}, metadata={"rows": 2})\n' + ), + "python/nodes/tasks/orders/__init__.py": ( + "from .export_orders.asset import export_orders\n" + "from .export_customers.asset import export_customers\n" + ), + "python/nodes/assets/orders/asset.py": """ from sqlbuild.assets import asset - - -@asset() -def export_orders(ctx): - '''Test task export_orders.''' - return ctx.result(payload={"rows": 3}, metadata={"rows": 3}) - - -@asset() -def export_customers(ctx): - '''Test task export_customers.''' - return ctx.result(payload={"rows": 2}, metadata={"rows": 2}) -""", - "python/assets/orders.py": """ -from sqlbuild.assets import asset -from python.tasks.orders import export_orders +from python.nodes.tasks.orders import export_orders @asset(depends_on=export_orders) @@ -48,10 +55,10 @@ def orders_asset(ctx): '''Test asset orders_asset.''' return ctx.result(payload={"asset_rows": 3}, metadata={"asset_rows": 3}) """, - "python/checks/orders.py": """ + "python/nodes/checks/orders/checks.py": """ from sqlbuild.checks import check -from python.assets.orders import orders_asset -from python.tasks.orders import export_customers, export_orders +from python.nodes.assets.orders.asset import orders_asset +from python.nodes.tasks.orders import export_customers, export_orders @check(depends_on=export_orders) @@ -115,7 +122,7 @@ def prepare_terminal_loader_check_project(*, tmp_path: Path) -> Path: [connection] database = "terminal_loader_check_project.duckdb" """, - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @@ -124,7 +131,7 @@ def raw_orders(ctx): '''Test loader raw_orders.''' return [{"order_id": 1}] """, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -134,9 +141,9 @@ def raw_orders(ctx): - name: order_id type: INTEGER """, - "python/checks/raw.py": """ + "python/nodes/checks/raw/checks.py": """ from sqlbuild.checks import check -from python.loaders.raw import raw_orders +from python.nodes.loaders.raw.loader import raw_orders @check(depends_on=raw_orders) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/helpers.py index d7bb7a2df0..7fafd6cd42 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/helpers.py @@ -148,7 +148,7 @@ def build_orders_project_files(*, schema_name: str, config: dict[str, object]) - config=config, extra="\n[settings]\nconcurrency = 4\nmicrobatch_concurrency = true\n", ), - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( f""" sources: - name: raw_events @@ -162,8 +162,8 @@ def build_orders_project_files(*, schema_name: str, config: dict[str, object]) - final: true """ ).lstrip(), - "seeds/regions.csv": "customer_id,region_name\n1,north\n2,south\n3,east\n", - "seeds/regions.yml": dedent( + "sql/seeds/regions.csv": "customer_id,region_name\n1,north\n2,south\n3,east\n", + "sql/seeds/regions.yml": dedent( """ seeds: - name: regions @@ -175,16 +175,16 @@ def build_orders_project_files(*, schema_name: str, config: dict[str, object]) - type: String """ ).lstrip(), - "functions/sql/half_amount.sql": ( + "sql/functions/sql/half_amount.sql": ( 'FUNCTION (\n description "Half of an amount",\n' " arguments (amount Int64),\n returns Float64,\n);\n\namount / 2\n" ), - "models/stg_events.sql": ( + "sql/models/stg_events.sql": ( "MODEL (description 'Staged events.', materialized view);\n\n" "SELECT event_id, customer_id, amount, event_time\n" 'FROM __source("raw_events")\n' ), - "models/customer_totals.sql": ( + "sql/models/customer_totals.sql": ( "MODEL (description 'One row per customer.');\n\n" "SELECT e.customer_id AS customer_id, r.region_name AS region_name,\n" " sum(e.amount) AS total_amount,\n" @@ -193,11 +193,11 @@ def build_orders_project_files(*, schema_name: str, config: dict[str, object]) - 'JOIN __seed("regions") AS r ON e.customer_id = r.customer_id\n' "GROUP BY e.customer_id, r.region_name\n" ), - "models/customer_names.sql": ( + "sql/models/customer_names.sql": ( "MODEL (description 'One row per customer name.');\n\n" 'SELECT customer_id, customer_name FROM __source("raw_customers")\n' ), - "models/customer_latest.sql": ( + "sql/models/customer_latest.sql": ( "MODEL (description 'Latest activity per customer.',\n" " materialized incremental,\n" " incremental_strategy merge,\n" @@ -207,7 +207,7 @@ def build_orders_project_files(*, schema_name: str, config: dict[str, object]) - 'FROM __ref("stg_events")\n' "GROUP BY customer_id\n" ), - "models/daily_events.sql": ( + "sql/models/daily_events.sql": ( "MODEL (description 'Events by day.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -237,7 +237,7 @@ def build_partitioned_events_project_files( "sqlbuild_project.toml": build_clickhouse_project_toml( project_name="clickhouse_layout", schema_name=schema_name, config=config ), - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( f""" sources: - name: raw_events @@ -246,7 +246,7 @@ def build_partitioned_events_project_files( table: raw_events """ ).lstrip(), - "models/events.sql": ( + "sql/models/events.sql": ( "MODEL (description 'One row per event.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -291,10 +291,10 @@ def prepare_clickhouse_waffle_shop( schema_name: str = build_unique_schema_name(prefix="sqb_waffle") project_dir: Path = prepare_waffle_shop(tmp_path) - (project_dir / "functions" / "sql" / "customer_orders.sql").unlink() + (project_dir / "sql" / "functions" / "sql" / "customer_orders.sql").unlink() (project_dir / "tests" / "unit" / "test_customer_orders_table_fn.sql").unlink() - (project_dir / "functions" / "python" / "is_completed_order_py.py").unlink() - fact_orders_path: Path = project_dir / "models" / "marts" / "fact_orders.sql" + (project_dir / "sql" / "functions" / "python" / "is_completed_order_py.py").unlink() + fact_orders_path: Path = project_dir / "sql" / "models" / "marts" / "fact_orders.sql" fact_orders_path.write_text( fact_orders_path.read_text(encoding="utf-8").replace( '__udf("is_completed_order_py")(o.status) AS is_completed_order_py,', @@ -303,15 +303,19 @@ def prepare_clickhouse_waffle_shop( encoding="utf-8", ) for model_name in ("dim_customers", "fact_orders", "scenario_order_prices"): - _alias_qualified_columns(project_dir / "models" / "marts" / f"{model_name}.sql") - materialization_path: Path = project_dir / "materializations" / "partition_tracked.py" + _alias_qualified_columns(project_dir / "sql" / "models" / "marts" / f"{model_name}.sql") + materialization_path: Path = ( + project_dir / "python" / "materializations" / "partition_tracked.py" + ) materialization_path.write_text( materialization_path.read_text(encoding="utf-8").replace( "CURRENT_TIMESTAMP", "CURRENT_TIMESTAMP()" ), encoding="utf-8", ) - time_macros_path: Path = project_dir / "models" / "marts" / "_macros" / "python" / "time.py" + time_macros_path: Path = ( + project_dir / "sql" / "models" / "marts" / "_macros" / "python" / "time.py" + ) time_macros_path.write_text( time_macros_path.read_text(encoding="utf-8").replace( "return f\"DATE_TRUNC('{grain}', {expression})\"", @@ -1066,7 +1070,7 @@ def representative_store(project_dir: Path) -> subprocess.Popen[bytes]: """A completed, a failed, an abandoned and a heartbeat-only invocation, and a running one.""" assert run(project_dir, "build").returncode == 0 - failing: Path = project_dir / "models" / "unparsed_orders.sql" + failing: Path = project_dir / "sql" / "models" / "unparsed_orders.sql" _ = failing.write_text(_FAILING_MODEL, encoding="utf-8") assert run(project_dir, "build").returncode != 0 failing.unlink() @@ -1125,7 +1129,7 @@ def prepare_janitor_usage_project( config=config, extra=JANITOR_SETTINGS, ).replace("\n[targets.dev]", connection_settings + "\n[targets.dev]"), - "models/orders.sql": "MODEL (description 'Orders.');\n\nSELECT toInt64(1) AS id\n", + "sql/models/orders.sql": "MODEL (description 'Orders.');\n\nSELECT toInt64(1) AS id\n", }, ) built: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse.py b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse.py index 440593cc8f..12d6ae6a5f 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse.py @@ -261,7 +261,7 @@ def test_given_snapshot_project_when_building_on_clickhouse_then_scd2_history_is ) ) == (test_case.expected_historical_check_rows) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="blocked", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -276,7 +276,7 @@ def test_given_snapshot_project_when_building_on_clickhouse_then_scd2_history_is test_case.expected_current_rows_after_initial_build ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="pro", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -346,7 +346,7 @@ def test_given_existing_snapshot_targets_when_building_on_clickhouse_then_change command=("--no-color", "build", "--concurrency", "4"), project_dir=project_dir ) assert initial.returncode == 0, initial.stdout + initial.stderr - models: Path = project_dir / "models" + models: Path = project_dir / "sql" / "models" (models / "current_check_customers.sql").write_text( build_current_check_customers_model_sql(changed=True), encoding="utf-8" ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_commands.py b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_commands.py index e86a871ea2..bf3c2556a2 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_commands.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_commands.py @@ -79,7 +79,7 @@ def test_given_clickhouse_targets_when_running_diff_then_all_modes_execute_end_t dev_schema=dev_schema, config=config, ), - "models/fact_orders.sql": _FACT_ORDERS_SQL, + "sql/models/fact_orders.sql": _FACT_ORDERS_SQL, }, ) try: @@ -144,8 +144,8 @@ def test_given_built_dev_target_when_cloning_to_prod_then_clickhouse_clones_rela dev_schema=dev_schema, config=config, ), - "models/fact_orders.sql": _FACT_ORDERS_SQL, - "models/order_summary.sql": ( + "sql/models/fact_orders.sql": _FACT_ORDERS_SQL, + "sql/models/order_summary.sql": ( "MODEL (description 'Order summary.', materialized view);\n\n" 'SELECT order_id, amount_cents FROM __ref("fact_orders")\n' ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_layout.py b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_layout.py index 732a93ae46..5e77d474f0 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_layout.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_layout.py @@ -167,7 +167,7 @@ def test_given_changed_layout_when_planning_incremental_then_warns_until_full_re command=("--no-color", "build"), project_dir=project_dir ) assert first.returncode == 0, first.stdout + first.stderr - model_path: Path = project_dir / "models" / "events.sql" + model_path: Path = project_dir / "sql" / "models" / "events.sql" model_path.write_text( model_path.read_text().replace( test_case.first_partition_by, test_case.changed_partition_by diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_nullability.py b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_nullability.py index 9bd05ca830..13a83b6650 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_nullability.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_nullability.py @@ -127,14 +127,14 @@ def test_given_non_nullable_target_when_model_starts_producing_nulls_then_policy "sqlbuild_project.toml": build_clickhouse_project_toml( project_name="clickhouse_nulls", schema_name=schema_name, config=config ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n" " description: Synthetic orders.\n" f" schema: {schema_name}\n" " table: raw_orders\n" ), - "models/orders.sql": test_case.model_sql + _FIRST_SELECT, + "sql/models/orders.sql": test_case.model_sql + _FIRST_SELECT, }, ) create_clickhouse_schema(config=config, schema_name=schema_name) @@ -151,7 +151,7 @@ def test_given_non_nullable_target_when_model_starts_producing_nulls_then_policy command=("--no-color", "build"), project_dir=project_dir ) assert first.returncode == 0, first.stdout + first.stderr - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( test_case.model_sql + test_case.edited_select ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_output_columns.py b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_output_columns.py index 2a61861e46..60f3d2fc1a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_output_columns.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clickhouse/test_clickhouse_output_columns.py @@ -57,7 +57,7 @@ def test_given_three_table_join_when_building_on_clickhouse_then_column_names_ma "sqlbuild_project.toml": build_clickhouse_project_toml( project_name="clickhouse_names", schema_name=schema_name, config=config ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" + "".join( f" - name: {name}\n description: Synthetic {name}.\n" @@ -65,7 +65,7 @@ def test_given_three_table_join_when_building_on_clickhouse_then_column_names_ma for name in ("orders", "products", "payments") ) ), - "models/order_lines.sql": ( + "sql/models/order_lines.sql": ( "MODEL (description 'One row per order.');\n\n" f"SELECT {test_case.selected_order_id}, o.quantity AS quantity, " "p.amount AS payment_cents\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clone/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/clone/helpers.py index 7b653bc1ff..18caf66fd9 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clone/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clone/helpers.py @@ -12,6 +12,7 @@ prepare_inline_project, run_sqb, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": dedent( @@ -55,8 +56,10 @@ allow_as_clone_destination = true """ ).lstrip(), - "python/loaders/raw.py": dedent( - """ + **node_module_files( + "python/nodes/loaders/raw.py", + dedent( + """ from sqlbuild.loaders import loader @@ -65,8 +68,9 @@ def raw_payments(ctx): '''Test loader raw_payments.''' return [{"payment_id": 1, "order_id": 1, "amount_cents": 500}] """ - ).lstrip(), - "sources/raw.yml": dedent( + ).lstrip(), + ), + "sql/sources/raw.yml": dedent( """ sources: - name: raw_payments @@ -88,8 +92,8 @@ def raw_payments(ctx): AS raw_orders(order_id, customer_id, amount_cents) """ ).lstrip(), - "seeds/customers.csv": "customer_id,customer_name\n101,Ada\n102,Grace\n", - "seeds/schema.yml": dedent( + "sql/seeds/customers.csv": "customer_id,customer_name\n101,Ada\n102,Grace\n", + "sql/seeds/schema.yml": dedent( """ seeds: - name: customers @@ -101,21 +105,21 @@ def raw_payments(ctx): type: VARCHAR """ ).lstrip(), - "models/staging/stg_orders.sql": dedent( + "sql/models/staging/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized view); SELECT order_id, customer_id, amount_cents, '@@region' AS region FROM __source("raw_orders") """ ).lstrip(), - "models/staging/stg_payments.sql": dedent( + "sql/models/staging/stg_payments.sql": dedent( """ MODEL (description "Test model stg_payments.", materialized view); SELECT * FROM __source("raw_payments") """ ).lstrip(), - "models/marts/fct_orders.sql": dedent( + "sql/models/marts/fct_orders.sql": dedent( """ MODEL (description "Test model fct_orders.", materialized table); @@ -124,7 +128,7 @@ def raw_payments(ctx): JOIN __seed("customers") AS c ON c.customer_id = o.customer_id """ ).lstrip(), - "models/marts/fct_order_events.sql": dedent( + "sql/models/marts/fct_order_events.sql": dedent( """ MODEL ( description "Test model fct_order_events.", @@ -135,7 +139,7 @@ def raw_payments(ctx): SELECT order_id, amount_cents FROM __ref("fct_orders") """ ).lstrip(), - "models/marts/orders_summary.sql": dedent( + "sql/models/marts/orders_summary.sql": dedent( """ MODEL (description "Test model orders_summary.", materialized view); @@ -144,21 +148,21 @@ def raw_payments(ctx): LEFT JOIN __ref("stg_payments") AS p ON p.order_id = f.order_id """ ).lstrip(), - "models/marts/orders_backlog.sql": dedent( + "sql/models/marts/orders_backlog.sql": dedent( """ MODEL (description "Test model orders_backlog.", materialized table); SELECT order_id FROM __ref("fct_orders") WHERE amount_cents > 150 """ ).lstrip(), - "models/marts/retired_orders.sql": dedent( + "sql/models/marts/retired_orders.sql": dedent( """ MODEL (description "Test model retired_orders.", materialized table, enabled false); SELECT order_id FROM __ref("fct_orders") """ ).lstrip(), - "functions/sql/cents_to_units.sql": dedent( + "sql/functions/sql/cents_to_units.sql": dedent( """ FUNCTION ( description "Test function cents_to_units.", @@ -225,12 +229,12 @@ def plan_missing_upstreams( f"allow_as_clone_destination = {str(destination_allowed).lower()}\n" ), **{ - f"models/{name}.sql": ( + f"sql/models/{name}.sql": ( f"MODEL (description '{name}.', materialized table);\n\nSELECT 1 AS id\n" ) for name in MISSING_UPSTREAMS }, - "models/report.sql": ( + "sql/models/report.sql": ( "MODEL (description 'Report.', materialized table);\n\n" 'SELECT customers.id FROM __ref("customers") AS customers\n' + "".join( @@ -268,13 +272,13 @@ def defer_clone_with_missing_origin( '[targets.dev]\nschema = "dev"\n\n' "[targets.dev.clone]\nallow_as_clone_destination = true\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n\nSELECT 1 AS id\n" ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Customers.', materialized table);\n\nSELECT 1 AS id\n" ), - "models/report.sql": ( + "sql/models/report.sql": ( "MODEL (description 'Report.', materialized table);\n\n" 'SELECT o.id FROM __ref("orders") AS o JOIN __ref("customers") AS c USING (id)\n' ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone.py b/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone.py index fb26169975..645b089e37 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone.py @@ -35,6 +35,7 @@ query_duckdb, run_sqb, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _CHANGED_CLONE_FIXTURE: Path = REPO_ROOT / "benchmarks/duckshop/edge_cases/changed_builds_clone" _UPSTREAMS: tuple[str, ...] = ( @@ -56,7 +57,7 @@ ), **{ str(path.relative_to(_DEFER_FIXTURE)): path.read_text(encoding="utf-8") - for path in sorted(_DEFER_FIXTURE.glob("models/*.sql")) + for path in sorted(_DEFER_FIXTURE.glob("sql/models/*.sql")) }, } @@ -95,7 +96,7 @@ """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -107,7 +108,7 @@ """ ).strip() + "\n", - "models/fact_orders.sql": dedent( + "sql/models/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table); @@ -115,7 +116,7 @@ """ ).strip() + "\n", - "models/orders_enriched.sql": dedent( + "sql/models/orders_enriched.sql": dedent( """ MODEL (description "Test model orders_enriched.", materialized view); @@ -124,7 +125,7 @@ """ ).strip() + "\n", - "models/missing_snapshot.sql": dedent( + "sql/models/missing_snapshot.sql": dedent( """ MODEL (description "Test model missing_snapshot.", materialized table); @@ -241,7 +242,7 @@ def test_given_clone_command_when_running_then_managed_relations_sync_as_expecte """ ).strip() + "\n", - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.', materialized table);\n\nSELECT 1 AS order_id, 100 AS amount_cents\n" ), }, @@ -338,8 +339,10 @@ def test_given_invalid_origin_connection_when_exact_cloning_then_destination_ses """ ).strip() + "\n", - "python/loaders/raw.py": dedent( - """ + **node_module_files( + "python/nodes/loaders/raw.py", + dedent( + """ from sqlbuild.loaders import loader @loader @@ -347,9 +350,10 @@ def raw_customers(ctx): '''Test loader raw_customers.''' return [] """ - ).strip() - + "\n", - "sources/raw.yml": dedent( + ).strip() + + "\n", + ), + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -364,7 +368,7 @@ def raw_customers(ctx): """ ).strip() + "\n", - "models/stg_customers.sql": dedent( + "sql/models/stg_customers.sql": dedent( """ MODEL (description "Test model stg_customers.", materialized view); @@ -420,8 +424,10 @@ def raw_customers(ctx): """ ).strip() + "\n", - "python/loaders/raw.py": dedent( - """ + **node_module_files( + "python/nodes/loaders/raw.py", + dedent( + """ from sqlbuild.loaders import loader @loader @@ -429,9 +435,10 @@ def raw_customers(ctx): '''Test loader raw_customers.''' return [] """ - ).strip() - + "\n", - "sources/raw.yml": dedent( + ).strip() + + "\n", + ), + "sql/sources/raw.yml": dedent( """ sources: - name: raw_customers @@ -446,7 +453,7 @@ def raw_customers(ctx): """ ).strip() + "\n", - "models/stg_customers.sql": dedent( + "sql/models/stg_customers.sql": dedent( """ MODEL (description "Test model stg_customers.", materialized view); @@ -584,8 +591,8 @@ def test_given_multi_schema_functions_when_cloning_then_destination_graph_is_que """ ).strip() + "\n", - "seeds/bonuses.csv": "bonus\n5\n", - "seeds/schema.yml": dedent( + "sql/seeds/bonuses.csv": "bonus\n5\n", + "sql/seeds/schema.yml": dedent( """ seeds: - name: bonuses @@ -597,7 +604,7 @@ def test_given_multi_schema_functions_when_cloning_then_destination_graph_is_que """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, schema model_origin); @@ -606,7 +613,7 @@ def test_given_multi_schema_functions_when_cloning_then_destination_graph_is_que """ ).strip() + "\n", - "functions/sql/add_bonus.sql": dedent( + "sql/functions/sql/add_bonus.sql": dedent( """ FUNCTION (description "Test function add_bonus.", schema scalar_origin, @@ -618,7 +625,7 @@ def test_given_multi_schema_functions_when_cloning_then_destination_graph_is_que """ ).strip() + "\n", - "functions/sql/order_rows.sql": dedent( + "sql/functions/sql/order_rows.sql": dedent( """ FUNCTION (description "Test function order_rows.", schema table_function_origin, @@ -635,7 +642,7 @@ def test_given_multi_schema_functions_when_cloning_then_destination_graph_is_que """ ).strip() + "\n", - "models/enriched_orders.sql": dedent( + "sql/models/enriched_orders.sql": dedent( """ MODEL (description "Test model enriched_orders.", materialized view, schema view_origin); @@ -714,7 +721,7 @@ def test_given_python_udf_when_cloning_then_recreates_for_clone_connection_scope """ ).strip() + "\n", - "functions/python/add_one.py": dedent( + "sql/functions/python/add_one.py": dedent( """ from sqlbuild.functions import udf @@ -800,8 +807,10 @@ def test_given_destination_source_deferral_when_cloning_then_function_reads_defe """ ).strip() + "\n", - "python/loaders/raw.py": dedent( - """ + **node_module_files( + "python/nodes/loaders/raw.py", + dedent( + """ from sqlbuild.loaders import loader @loader @@ -809,9 +818,10 @@ def raw_bonus(ctx): '''Test loader raw_bonus.''' return [] """ - ).strip() - + "\n", - "sources/raw.yml": dedent( + ).strip() + + "\n", + ), + "sql/sources/raw.yml": dedent( """ sources: - name: raw_bonus @@ -824,7 +834,7 @@ def raw_bonus(ctx): """ ).strip() + "\n", - "functions/sql/add_deferred_bonus.sql": dedent( + "sql/functions/sql/add_deferred_bonus.sql": dedent( """ FUNCTION (description "Test function add_deferred_bonus.", arguments (amount INTEGER), returns INTEGER); @@ -978,7 +988,7 @@ def test_given_cloned_table_when_planning_changed_then_it_rebuilds( + "\n", **{ str(path.relative_to(_CHANGED_CLONE_FIXTURE)): path.read_text(encoding="utf-8") - for path in sorted(_CHANGED_CLONE_FIXTURE.glob("models/*.sql")) + for path in sorted(_CHANGED_CLONE_FIXTURE.glob("sql/models/*.sql")) }, }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone_preparation.py b/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone_preparation.py index 2c2906edf4..c106f0b889 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone_preparation.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone_preparation.py @@ -287,14 +287,14 @@ def test_given_terminal_when_cloning_then_preparation_spinner_stops_before_items ClonePreparationFailureE2ETestCase( description="compile error stops the preparation spinner before the error prints", columns=120, - broken_model_path="models/marts/orders_backlog.sql", + broken_model_path="sql/models/marts/orders_backlog.sql", broken_model_sql=( 'MODEL (description "Test model orders_backlog.", materialized table);\n\n' 'SELECT order_id FROM __ref("missing_orders")\n' ), expected_screen_fragments=( "✓ Warehouse connected duckdb", - "error[P001]: Model file models/marts/orders_backlog.sql references unknown " + "error[P001]: Model file sql/models/marts/orders_backlog.sql references unknown " "model 'missing_orders'", ), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone_timings.py b/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone_timings.py index d25df752cc..32129f56bd 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone_timings.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone_timings.py @@ -25,7 +25,7 @@ '[targets.dev]\nschema = "dev"\n\n' "[targets.dev.clone]\nallow_as_clone_destination = true\n" ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( 'MODEL (description "Test model fact_orders.", materialized table);\n\n' "SELECT 1 AS order_id\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/_test_types.py index c50594341d..2cf2c765a6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/_test_types.py @@ -1472,3 +1472,10 @@ class DynamicCompileE2ETestCase: daily_totals_header: str expected_exit_code: int expected_fragments: tuple[str, ...] + + +@dataclass(frozen=True) +class PythonLayoutBuildTestCase: + description: str + repo_files: dict[str, str] + expected_build_fragments: tuple[str, ...] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/attachment_errors/test_native_attachment_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/attachment_errors/test_native_attachment_errors.py index 411925d3d9..3685d6b8f5 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/attachment_errors/test_native_attachment_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/attachment_errors/test_native_attachment_errors.py @@ -15,18 +15,19 @@ NativeAttachmentErrorTestCase, ) from tests.e2e.src.sqlbuild.cli.commands.main.compile.helpers import ( + MACRO_CALL_LOG_CODE, CompileReuseRun, lifecycle_error_type, + macro_call_log, run_reuse_compile, write_project_file, ) -_CALL_LOG: str = "macro_calls.log" _COUNTED_MACRO: str = ( "from pathlib import Path\n\n\n" "def counted(expression: str) -> str:\n" ' """Return the expression, logging each execution."""\n\n' - f" with (Path(__file__).resolve().parents[2] / {_CALL_LOG!r}).open(\n" + f" with {MACRO_CALL_LOG_CODE}.open(\n" ' "a", encoding="utf-8"\n' " ) as log:\n" ' _ = log.write("call\\n")\n' @@ -103,14 +104,14 @@ def test_given_attachment_error_when_compiling_then_the_error_and_type_are_repor project_dir: Path = tmp_path / "orders" files: dict[str, str] = { **case.files, - "macros/python/counted.py": _COUNTED_MACRO, + "sql/macros/python/counted.py": _COUNTED_MACRO, FAILURE_MART_PATH: FAILURE_BASE_MART.replace("SUM(amount)", "SUM(@py.counted('amount'))"), - _CALL_LOG: "", } for relative_path, contents in files.items(): write_project_file(project_dir, relative_path, contents) + _ = macro_call_log(project_dir).write_text("", encoding="utf-8") run: CompileReuseRun = run_reuse_compile(project_dir=project_dir) - macro_calls: int = len((project_dir / _CALL_LOG).read_text(encoding="utf-8").splitlines()) + macro_calls: int = len(macro_call_log(project_dir).read_text(encoding="utf-8").splitlines()) error_type: str = lifecycle_error_type(project_dir=project_dir, monkeypatch=monkeypatch) output: str = run.report + run.stderr diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/conftest.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/conftest.py index 60b8811e59..cd0b3ea107 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/conftest.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/conftest.py @@ -29,7 +29,7 @@ def semantic_playground(tmp_path_factory: pytest.TempPathFactory) -> Path: ) assert result.returncode == 0, result.stdout + result.stderr typed: Path = Path(__file__).parent / "fixtures" / "semantic" / "typed_orders.sql" - (project / "models" / "staging" / "stg_orders_typed.sql").write_text( + (project / "sql" / "models" / "staging" / "stg_orders_typed.sql").write_text( typed.read_text(encoding="utf-8"), encoding="utf-8" ) return project diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/fast_lineage/test_native_fast_lineage.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/fast_lineage/test_native_fast_lineage.py index 0621386f95..c1753e4252 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/fast_lineage/test_native_fast_lineage.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/fast_lineage/test_native_fast_lineage.py @@ -25,21 +25,21 @@ "sqlbuild_project.toml": ( 'name = "orders_lineage"\nadapter = "duckdb"\n\n[connection]\ndatabase = "orders.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Orders feed.\n expression: >-\n" " (SELECT 1 AS order_id, 10 AS customer_id, CAST(5 AS DOUBLE) AS amount)\n" " columns:\n - name: order_id\n type: INTEGER\n" " - name: customer_id\n type: INTEGER\n - name: amount\n type: DOUBLE\n" ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( 'MODEL (description "Staged orders");\n\nSELECT * FROM __source("raw_orders")\n' ), - "models/marts/order_union.sql": ( + "sql/models/marts/order_union.sql": ( 'MODEL (description "Orders twice", sql_analysis false);\n\n' 'SELECT o.*, 1 AS copy_number FROM __ref("stg_orders") o\n' 'UNION ALL\nSELECT *, 2 FROM __ref("stg_orders")\n' ), - "models/marts/customer_totals.sql": ( + "sql/models/marts/customer_totals.sql": ( 'MODEL (description "Totals per customer", sql_analysis false);\n\n' "WITH totals AS (\n" ' SELECT customer_id, SUM(amount) AS "Total_Amount" FROM __ref("order_union")\n' @@ -47,7 +47,7 @@ 'SELECT T.customer_id, "Total_Amount", CAST("Total_Amount" AS BIGINT) AS rounded\n' "FROM totals AS T\n" ), - "models/marts/order_copies.sql": ( + "sql/models/marts/order_copies.sql": ( 'MODEL (description "Order copies");\n\n' 'SELECT u.*, c.rounded FROM __ref("order_union") u\n' 'JOIN __ref("customer_totals") c ON u.customer_id = c.customer_id\n' @@ -63,15 +63,15 @@ _DEEP_UNION_BRANCHES: int = 480 _DEEP_UNION_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_FILES["sqlbuild_project.toml"], - "sources/raw.yml": _PROJECT_FILES["sources/raw.yml"], - "models/marts/orders_union.sql": ( + "sql/sources/raw.yml": _PROJECT_FILES["sql/sources/raw.yml"], + "sql/models/marts/orders_union.sql": ( 'MODEL (description "Orders repeated", sql_analysis false);\n\n' + " UNION ALL ".join( ['SELECT order_id, amount FROM __source("raw_orders")'] * _DEEP_UNION_BRANCHES ) + "\n" ), - "models/marts/orders_second.sql": ( + "sql/models/marts/orders_second.sql": ( 'MODEL (description "Order ids", sql_analysis false);\n\n' 'SELECT order_id FROM __source("raw_orders")\n' ), @@ -80,14 +80,14 @@ _RICH_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_FILES["sqlbuild_project.toml"], - "sources/raw.yml": _PROJECT_FILES["sources/raw.yml"], - "seeds/regions.csv": "region_id,label\n1,north\n", - "seeds/regions.yml": ( + "sql/sources/raw.yml": _PROJECT_FILES["sql/sources/raw.yml"], + "sql/seeds/regions.csv": "region_id,label\n1,north\n", + "sql/seeds/regions.yml": ( "seeds:\n - name: regions\n description: Regions.\n columns:\n" " - name: region_id\n type: INTEGER\n - name: label\n type: VARCHAR\n" ), - "models/staging/stg_orders.sql": _PROJECT_FILES["models/staging/stg_orders.sql"], - "models/marts/order_facts.sql": ( + "sql/models/staging/stg_orders.sql": _PROJECT_FILES["sql/models/staging/stg_orders.sql"], + "sql/models/marts/order_facts.sql": ( 'MODEL (description "Order facts");\n\n' "WITH ranked AS (\n" " SELECT o.*, r.label, CAST(o.amount AS BIGINT) AS whole_amount\n" @@ -98,7 +98,7 @@ " whole_amount, amount * 2 AS doubled, 'fixed' AS tag\n" "FROM ranked\n" ), - "models/marts/customer_totals.sql": ( + "sql/models/marts/customer_totals.sql": ( 'MODEL (description "Totals per customer");\n\n' "SELECT customer_id, SUM(doubled) AS total_doubled, COUNT(*) AS order_count,\n" " MAX(region_label) AS region_label\n" @@ -106,7 +106,7 @@ "UNION ALL\n" 'SELECT customer_id, amount, 1, NULL FROM __source("raw_orders")\n' ), - "models/marts/customer_copies.sql": ( + "sql/models/marts/customer_copies.sql": ( 'MODEL (description "Customer copies");\n\n' 'SELECT t.*, f.tag FROM __ref("customer_totals") AS t\n' 'JOIN __ref("order_facts") AS f USING (customer_id)\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/fixtures/semantic/corpus.json b/tests/e2e/src/sqlbuild/cli/commands/main/compile/fixtures/semantic/corpus.json index 501e6324a2..5615de9ee5 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/fixtures/semantic/corpus.json +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/fixtures/semantic/corpus.json @@ -7,7 +7,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\")\n" } }, { @@ -17,7 +17,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity AS q, q + 1 AS q2 FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity AS q, q + 1 AS q2 FROM __source(\"raw__orders\")\n" } }, { @@ -27,7 +27,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at > '2026-01-01'\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at > '2026-01-01'\n" } }, { @@ -37,7 +37,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status, COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY ALL\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status, COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY ALL\n" } }, { @@ -47,7 +47,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * EXCLUDE (status) FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * EXCLUDE (status) FROM __source(\"raw__orders\")\n" } }, { @@ -57,7 +57,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity * 2.5 AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity * 2.5 AS x FROM __source(\"raw__orders\")\n" } }, { @@ -67,7 +67,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id, p.amount_cents FROM __ref(\"stg_orders_typed\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id, p.amount_cents FROM __ref(\"stg_orders_typed\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" } }, { @@ -77,7 +77,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity AS q FROM __source(\"raw__orders\") ORDER BY q\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity AS q FROM __source(\"raw__orders\") ORDER BY q\n" } }, { @@ -87,7 +87,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o WHERE EXISTS (SELECT 1 FROM __source(\"raw__customers\") c WHERE c.id = o.customer_id)\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o WHERE EXISTS (SELECT 1 FROM __source(\"raw__customers\") c WHERE c.id = o.customer_id)\n" } }, { @@ -97,7 +97,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_at) = 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_at) = 1\n" }, "ignored_rules": [ "SQLCLEAN018" @@ -110,7 +110,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT AVG(ordered_at) AS a FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT AVG(ordered_at) AS a FROM __source(\"raw__orders\")\n" } }, { @@ -120,7 +120,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity\n" } }, { @@ -130,7 +130,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT NOT quantity AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT NOT quantity AS x FROM __source(\"raw__orders\")\n" } }, { @@ -140,7 +140,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at AS x FROM __source(\"raw__orders\") UNION ALL SELECT email FROM __source(\"raw__customers\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at AS x FROM __source(\"raw__orders\") UNION ALL SELECT email FROM __source(\"raw__customers\")\n" } }, { @@ -150,7 +150,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity AS x FROM __source(\"raw__orders\") UNION ALL SELECT TRUE FROM __source(\"raw__customers\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity AS x FROM __source(\"raw__orders\") UNION ALL SELECT TRUE FROM __source(\"raw__customers\")\n" } }, { @@ -160,7 +160,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, id FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, id FROM __source(\"raw__orders\")\n" } }, { @@ -170,7 +170,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH c(a, b) AS (SELECT id FROM __source(\"raw__orders\")) SELECT a FROM c\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH c(a, b) AS (SELECT id FROM __source(\"raw__orders\")) SELECT a FROM c\n" } }, { @@ -180,7 +180,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity + 1 FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity + 1 FROM __source(\"raw__orders\")\n" } }, { @@ -190,7 +190,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(status = 'x') AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(status = 'x') AS s FROM __source(\"raw__orders\")\n" } }, { @@ -200,7 +200,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity AND status = 'x'\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity AND status = 'x'\n" } }, { @@ -210,7 +210,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.customer_id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.customer_id\n" } }, { @@ -220,7 +220,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH c(a, b, d) AS (SELECT id, status FROM __source(\"raw__orders\")) SELECT a FROM c\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH c(a, b, d) AS (SELECT id, status FROM __source(\"raw__orders\")) SELECT a FROM c\n" } }, { @@ -230,7 +230,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.customer_id = c.id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.customer_id = c.id\n" } }, { @@ -240,14 +240,14 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT DISTINCT status FROM __source(\"raw__orders\") ORDER BY quantity\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT DISTINCT status FROM __source(\"raw__orders\") ORDER BY quantity\n" } }, { "description": "control: declared scalar UDF return type", "category": "control", "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table, contract enforced, columns (valid (type BOOLEAN)));\nSELECT __udf(\"udf__is_completed_order\")(status) AS valid FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table, contract enforced, columns (valid (type BOOLEAN)));\nSELECT __udf(\"udf__is_completed_order\")(status) AS valid FROM __source(\"raw__orders\")\n" }, "expected_exit_code": 0, "expected_codes": [], @@ -260,7 +260,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH o AS (SELECT * FROM __source(\"raw__orders\")), c AS (SELECT * FROM __source(\"raw__customers\")) SELECT o.id FROM o JOIN c ON o.id = c.id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH o AS (SELECT * FROM __source(\"raw__orders\")), c AS (SELECT * FROM __source(\"raw__customers\")) SELECT o.id FROM o JOIN c ON o.id = c.id\n" } } ], @@ -274,7 +274,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT qty FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT qty FROM __source(\"raw__orders\")\n" } }, { @@ -286,7 +286,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.qty FROM __source(\"raw__orders\") o\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.qty FROM __source(\"raw__orders\") o\n" } }, { @@ -298,7 +298,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT qty FROM __ref(\"stg_orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT qty FROM __ref(\"stg_orders\")\n" } }, { @@ -310,7 +310,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.qty FROM __ref(\"stg_orders_typed\") o\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.qty FROM __ref(\"stg_orders_typed\") o\n" } }, { @@ -322,7 +322,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT amount_usd FROM __source(\"raw__payments\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT amount_usd FROM __source(\"raw__payments\")\n" } }, { @@ -334,7 +334,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT price_usd FROM __seed(\"waffle_types\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT price_usd FROM __seed(\"waffle_types\")\n" } }, { @@ -346,7 +346,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE qty > 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE qty > 1\n" } }, { @@ -358,7 +358,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY stat\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY stat\n" } }, { @@ -370,7 +370,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") ORDER BY qty\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") ORDER BY qty\n" } }, { @@ -382,7 +382,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.customer = c.id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.customer = c.id\n" } }, { @@ -394,7 +394,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, ROW_NUMBER() OVER (PARTITION BY cust ORDER BY ordered_at) AS rn FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, ROW_NUMBER() OVER (PARTITION BY cust ORDER BY ordered_at) AS rn FROM __source(\"raw__orders\")\n" } }, { @@ -406,7 +406,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") QUALIFY ROW_NUMBER() OVER (PARTITION BY cust ORDER BY ordered_at) = 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") QUALIFY ROW_NUMBER() OVER (PARTITION BY cust ORDER BY ordered_at) = 1\n" } }, { @@ -418,7 +418,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status, COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY status HAVING SUM(qty) > 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status, COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY status HAVING SUM(qty) > 1\n" } }, { @@ -430,7 +430,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CASE WHEN qty > 1 THEN 'a' END AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CASE WHEN qty > 1 THEN 'a' END AS x FROM __source(\"raw__orders\")\n" } }, { @@ -442,7 +442,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT UPPER(stat) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT UPPER(stat) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -454,7 +454,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH x AS (SELECT id FROM __source(\"raw__orders\")) SELECT quantity FROM x\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH x AS (SELECT id FROM __source(\"raw__orders\")) SELECT quantity FROM x\n" } }, { @@ -466,7 +466,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT s.quantity FROM (SELECT id FROM __source(\"raw__orders\")) s\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT s.quantity FROM (SELECT id FROM __source(\"raw__orders\")) s\n" } }, { @@ -478,7 +478,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT z.id FROM __source(\"raw__orders\") o\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT z.id FROM __source(\"raw__orders\") o\n" } }, { @@ -490,7 +490,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o WHERE EXISTS (SELECT 1 FROM __source(\"raw__customers\") c WHERE c.id = o.cust)\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o WHERE EXISTS (SELECT 1 FROM __source(\"raw__customers\") c WHERE c.id = o.cust)\n" } }, { @@ -502,7 +502,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE customer_id IN (SELECT cust_id FROM __source(\"raw__customers\"))\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE customer_id IN (SELECT cust_id FROM __source(\"raw__customers\"))\n" } }, { @@ -514,7 +514,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id FROM __ref(\"stg_orders\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id WHERE p.amount > 0\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id FROM __ref(\"stg_orders\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id WHERE p.amount > 0\n" } }, { @@ -526,7 +526,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c USING (cust_id)\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c USING (cust_id)\n" } }, { @@ -538,7 +538,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT @py.cents_to_dollars('SUM(amount_usd)') AS d FROM __source(\"raw__payments\")\n" + "sql/models/marts/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT @py.cents_to_dollars('SUM(amount_usd)') AS d FROM __source(\"raw__payments\")\n" } }, { @@ -550,7 +550,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")(stat) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")(stat) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -562,7 +562,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT order_id FROM __ref(\"stg_orders\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT order_id FROM __ref(\"stg_orders\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" } }, { @@ -574,7 +574,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.customer_id = c.id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.customer_id = c.id\n" } }, { @@ -586,7 +586,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON id = c.id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON id = c.id\n" } }, { @@ -598,7 +598,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id FROM __ref(\"stg_orders\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id WHERE order_id > 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id FROM __ref(\"stg_orders\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id WHERE order_id > 1\n" } }, { @@ -610,7 +610,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")(quantity) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")(quantity) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -622,7 +622,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status, quantity, COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY status\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status, quantity, COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY status\n" } }, { @@ -634,7 +634,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE SUM(quantity) > 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE SUM(quantity) > 1\n" } }, { @@ -646,7 +646,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(COUNT(*)) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(COUNT(*)) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -658,7 +658,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ROW_NUMBER() OVER () = 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ROW_NUMBER() OVER () = 1\n" } }, { @@ -670,7 +670,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, COUNT(*) AS n FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, COUNT(*) AS n FROM __source(\"raw__orders\")\n" } }, { @@ -682,7 +682,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status FROM __source(\"raw__orders\") GROUP BY status HAVING quantity > 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status FROM __source(\"raw__orders\") GROUP BY status HAVING quantity > 1\n" } }, { @@ -694,7 +694,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status FROM __source(\"raw__orders\") GROUP BY 3\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status FROM __source(\"raw__orders\") GROUP BY 3\n" } }, { @@ -706,7 +706,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")(status, id) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")(status, id) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -718,7 +718,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH x AS (SELECT 1 AS id) SELECT quantity FROM x\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH x AS (SELECT 1 AS id) SELECT quantity FROM x\n" } }, { @@ -730,7 +730,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT order_id FROM __ref(\"stg_orders_typed\") WHERE qty > 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT order_id FROM __ref(\"stg_orders_typed\") WHERE qty > 1\n" } }, { @@ -742,7 +742,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id FROM __ref(\"stg_orders_typed\") o JOIN __seed(\"waffle_types\") w ON o.waffle = w.waffle_type_id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id FROM __ref(\"stg_orders_typed\") o JOIN __seed(\"waffle_types\") w ON o.waffle = w.waffle_type_id\n" } }, { @@ -754,7 +754,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT waffle_type_id FROM __ref(\"stg_orders_typed\") o JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT waffle_type_id FROM __ref(\"stg_orders_typed\") o JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\n" } }, { @@ -766,7 +766,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH x AS (SELECT order_id FROM __ref(\"stg_orders_typed\")) SELECT quantity FROM x\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH x AS (SELECT order_id FROM __ref(\"stg_orders_typed\")) SELECT quantity FROM x\n" } }, { @@ -778,7 +778,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT qty FROM __ref(\"stg_orders_typed\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT qty FROM __ref(\"stg_orders_typed\")\n" } }, { @@ -790,7 +790,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT w.price_usd FROM __source(\"raw__orders\") o JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT w.price_usd FROM __source(\"raw__orders\") o JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\n" } }, { @@ -802,7 +802,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/probe_m.sql": "MODEL (description \"Test model probe_m.\", materialized table);\n\nSELECT @py.cents_to_dollars('SUM(amount_usd)') AS d FROM __source(\"raw__payments\")\n" + "sql/models/marts/probe_m.sql": "MODEL (description \"Test model probe_m.\", materialized table);\n\nSELECT @py.cents_to_dollars('SUM(amount_usd)') AS d FROM __source(\"raw__payments\")\n" } }, { @@ -814,7 +814,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"total_revenue_cents >= 0\",\n ),\n ],\n contract enforced,\n columns (\n revenue_date (nullable false),\n order_count (type BIGINT),\n waffles_sold (type HUGEINT),\n total_revenue_cents (type VARCHAR),\n total_revenue_dollars (type DOUBLE),\n avg_order_value_cents (type DOUBLE),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" + "sql/models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"total_revenue_cents >= 0\",\n ),\n ],\n contract enforced,\n columns (\n revenue_date (nullable false),\n order_count (type BIGINT),\n waffles_sold (type HUGEINT),\n total_revenue_cents (type VARCHAR),\n total_revenue_dollars (type DOUBLE),\n avg_order_value_cents (type DOUBLE),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" } }, { @@ -826,7 +826,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders_typed.sql": "MODEL (description \"Test model stg_orders_typed.\",\n materialized view,\n contract enforced,\n columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n waffle_type_id (type INTEGER),\n quantity (type VARCHAR),\n ordered_at (type TIMESTAMP),\n status (type VARCHAR),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders_typed.sql": "MODEL (description \"Test model stg_orders_typed.\",\n materialized view,\n contract enforced,\n columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n waffle_type_id (type INTEGER),\n quantity (type VARCHAR),\n ordered_at (type TIMESTAMP),\n status (type VARCHAR),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -839,7 +839,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_payments.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned payment records.\",\n columns (\n payment_id (audits [not_null, unique]),\n order_id (\n audits [not_null, relationships (to __source(\"raw__orders\"), field id)],\n ),\n ),\n);\n\nSELECT\n id AS payment_id,\n order_id,\n payment_method,\n paid_at,\n status AS payment_status\nFROM __source(\"raw__payments\")\n" + "sql/models/staging/stg_payments.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned payment records.\",\n columns (\n payment_id (audits [not_null, unique]),\n order_id (\n audits [not_null, relationships (to __source(\"raw__orders\"), field id)],\n ),\n ),\n);\n\nSELECT\n id AS payment_id,\n order_id,\n payment_method,\n paid_at,\n status AS payment_status\nFROM __source(\"raw__payments\")\n" } }, { @@ -851,8 +851,8 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders_typed.sql": "MODEL (description \"Test model stg_orders_typed.\",\n materialized view,\n contract enforced,\n columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n waffle_type_id (type INTEGER),\n qty (type INTEGER),\n ordered_at (type TIMESTAMP),\n status (type VARCHAR),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity AS qty,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n", - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity FROM __ref(\"stg_orders_typed\")\n" + "sql/models/staging/stg_orders_typed.sql": "MODEL (description \"Test model stg_orders_typed.\",\n materialized view,\n contract enforced,\n columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n waffle_type_id (type INTEGER),\n qty (type INTEGER),\n ordered_at (type TIMESTAMP),\n status (type VARCHAR),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity AS qty,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n", + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity FROM __ref(\"stg_orders_typed\")\n" } }, { @@ -864,7 +864,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n p.amount_usd AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" + "sql/models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n p.amount_usd AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" } }, { @@ -876,7 +876,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n CAST(NULL AS INTEGER) AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n CAST(NULL AS INTEGER) AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -888,7 +888,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY SUM(quantity)\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY SUM(quantity)\n" } }, { @@ -900,7 +900,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) FILTER (WHERE qty > 1) AS n FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) FILTER (WHERE qty > 1) AS n FROM __source(\"raw__orders\")\n" } }, { @@ -912,7 +912,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON SUM(o.customer_id) = c.id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON SUM(o.customer_id) = c.id\n" } }, { @@ -924,7 +924,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(ROW_NUMBER() OVER ()) AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(ROW_NUMBER() OVER ()) AS s FROM __source(\"raw__orders\")\n" } }, { @@ -936,7 +936,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY ROW_NUMBER() OVER ()\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY ROW_NUMBER() OVER ()\n" } }, { @@ -948,7 +948,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LAG(quantity) OVER (ORDER BY ordered) AS l FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LAG(quantity) OVER (ORDER BY ordered) AS l FROM __source(\"raw__orders\")\n" } }, { @@ -958,7 +958,7 @@ "expected_codes": [], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT UPPER(status, status) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT UPPER(status, status) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -970,7 +970,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT x.id FROM (SELECT id FROM __source(\"raw__orders\"))\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT x.id FROM (SELECT id FROM __source(\"raw__orders\"))\n" } }, { @@ -982,7 +982,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") o WHERE EXISTS (SELECT 1 FROM __source(\"raw__customers\") c WHERE c.id = z.customer_id)\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") o WHERE EXISTS (SELECT 1 FROM __source(\"raw__customers\") c WHERE c.id = z.customer_id)\n" } }, { @@ -994,7 +994,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id, l.x FROM __source(\"raw__orders\") o, LATERAL (SELECT o.qty AS x) l\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id, l.x FROM __source(\"raw__orders\") o, LATERAL (SELECT o.qty AS x) l\n" } }, { @@ -1006,7 +1006,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT a.id FROM (SELECT id, status FROM __source(\"raw__orders\")) a JOIN (SELECT id FROM __source(\"raw__customers\")) b USING (status)\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT a.id FROM (SELECT id, status FROM __source(\"raw__orders\")) a JOIN (SELECT id FROM __source(\"raw__customers\")) b USING (status)\n" } }, { @@ -1018,7 +1018,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON c.id = p.order_id JOIN __source(\"raw__payments\") p ON p.order_id = o.id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON c.id = p.order_id JOIN __source(\"raw__payments\") p ON p.order_id = o.id\n" } }, { @@ -1030,7 +1030,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT z FROM (SELECT id FROM __source(\"raw__orders\") UNION ALL BY NAME SELECT id FROM __source(\"raw__customers\")) u\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT z FROM (SELECT id FROM __source(\"raw__orders\") UNION ALL BY NAME SELECT id FROM __source(\"raw__customers\")) u\n" } }, { @@ -1042,7 +1042,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status, COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY status ORDER BY quantity\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status, COUNT(*) AS n FROM __source(\"raw__orders\") GROUP BY status ORDER BY quantity\n" } }, { @@ -1054,7 +1054,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")() AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")() AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1066,7 +1066,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT t.amount FROM __table_fn(\"table_fn__customer_orders\")(1) t\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT t.amount FROM __table_fn(\"table_fn__customer_orders\")(1) t\n" } }, { @@ -1078,7 +1078,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT t.order_id FROM __table_fn(\"table_fn__customer_orders\")(1, 2) t\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT t.order_id FROM __table_fn(\"table_fn__customer_orders\")(1, 2) t\n" } }, { @@ -1090,7 +1090,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/probe_m.sql": "MODEL (description \"Test model probe_m.\", materialized table);\n\nSELECT @py.cents_to_dollars('SUM(p.amount_usd)') AS d FROM __ref(\"stg_payments\") p\n" + "sql/models/marts/probe_m.sql": "MODEL (description \"Test model probe_m.\", materialized table);\n\nSELECT @py.cents_to_dollars('SUM(p.amount_usd)') AS d FROM __ref(\"stg_payments\") p\n" } }, { @@ -1102,7 +1102,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/dim_customers.sql": "MODEL (\n materialized table,\n unique_key [customer_key],\n row_diff_exclude_columns [email],\n tags [marts],\n description \"Customer dimension with lifetime metrics.\",\n columns (\n customer_id (nullable false, audits [not_null, unique]),\n ),\n);\n\nSELECT\n c.customer_id,\n c.first_name,\n c.last_name,\n c.email,\n c.created_at AS customer_since,\n COUNT(DISTINCT o.order_id) AS lifetime_orders,\n COALESCE(SUM(p.amount_cents), 0) AS lifetime_spend_cents\nFROM __ref(\"stg_customers\") c\nLEFT JOIN __ref(\"stg_orders\") o ON c.customer_id = o.customer_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.created_at\n" + "sql/models/marts/dim_customers.sql": "MODEL (\n materialized table,\n unique_key [customer_key],\n row_diff_exclude_columns [email],\n tags [marts],\n description \"Customer dimension with lifetime metrics.\",\n columns (\n customer_id (nullable false, audits [not_null, unique]),\n ),\n);\n\nSELECT\n c.customer_id,\n c.first_name,\n c.last_name,\n c.email,\n c.created_at AS customer_since,\n COUNT(DISTINCT o.order_id) AS lifetime_orders,\n COALESCE(SUM(p.amount_cents), 0) AS lifetime_spend_cents\nFROM __ref(\"stg_customers\") c\nLEFT JOIN __ref(\"stg_orders\") o ON c.customer_id = o.customer_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.created_at\n" } }, { @@ -1114,7 +1114,7 @@ ], "pending_native": false, "repo_files": { - "models/intermediate/order_status_index.sql": "MODEL (\n materialized incremental,\n incremental_strategy delete_insert,\n unique_key [order_id],\n cursor order_key,\n cursor_type integer,\n on_schema_change append_new_columns,\n replay_on_change bounded-7d,\n tags [intermediate, acceptance],\n description \"Integer-cursor incremental projection over fact orders.\",\n columns (\n order_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n order_id,\n customer_id,\n order_status,\n ordered_at,\n line_total_cents\nFROM __ref(\"fact_orders\")\n" + "sql/models/intermediate/order_status_index.sql": "MODEL (\n materialized incremental,\n incremental_strategy delete_insert,\n unique_key [order_id],\n cursor order_key,\n cursor_type integer,\n on_schema_change append_new_columns,\n replay_on_change bounded-7d,\n tags [intermediate, acceptance],\n description \"Integer-cursor incremental projection over fact orders.\",\n columns (\n order_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n order_id,\n customer_id,\n order_status,\n ordered_at,\n line_total_cents\nFROM __ref(\"fact_orders\")\n" } }, { @@ -1126,7 +1126,7 @@ ], "pending_native": false, "repo_files": { - "models/intermediate/order_status_index.sql": "MODEL (\n materialized incremental,\n incremental_strategy delete_insert,\n unique_key [order_id],\n cursor ordered_at,\n cursor_type integer,\n on_schema_change append_new_columns,\n replay_on_change bounded-7d,\n tags [intermediate, acceptance],\n description \"Integer-cursor incremental projection over fact orders.\",\n columns (\n order_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n order_id,\n customer_id,\n order_status,\n ordered_at,\n line_total_cents\nFROM __ref(\"fact_orders\")\n" + "sql/models/intermediate/order_status_index.sql": "MODEL (\n materialized incremental,\n incremental_strategy delete_insert,\n unique_key [order_id],\n cursor ordered_at,\n cursor_type integer,\n on_schema_change append_new_columns,\n replay_on_change bounded-7d,\n tags [intermediate, acceptance],\n description \"Integer-cursor incremental projection over fact orders.\",\n columns (\n order_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n order_id,\n customer_id,\n order_status,\n ordered_at,\n line_total_cents\nFROM __ref(\"fact_orders\")\n" } }, { @@ -1138,7 +1138,7 @@ ], "pending_native": false, "repo_files": { - "models/intermediate/customer_status_snapshot.sql": "MODEL (\n materialized incremental,\n incremental_strategy merge,\n unique_key [customer_id],\n cursor last_ordered_at,\n cursor_type timestamp,\n cursor_grain second,\n row_diff_exclude_columns [latest_order_status],\n row_diff_tolerances (\n by_column (\n total_revenue_cents (\n absolute 1,\n ),\n ),\n ),\n cursor_inputs (\n fact_orders ordered_ts,\n ),\n on_schema_change sync_all_columns,\n replay_on_change full,\n tags [intermediate, acceptance],\n description \"Merge-based customer snapshot with timestamp cursor and explicit backfill policies.\",\n columns (\n customer_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n customer_id,\n MAX(ordered_at) AS last_ordered_at,\n MAX(order_status) AS latest_order_status,\n COUNT(*) AS total_orders,\n SUM(line_total_cents) AS total_revenue_cents\nFROM __ref(\"fact_orders\")\nGROUP BY customer_id\n" + "sql/models/intermediate/customer_status_snapshot.sql": "MODEL (\n materialized incremental,\n incremental_strategy merge,\n unique_key [customer_id],\n cursor last_ordered_at,\n cursor_type timestamp,\n cursor_grain second,\n row_diff_exclude_columns [latest_order_status],\n row_diff_tolerances (\n by_column (\n total_revenue_cents (\n absolute 1,\n ),\n ),\n ),\n cursor_inputs (\n fact_orders ordered_ts,\n ),\n on_schema_change sync_all_columns,\n replay_on_change full,\n tags [intermediate, acceptance],\n description \"Merge-based customer snapshot with timestamp cursor and explicit backfill policies.\",\n columns (\n customer_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n customer_id,\n MAX(ordered_at) AS last_ordered_at,\n MAX(order_status) AS latest_order_status,\n COUNT(*) AS total_orders,\n SUM(line_total_cents) AS total_revenue_cents\nFROM __ref(\"fact_orders\")\nGROUP BY customer_id\n" } }, { @@ -1150,7 +1150,7 @@ ], "pending_native": false, "repo_files": { - "models/intermediate/customer_status_snapshot.sql": "MODEL (\n materialized incremental,\n incremental_strategy merge,\n unique_key [customer_id],\n cursor last_ordered_at,\n cursor_type timestamp,\n cursor_grain second,\n row_diff_exclude_columns [latest_status],\n row_diff_tolerances (\n by_column (\n total_revenue_cents (\n absolute 1,\n ),\n ),\n ),\n cursor_inputs (\n fact_orders ordered_at,\n ),\n on_schema_change sync_all_columns,\n replay_on_change full,\n tags [intermediate, acceptance],\n description \"Merge-based customer snapshot with timestamp cursor and explicit backfill policies.\",\n columns (\n customer_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n customer_id,\n MAX(ordered_at) AS last_ordered_at,\n MAX(order_status) AS latest_order_status,\n COUNT(*) AS total_orders,\n SUM(line_total_cents) AS total_revenue_cents\nFROM __ref(\"fact_orders\")\nGROUP BY customer_id\n" + "sql/models/intermediate/customer_status_snapshot.sql": "MODEL (\n materialized incremental,\n incremental_strategy merge,\n unique_key [customer_id],\n cursor last_ordered_at,\n cursor_type timestamp,\n cursor_grain second,\n row_diff_exclude_columns [latest_status],\n row_diff_tolerances (\n by_column (\n total_revenue_cents (\n absolute 1,\n ),\n ),\n ),\n cursor_inputs (\n fact_orders ordered_at,\n ),\n on_schema_change sync_all_columns,\n replay_on_change full,\n tags [intermediate, acceptance],\n description \"Merge-based customer snapshot with timestamp cursor and explicit backfill policies.\",\n columns (\n customer_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n customer_id,\n MAX(ordered_at) AS last_ordered_at,\n MAX(order_status) AS latest_order_status,\n COUNT(*) AS total_orders,\n SUM(line_total_cents) AS total_revenue_cents\nFROM __ref(\"fact_orders\")\nGROUP BY customer_id\n" } }, { @@ -1162,7 +1162,7 @@ ], "pending_native": false, "repo_files": { - "models/intermediate/customer_status_snapshot.sql": "MODEL (\n materialized incremental,\n incremental_strategy merge,\n unique_key [customer_id],\n cursor last_ordered_at,\n cursor_type timestamp,\n cursor_grain second,\n row_diff_exclude_columns [latest_order_status],\n row_diff_tolerances (\n by_column (\n total_revenue (\n absolute 1,\n ),\n ),\n ),\n cursor_inputs (\n fact_orders ordered_at,\n ),\n on_schema_change sync_all_columns,\n replay_on_change full,\n tags [intermediate, acceptance],\n description \"Merge-based customer snapshot with timestamp cursor and explicit backfill policies.\",\n columns (\n customer_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n customer_id,\n MAX(ordered_at) AS last_ordered_at,\n MAX(order_status) AS latest_order_status,\n COUNT(*) AS total_orders,\n SUM(line_total_cents) AS total_revenue_cents\nFROM __ref(\"fact_orders\")\nGROUP BY customer_id\n" + "sql/models/intermediate/customer_status_snapshot.sql": "MODEL (\n materialized incremental,\n incremental_strategy merge,\n unique_key [customer_id],\n cursor last_ordered_at,\n cursor_type timestamp,\n cursor_grain second,\n row_diff_exclude_columns [latest_order_status],\n row_diff_tolerances (\n by_column (\n total_revenue (\n absolute 1,\n ),\n ),\n ),\n cursor_inputs (\n fact_orders ordered_at,\n ),\n on_schema_change sync_all_columns,\n replay_on_change full,\n tags [intermediate, acceptance],\n description \"Merge-based customer snapshot with timestamp cursor and explicit backfill policies.\",\n columns (\n customer_id (audits [not_null, unique]),\n ),\n);\n\nSELECT\n customer_id,\n MAX(ordered_at) AS last_ordered_at,\n MAX(order_status) AS latest_order_status,\n COUNT(*) AS total_orders,\n SUM(line_total_cents) AS total_revenue_cents\nFROM __ref(\"fact_orders\")\nGROUP BY customer_id\n" } }, { @@ -1174,7 +1174,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/daily_order_partitioned.sql": "MODEL (\n materialized partition_tracked,\n tags [marts],\n placeholders (\n partition_start \"'2026-04-01'\",\n partition_end \"'2026-04-05'\",\n ),\n config (\n tracking_table partition_state,\n partition_column order_day,\n date_range_start 2026-04-01,\n date_range_end 2026-04-05,\n ),\n description \"Partition-tracked daily order summary using custom materialization.\",\n columns (\n order_date (audits [not_null]),\n ),\n audits [\n expression_is_true (\n name \"waffles_ordered_is_positive\",\n expression \"waffles_ordered > 0\",\n ),\n ],\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS order_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_ordered,\n COUNT(DISTINCT o.customer_id) AS unique_customers\nFROM __ref(\"stg_orders\") o\nWHERE CAST(o.ordered_at AS DATE) >= CAST(@@@partition_start AS DATE)\n AND CAST(o.ordered_at AS DATE) < CAST(@@@partition_end AS DATE)\nGROUP BY CAST(o.ordered_at AS DATE)\n" + "sql/models/marts/daily_order_partitioned.sql": "MODEL (\n materialized partition_tracked,\n tags [marts],\n placeholders (\n partition_start \"'2026-04-01'\",\n partition_end \"'2026-04-05'\",\n ),\n config (\n tracking_table partition_state,\n partition_column order_day,\n date_range_start 2026-04-01,\n date_range_end 2026-04-05,\n ),\n description \"Partition-tracked daily order summary using custom materialization.\",\n columns (\n order_date (audits [not_null]),\n ),\n audits [\n expression_is_true (\n name \"waffles_ordered_is_positive\",\n expression \"waffles_ordered > 0\",\n ),\n ],\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS order_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_ordered,\n COUNT(DISTINCT o.customer_id) AS unique_customers\nFROM __ref(\"stg_orders\") o\nWHERE CAST(o.ordered_at AS DATE) >= CAST(@@@partition_start AS DATE)\n AND CAST(o.ordered_at AS DATE) < CAST(@@@partition_end AS DATE)\nGROUP BY CAST(o.ordered_at AS DATE)\n" } }, { @@ -1186,7 +1186,7 @@ ], "pending_native": false, "repo_files": { - "sources/raw.yml": "sources:\n - name: raw__customers\n contract: enforced\n managed: true\n write_strategy: table\n columns:\n - name: id\n type: INTEGER\n - name: first_name\n type: VARCHAR\n - name: last_name\n type: VARCHAR\n - name: email\n type: VARCHAR\n - name: created_at\n type: TIMESTAMP\n\n - name: raw__orders\n contract: enforced\n managed: true\n write_strategy: delete_insert\n cursor_column: ordered_ts\n columns:\n - name: id\n type: INTEGER\n - name: customer_id\n type: INTEGER\n - name: waffle_type_id\n type: INTEGER\n - name: quantity\n type: INTEGER\n - name: ordered_at\n type: TIMESTAMP\n - name: status\n type: VARCHAR\n\n - name: raw__payments\n expression: |\n SELECT 1 AS id, 1 AS order_id, 1700 AS amount_cents, 'credit_card' AS payment_method, CAST('2026-04-01 09:16:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 2 AS id, 2 AS order_id, 1050 AS amount_cents, 'credit_card' AS payment_method, CAST('2026-04-01 09:16:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 3 AS id, 3 AS order_id, 4350 AS amount_cents, 'cash' AS payment_method, CAST('2026-04-01 10:31:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 4 AS id, 4 AS order_id, 950 AS amount_cents, 'credit_card' AS payment_method, CAST('2026-04-02 08:46:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 5 AS id, 5 AS order_id, 850 AS amount_cents, 'debit_card' AS payment_method, CAST('2026-04-02 12:01:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 6 AS id, 6 AS order_id, 750 AS amount_cents, 'debit_card' AS payment_method, CAST('2026-04-02 12:01:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 7 AS id, 7 AS order_id, 2200 AS amount_cents, 'credit_card' AS payment_method, CAST(NULL AS TIMESTAMP) AS paid_at, 'failed' AS status\n UNION ALL SELECT 8 AS id, 8 AS order_id, 950 AS amount_cents, 'cash' AS payment_method, CAST('2026-04-03 11:01:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n columns:\n - name: amount_cents\n type: INTEGER\n" + "sql/sources/raw.yml": "sources:\n - name: raw__customers\n contract: enforced\n managed: true\n write_strategy: table\n columns:\n - name: id\n type: INTEGER\n - name: first_name\n type: VARCHAR\n - name: last_name\n type: VARCHAR\n - name: email\n type: VARCHAR\n - name: created_at\n type: TIMESTAMP\n\n - name: raw__orders\n contract: enforced\n managed: true\n write_strategy: delete_insert\n cursor_column: ordered_ts\n columns:\n - name: id\n type: INTEGER\n - name: customer_id\n type: INTEGER\n - name: waffle_type_id\n type: INTEGER\n - name: quantity\n type: INTEGER\n - name: ordered_at\n type: TIMESTAMP\n - name: status\n type: VARCHAR\n\n - name: raw__payments\n expression: |\n SELECT 1 AS id, 1 AS order_id, 1700 AS amount_cents, 'credit_card' AS payment_method, CAST('2026-04-01 09:16:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 2 AS id, 2 AS order_id, 1050 AS amount_cents, 'credit_card' AS payment_method, CAST('2026-04-01 09:16:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 3 AS id, 3 AS order_id, 4350 AS amount_cents, 'cash' AS payment_method, CAST('2026-04-01 10:31:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 4 AS id, 4 AS order_id, 950 AS amount_cents, 'credit_card' AS payment_method, CAST('2026-04-02 08:46:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 5 AS id, 5 AS order_id, 850 AS amount_cents, 'debit_card' AS payment_method, CAST('2026-04-02 12:01:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 6 AS id, 6 AS order_id, 750 AS amount_cents, 'debit_card' AS payment_method, CAST('2026-04-02 12:01:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n UNION ALL SELECT 7 AS id, 7 AS order_id, 2200 AS amount_cents, 'credit_card' AS payment_method, CAST(NULL AS TIMESTAMP) AS paid_at, 'failed' AS status\n UNION ALL SELECT 8 AS id, 8 AS order_id, 950 AS amount_cents, 'cash' AS payment_method, CAST('2026-04-03 11:01:00' AS TIMESTAMP) AS paid_at, 'success' AS status\n columns:\n - name: amount_cents\n type: INTEGER\n" } }, { @@ -1198,7 +1198,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/dim_customers.sql": "MODEL (\n materialized table,\n unique_key [customer_id],\n row_diff_exclude_columns [e_mail],\n tags [marts],\n description \"Customer dimension with lifetime metrics.\",\n columns (\n customer_id (nullable false, audits [not_null, unique]),\n ),\n);\n\nSELECT\n c.customer_id,\n c.first_name,\n c.last_name,\n c.email,\n c.created_at AS customer_since,\n COUNT(DISTINCT o.order_id) AS lifetime_orders,\n COALESCE(SUM(p.amount_cents), 0) AS lifetime_spend_cents\nFROM __ref(\"stg_customers\") c\nLEFT JOIN __ref(\"stg_orders\") o ON c.customer_id = o.customer_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.created_at\n" + "sql/models/marts/dim_customers.sql": "MODEL (\n materialized table,\n unique_key [customer_id],\n row_diff_exclude_columns [e_mail],\n tags [marts],\n description \"Customer dimension with lifetime metrics.\",\n columns (\n customer_id (nullable false, audits [not_null, unique]),\n ),\n);\n\nSELECT\n c.customer_id,\n c.first_name,\n c.last_name,\n c.email,\n c.created_at AS customer_since,\n COUNT(DISTINCT o.order_id) AS lifetime_orders,\n COALESCE(SUM(p.amount_cents), 0) AS lifetime_spend_cents\nFROM __ref(\"stg_customers\") c\nLEFT JOIN __ref(\"stg_orders\") o ON c.customer_id = o.customer_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.created_at\n" } }, { @@ -1210,7 +1210,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"total_revenue >= 0\",\n ),\n ],\n columns (\n revenue_date (nullable false),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" + "sql/models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"total_revenue >= 0\",\n ),\n ],\n columns (\n revenue_date (nullable false),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" } }, { @@ -1222,7 +1222,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -1234,7 +1234,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_kinds\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_kinds\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -1246,7 +1246,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null, accepted_values (values [\"a\", \"b\"])]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null, accepted_values (values [\"a\", \"b\"])]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -1258,7 +1258,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n order_ref (audits [not_null]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n order_ref (audits [not_null]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -1270,7 +1270,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_name)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_name)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -1282,7 +1282,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders_typed.sql": "MODEL (description \"Test model stg_orders_typed.\",\n materialized view,\n contract enforced,\n columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n waffle_type_id (type INTEGER),\n quantity (type INTEGER),\n ordered_at (type TIMESTAMP),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders_typed.sql": "MODEL (description \"Test model stg_orders_typed.\",\n materialized view,\n contract enforced,\n columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n waffle_type_id (type INTEGER),\n quantity (type INTEGER),\n ordered_at (type TIMESTAMP),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -1294,7 +1294,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders_typed.sql": "MODEL (description \"Test model stg_orders_typed.\",\n materialized view,\n contract enforced,\n columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n waffle_type_id (type INTEGER),\n quantity (type INTEGER),\n ordered_at (type TIMESTAMP),\n status (type STRINGY),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders_typed.sql": "MODEL (description \"Test model stg_orders_typed.\",\n materialized view,\n contract enforced,\n columns (\n order_id (type INTEGER),\n customer_id (type INTEGER),\n waffle_type_id (type INTEGER),\n quantity (type INTEGER),\n ordered_at (type TIMESTAMP),\n status (type STRINGY),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -1306,7 +1306,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"total_revenue_cents >= 0\",\n ),\n ],\n contract enforced,\n columns (\n revenue_date (type DATE),\n order_count (type BIGINT),\n waffles_sold (type HUGEINT),\n total_revenue_cents (type TIMESTAMP),\n total_revenue_dollars (type DOUBLE),\n avg_order_value_cents (type DOUBLE),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" + "sql/models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"total_revenue_cents >= 0\",\n ),\n ],\n contract enforced,\n columns (\n revenue_date (type DATE),\n order_count (type BIGINT),\n waffles_sold (type HUGEINT),\n total_revenue_cents (type TIMESTAMP),\n total_revenue_dollars (type DOUBLE),\n avg_order_value_cents (type DOUBLE),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" } }, { @@ -1318,7 +1318,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"total_revenue_cents >= 0\",\n ),\n ],\n contract enforced,\n columns (\n revenue_date (type INTEGER),\n order_count (type BIGINT),\n waffles_sold (type HUGEINT),\n total_revenue_cents (type HUGEINT),\n total_revenue_dollars (type DOUBLE),\n avg_order_value_cents (type DOUBLE),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" + "sql/models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"total_revenue_cents >= 0\",\n ),\n ],\n contract enforced,\n columns (\n revenue_date (type INTEGER),\n order_count (type BIGINT),\n waffles_sold (type HUGEINT),\n total_revenue_cents (type HUGEINT),\n total_revenue_dollars (type DOUBLE),\n avg_order_value_cents (type DOUBLE),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" } }, { @@ -1342,7 +1342,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n p.amount_usd AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" + "sql/models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n p.amount_usd AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" } }, { @@ -1354,7 +1354,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n amount_usd AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" + "sql/models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n amount_usd AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" } }, { @@ -1366,7 +1366,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_payments.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned payment records.\",\n columns (\n payment_id (audits [not_null, unique]),\n order_id (\n audits [not_null, relationships (to __source(\"raw__orders\"), field id)],\n ),\n ),\n);\n\nSELECT\n id AS payment_id,\n order_id,\n amount_usd,\n payment_method,\n paid_at,\n status AS payment_status\nFROM __source(\"raw__payments\")\n" + "sql/models/staging/stg_payments.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned payment records.\",\n columns (\n payment_id (audits [not_null, unique]),\n order_id (\n audits [not_null, relationships (to __source(\"raw__orders\"), field id)],\n ),\n ),\n);\n\nSELECT\n id AS payment_id,\n order_id,\n amount_usd,\n payment_method,\n paid_at,\n status AS payment_status\nFROM __source(\"raw__payments\")\n" } }, { @@ -1378,7 +1378,7 @@ ], "pending_native": false, "repo_files": { - "models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n qty,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n qty,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -1390,7 +1390,7 @@ ], "pending_native": false, "repo_files": { - "models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.qty,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n p.amount_cents AS payment_amount_cents\nFROM __ref(\"stg_orders_typed\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" + "sql/models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.qty,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n p.amount_cents AS payment_amount_cents\nFROM __ref(\"stg_orders_typed\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" } }, { @@ -1409,7 +1409,7 @@ "description": "metadata-udf: scalar UDF declared argument type", "category": "udf", "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\nSELECT __udf(\"udf__is_completed_order\")(quantity) AS valid FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\nSELECT __udf(\"udf__is_completed_order\")(quantity) AS valid FROM __source(\"raw__orders\")\n" }, "expected_exit_code": 1, "expected_codes": [ @@ -1426,7 +1426,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH o AS (SELECT * FROM __source(\"raw__orders\")), c AS (SELECT * FROM __source(\"raw__customers\")) SELECT o.id FROM o JOIN c ON o.id = c.email\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH o AS (SELECT * FROM __source(\"raw__orders\")), c AS (SELECT * FROM __source(\"raw__customers\")) SELECT o.id FROM o JOIN c ON o.id = c.email\n" } }, { @@ -1438,7 +1438,7 @@ ], "pending_native": false, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM (SELECT * FROM __source(\"raw__orders\")) AS o JOIN __source(\"raw__customers\") AS c ON o.id = c.email\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM (SELECT * FROM __source(\"raw__orders\")) AS o JOIN __source(\"raw__customers\") AS c ON o.id = c.email\n" } } ], @@ -1450,7 +1450,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH x AS (SELECT * FROM __source(\"raw__orders\")) SELECT qty FROM x\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH x AS (SELECT * FROM __source(\"raw__orders\")) SELECT qty FROM x\n" } }, { @@ -1460,7 +1460,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * EXCLUDE (qty) FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * EXCLUDE (qty) FROM __source(\"raw__orders\")\n" } }, { @@ -1470,7 +1470,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at > 5\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at > 5\n" } }, { @@ -1480,7 +1480,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity * status AS q FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity * status AS q FROM __source(\"raw__orders\")\n" } }, { @@ -1490,7 +1490,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.id = c.email\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") c ON o.id = c.email\n" } }, { @@ -1500,7 +1500,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(status) AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(status) AS s FROM __source(\"raw__orders\")\n" } }, { @@ -1510,7 +1510,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status > 5\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status > 5\n" } }, { @@ -1520,7 +1520,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status\n" } }, { @@ -1530,7 +1530,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CASE WHEN quantity > 1 THEN quantity ELSE status END AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CASE WHEN quantity > 1 THEN quantity ELSE status END AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1540,7 +1540,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COALESCE(quantity, status) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COALESCE(quantity, status) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1550,7 +1550,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity IN ('a', 'b')\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity IN ('a', 'b')\n" } }, { @@ -1560,7 +1560,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity LIKE '1%'\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity LIKE '1%'\n" } }, { @@ -1570,7 +1570,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT DATE_TRUNC('day', status) AS d FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT DATE_TRUNC('day', status) AS d FROM __source(\"raw__orders\")\n" } }, { @@ -1580,7 +1580,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at + status AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at + status AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1590,7 +1590,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LENGTH(quantity) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LENGTH(quantity) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1600,7 +1600,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at = 'not a date'\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at = 'not a date'\n" } }, { @@ -1610,7 +1610,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity - ordered_at AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity - ordered_at AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1620,7 +1620,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at BETWEEN 1 AND 5\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at BETWEEN 1 AND 5\n" } }, { @@ -1630,7 +1630,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o WHERE o.ordered_at > (SELECT MAX(email) FROM __source(\"raw__customers\"))\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o WHERE o.ordered_at > (SELECT MAX(email) FROM __source(\"raw__customers\"))\n" } }, { @@ -1640,7 +1640,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id FROM __ref(\"stg_orders_typed\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.payment_method\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.order_id FROM __ref(\"stg_orders_typed\") o JOIN __ref(\"stg_payments\") p ON o.order_id = p.payment_method\n" } }, { @@ -1650,7 +1650,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(p.payment_method) OVER () AS s FROM __ref(\"stg_payments\") p\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(p.payment_method) OVER () AS s FROM __ref(\"stg_payments\") p\n" } }, { @@ -1660,7 +1660,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT UPPER(quantity) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT UPPER(quantity) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1670,7 +1670,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status = TRUE\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status = TRUE\n" } }, { @@ -1680,7 +1680,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST(ordered_at AS INTEGER) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST(ordered_at AS INTEGER) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1690,7 +1690,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT order_id FROM __ref(\"stg_orders_typed\") WHERE ordered_at > 5\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT order_id FROM __ref(\"stg_orders_typed\") WHERE ordered_at > 5\n" } }, { @@ -1700,7 +1700,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity * status AS q FROM __ref(\"stg_orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity * status AS q FROM __ref(\"stg_orders\")\n" } }, { @@ -1710,7 +1710,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, status FROM __source(\"raw__orders\") UNION ALL SELECT id FROM __source(\"raw__customers\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, status FROM __source(\"raw__orders\") UNION ALL SELECT id FROM __source(\"raw__customers\")\n" } }, { @@ -1720,7 +1720,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") INTERSECT SELECT id, email FROM __source(\"raw__customers\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") INTERSECT SELECT id, email FROM __source(\"raw__customers\")\n" } }, { @@ -1730,7 +1730,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT not_a_function(id) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT not_a_function(id) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1740,7 +1740,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT DATE_TRUNC('day') AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT DATE_TRUNC('day') AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1750,7 +1750,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ROUND(status, 2) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ROUND(status, 2) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1760,7 +1760,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUBSTRING(status) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUBSTRING(status) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1770,7 +1770,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") ORDER BY 5\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") ORDER BY 5\n" } }, { @@ -1780,7 +1780,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH a AS (SELECT id FROM __source(\"raw__orders\")) SELECT * FROM b\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH a AS (SELECT id FROM __source(\"raw__orders\")) SELECT * FROM b\n" }, "ignored_rules": [ "SQLCLEAN005" @@ -1793,7 +1793,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM raw_orders\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM raw_orders\n" } }, { @@ -1803,7 +1803,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST('2020-01-01' AS TIMESTAMP) > 5 AS x\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST('2020-01-01' AS TIMESTAMP) > 5 AS x\n" } }, { @@ -1813,7 +1813,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity * status AS q FROM __ref(\"stg_orders_typed\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity * status AS q FROM __ref(\"stg_orders_typed\")\n" } }, { @@ -1823,7 +1823,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/staging/stg_payments.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned payment records.\",\n columns (\n payment_id (audits [not_null, unique]),\n order_id (\n audits [not_null, relationships (to __source(\"raw__orders\"), field id)],\n ),\n ),\n);\n\nSELECT\n id AS payment_id,\n order_id,\n CAST(amount_cents AS VARCHAR) AS amount_cents,\n payment_method,\n paid_at,\n status AS payment_status\nFROM __source(\"raw__payments\")\n" + "sql/models/staging/stg_payments.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned payment records.\",\n columns (\n payment_id (audits [not_null, unique]),\n order_id (\n audits [not_null, relationships (to __source(\"raw__orders\"), field id)],\n ),\n ),\n);\n\nSELECT\n id AS payment_id,\n order_id,\n CAST(amount_cents AS VARCHAR) AS amount_cents,\n payment_method,\n paid_at,\n status AS payment_status\nFROM __source(\"raw__payments\")\n" } }, { @@ -1833,7 +1833,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(ordered_at) AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(ordered_at) AS s FROM __source(\"raw__orders\")\n" } }, { @@ -1843,7 +1843,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT AVG(status) AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT AVG(status) AS s FROM __source(\"raw__orders\")\n" } }, { @@ -1853,7 +1853,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(CAST(ordered_at AS DATE)) AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(CAST(ordered_at AS DATE)) AS s FROM __source(\"raw__orders\")\n" } }, { @@ -1863,7 +1863,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(quantity, id) AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(quantity, id) AS s FROM __source(\"raw__orders\")\n" } }, { @@ -1873,7 +1873,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT STDDEV(status) AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT STDDEV(status) AS s FROM __source(\"raw__orders\")\n" } }, { @@ -1883,7 +1883,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(status) AS s FROM __ref(\"stg_orders_typed\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(status) AS s FROM __ref(\"stg_orders_typed\")\n" } }, { @@ -1893,7 +1893,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(waffle_name) AS s FROM __seed(\"waffle_types\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(waffle_name) AS s FROM __seed(\"waffle_types\")\n" } }, { @@ -1903,7 +1903,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) FILTER (WHERE status) AS n FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COUNT(*) FILTER (WHERE status) AS n FROM __source(\"raw__orders\")\n" } }, { @@ -1913,7 +1913,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ROW_NUMBER() AS rn FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ROW_NUMBER() AS rn FROM __source(\"raw__orders\")\n" } }, { @@ -1923,7 +1923,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LAG(quantity, status) OVER (ORDER BY id) AS l FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LAG(quantity, status) OVER (ORDER BY id) AS l FROM __source(\"raw__orders\")\n" } }, { @@ -1933,7 +1933,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT NTILE('a') OVER (ORDER BY id) AS t FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT NTILE('a') OVER (ORDER BY id) AS t FROM __source(\"raw__orders\")\n" } }, { @@ -1943,7 +1943,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(quantity) OVER (ORDER BY status RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(quantity) OVER (ORDER BY status RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) AS s FROM __source(\"raw__orders\")\n" } }, { @@ -1953,7 +1953,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(quantity) OVER w AS s FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(quantity) OVER w AS s FROM __source(\"raw__orders\")\n" } }, { @@ -1963,7 +1963,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") QUALIFY quantity > 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") QUALIFY quantity > 1\n" } }, { @@ -1973,7 +1973,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ABS(status) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ABS(status) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1983,7 +1983,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ROUND(ordered_at) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ROUND(ordered_at) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -1993,7 +1993,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT EXTRACT(year FROM status) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT EXTRACT(year FROM status) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2003,7 +2003,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT DATE_DIFF('day', status, ordered_at) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT DATE_DIFF('day', status, ordered_at) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2013,7 +2013,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SPLIT_PART(quantity, ',', 1) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SPLIT_PART(quantity, ',', 1) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2023,7 +2023,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT REGEXP_MATCHES(quantity, 'a') AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT REGEXP_MATCHES(quantity, 'a') AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2033,7 +2033,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SQRT(status) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SQRT(status) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2043,7 +2043,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT GREATEST(quantity, status) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT GREATEST(quantity, status) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2053,7 +2053,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LEAST(ordered_at, quantity) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LEAST(ordered_at, quantity) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2063,7 +2063,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT NULLIF(quantity, status) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT NULLIF(quantity, status) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2073,7 +2073,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT IFNULL(ordered_at, quantity) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT IFNULL(ordered_at, quantity) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2083,7 +2083,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT STRFTIME(quantity, '%Y') AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT STRFTIME(quantity, '%Y') AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2093,7 +2093,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LOWER(ordered_at) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LOWER(ordered_at) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2103,7 +2103,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LEFT(quantity, 2) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT LEFT(quantity, 2) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2113,7 +2113,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COALESCE() AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COALESCE() AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2123,7 +2123,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE is_valid(status)\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE is_valid(status)\n" } }, { @@ -2133,7 +2133,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT not_an_agg(quantity) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT not_an_agg(quantity) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2143,7 +2143,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status OR quantity > 1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status OR quantity > 1\n" } }, { @@ -2153,7 +2153,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at * 2 AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at * 2 AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2163,7 +2163,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status % 2 AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status % 2 AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2173,7 +2173,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status IS TRUE\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE status IS TRUE\n" } }, { @@ -2183,7 +2183,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at LIKE '2026%'\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at LIKE '2026%'\n" } }, { @@ -2193,7 +2193,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity BETWEEN 'a' AND 'b'\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE quantity BETWEEN 'a' AND 'b'\n" } }, { @@ -2203,7 +2203,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CASE WHEN status THEN 1 END AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CASE WHEN status THEN 1 END AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2213,7 +2213,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT -status AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT -status AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2223,7 +2223,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at - status AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at - status AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2233,7 +2233,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status FROM __source(\"raw__orders\") GROUP BY status HAVING status\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT status FROM __source(\"raw__orders\") GROUP BY status HAVING status\n" } }, { @@ -2243,7 +2243,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST(quantity AS NOT_A_TYPE) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST(quantity AS NOT_A_TYPE) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2253,7 +2253,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST(status = 'x' AS TIMESTAMP) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST(status = 'x' AS TIMESTAMP) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2263,7 +2263,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST(ordered_at AS BOOLEAN) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT CAST(ordered_at AS BOOLEAN) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2273,7 +2273,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at > DATE '2026-13-45'\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at > DATE '2026-13-45'\n" } }, { @@ -2283,7 +2283,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at + INTERVAL 'banana' AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT ordered_at + INTERVAL 'banana' AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2293,7 +2293,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE customer_id IN (SELECT id, email FROM __source(\"raw__customers\"))\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE customer_id IN (SELECT id, email FROM __source(\"raw__customers\"))\n" } }, { @@ -2303,7 +2303,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT (SELECT id, email FROM __source(\"raw__customers\") LIMIT 1) AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT (SELECT id, email FROM __source(\"raw__customers\") LIMIT 1) AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2313,7 +2313,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at IN (SELECT email FROM __source(\"raw__customers\"))\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE ordered_at IN (SELECT email FROM __source(\"raw__customers\"))\n" } }, { @@ -2323,7 +2323,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE (id, customer_id) = (1, 2, 3)\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") WHERE (id, customer_id) = (1, 2, 3)\n" } }, { @@ -2333,7 +2333,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") o ON o.id = o.id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT o.id FROM __source(\"raw__orders\") o JOIN __source(\"raw__customers\") o ON o.id = o.id\n" } }, { @@ -2343,7 +2343,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * FROM (SELECT id FROM __source(\"raw__orders\")) a JOIN (SELECT email AS id FROM __source(\"raw__customers\")) b USING (id)\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * FROM (SELECT id FROM __source(\"raw__orders\")) a JOIN (SELECT email AS id FROM __source(\"raw__customers\")) b USING (id)\n" } }, { @@ -2353,7 +2353,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") JOIN __source(\"raw__orders\") ON id = id\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") JOIN __source(\"raw__orders\") ON id = id\n" } }, { @@ -2363,7 +2363,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH a AS (SELECT id FROM __source(\"raw__orders\")), a AS (SELECT id FROM __source(\"raw__customers\")) SELECT id FROM a\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH a AS (SELECT id FROM __source(\"raw__orders\")), a AS (SELECT id FROM __source(\"raw__customers\")) SELECT id FROM a\n" } }, { @@ -2373,7 +2373,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT 'x' FROM r WHERE n < 3) SELECT n FROM r\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT 'x' FROM r WHERE n < 3) SELECT n FROM r\n" } }, { @@ -2383,7 +2383,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH a AS (SELECT id FROM b), b AS (SELECT id FROM __source(\"raw__orders\")) SELECT id FROM a\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nWITH a AS (SELECT id FROM b), b AS (SELECT id FROM __source(\"raw__orders\")) SELECT id FROM a\n" } }, { @@ -2393,7 +2393,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") UNION ALL SELECT id FROM __source(\"raw__customers\") ORDER BY status\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") UNION ALL SELECT id FROM __source(\"raw__customers\") ORDER BY status\n" } }, { @@ -2403,7 +2403,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, status FROM __source(\"raw__orders\") EXCEPT SELECT id FROM __source(\"raw__customers\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id, status FROM __source(\"raw__orders\") EXCEPT SELECT id FROM __source(\"raw__customers\")\n" } }, { @@ -2413,7 +2413,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity AS x FROM __source(\"raw__orders\") UNION ALL SELECT created_at FROM __source(\"raw__customers\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT quantity AS x FROM __source(\"raw__orders\") UNION ALL SELECT created_at FROM __source(\"raw__customers\")\n" } }, { @@ -2423,7 +2423,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT z.* FROM __source(\"raw__orders\") o\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT z.* FROM __source(\"raw__orders\") o\n" } }, { @@ -2433,7 +2433,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * REPLACE (1 AS qty) FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT * REPLACE (1 AS qty) FROM __source(\"raw__orders\")\n" } }, { @@ -2443,7 +2443,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COLUMNS('^nothing_') FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT COLUMNS('^nothing_') FROM __source(\"raw__orders\")\n" } }, { @@ -2453,7 +2453,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT x.qty FROM (SELECT * FROM __ref(\"stg_orders\")) x\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT x.qty FROM (SELECT * FROM __ref(\"stg_orders\")) x\n" } }, { @@ -2463,7 +2463,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") LIMIT 'x'\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") LIMIT 'x'\n" } }, { @@ -2473,7 +2473,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") LIMIT -1\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") LIMIT -1\n" } }, { @@ -2483,7 +2483,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") LIMIT quantity\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT id FROM __source(\"raw__orders\") LIMIT quantity\n" } }, { @@ -2493,7 +2493,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")(status) + 1 AS x FROM __source(\"raw__orders\")\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT __udf(\"udf__is_completed_order\")(status) + 1 AS x FROM __source(\"raw__orders\")\n" } }, { @@ -2503,7 +2503,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT t.order_id FROM __table_fn(\"table_fn__customer_orders\")('abc') t\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT t.order_id FROM __table_fn(\"table_fn__customer_orders\")('abc') t\n" } }, { @@ -2513,7 +2513,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(t.waffle_name) AS s FROM __table_fn(\"table_fn__customer_orders\")(1) t\n" + "sql/models/probe.sql": "MODEL (description \"Test model probe.\", materialized table);\n\nSELECT SUM(t.waffle_name) AS s FROM __table_fn(\"table_fn__customer_orders\")(1) t\n" } }, { @@ -2523,7 +2523,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/marts/probe_m.sql": "MODEL (description \"Test model probe_m.\", materialized table);\n\nSELECT UPPER(@py.cents_to_dollars('p.amount_cents')) AS d FROM __ref(\"stg_payments\") p\n" + "sql/models/marts/probe_m.sql": "MODEL (description \"Test model probe_m.\", materialized table);\n\nSELECT UPPER(@py.cents_to_dollars('p.amount_cents')) AS d FROM __ref(\"stg_payments\") p\n" } }, { @@ -2533,7 +2533,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"revenue_date > 5\",\n ),\n ],\n columns (\n revenue_date (nullable false),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" + "sql/models/marts/daily_revenue.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Daily revenue aggregation.\",\n audits [\n expression_is_true (\n name \"revenue_is_non_negative\",\n expression \"revenue_date > 5\",\n ),\n ],\n columns (\n revenue_date (nullable false),\n ),\n);\n\nSELECT\n CAST(o.ordered_at AS DATE) AS revenue_date,\n COUNT(DISTINCT o.order_id) AS order_count,\n SUM(o.quantity) AS waffles_sold,\n SUM(p.amount_cents) AS total_revenue_cents,\n @py.cents_to_dollars('SUM(p.amount_cents)') AS total_revenue_dollars,\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\nFROM __ref(\"stg_orders\") o\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = 'success'\nGROUP BY CAST(o.ordered_at AS DATE)\n" } }, { @@ -2543,7 +2543,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\nWHERE ordered_at > 5\n" + "sql/models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\nWHERE ordered_at > 5\n" } }, { @@ -2553,7 +2553,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity * status AS quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" + "sql/models/staging/stg_orders.sql": "MODEL (\n materialized view,\n tags [staging],\n description \"Cleaned order records.\",\n columns (\n order_id (nullable false, audits [not_null, unique]),\n customer_id (nullable false, audits [not_null]),\n waffle_type_id (\n audits [relationships (to __seed(\"waffle_types\"), field waffle_type_id)],\n ),\n status (\n audits [\n accepted_values (values [\"placed\", \"preparing\", \"ready\", \"completed\", \"cancelled\"]),\n ],\n ),\n ),\n);\n\nSELECT\n id AS order_id,\n customer_id,\n waffle_type_id,\n quantity * status AS quantity,\n ordered_at,\n status\nFROM __source(\"raw__orders\")\n" } }, { @@ -2563,7 +2563,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n p.amount_cents AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.payment_method\n" + "sql/models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n p.amount_cents AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.payment_method\n" } }, { @@ -2573,7 +2573,7 @@ "expected_codes": [], "pending_native": true, "repo_files": { - "models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n SUM(p.payment_method) OVER () AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" + "sql/models/marts/fact_orders.sql": "MODEL (\n materialized table,\n tags [marts],\n description \"Order fact table with waffle and payment details.\",\n columns (\n order_id (nullable false, audits [not_null]),\n ),\n);\n\nSELECT\n o.order_id,\n o.customer_id,\n o.waffle_type_id,\n w.waffle_name,\n w.category AS waffle_category,\n o.quantity,\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\n o.ordered_at,\n o.status AS order_status,\n __udf(\"udf__is_completed_order\")(o.status) AS is_completed_order,\n p.payment_method,\n p.payment_status,\n SUM(p.payment_method) OVER () AS payment_amount_cents\nFROM __ref(\"stg_orders\") o\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id\n" } } ] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/header_strings/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/header_strings/helpers.py index e6309efefd..e7d32f5930 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/header_strings/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/header_strings/helpers.py @@ -11,8 +11,8 @@ 'name = "shop"\nadapter = "duckdb"\n\n[connection]\ndatabase = "shop.duckdb"\n\n' "[scopes]\nenforce_placement = false\n" ), - "seeds/raw_customers.csv": "customer_id,title\n1,Miss\n2,Mr\n", - "seeds/raw_customers.yml": ( + "sql/seeds/raw_customers.csv": "customer_id,title\n1,Miss\n2,Mr\n", + "sql/seeds/raw_customers.yml": ( "seeds:\n - name: raw_customers\n description: Raw customers.\n" " columns:\n - name: customer_id\n type: BIGINT\n" " - name: title\n type: VARCHAR\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/header_strings/test_header_strings.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/header_strings/test_header_strings.py index e84f2ca867..9408302c36 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/header_strings/test_header_strings.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/header_strings/test_header_strings.py @@ -74,29 +74,29 @@ [ HeaderQuoteErrorTestCase( description="model_description_escaping_a_quote", - path="models/customers.sql", + path="sql/models/customers.sql", contents=( 'MODEL (\n description "Matches a title (\\"Miss\\").",\n);\n\n' "SELECT 1 AS customer_id\n" ), expected_code="D002", - expected_location="models/customers.sql:2:34", + expected_location="sql/models/customers.sql:2:34", expected_message=_QUOTE_MESSAGE, ), HeaderQuoteErrorTestCase( description="macro_description_escaping_a_quote", - path="macros/sql/title.sql", + path="sql/macros/sql/title.sql", contents=( 'MACRO (\n description "Matches a title (\\"Miss\\").",\n' " arguments (value VARCHAR),\n returns VARCHAR,\n);\n\n@value\n" ), expected_code="P015", - expected_location="macros/sql/title.sql:2:34", + expected_location="sql/macros/sql/title.sql:2:34", expected_message=_QUOTE_MESSAGE, ), HeaderQuoteErrorTestCase( description="wrapped_macro_description_with_apostrophes_escaping_quotes", - path="macros/sql/title.sql", + path="sql/macros/sql/title.sql", contents=( "MACRO (\n" " description \"True when a name starts with a woman's title: Mme, Mlle, Miss, " @@ -107,71 +107,71 @@ " arguments (value VARCHAR),\n returns VARCHAR,\n);\n\n@value\n" ), expected_code="P015", - expected_location="macros/sql/title.sql:3:25", + expected_location="sql/macros/sql/title.sql:3:25", expected_message=_QUOTE_MESSAGE, ), HeaderQuoteErrorTestCase( description="schema_description_escaping_a_quote", - path="schemas/customer.sql", + path="sql/schemas/customer.sql", contents=( 'SCHEMA (\n name customer,\n description "The \\"shop\\" customer",\n' " columns (customer_id (type BIGINT)),\n);\n" ), expected_code="D013", - expected_location="schemas/customer.sql:3:21", + expected_location="sql/schemas/customer.sql:3:21", expected_message=_QUOTE_MESSAGE, ), HeaderQuoteErrorTestCase( description="model_description_doubling_a_quote", - path="models/customers.sql", + path="sql/models/customers.sql", contents=('MODEL (\n description "say ""hi"" now",\n);\n\nSELECT 1 AS customer_id\n'), expected_code="D002", - expected_location="models/customers.sql:2:20", + expected_location="sql/models/customers.sql:2:20", expected_message=_QUOTE_MESSAGE, ), HeaderQuoteErrorTestCase( description="macro_description_doubling_a_quote", - path="macros/sql/title.sql", + path="sql/macros/sql/title.sql", contents=( 'MACRO (\n description "say ""hi"" now",\n' " arguments (value VARCHAR),\n returns VARCHAR,\n);\n\n@value\n" ), expected_code="P015", - expected_location="macros/sql/title.sql:2:20", + expected_location="sql/macros/sql/title.sql:2:20", expected_message=_QUOTE_MESSAGE, ), HeaderQuoteErrorTestCase( description="audit_header_scanned_past_a_triple_quoted_string", - path="audits/singular/orders_have_customers.sql", + path="sql/audits/singular/orders_have_customers.sql", contents=( 'AUDIT (name "orders_have_customers", ' 'description """Rerun "sqb audit --all" after loads""");\n\n' 'SELECT 1 FROM __seed("raw_customers") WHERE FALSE\n' ), expected_code="D004", - expected_location="audits/singular/orders_have_customers.sql:1", + expected_location="sql/audits/singular/orders_have_customers.sql:1", expected_message="has unsupported keys: description", ), HeaderQuoteErrorTestCase( description="unclosed_triple_quote", - path="models/customers.sql", + path="sql/models/customers.sql", contents=( 'MODEL (\n description """Never closed,\n materialized table,\n);\n\n' "SELECT 1 AS customer_id\n" ), expected_code="D002", - expected_location="models/customers.sql:2:15", + expected_location="sql/models/customers.sql:2:15", expected_message='this """ string is never closed', ), HeaderQuoteErrorTestCase( description="triple_quote_inside_a_triple_quoted_string", - path="models/customers.sql", + path="sql/models/customers.sql", contents=( 'MODEL (\n description """He said """hi""" twice.""",\n);\n\n' "SELECT 1 AS customer_id\n" ), expected_code="D002", - expected_location="models/customers.sql:2:26", + expected_location="sql/models/customers.sql:2:26", expected_message='""" inside a """...""" string ends it early', ), ], @@ -199,9 +199,9 @@ def test_given_misquoted_header_string_when_compiling_then_error_names_the_quote FoldedDescriptionTestCase( description="triple_quoted_and_wrapped_model_schema_and_macro_descriptions", files={ - "macros/sql/is_womans_title.sql": _TITLE_MACRO, - "schemas/customer.sql": _CUSTOMER_SCHEMA, - "models/customers.sql": _CUSTOMERS_MODEL, + "sql/macros/sql/is_womans_title.sql": _TITLE_MACRO, + "sql/schemas/customer.sql": _CUSTOMER_SCHEMA, + "sql/models/customers.sql": _CUSTOMERS_MODEL, }, expected_description=( 'Customers with a "woman\'s title" flag, one row each.\n\nBuilt from the raw seed.' @@ -271,7 +271,7 @@ def test_given_model_description_quoted_as_before_when_compiling_then_its_text_i test_case: AcceptedDescriptionTestCase, tmp_path: Path ) -> None: project_dir: Path = header_strings_project( - tmp_path, {"models/customers.sql": test_case.header + "\nSELECT 1 AS customer_id\n"} + tmp_path, {"sql/models/customers.sql": test_case.header + "\nSELECT 1 AS customer_id\n"} ) dag: subprocess.CompletedProcess[str] = run_sqb( @@ -312,11 +312,11 @@ def test_given_macro_description_quoted_as_before_when_compiling_then_the_projec project_dir: Path = header_strings_project( tmp_path, { - "macros/sql/lowered.sql": ( + "sql/macros/sql/lowered.sql": ( f"MACRO (\n {test_case.header},\n arguments (value VARCHAR),\n" " returns VARCHAR,\n);\n\nLOWER(@value)\n" ), - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (description "Customers.");\n\n' "SELECT customer_id, @sql.lowered(title) AS title\n" 'FROM __seed("raw_customers")\n' @@ -353,7 +353,7 @@ def test_given_adjacent_strings_outside_descriptions_when_compiling_then_they_re project_dir: Path = header_strings_project( tmp_path, { - "models/customers.sql": ( + "sql/models/customers.sql": ( f'MODEL (\n description "Customers.",\n tags {test_case.tags},\n);\n\n' "SELECT 1 AS customer_id\n" ) @@ -386,7 +386,7 @@ def test_given_meta_description_with_escaped_quote_when_building_then_meta_keeps project_dir: Path = header_strings_project( tmp_path, { - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (\n description "Customers.",\n' f" audits [not_null (column customer_id, {test_case.meta})],\n);\n\n" "SELECT 1 AS customer_id\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/helpers.py index 73ca6cd767..3253a9da12 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/helpers.py @@ -151,7 +151,7 @@ def prepare_semantic_corpus_project( path.write_text(contents, encoding="utf-8") ignored: str = ", ".join(f'"{code}"' for code in test_case.ignored_rules) ignore_entry: str = ( - f'\n[[rules.rule_ignores]]\nrules = [{ignored}]\npaths = ["models/**"]\n' + f'\n[[rules.rule_ignores]]\nrules = [{ignored}]\npaths = ["sql/models/**"]\n' 'reason = "The probe SQL exercises compiler semantics, not this Rule."\n' ) with (project / "sqlbuild_project.toml").open("a", encoding="utf-8") as config: @@ -384,7 +384,7 @@ def run_test_heavy_compile_benchmark( project_dir=project_dir, expected_max_seconds=expected_warm_max_seconds, ) - _append_benchmark_edit(project_dir / "models" / "model_00000.sql", "model") + _append_benchmark_edit(project_dir / "sql" / "models" / "model_00000.sql", "model") model_edit_seconds: float = _run_compile_benchmark( project_dir=project_dir, expected_max_seconds=expected_edit_max_seconds, @@ -457,7 +457,7 @@ def run_layered_production_compile_benchmark( project_dir=project_dir, expected_max_seconds=expected_edit_max_seconds, ) - macro_path: Path = project_dir / "macros" / "python" / "macro_00000.py" + macro_path: Path = project_dir / "sql" / "macros" / "python" / "macro_00000.py" _replace_benchmark_text( path=macro_path, old='return f"({expression} + 0)"', @@ -1273,11 +1273,11 @@ def _generated_model_path(project_dir: Path, index: int) -> Path: (False, True): "intermediate", (False, False): "mart", }[(layer_index < 4, layer_index < 8)] - return project_dir / "models" / folder / f"model_{index:05d}.sql" + return project_dir / "sql" / "models" / folder / f"model_{index:05d}.sql" def measure_model_sql_bytes(project_dir: Path) -> int: - return sum(path.stat().st_size for path in (project_dir / "models").rglob("*.sql")) + return sum(path.stat().st_size for path in (project_dir / "sql" / "models").rglob("*.sql")) def measure_compiled_test_sql_bytes(project_dir: Path) -> int: @@ -1288,7 +1288,7 @@ def measure_compiled_test_sql_bytes(project_dir: Path) -> int: def measure_declared_model_columns(project_dir: Path) -> int: return sum( path.read_text(encoding="utf-8").count("(type ") - for path in (project_dir / "models").rglob("*.sql") + for path in (project_dir / "sql" / "models").rglob("*.sql") ) @@ -1314,7 +1314,7 @@ def write_advanced_compile_project( model_count: int, scan_event_lines_per_model: int = 0, ) -> None: - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" models_dir.mkdir(parents=True) _write_compile_project_config(project_dir) base_model_sql: str = _with_reference_scan_workload( @@ -1333,7 +1333,7 @@ def write_advanced_compile_project( def write_dbt_shaped_compile_project(*, project_dir: Path, model_count: int) -> None: - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" models_dir.mkdir(parents=True) _write_compile_project_config(project_dir) base_model_sql: str = _with_base_generated_logic( @@ -1357,7 +1357,7 @@ def write_test_heavy_compile_project( chain_depth: int, fixture_row_count: int, ) -> None: - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" tests_dir: Path = project_dir / "tests" / "unit" models_dir.mkdir(parents=True) tests_dir.mkdir(parents=True) @@ -1400,7 +1400,7 @@ def _write_compile_project_config(project_dir: Path) -> None: "", "[[rules.rule_ignores]]", 'rules = ["SQLCLEAN018"]', - 'paths = ["models/**"]', + 'paths = ["sql/models/**"]', 'reason = "The generated workload ranks by a non-unique id; keep its SQL stable."', "", ) @@ -1780,7 +1780,7 @@ def _layered_write_project_config(*, project_dir: Path, compiler_only: bool = Fa {rules_selection}[[rules.rule_ignores]] rules = ["SQLCLEAN039"] -paths = ["models/**"] +paths = ["sql/models/**"] reason = "The workload mixes nested query shapes on purpose to cover their compile path." """, encoding="utf-8", @@ -1788,8 +1788,8 @@ def _layered_write_project_config(*, project_dir: Path, compiler_only: bool = Fa def _layered_write_sources(*, project_dir: Path, source_count: int) -> None: - sources_dir: Path = project_dir / "sources" - sources_dir.mkdir() + sources_dir: Path = project_dir / "sql" / "sources" + sources_dir.mkdir(parents=True) entries: str = "\n".join( f""" - name: source_{index:05d} description: Test source source_{index:05d}. @@ -1807,8 +1807,8 @@ def _layered_write_sources(*, project_dir: Path, source_count: int) -> None: def _layered_write_seeds(*, project_dir: Path, seed_count: int) -> None: - seeds_dir: Path = project_dir / "seeds" - seeds_dir.mkdir() + seeds_dir: Path = project_dir / "sql" / "seeds" + seeds_dir.mkdir(parents=True) schema_entries: str = "\n".join( f""" - name: seed_{index:05d} description: Test seed seed_{index:05d}. @@ -1828,7 +1828,7 @@ def _layered_write_seeds(*, project_dir: Path, seed_count: int) -> None: def _layered_write_functions(*, project_dir: Path, function_count: int) -> None: - functions_dir: Path = project_dir / "functions" / "sql" + functions_dir: Path = project_dir / "sql" / "functions" / "sql" functions_dir.mkdir(parents=True) for index in range(function_count): (functions_dir / f"fn_{index:05d}.sql").write_text( @@ -1844,7 +1844,7 @@ def _layered_write_functions(*, project_dir: Path, function_count: int) -> None: def _layered_write_macros(*, project_dir: Path, macro_count: int) -> None: - macros_dir: Path = project_dir / "macros" / "python" + macros_dir: Path = project_dir / "sql" / "macros" / "python" macros_dir.mkdir(parents=True) for index in range(macro_count): composed_dependency: str = { @@ -1878,17 +1878,19 @@ def _scope_single_folder_macros(*, project_dir: Path) -> None: """Move each macro beside its only consuming folder and drop unused macros.""" consumer_folders: dict[str, set[str]] = {} - for model_path in sorted((project_dir / "models").rglob("*.sql")): + for model_path in sorted((project_dir / "sql" / "models").rglob("*.sql")): for call in _BENCHMARK_MACRO_CALL.findall(model_path.read_text(encoding="utf-8")): consumer_folders.setdefault(call, set()).add(model_path.parent.name) - macros_dir: Path = project_dir / "macros" / "python" + macros_dir: Path = project_dir / "sql" / "macros" / "python" generated: set[str] = {path.stem for path in macros_dir.glob("macro_*.py")} for unused_stem in sorted(generated - set(consumer_folders)): (macros_dir / f"{unused_stem}.py").unlink() assert all(len(folders) == 1 for folders in consumer_folders.values()) for stem, folders in sorted(consumer_folders.items()): (folder,) = folders - scoped_dir: Path = project_dir / "models" / folder / "_sqlbuild" / "_macros" / "python" + scoped_dir: Path = ( + project_dir / "sql" / "models" / folder / "_sqlbuild" / "_macros" / "python" + ) scoped_dir.mkdir(parents=True, exist_ok=True) (macros_dir / f"{stem}.py").rename(scoped_dir / f"{stem}.py") @@ -1897,7 +1899,7 @@ def _layered_write_schemas(*, project_dir: Path) -> None: """Write the contract schema beside its only consumer, the first staging model.""" schemas_dir: Path = ( - project_dir / "models" / _layered_model_folder(index=0) / "_sqlbuild" / "_schemas" + project_dir / "sql" / "models" / _layered_model_folder(index=0) / "_sqlbuild" / "_schemas" ) schemas_dir.mkdir(parents=True) (schemas_dir / "benchmark_row.sql").write_text( @@ -1926,7 +1928,7 @@ def _layered_write_models( ) -> None: for index in range(model_count): folder: str = _layered_model_folder(index=index) - model_dir: Path = project_dir / "models" / folder + model_dir: Path = project_dir / "sql" / "models" / folder model_dir.mkdir(parents=True, exist_ok=True) sql: str = _layered_model_sql( index=index, @@ -2112,7 +2114,7 @@ def _semantic_write_models( macro_call_interval: int = _MACRO_INTERVAL, ) -> None: for index in range(model_count): - model_dir: Path = project_dir / "models" / _layered_model_folder(index=index) + model_dir: Path = project_dir / "sql" / "models" / _layered_model_folder(index=index) model_dir.mkdir(parents=True, exist_ok=True) column_count: int = _semantic_model_column_count(index=index, model_count=model_count) builders: dict[bool, Callable[[], str]] = { @@ -2320,7 +2322,7 @@ def write_shared_diamond_models(*, project_dir: Path, layer_count: int, width: i exponentially many paths, and the rollup fans the final layer back in. """ - model_dir: Path = project_dir / "models" / _SHARED_DIAMOND_FOLDER + model_dir: Path = project_dir / "sql" / "models" / _SHARED_DIAMOND_FOLDER model_dir.mkdir(parents=True) files: dict[str, str] = { SHARED_DIAMOND_HUB: _shared_diamond_sql(inputs=(_SHARED_DIAMOND_UPSTREAM_MODEL,)), @@ -2515,19 +2517,19 @@ def build_rule_gated_test_project_files(*, filler_model_count: int) -> dict[str, "sqlbuild_project.toml": ( 'name = "rule_gated_orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQBRMODEL102"]\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" " - name: raw_refunds\n description: Test source raw_refunds.\n" " schema: main\n table: raw_refunds\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized view);\n\n" 'SELECT o.order_id, r.refund_id FROM __source("raw_orders") AS o\n' 'LEFT JOIN __source("raw_refunds") AS r ON r.order_id = o.order_id\n' ), - "models/bad_star.sql": ( + "sql/models/bad_star.sql": ( 'MODEL (description "Test model bad_star.", ' 'materialized view);\n\nSELECT * FROM __source("raw_orders")\n' ), @@ -2540,7 +2542,7 @@ def build_rule_gated_test_project_files(*, filler_model_count: int) -> dict[str, ), } for index in range(filler_model_count): - files[f"models/filler/filler_{index:03d}.sql"] = ( + files[f"sql/models/filler/filler_{index:03d}.sql"] = ( "MODEL (description 'Test model.', " f"materialized view);\n\nSELECT {index} AS filler_id\n" ) @@ -2566,24 +2568,24 @@ def build_empty_input_test_project_files( "[rules.thresholds]\nmin_tests_per_model = 1\n\n" f"[rules.rule_options.SQBRTEST203]\nallowed_tests = {allowed_tests_toml}\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized view);\n\n" "SELECT order_id, amount * 2 AS doubled_amount\n" 'FROM __source("raw_orders")\nWHERE amount > 0\n' ), - "models/large_orders.sql": ( + "sql/models/large_orders.sql": ( "MODEL (description 'Test model large_orders.', materialized view);\n\n" 'SELECT order_id FROM __source("raw_orders") WHERE amount > 100\n' ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Test model customers.', materialized view);\n\n" 'SELECT order_id AS customer_id FROM __source("raw_orders") WHERE amount > 10\n' ), - "models/order_summary.sql": ( + "sql/models/order_summary.sql": ( "MODEL (description 'Test model order_summary.', materialized view);\n\n" "SELECT COUNT(*) AS order_count, COALESCE(SUM(amount), 0) AS total_amount\n" 'FROM __source("raw_orders")\n' @@ -2690,7 +2692,7 @@ def change_benchmark_models( def _benchmark_model_path(*, project_dir: Path, name: str) -> Path: - return next((project_dir / "models").rglob(f"{name}.sql")) + return next((project_dir / "sql" / "models").rglob(f"{name}.sql")) def plan_reasons_and_migrations( @@ -2733,21 +2735,21 @@ def write_relation_stub_project( 'schema = "main"\n\n' "[[rules.rule_ignores]]\n" 'rules = ["SQLCLEAN005"]\n' - 'paths = ["models/order_status.sql"]\n' + 'paths = ["sql/models/order_status.sql"]\n' 'reason = "The stub-named CTE is left unread on purpose."\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', " "materialized table);\n\nSELECT CAST(7 AS INTEGER) AS order_id\n" ), - "models/order_status.sql": ( + "sql/models/order_status.sql": ( "MODEL (description 'Test model order_status.', materialized table);\n\n" f"WITH {stub_cte_name} AS (\n" " SELECT 'pending' AS order_id, 'pending' AS ghost_status\n" ")\n" f'SELECT {selected_column} FROM __ref("orders")\n' ), - "models/next_order.sql": ( + "sql/models/next_order.sql": ( "MODEL (description 'Test model next_order.',\n" " materialized table,\n" " contract enforced,\n" @@ -2765,13 +2767,13 @@ def write_relation_stub_project( r"^(?:error|warning)\[.*$", re.MULTILINE ) _COMPILE_CACHE_EXTRA_PROJECT_FILES: dict[str, str] = { - "models/marts/_sqlbuild/_enums/order_channel.sql": ( + "sql/models/marts/_sqlbuild/_enums/order_channel.sql": ( 'ENUM (\n name order_channel,\n members (WEB "web", PARTNER "partner"),\n);\n' ), - "models/marts/_sqlbuild/_constants/min_quantity.sql": ( + "sql/models/marts/_sqlbuild/_constants/min_quantity.sql": ( "CONSTANT (name min_quantity, value 1);\n" ), - "models/marts/channel_orders.sql": ( + "sql/models/marts/channel_orders.sql": ( "MODEL (description 'Test model channel_orders.',\n" " materialized table,\n" " columns (\n" @@ -2914,7 +2916,7 @@ def prepare_compile_cache_invalidation_project(*, project_dir: Path) -> None: ) -RESOURCE_SQL_MODELS: str = "models/staging" +RESOURCE_SQL_MODELS: str = "sql/models/staging" RESOURCE_SQL_ORDERS: str = f"{RESOURCE_SQL_MODELS}/orders.sql" RESOURCE_SQL_SINGULAR_AUDIT: str = ( f"{RESOURCE_SQL_MODELS}/_sqlbuild/audits/singular/orders_have_customers.sql" @@ -3062,7 +3064,7 @@ def write_set_operation_project( ), } for model in models: - files[f"models/{model.name}.sql"] = ( + files[f"sql/models/{model.name}.sql"] = ( "MODEL (description 'Test model.', materialized view, schema analytics);\n\n" f"{model.query_sql}\n" ) @@ -3135,7 +3137,7 @@ def format_set_operation_models( ) -> tuple[subprocess.CompletedProcess[str], tuple[str, ...]]: """Format every model and return the result and any set-operation lines left indented.""" - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" formatted: subprocess.CompletedProcess[str] = run_sqb( project_dir=project_dir, command=("format", str(models_dir)) ) @@ -3192,11 +3194,11 @@ def write_union_fixture_test_project( f'name = "orders"\nadapter = "duckdb"\n[connection]\n' f'database = "{project_dir / "orders.duckdb"}"\n[rules]\nselect = []\n' ), - "models/base_orders.sql": ( + "sql/models/base_orders.sql": ( "MODEL (description 'Test model base_orders.', materialized view);\n\n" "SELECT 1 AS order_id, CAST(1 AS DOUBLE) AS amount, 'open' AS status\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized view);\n\n" 'SELECT b.order_id, b.amount, b.status FROM __ref("base_orders") AS b\n' ), @@ -3259,7 +3261,7 @@ def hooked_model_file(*, model_name: str, hook: str) -> tuple[str, str]: """Return a described model file whose post hook references ``hook``.""" return ( - f"models/{model_name}.sql", + f"sql/models/{model_name}.sql", f'MODEL (description "Orders with a hook", post_hooks [{hook}]);\n\nSELECT 1 AS order_id\n', ) @@ -3298,7 +3300,7 @@ def compile_inline_files( project_name="orders", repo_files={ "sqlbuild_project.toml": REQUIRED_DESCRIPTIONS_PROJECT, - "models/orders.sql": _REQUIRED_DESCRIPTIONS_ORDERS_MODEL, + "sql/models/orders.sql": _REQUIRED_DESCRIPTIONS_ORDERS_MODEL, **dict(files), }, ) @@ -3366,36 +3368,36 @@ def diagnostic_location_keys(payload: dict[str, Any]) -> tuple[tuple[str, str, i _PROGRESS_LINE: re.Pattern[str] = re.compile(r".+ (START|OK \(\d+\.\d+s\))") _COMPILE_TIMINGS_PATTERN: re.Pattern[str] = re.compile(r'\n "compile_timings": \{[^{}]*\n \}') _COMPILE_REUSE_EXTRA_PROJECT_FILES: dict[str, str] = { - "macros/python/_rounding.py": ( + "sql/macros/python/_rounding.py": ( "_SCALE: int = 2\n\n\ndef scale() -> int:\n" ' """Return the rounding scale."""\n return _SCALE\n' ), - "macros/python/currency.py": ( - '"""Project-wide currency macros."""\n\nfrom macros.python._rounding import scale\n\n\n' + "sql/macros/python/currency.py": ( + '"""Project-wide currency macros."""\n\nfrom sql.macros.python._rounding import scale\n\n\n' "def line_total_cents(price_cents: str, quantity: str) -> str:\n" ' """Calculate line total cents from a unit price and quantity."""\n' ' return f"ROUND({price_cents} * {quantity}, {scale()})"\n' ), - "models/marts/regional_orders.sql": ( + "sql/models/marts/regional_orders.sql": ( "MODEL (description 'Orders tagged with the configured region.');\n\n" f"SELECT order_id, '@@ENV:{COMPILE_REUSE_REGION_ENV_VAR}' AS region " 'FROM __ref("stg_orders")\n' ), - "models/marts/_sqlbuild/_macros/python/order_source.py": ( + "sql/models/marts/_sqlbuild/_macros/python/order_source.py": ( '"""Mart relation macros."""\n\n\n' "def order_source() -> str:\n" ' """Return the relation orders are read from."""\n' " return '__ref(\"stg_orders\")'\n" ), - "models/marts/referenced_orders.sql": ( + "sql/models/marts/referenced_orders.sql": ( "MODEL (description 'Orders read through a direct reference.');\n\n" 'SELECT order_id FROM __ref("stg_orders")\n' ), - "models/marts/macro_sourced_orders.sql": ( + "sql/models/marts/macro_sourced_orders.sql": ( "MODEL (description 'Orders read through a macro-built reference.');\n\n" "SELECT order_id FROM @py.order_source()\n" ), - "models/marts/var_sourced_orders.sql": ( + "sql/models/marts/var_sourced_orders.sql": ( "MODEL (description 'Orders read through a variable reference.');\n\n" 'SELECT order_id FROM __ref("@@orders_model")\n' ), @@ -3540,9 +3542,9 @@ def write_recording_sink( kinds: str = ", ".join(f"LifecycleEventKind.{kind}" for kind in event_kinds) write_project_file( project_dir, - f"sinks/{sink_name}.py", + f"python/event_sinks/{sink_name}.py", "import os\nfrom pathlib import Path\n\n" - "from sqlbuild.sinks import (\n LifecycleEvent,\n LifecycleEventKind,\n" + "from sqlbuild.event_sinks import (\n LifecycleEvent,\n LifecycleEventKind,\n" " lifecycle_event_sink,\n lifecycle_event_to_json,\n)\n\n\n" f'@lifecycle_event_sink(name="{sink_name}", ' f"event_kinds={{{kinds}}})\n" @@ -3576,7 +3578,7 @@ def compile_reuse_entry_paths(*, project_dir: Path) -> tuple[Path, ...]: def touch_model_without_change(project_dir: Path) -> None: """Move a model's mtime forward without changing its content.""" - path: Path = project_dir / "models/staging/stg_orders.sql" + path: Path = project_dir / "sql/models/staging/stg_orders.sql" mtime_ns: int = path.stat().st_mtime_ns + _FUTURE_MTIME_OFFSET_NS os.utime(path, ns=(mtime_ns, mtime_ns)) @@ -3584,27 +3586,27 @@ def touch_model_without_change(project_dir: Path) -> None: def rewrite_macro_without_change(project_dir: Path) -> None: """Rewrite a macro file with identical bytes.""" - path: Path = project_dir / "macros/python/currency.py" + path: Path = project_dir / "sql/macros/python/currency.py" path.write_bytes(path.read_bytes()) def delete_compiled_model(project_dir: Path) -> None: """Delete one compiled artifact by hand.""" - (project_dir / "target/compiled/models/marts/regional_orders.sql").unlink() + (project_dir / "target/compiled/sql/models/marts/regional_orders.sql").unlink() def edit_compiled_model(project_dir: Path) -> None: """Edit one compiled artifact by hand.""" - path: Path = project_dir / "target/compiled/models/marts/regional_orders.sql" + path: Path = project_dir / "target/compiled/sql/models/marts/regional_orders.sql" path.write_text(path.read_text(encoding="utf-8") + "-- edited by hand\n", encoding="utf-8") def add_stale_compiled_file(project_dir: Path) -> None: """Add a compiled artifact that no model produces.""" - write_project_file(project_dir, "target/compiled/models/stale_model.sql", "SELECT 1\n") + write_project_file(project_dir, "target/compiled/sql/models/stale_model.sql", "SELECT 1\n") COMPILED_TREE_STAMP_FILE_NAME: str = "compiled-tree.bin" @@ -3619,7 +3621,7 @@ def compiled_tree_stamp_path(*, project_dir: Path) -> Path: def add_stale_compiled_file_beside_models(project_dir: Path) -> None: """Add an unmanaged compiled file to a folder that already holds compiled models.""" - write_project_file(project_dir, "target/compiled/models/marts/stale_mart.sql", "SELECT 1\n") + write_project_file(project_dir, "target/compiled/sql/models/marts/stale_mart.sql", "SELECT 1\n") def link_compiled_root(project_dir: Path) -> None: @@ -3719,7 +3721,7 @@ def write_orders_api_provider(*, project_dir: Path) -> None: write_project_file( project_dir, - "providers/orders_api.py", + "python/providers/orders_api.py", "from pydantic_settings import SettingsConfigDict\n" "from sqlbuild.providers import Provider\n\n\n" "class OrdersApi(Provider):\n" @@ -3737,7 +3739,7 @@ def write_custom_source_provider(project_dir: Path) -> None: write_project_file( project_dir, - "providers/orders_vault.py", + "python/providers/orders_vault.py", "from pydantic_settings import BaseSettings, PydanticBaseSettingsSource\n" "from sqlbuild.providers import Provider\n\n\n" "class OrdersVault(Provider):\n" @@ -3806,14 +3808,14 @@ def __exit__(self, *exception: object) -> None: def edit_project_model_during_compile(project_dir: Path) -> None: """Change one model's bytes after the compile read it and before it stores.""" - path: Path = project_dir / "models/staging/stg_orders.sql" + path: Path = project_dir / "sql/models/staging/stg_orders.sql" path.write_bytes(path.read_bytes() + b"\n") def rewrite_compiled_model_unchanged(project_dir: Path) -> None: """Rewrite one compiled artifact with the bytes it already holds.""" - path: Path = project_dir / "target/compiled/models/marts/regional_orders.sql" + path: Path = project_dir / "target/compiled/sql/models/marts/regional_orders.sql" path.write_bytes(path.read_bytes()) @@ -4012,7 +4014,7 @@ def write_generated_edit_models(*, project_dir: Path, model_count: int, seed: in ) twin_chooser: random.Random = random.Random(seed + 3) for index, upstream in enumerate(upstreams): - name: str = f"models/generated/{GENERATED_EDIT_MODEL_PREFIX}{index:03d}" + name: str = f"sql/models/generated/{GENERATED_EDIT_MODEL_PREFIX}{index:03d}" contents: str = (_generated_edit_model_sql, _generated_star_model_sql)[ star_chooser.random() < _STAR_MODEL_SHARE ](upstream=upstream) @@ -4069,8 +4071,8 @@ class RandomEditChain: def __init__(self, *, project_dir: Path, seed: int) -> None: self._project_dir: Path = project_dir self._random: random.Random = random.Random(seed) - self._broken: Path = project_dir / "models" / "generated" / "unbroken.sql" - self._dropped: Path = project_dir / "models" / "generated" / "undropped.sql" + self._broken: Path = project_dir / "sql" / "models" / "generated" / "unbroken.sql" + self._dropped: Path = project_dir / "sql" / "models" / "generated" / "undropped.sql" self._added: int = 0 self._interventions: random.Random = random.Random(seed + 1) @@ -4090,7 +4092,7 @@ def apply(self, kind: str) -> None: models: list[Path] = list( filter( lambda model: anchor in model.read_text(encoding="utf-8"), - sorted((self._project_dir / "models" / "generated").glob("*.sql")), + sorted((self._project_dir / "sql" / "models" / "generated").glob("*.sql")), ) ) edit: Callable[[Path], None] = getattr(self, f"_{kind}") @@ -4139,14 +4141,14 @@ def _add_model(self, model: Path) -> None: self._added += 1 write_project_file( self._project_dir, - f"models/generated/added_step_{self._added:03d}.sql", + f"sql/models/generated/added_step_{self._added:03d}.sql", _generated_edit_model_sql(upstream=model.stem), ) def _macro_edit(self, _model: Path) -> None: scale: str = f"_SCALE: int = {2 + self._random.randrange(3)}" self._rewrite( - self._project_dir / "macros" / "python" / "_rounding.py", + self._project_dir / "sql" / "macros" / "python" / "_rounding.py", lambda contents: re.sub(r"_SCALE: int = \d+", scale, contents), ) @@ -4158,10 +4160,10 @@ def _test_edit(self, _model: Path) -> None: ) -STG_ORDERS_MODEL: str = "models/staging/stg_orders.sql" -STG_PAYMENTS_MODEL: str = "models/staging/stg_payments.sql" -FACT_ORDERS_MODEL: str = "models/marts/fact_orders.sql" -DIM_CUSTOMERS_ARTIFACT: str = "target/compiled/models/marts/dim_customers.sql" +STG_ORDERS_MODEL: str = "sql/models/staging/stg_orders.sql" +STG_PAYMENTS_MODEL: str = "sql/models/staging/stg_payments.sql" +FACT_ORDERS_MODEL: str = "sql/models/marts/fact_orders.sql" +DIM_CUSTOMERS_ARTIFACT: str = "target/compiled/sql/models/marts/dim_customers.sql" _FACT_QUANTITY_TYPE: str = " quantity (type INTEGER),\n" _FACT_ORDER_ID_COLUMN: str = " order_id (nullable false, audits [not_null]),\n" @@ -4229,11 +4231,11 @@ def compile_without_reuse_between(root: Path) -> None: compile_without_reuse_between, ) _STAR_CHAIN_MODELS: dict[str, str] = { - "models/marts/chain_mid.sql": ( + "sql/models/marts/chain_mid.sql": ( "MODEL (description 'Every staged order column.', materialized view);\n\n" 'SELECT * FROM __ref("stg_orders")\n' ), - "models/marts/chain_leaf.sql": ( + "sql/models/marts/chain_leaf.sql": ( "MODEL (description 'Every chained order column.', materialized view);\n\n" 'SELECT * FROM __ref("chain_mid")\n' ), @@ -4241,14 +4243,14 @@ def compile_without_reuse_between(root: Path) -> None: _STAGING_LAST_COLUMN: str = " status\nFROM __source" -_TWIN_MODEL: str = "models/marts/chain_a_twin.sql" +_TWIN_MODEL: str = "sql/models/marts/chain_a_twin.sql" def star_chain_with_twin_added(root: Path) -> None: """Add the star chain and a twin of its leaf with the same SQL, so both share a cache key.""" star_chain_added(root) - write_project_file(root, _TWIN_MODEL, _STAR_CHAIN_MODELS["models/marts/chain_leaf.sql"]) + write_project_file(root, _TWIN_MODEL, _STAR_CHAIN_MODELS["sql/models/marts/chain_leaf.sql"]) def twin_header_changed(root: Path) -> None: @@ -4363,7 +4365,7 @@ def payment_expression_type_change(root: Path) -> None: replace_project_text( root, - "sources/raw.yml", + "sql/sources/raw.yml", "SELECT 1 AS id, 1 AS order_id,", "SELECT 1 AS id, CAST(1 AS BIGINT) AS order_id,", ) @@ -4374,7 +4376,7 @@ def completed_order_udf_signature_change(root: Path) -> None: replace_project_text( root, - "functions/sql/udf__is_completed_order.sql", + "sql/functions/sql/udf__is_completed_order.sql", "returns BOOLEAN,\n);\n\norder_status = 'completed'", "returns INTEGER,\n);\n\nCAST(order_status = 'completed' AS INTEGER)", ) @@ -4385,7 +4387,7 @@ def order_status_nullability_change(root: Path) -> None: replace_project_text( root, - "sources/raw.yml", + "sql/sources/raw.yml", " - name: status\n type: VARCHAR\n", " - name: status\n type: VARCHAR\n nullable: false\n", ) @@ -4674,12 +4676,12 @@ def keep_invalidation(_monkeypatch: pytest.MonkeyPatch) -> None: def ignore_project_changes(monkeypatch: pytest.MonkeyPatch) -> None: - """Make compile reuse stop watching the models folder, so a model edit goes unseen.""" + """Make compile reuse stop watching the sql folder, so a model edit goes unseen.""" monkeypatch.setattr( native_module, "COMPILE_REUSE_EXCLUDED_ROOT_DIRECTORIES", - native_module.COMPILE_REUSE_EXCLUDED_ROOT_DIRECTORIES | {"models"}, + native_module.COMPILE_REUSE_EXCLUDED_ROOT_DIRECTORIES | {"sql"}, ) @@ -4699,7 +4701,7 @@ def add_external_flavor_macro(*, project_dir: Path, extlib: Path, value: str) -> write_external_flavor(extlib, value) write_project_file( project_dir, - "models/marts/_sqlbuild/_macros/python/flavor.py", + "sql/models/marts/_sqlbuild/_macros/python/flavor.py", '"""Flavor macros backed by an outside module."""\n\n\n' "def flavor() -> str:\n" ' """Return the configured flavor literal."""\n' @@ -4734,7 +4736,7 @@ def add_stored_flavor_macro( write_project_file( project_dir, - "models/marts/_sqlbuild/_macros/python/flavor.py", + "sql/models/marts/_sqlbuild/_macros/python/flavor.py", '"""Flavor macros backed by an outside module."""\n\n\n' "def flavor() -> str:\n" ' """Return the configured flavor literal and log the call."""\n' @@ -4819,12 +4821,12 @@ def prepare_reference_call_project(*, tmp_path: Path, staging_from: str, mart_fr project_name="orders", repo_files={ "sqlbuild_project.toml": _REFERENCE_CALL_PROJECT_TOML, - "sources/raw.yml": _REFERENCE_CALL_SOURCES_YML, - "models/staging/stg_orders.sql": ( + "sql/sources/raw.yml": _REFERENCE_CALL_SOURCES_YML, + "sql/models/staging/stg_orders.sql": ( 'MODEL (description "Staged orders.", materialized view);\n\n' f"SELECT order_id, amount_cents FROM {staging_from}\n" ), - "models/marts/order_totals.sql": ( + "sql/models/marts/order_totals.sql": ( 'MODEL (description "Order totals.", materialized table);\n\n' "SELECT COUNT(*) AS order_count, SUM(amount_cents) AS total_cents\n" f"FROM {mart_from} AS orders\n" @@ -4866,12 +4868,12 @@ def prepare_macro_reference_call_project(*, tmp_path: Path) -> Path: project_name="orders", repo_files={ "sqlbuild_project.toml": _REFERENCE_CALL_PROJECT_TOML, - "sources/raw.yml": _REFERENCE_CALL_SOURCES_YML, - "models/staging/customers.sql": ( + "sql/sources/raw.yml": _REFERENCE_CALL_SOURCES_YML, + "sql/models/staging/customers.sql": ( 'MODEL (description "Customers.", materialized view);\n\n' 'SELECT order_id AS customer_id FROM __source("raw_orders")\n' ), - "models/marts/_sqlbuild/_macros/python/customer_relation.py": ( + "sql/models/marts/_sqlbuild/_macros/python/customer_relation.py": ( '"""A macro that returns an unquoted reference call."""\n\n' "import os\n\n\n" "def customer_relation() -> str:\n" @@ -4883,7 +4885,7 @@ def prepare_macro_reference_call_project(*, tmp_path: Path) -> Path: ' return "__ref(customers)"\n' ), **{ - f"models/marts/{name}.sql": ( + f"sql/models/marts/{name}.sql": ( f'MODEL (description "{name}.", materialized view);\n\n' "SELECT customer_id FROM @py.customer_relation()\n" ) @@ -4931,7 +4933,7 @@ def macro_reference_call_runs( STORE_ARGUMENT_ENV_VAR: str = "STORE_TEST_ARGUMENT" _REUSE_DISABLED_VALUES: dict[bool, str] = {True: "0", False: "1"} STALE_FLAVOR_EDIT: str = "salty" -_SOUTH_MODEL: str = "models/south/orders_south.sql" +_SOUTH_MODEL: str = "sql/models/south/orders_south.sql" _STORE_EXTERNAL_MODULE: str = "store_flavor_values" _ZIPPED_FLAVOR_MODULE: str = "zipped_flavor_values" _STORE_IMPORTED_MODULES: tuple[str, ...] = ( @@ -4941,7 +4943,7 @@ def macro_reference_call_runs( "macros._label_values", ) _STORE_PROJECT_EXTRA_FILES: dict[str, str] = { - "macros/python/context_labels.py": ( + "sql/macros/python/context_labels.py": ( '"""Macros that read the target, the environment and an outside module."""\n\n' "import os\n\n\n" "def env_region() -> str:\n" @@ -4955,11 +4957,11 @@ def macro_reference_call_runs( f" import {_STORE_EXTERNAL_MODULE}\n\n" f" return repr({_STORE_EXTERNAL_MODULE}.VALUE)\n" ), - "macros/python/_label_values.py": ( + "sql/macros/python/_label_values.py": ( 'def label_value() -> str:\n """Return the label literal."""\n return "\'first\'"\n' ), - "macros/python/labels.py": ( - "from macros.python._label_values import label_value\n\n\n" + "sql/macros/python/labels.py": ( + "from sql.macros.python._label_values import label_value\n\n\n" 'def label() -> str:\n """Return the label from a helper module."""\n' " return label_value()\n" ), @@ -5023,7 +5025,7 @@ def write_store_flavor(*, extlib: Path, value: str) -> None: def edit_label_helper(project_dir: Path, value: str) -> None: """Change the literal the helper module behind the label macro returns.""" - replace_project_text(project_dir, "macros/python/_label_values.py", "'first'", f"'{value}'") + replace_project_text(project_dir, "sql/macros/python/_label_values.py", "'first'", f"'{value}'") def edit_south_model(project_dir: Path, old: str, new: str) -> None: @@ -5380,12 +5382,25 @@ def fallback(**_kwargs: object) -> object: return run, called +MACRO_CALL_LOG_CODE: str = ( + "(Path(__file__).resolve().parents[3].parent" + " / (Path(__file__).resolve().parents[3].name + '_macro_calls.log'))" +) + + +def macro_call_log(project_dir: Path) -> Path: + """The file a project's counted macros log their calls to, beside the project.""" + + return project_dir.parent / f"{project_dir.name}_macro_calls.log" + + def write_counted_error_project(*, project_dir: Path, files: dict[str, str]) -> None: """Write the failure base project with `files` added or replaced into a fresh directory.""" shutil.rmtree(project_dir, ignore_errors=True) for relative_path, contents in {**FAILURE_BASE_FILES, **files}.items(): write_project_file(project_dir, relative_path, contents) + _ = macro_call_log(project_dir).write_text("", encoding="utf-8") def compile_with_binding_error(project_dir: Path) -> dict[str, Any]: @@ -5418,12 +5433,12 @@ def slow_lint_model_files(*, model_count: int) -> dict[str, str]: """A macro used by a model, a function, and macro tests that pause when linted.""" return { - "macros/python/slow.py": _SLOW_LINT_MACRO, - "functions/sql/slow_amount.sql": ( + "sql/macros/python/slow.py": _SLOW_LINT_MACRO, + "sql/functions/sql/slow_amount.sql": ( 'FUNCTION (description "Slow amount", arguments (p_amount INTEGER), returns INTEGER);\n' 'SELECT @py.slow_total("p_amount")\n' ), - "models/slow_total.sql": ( + "sql/models/slow_total.sql": ( 'MODEL (description "Slow total");\n' 'SELECT @py.slow_total("model_amount") AS amount\n' "FROM (SELECT 5 AS model_amount) AS input_values\n" @@ -5531,7 +5546,7 @@ def dialect_ignored_rules_entry(codes: tuple[str, ...]) -> str: ignored: str = ", ".join(f'"{code}"' for code in codes) return ( - f'\n[[rules.rule_ignores]]\nrules = [{ignored}]\npaths = ["models/**"]\n' + f'\n[[rules.rule_ignores]]\nrules = [{ignored}]\npaths = ["sql/models/**"]\n' 'reason = "The case covers parsing this SQL shape."\n' ) @@ -5553,7 +5568,7 @@ def compile_dialect_syntax_project( bool(test_case.ignored_rules) ] ), - **{f"models/{name}.sql": sql for name, sql in test_case.models.items()}, + **{f"sql/models/{name}.sql": sql for name, sql in test_case.models.items()}, }, ) @@ -5596,7 +5611,7 @@ def orders_job_project(job_values: str) -> dict[str, str]: """Return a one-model project whose `orders_job` TOML file continues with `job_values`.""" return { "sqlbuild_project.toml": 'name = "python_layout"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", "orchestration/jobs/orders_job.toml": ( 'name = "orders_job"\ndescription = "Orders."\n' + job_values ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/semantic_checks/test_native_semantic_checks_cli.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/semantic_checks/test_native_semantic_checks_cli.py index 5ab7bd6a82..7751867fbd 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/semantic_checks/test_native_semantic_checks_cli.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/semantic_checks/test_native_semantic_checks_cli.py @@ -29,18 +29,18 @@ ) _FAILING_FILES: dict[str, str] = { "sqlbuild_project.toml": _CONFIG + "\n[settings]\nrequire_sql_analysis = true\n", - "sources/raw.yml": _SOURCES, - "models/staging/stg_orders.sql": ( + "sql/sources/raw.yml": _SOURCES, + "sql/models/staging/stg_orders.sql": ( 'MODEL (description "Staged orders");\n\n' "SELECT order_id, customer_id, amonut, status + 1 AS status_rank, ordered_at\n" 'FROM __source("raw_orders")\n' ), - "models/marts/customer_totals.sql": ( + "sql/models/marts/customer_totals.sql": ( 'MODEL (description "Totals per customer");\n\n' "SELECT o.customer_id, SUM(o.amount) AS total_amount, MAX(o.status_rank) AS top_rank\n" 'FROM __ref("stg_orders") AS o\nWHERE o.ordered_at > 5\nGROUP BY o.customer_id\n' ), - "models/marts/customer_labels.sql": ( + "sql/models/marts/customer_labels.sql": ( 'MODEL (description "Labels per customer", sql_analysis false);\n\n' "SELECT customer_id, UPPER(labell) AS label\n" 'FROM __ref("stg_orders")\n' @@ -48,29 +48,29 @@ } _METADATA_FILES: dict[str, str] = { "sqlbuild_project.toml": _CONFIG, - "sources/raw.yml": _SOURCES + "sql/sources/raw.yml": _SOURCES + ( " - name: raw_events\n description: Loaded events.\n managed: true\n" " write_strategy: append\n contract: enforced\n cursor_column: loaded_at\n" " columns:\n - name: event_id\n type: INTEGER\n" " - name: load_seq\n type: INTEGER\n" ), - "python/loaders/raw_events.py": ( + "python/nodes/loaders/raw_events/loader.py": ( "from sqlbuild.loaders import loader\n\n\n@loader\n" "def raw_events(ctx):\n '''Load events.'''\n" " return [{'event_id': 1, 'load_seq': 1}]\n" ), - "functions/sql/scaled_amount.sql": ( + "sql/functions/sql/scaled_amount.sql": ( 'FUNCTION (\n description "Scale an amount",\n' " arguments (p_amount DOUBLE, p_factor INTEGER),\n returns DOUBLE,\n);\n\n" "p_amount * p_factor\n" ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( 'MODEL (description "Staged orders");\n\n' "SELECT order_id, customer_id, amount, status, ordered_at\n" 'FROM __source("raw_orders")\n' ), - "models/marts/customer_totals.sql": ( + "sql/models/marts/customer_totals.sql": ( 'MODEL (\n description "Totals per customer",\n' " materialized incremental,\n incremental_strategy delete_insert,\n" " unique_key [customer_key],\n cursor ordered_at,\n cursor_type integer,\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/helpers.py index 4874af6993..0abae7dc0e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/helpers.py @@ -27,10 +27,10 @@ "[scopes]\nenforce_placement = false\n\n" "[[rules.rule_ignores]]\n" 'rules = ["SQLCLEAN018"]\n' - 'paths = ["macros/sql/**", "models/**"]\n' + 'paths = ["sql/macros/sql/**", "sql/models/**"]\n' 'reason = "The dedup macros rank by updated_at alone; these tests cover expansion."\n' ), - "seeds/raw_orders.csv": ( + "sql/seeds/raw_orders.csv": ( "order_id,status,amount_cents,fee_cents,tax_cents,created_at,updated_at,is_deleted," "country_code\n" "1,open,1250,100,20,2026-01-01 00:00:00,2026-01-02 00:00:00,false,GB\n" @@ -38,22 +38,24 @@ "2,closed,500,50,5,2026-01-01 00:00:00,2026-01-01 00:00:00,false,FR\n" "3,open,900,0,0,2026-01-01 00:00:00,2026-01-04 00:00:00,true,US\n" ), - "seeds/raw_orders.yml": "seeds:\n - name: raw_orders\n description: Raw orders.\n" + "sql/seeds/raw_orders.yml": "seeds:\n - name: raw_orders\n description: Raw orders.\n" " columns:\n" + "".join( f" - name: {name}\n type: {data_type}\n" for name, data_type in _SEED_COLUMNS ), - "enums/order_status.sql": 'ENUM (name order_status, members (OPEN "open", CLOSED "closed"));\n', - "constants/supported_countries.sql": ( + "sql/enums/order_status.sql": ( + 'ENUM (name order_status, members (OPEN "open", CLOSED "closed"));\n' + ), + "sql/constants/supported_countries.sql": ( 'CONSTANT (name supported_countries, value ["GB", "FR", "HK"]);\n' ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( 'MODEL (description "Staged orders");\n\nSELECT * FROM __seed("raw_orders")\n' ), } CENTS_TO_DOLLARS: dict[str, str] = { - "macros/sql/cents_to_dollars.sql": ( + "sql/macros/sql/cents_to_dollars.sql": ( 'MACRO (\n description "Cents to dollars",\n' " arguments (amount_cents BIGINT, places INT CONST DEFAULT 2),\n" " returns DECIMAL(18, 2),\n);\n\n" @@ -61,7 +63,7 @@ ) } NET_AMOUNT: dict[str, str] = { - "macros/sql/net_amount.sql": ( + "sql/macros/sql/net_amount.sql": ( 'MACRO (\n description "Net amount in dollars",\n' " arguments (gross_cents BIGINT, refund_cents BIGINT),\n" " returns DECIMAL(18, 2),\n);\n\n" @@ -69,7 +71,7 @@ ) } CLEAN_ORDERS: dict[str, str] = { - "macros/sql/clean_orders.sql": ( + "sql/macros/sql/clean_orders.sql": ( 'MACRO (\n description "Deduplicated, non-deleted orders",\n' " arguments (src RELATION (order_id BIGINT, updated_at TIMESTAMP, is_deleted BOOLEAN)),\n" ");\n\n" @@ -82,7 +84,7 @@ ) } AUDIT_COLUMNS: dict[str, str] = { - "macros/sql/audit_columns.sql": ( + "sql/macros/sql/audit_columns.sql": ( 'MACRO (\n description "Standard audit columns",\n' " arguments (src RELATION (created_at TIMESTAMP, updated_at TIMESTAMP)),\n);\n\n" "SELECT @src.created_at, @src.updated_at, @src.updated_at > @src.created_at AS " @@ -90,7 +92,7 @@ ) } IS_OPEN_STATUS: dict[str, str] = { - "macros/sql/is_open_status.sql": ( + "sql/macros/sql/is_open_status.sql": ( 'MACRO (\n description "Whether a status is still open",\n' " arguments (status VARCHAR, closed ENUM order_status DEFAULT " '@enum("order_status").CLOSED),\n' @@ -98,14 +100,14 @@ ) } IN_SUPPORTED_COUNTRY: dict[str, str] = { - "macros/sql/in_supported_country.sql": ( + "sql/macros/sql/in_supported_country.sql": ( 'MACRO (\n description "Whether a country code is supported",\n' ' arguments (country VARCHAR, countries LIST VARCHAR DEFAULT ["GB", "FR"]),\n' " returns BOOLEAN,\n);\n\n@country IN @countries\n" ) } LATEST_PER_KEY: dict[str, str] = { - "macros/sql/latest_per_key.sql": ( + "sql/macros/sql/latest_per_key.sql": ( 'MACRO (\n description "Latest row per key",\n' " arguments (\n src RELATION (updated_at TIMESTAMP, keys COLUMNS),\n " "),\n);\n\n" @@ -117,7 +119,7 @@ ) } BRACKET: dict[str, str] = { - "macros/python/labels.py": ( + "sql/macros/python/labels.py": ( "def bracket(expression: str) -> str:\n" ' """Wrap an expression in brackets."""\n' " return f\"'[' || CAST({expression} AS VARCHAR) || ']'\"\n" @@ -140,7 +142,7 @@ def orders_model(sql: str) -> dict[str, str]: """The `orders` mart model with `sql` as its query.""" - return {"models/marts/orders.sql": MODEL_HEADER + sql} + return {"sql/models/marts/orders.sql": MODEL_HEADER + sql} def run_project( @@ -163,7 +165,7 @@ def wave_models(count: int) -> dict[str, str]: files: dict[str, str] = {} upstreams: list[str] = ["stg_orders", *(f"level_{level}" for level in range(1, count))] for level, upstream in enumerate(upstreams, start=1): - files[f"models/marts/level_{level}.sql"] = ( + files[f"sql/models/marts/level_{level}.sql"] = ( f'MODEL (description "Level {level}");\n\n' "SELECT o.order_id, o.status, o.amount_cents,\n" f" @sql.cents_to_dollars(o.amount_cents) AS dollars_{level},\n" @@ -189,7 +191,7 @@ def inspected_text(*, project_dir: Path, relative_paths: tuple[str, ...]) -> str WRAPPING_MACROS: dict[str, str] = { - "macros/python/wrapping.py": ( + "sql/macros/python/wrapping.py": ( "def wrap(expr: str) -> str:\n" ' """Wrap an expression in parentheses."""\n' ' return f"({expr})"\n\n\n' @@ -204,7 +206,7 @@ def inspected_text(*, project_dir: Path, relative_paths: tuple[str, ...]) -> str ' return f"UPPER({expr}) /* noted */"\n' ) } -CHECK_MACRO_PATH: str = "macros/sql/check.sql" +CHECK_MACRO_PATH: str = "sql/macros/sql/check.sql" def with_rules(*codes: str) -> dict[str, str]: @@ -239,10 +241,10 @@ def check_macro(arguments: str, body: str) -> dict[str, str]: def python_normalise_macros(names: list[str]) -> dict[str, str]: - """One Python macro file per name in the `normalise` bucket of `macros/python/`.""" + """One Python macro file per name in the `normalise` bucket of `sql/macros/python/`.""" return { - f"macros/python/normalise/{name}.py": ( + f"sql/macros/python/normalise/{name}.py": ( f"def {name}(expression: str) -> str:\n" f' """Clean a value with {name}."""\n' ' return f"TRIM({expression})"\n' @@ -252,10 +254,10 @@ def python_normalise_macros(names: list[str]) -> dict[str, str]: def sql_text_macros(folder: str, names: list[str]) -> dict[str, str]: - """One lower-casing SQL macro file per name in `macros/sql//`.""" + """One lower-casing SQL macro file per name in `sql/macros/sql//`.""" return { - f"macros/sql/{folder}/{name}.sql": ( + f"sql/macros/sql/{folder}/{name}.sql": ( f'MACRO (description "Tidy {name}", arguments (value VARCHAR), returns VARCHAR);\n\n' "LOWER(@value)\n" ) @@ -279,7 +281,7 @@ def _value_macro(name: str, declared: str, body: str, argument: str) -> dict[str """The SQL macro `name` taking one `argument`-typed value, with its `declared` header lines.""" return { - f"macros/sql/{name}.sql": ( + f"sql/macros/sql/{name}.sql": ( f'MACRO (\n description "Text from a value",\n arguments (value {argument}),\n' f"{declared});\n\n{body}\n" ) @@ -290,7 +292,7 @@ def contract_model(name: str, columns: str, sql: str) -> dict[str, str]: """The mart model `name` with an enforced contract over `columns`.""" return { - f"models/marts/{name}.sql": ( + f"sql/models/marts/{name}.sql": ( f'MODEL (\n description "Typed {name}",\n contract enforced,\n' f" columns ({columns}),\n);\n\n{sql}" ) @@ -333,7 +335,7 @@ def picked_orders(body: str) -> dict[str, str]: """The CTE-list macro `pick` over relation `src` with `body`, called once as `__cte := a`.""" return { - "macros/sql/pick.sql": ( + "sql/macros/sql/pick.sql": ( 'MACRO (\n description "Picked orders",\n' " arguments (src RELATION (order_id BIGINT)),\n);\n\n" + body + "\n" ), @@ -345,11 +347,11 @@ def picked_orders(body: str) -> dict[str, str]: WEEKLY_ORDERS: dict[str, str] = { - "seeds/weekly_orders.csv": ( + "sql/seeds/weekly_orders.csv": ( "week,product_id,region,orders_placed,refund_count\n" "1,10,EU,4,1\n1,10,US,6,0\n1,20,EU,5,2\n2,20,US,8,2\n" ), - "seeds/weekly_orders.yml": ( + "sql/seeds/weekly_orders.yml": ( "seeds:\n - name: weekly_orders\n description: Weekly orders per product and region.\n" " columns:\n" " - name: week\n type: BIGINT\n" @@ -366,7 +368,7 @@ def rates_macro(name: str, arguments: str, keys: tuple[str, str], orders: str) - aliased, plain = keys return { - f"macros/sql/{name}.sql": ( + f"sql/macros/sql/{name}.sql": ( f'MACRO (\n description "Weekly refund rates",\n arguments ({arguments}),\n);\n\n' "WITH counted AS (\n" " SELECT\n" @@ -417,7 +419,7 @@ def rates_model(name: str, per_product: str, per_product_region: str) -> dict[st """A model reading weekly refund rates at two grains through the two given macro calls.""" return { - f"models/marts/{name}.sql": ( + f"sql/models/marts/{name}.sql": ( 'MODEL (description "Refund rates per product, and per product and region");\n\n' 'WITH weekly AS (SELECT * FROM __seed("weekly_orders")),\n' f"{per_product}\n" @@ -450,7 +452,7 @@ def slot_model(call: str) -> dict[str, str]: """A model calling the weekly rates macro once with `call`'s mappings.""" return { - "models/marts/rates.sql": ( + "sql/models/marts/rates.sql": ( 'MODEL (description "Refund rates");\n\n' 'WITH weekly AS (SELECT * FROM __seed("weekly_orders")),\n' f"@sql.weekly_rates(weekly, {call})\n" @@ -460,14 +462,14 @@ def slot_model(call: str) -> dict[str, str]: ORDER_COLUMNS: dict[str, str] = { - "macros/sql/order_columns.sql": ( + "sql/macros/sql/order_columns.sql": ( 'MACRO (\n description "Grain and order count columns",\n' " arguments (weekly RELATION (keys COLUMNS, order_count BIGINT)),\n);\n\n" "SELECT @weekly.keys, @weekly.order_count AS orders\n" ) } UNNAMED_COUNT: dict[str, str] = { - "macros/sql/order_columns.sql": ( + "sql/macros/sql/order_columns.sql": ( 'MACRO (\n description "Order count column",\n' " arguments (weekly RELATION (order_count BIGINT)),\n);\n\n" "SELECT @weekly.order_count\n" @@ -476,7 +478,7 @@ def slot_model(call: str) -> dict[str, str]: LINEAGE_MODEL: dict[str, str] = { - "models/marts/order_counts.sql": ( + "sql/models/marts/order_counts.sql": ( 'MODEL (description "Order counts per product and region");\n\n' "SELECT @sql.order_columns(w, weekly.keys := (product_id, region), " "weekly.order_count := orders_placed)\n" @@ -489,7 +491,7 @@ def rate_model(name: str, expression: str) -> dict[str, str]: """A model whose one `refund_rate` column is `expression` and is declared `VARCHAR`.""" return { - f"models/marts/{name}.sql": ( + f"sql/models/marts/{name}.sql": ( 'MODEL (\n description "Refund rates",\n' " contract enforced,\n columns (refund_rate (type VARCHAR)),\n);\n\n" f"SELECT {expression} AS refund_rate\n" @@ -499,7 +501,7 @@ def rate_model(name: str, expression: str) -> dict[str, str]: REFUND_RATE_MACRO: dict[str, str] = { - "macros/sql/refund_rate.sql": ( + "sql/macros/sql/refund_rate.sql": ( 'MACRO (\n description "Refund rate of one row",\n' " arguments (weekly RELATION (order_count BIGINT, refund_count BIGINT)),\n);\n\n" "@weekly.refund_count / NULLIF(@weekly.order_count, 0)\n" @@ -526,8 +528,8 @@ def hand_written(text: str) -> str: REFUNDS: dict[str, str] = { - "seeds/refunds.csv": "week,product_id,refund_count\n1,10,1\n2,20,2\n", - "seeds/refunds.yml": ( + "sql/seeds/refunds.csv": "week,product_id,refund_count\n1,10,1\n2,20,2\n", + "sql/seeds/refunds.yml": ( "seeds:\n - name: refunds\n description: Refunds per week and product.\n" " columns:\n" " - name: week\n type: BIGINT\n" @@ -541,7 +543,7 @@ def refunded_weeks(query: str) -> dict[str, str]: """A macro whose `refunded` CTE is `query`, and a model calling it on orders and refunds.""" return { - "macros/sql/refunded_weeks.sql": ( + "sql/macros/sql/refunded_weeks.sql": ( 'MACRO (\n description "Weeks with refunds",\n' " arguments (\n" " weekly RELATION (keys COLUMNS, week BIGINT),\n" @@ -550,7 +552,7 @@ def refunded_weeks(query: str) -> dict[str, str]: ");\n\n" f"WITH refunded AS ({query})\n" ), - "models/marts/refunded.sql": ( + "sql/models/marts/refunded.sql": ( 'MODEL (description "Refunded weeks");\n\n' 'WITH weekly AS (SELECT * FROM __seed("weekly_orders")),\n' 'refunds AS (SELECT * FROM __seed("refunds")),\n' @@ -564,7 +566,7 @@ def macro_file(name: str, arguments: str, body: str) -> dict[str, str]: """One SQL macro file called `name`, declaring `arguments`, whose body is `body`.""" return { - f"macros/sql/{name}.sql": ( + f"sql/macros/sql/{name}.sql": ( f'MACRO (\n description "Macro {name}",\n arguments ({arguments}),\n);\n\n{body}\n' ) } @@ -577,7 +579,7 @@ def scoped_model(macros: dict[str, str], body: str) -> dict[str, str]: **WEEKLY_ORDERS, **REFUNDS, **macros, - "models/marts/scoped.sql": ( + "sql/models/marts/scoped.sql": ( 'MODEL (description "Scoped slot reads");\n\n' 'WITH weekly AS (SELECT * FROM __seed("weekly_orders")),\n' 'refunds AS (SELECT * FROM __seed("refunds")),\n' @@ -596,7 +598,7 @@ def rates_with_middle_cte(middle: str) -> dict[str, str]: """The docs' weekly refund rates macro with `middle` as a CTE between its two, and a model.""" return { - "macros/sql/weekly_rates.sql": ( + "sql/macros/sql/weekly_rates.sql": ( 'MACRO (\n description "Weekly refund rate per grain",\n' " arguments (weekly RELATION (keys COLUMNS, order_count BIGINT, refund_count BIGINT))," "\n);\n\n" @@ -616,7 +618,7 @@ def rates_with_middle_cte(middle: str) -> dict[str, str]: " GROUP BY @weekly.keys\n" ")\n" ), - "models/marts/rates.sql": ( + "sql/models/marts/rates.sql": ( 'MODEL (description "Refund rates");\n\n' 'WITH weekly AS (SELECT * FROM __seed("weekly_orders")),\n' "@sql.weekly_rates(weekly, weekly.keys := (product_id, region), " diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_body_rules.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_body_rules.py index d37353cbd4..fc3391d558 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_body_rules.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_body_rules.py @@ -63,9 +63,9 @@ expected_returncode=1, expected_fragments=( "error[SQLCLEAN028]: Single-relation query mixes qualified and unqualified columns " - "(in SQL generated by @weekly)\n --> macros/sql/weekly_rates.sql:14:18", + "(in SQL generated by @weekly)\n --> sql/macros/sql/weekly_rates.sql:14:18", "error[SQLCLEAN028]: Single-relation query mixes qualified and unqualified columns\n" - " --> macros/sql/weekly_rates.sql:14:42", + " --> sql/macros/sql/weekly_rates.sql:14:42", ), expected_absent_fragments=("SQLCLEAN029",), ), @@ -77,7 +77,7 @@ **rates_with_middle_cte( "plain AS (SELECT @weekly.keys, orders, refunds FROM counted)" ), - "macros/sql/uncalled_rates.sql": ( + "sql/macros/sql/uncalled_rates.sql": ( 'MACRO (\n description "Weekly orders per grain",\n' " arguments (weekly RELATION (keys COLUMNS, order_count BIGINT)),\n);\n\n" "WITH counted AS (\n" @@ -89,12 +89,12 @@ expected_returncode=1, expected_fragments=( "error[SQLCLEAN029]: Qualified reference uses a relation absent from this query " - "scope\n --> macros/sql/uncalled_rates.sql:10:32", + "scope\n --> sql/macros/sql/uncalled_rates.sql:10:32", ), expected_absent_fragments=( "error[SQLCLEAN029]: Qualified reference uses a relation absent from this query " "scope (in SQL generated by @weekly)", - "--> macros/sql/weekly_rates.sql", + "--> sql/macros/sql/weekly_rates.sql", ), ), ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_build.py index 16c69ca91b..bc47f4f455 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_build.py @@ -32,38 +32,38 @@ from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import query_duckdb, run_sqb _UNION_COLUMNS: dict[str, str] = { - "macros/sql/order_columns.sql": ( + "sql/macros/sql/order_columns.sql": ( 'MACRO (description "Order columns in a fixed order", arguments (src RELATION ' "(order_id BIGINT, status VARCHAR)));\n\nSELECT @src.order_id, @src.status\n" ) } _HAS_TAG: dict[str, str] = { - "macros/sql/has_tag.sql": ( + "sql/macros/sql/has_tag.sql": ( 'MACRO (description "Whether the tags hold a tag", arguments (tags VARCHAR[], ' "tag VARCHAR CONST), returns BOOLEAN);\n\nlist_contains(@tags, @tag)\n" ) } _STATUS_LABEL: dict[str, str] = { - "macros/sql/status_label.sql": ( + "sql/macros/sql/status_label.sql": ( 'MACRO (description "Status label", arguments (status VARCHAR CONST), returns VARCHAR);' "\n\n'status: ' || @status\n" ) } _FIRST_ORDERS: dict[str, str] = { - "macros/sql/first_orders.sql": ( + "sql/macros/sql/first_orders.sql": ( 'MACRO (description "First orders", arguments (src RELATION (order_id BIGINT), ' "n BIGINT CONST));\n\nWITH firsts AS (SELECT s.order_id FROM @src AS s " "ORDER BY s.order_id LIMIT @n)\n" ) } _IS_STATUS: dict[str, str] = { - "macros/sql/is_status.sql": ( + "sql/macros/sql/is_status.sql": ( 'MACRO (description "Whether the status column matches", arguments (status VARCHAR), ' "returns BOOLEAN);\n\nstatus = @status\n" ) } _SCOPED_DOUBLED: dict[str, str] = { - "models/marts/_sqlbuild/_macros/sql/doubled.sql": ( + "sql/models/marts/_sqlbuild/_macros/sql/doubled.sql": ( 'MACRO (description "Doubled", arguments (v BIGINT), returns BIGINT);\n\n@v * 2\n' ) } @@ -87,42 +87,42 @@ ), ) _REFUNDS: dict[str, str] = { - "seeds/raw_refunds.csv": "refund_id,status\n1,250\n", - "seeds/raw_refunds.yml": ( + "sql/seeds/raw_refunds.csv": "refund_id,status\n1,250\n", + "sql/seeds/raw_refunds.yml": ( "seeds:\n - name: raw_refunds\n description: Raw refunds.\n columns:\n" " - name: refund_id\n type: BIGINT\n" " - name: status\n type: BIGINT\n" ), - "models/staging/stg_refunds.sql": ( + "sql/models/staging/stg_refunds.sql": ( 'MODEL (description "Staged refunds");\n\nSELECT * FROM __seed("raw_refunds")\n' ), } _PLUS_ONE_HOUR: dict[str, str] = { - "macros/sql/plus_one_hour.sql": ( + "sql/macros/sql/plus_one_hour.sql": ( 'MACRO (description "One hour later", arguments (ts TIMESTAMP), returns TIMESTAMP);' "\n\n@ts + INTERVAL 1 HOUR\n" ) } _BODY_SCOPED: dict[str, str] = { - "models/marts/_sqlbuild/_constants/fee_divisor.sql": "CONSTANT (name fee_divisor, value 100);\n", - "models/marts/_sqlbuild/macros/sql/fee_dollars.sql": ( + "sql/models/marts/_sqlbuild/_constants/fee_divisor.sql": "CONSTANT (name fee_divisor, value 100);\n", + "sql/models/marts/_sqlbuild/macros/sql/fee_dollars.sql": ( 'MACRO (description "Fee in dollars", arguments (cents BIGINT), returns DOUBLE);' '\n\n@cents / @const("fee_divisor")\n' ), - "models/marts/daily/orders.sql": ( + "sql/models/marts/daily/orders.sql": ( 'MODEL (description "Orders");\n\nSELECT DISTINCT order_id, @sql.fee_dollars(fee_cents) ' 'AS fee FROM __ref("stg_orders") WHERE order_id = 2\n' ), } _NESTED_LOCAL: dict[str, str] = { - "models/marts/_sqlbuild/macros/sql/doubled_fee.sql": ( + "sql/models/marts/_sqlbuild/macros/sql/doubled_fee.sql": ( 'MACRO (description "Fee doubled", arguments (cents BIGINT), returns BIGINT);' "\n\n@sql.doubled_inner(@cents)\n" ), - "models/marts/_sqlbuild/_macros/sql/doubled_inner.sql": ( + "sql/models/marts/_sqlbuild/_macros/sql/doubled_inner.sql": ( 'MACRO (description "Doubled", arguments (v BIGINT), returns BIGINT);\n\n@v * 2\n' ), - "models/marts/daily/orders.sql": ( + "sql/models/marts/daily/orders.sql": ( 'MODEL (description "Orders");\n\nSELECT DISTINCT order_id, @sql.doubled_fee(fee_cents) ' 'AS fee FROM __ref("stg_orders") WHERE order_id = 2\n' ), @@ -380,7 +380,7 @@ def test_given_any_spelling_of_list_calls_when_building_then_the_model_holds_the command=("compile",), expected_returncode=0, expected_fragments=("'[' || CAST(order_id AS VARCHAR) || ']' AS label",), - inspected_paths=("target/compiled/models/marts/orders.sql",), + inspected_paths=("target/compiled/sql/models/marts/orders.sql",), ), SqlMacroCommandTestCase( description="typed_argument_in_a_later_union_branch_is_not_checked", @@ -454,13 +454,13 @@ def test_given_any_spelling_of_list_calls_when_building_then_the_model_holds_the }, command=("rules", "run", "SQBRMODEL102"), expected_returncode=1, - expected_fragments=("models/marts/orders.sql", "[SQBRMODEL102]"), + expected_fragments=("sql/models/marts/orders.sql", "[SQBRMODEL102]"), ), SqlMacroCommandTestCase( description="scope_names_the_invalid_sql_macro_file_and_keeps_the_valid_ones", files={ **CENTS_TO_DOLLARS, - "macros/sql/zz_invalid.sql": ( + "sql/macros/sql/zz_invalid.sql": ( 'MACRO (description "Invalid", returns BIGINT);\n\nWITH a AS (SELECT 1)\n' ), **orders_model( @@ -471,7 +471,7 @@ def test_given_any_spelling_of_list_calls_when_building_then_the_model_holds_the expected_returncode=1, expected_fragments=( "Resource: macro:cents_to_dollars", - "ERROR S021 macros/sql/zz_invalid.sql: CTE-list macro zz_invalid() cannot declare returns", + "ERROR S021 sql/macros/sql/zz_invalid.sql: CTE-list macro zz_invalid() cannot declare returns", ), ), ], @@ -504,7 +504,7 @@ def test_given_a_project_with_macros_when_running_a_command_then_its_output_refl 'FROM __ref("stg_orders")\nWHERE order_id = 2\n' ), }, - edited_path="macros/sql/cents_to_dollars.sql", + edited_path="sql/macros/sql/cents_to_dollars.sql", replaced_text=("/ 100", "/ 10"), query="SELECT fee FROM orders", expected_rows=[(5.0,)], @@ -513,13 +513,13 @@ def test_given_a_project_with_macros_when_running_a_command_then_its_output_refl description="sql_macro_called_only_from_a_hook", files={ **CENTS_TO_DOLLARS, - "models/marts/orders.sql": ( + "sql/models/marts/orders.sql": ( 'MODEL (description "Orders", post_hooks [inline_sql("CREATE OR REPLACE TABLE ' 'hook_fee AS SELECT @sql.cents_to_dollars(50) AS fee")]);\n\n' 'SELECT DISTINCT order_id FROM __ref("stg_orders")\n' ), }, - edited_path="macros/sql/cents_to_dollars.sql", + edited_path="sql/macros/sql/cents_to_dollars.sql", replaced_text=("/ 100", "/ 10"), query="SELECT fee FROM hook_fee", expected_rows=[(5.0,)], @@ -551,7 +551,7 @@ def test_given_an_edited_sql_macro_when_rebuilding_then_its_callers_use_the_new_ SqlMacroFormatTestCase( description="cte_list_macro_and_its_call", files={ - "macros/sql/pair.sql": ( + "sql/macros/sql/pair.sql": ( 'MACRO (description "Pair", arguments (src RELATION (order_id BIGINT)));\n\n' "with a as (select * from @src), b as (select order_id from a)\n" ), @@ -560,7 +560,7 @@ def test_given_an_edited_sql_macro_when_rebuilding_then_its_callers_use_the_new_ "final AS (SELECT order_id FROM b)\nSELECT * FROM final\n" ), }, - formatted_path="macros/sql/pair.sql", + formatted_path="sql/macros/sql/pair.sql", expected_ending=( "WITH a AS (\n SELECT *\n FROM @src\n),\n\nb AS (\n SELECT order_id\n" " FROM a\n)\n" @@ -569,7 +569,7 @@ def test_given_an_edited_sql_macro_when_rebuilding_then_its_callers_use_the_new_ SqlMacroFormatTestCase( description="expression_macro_body_and_one_line_header", files={ - "macros/sql/net.sql": ( + "sql/macros/sql/net.sql": ( 'MACRO (description "Net", arguments (gross BIGINT,refund BIGINT), ' "returns DOUBLE);\n\nround(cast((@gross - coalesce(@refund, 0)) as double) " "/ 100, 2)\n" @@ -578,7 +578,7 @@ def test_given_an_edited_sql_macro_when_rebuilding_then_its_callers_use_the_new_ 'SELECT DISTINCT order_id, @sql.net(amount_cents, fee_cents) AS net FROM __ref("stg_orders")\n' ), }, - formatted_path="macros/sql/net.sql", + formatted_path="sql/macros/sql/net.sql", expected_start=( 'MACRO (description "Net", arguments (gross BIGINT, refund BIGINT), ' "returns DOUBLE);\n\n" @@ -588,13 +588,13 @@ def test_given_an_edited_sql_macro_when_rebuilding_then_its_callers_use_the_new_ SqlMacroFormatTestCase( description="column_list_macro_body_and_multi_line_header", files={ - "macros/sql/stamps.sql": ( + "sql/macros/sql/stamps.sql": ( 'MACRO (description "Stamps",\n arguments (src RELATION (created_at TIMESTAMP, ' "updated_at TIMESTAMP)));\n\nselect @src.created_at,@src.updated_at\n" ), **orders_model('SELECT o.order_id, @sql.stamps(o) FROM __ref("stg_orders") AS o\n'), }, - formatted_path="macros/sql/stamps.sql", + formatted_path="sql/macros/sql/stamps.sql", expected_start=( 'MACRO (\n description "Stamps",\n arguments (src RELATION (created_at TIMESTAMP, ' "updated_at TIMESTAMP)),\n);\n\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_cte_names.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_cte_names.py index b1a106cea5..ebab5647a7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_cte_names.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_cte_names.py @@ -292,7 +292,7 @@ def test_given_an_invalid_cte_name_when_compiling_then_the_error_names_the_probl "@sql.clean_orders(gb_raw, __cte := gb_orders)", "@sql.clean_orders(fr_raw, __cte := fr_orders)", ), - inspected_paths=("models/marts/orders.sql",), + inspected_paths=("sql/models/marts/orders.sql",), ), SqlMacroCommandTestCase( description="lint_sees_renamed_ctes_as_hand_written", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_errors.py index 8884799245..8578a7d19a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_errors.py @@ -47,37 +47,39 @@ expected_fragments=( "macro call @cents_to_dollars() does not say which kind of macro it calls", "write @sql.cents_to_dollars(...) to call a SQL macro or @py.cents_to_dollars(...) to call a Python macro", - "models/marts/orders.sql:4:3", + "sql/models/marts/orders.sql:4:3", ), ), SqlMacroErrorTestCase( description="python_file_directly_under_macros", - files={"macros/currency.py": "def c(x):\n return x\n"}, + files={"sql/macros/currency.py": "def c(x):\n return x\n"}, expected_code="D013", expected_fragments=( - "macro file macros/currency.py must live in macros/python/ or macros/sql/", - "move it to macros/python/currency.py", + "macro file sql/macros/currency.py must live in sql/macros/python/ or sql/macros/sql/", + "move it to sql/macros/python/currency.py", ), ), SqlMacroErrorTestCase( description="sql_file_in_python_folder", - files={"macros/python/c.sql": CENTS_TO_DOLLARS["macros/sql/cents_to_dollars.sql"]}, + files={ + "sql/macros/python/c.sql": CENTS_TO_DOLLARS["sql/macros/sql/cents_to_dollars.sql"] + }, expected_code="D013", expected_fragments=( - "macro file macros/python/c.sql must live in macros/python/ or macros/sql/", - "move it to macros/sql/c.sql", + "macro file sql/macros/python/c.sql must live in sql/macros/python/ or sql/macros/sql/", + "move it to sql/macros/sql/c.sql", ), ), SqlMacroErrorTestCase( description="scoped_file_outside_kind_folder", files={ - "models/marts/_sqlbuild/_macros/c.sql": CENTS_TO_DOLLARS[ - "macros/sql/cents_to_dollars.sql" + "sql/models/marts/_sqlbuild/_macros/c.sql": CENTS_TO_DOLLARS[ + "sql/macros/sql/cents_to_dollars.sql" ] }, expected_code="D013", expected_fragments=( - "models/marts/_sqlbuild/_macros/python/ or models/marts/_sqlbuild/_macros/sql/", + "sql/models/marts/_sqlbuild/_macros/python/ or sql/models/marts/_sqlbuild/_macros/sql/", ), ), SqlMacroErrorTestCase( @@ -115,36 +117,38 @@ description="sql_body_calls_python_macro", files={ **BRACKET, - "macros/sql/x.sql": _X_HEADER.format(args="v BIGINT", returns=", returns BIGINT") + "sql/macros/sql/x.sql": _X_HEADER.format( + args="v BIGINT", returns=", returns BIGINT" + ) + "@py.bracket(@v) + 1\n", **_CALL_X, }, expected_code="P020", expected_fragments=( "SQL macro x() calls Python macro bracket(); SQL and Python macros never call each other", - "macros/sql/x.sql:3:1", + "sql/macros/sql/x.sql:3:1", ), ), SqlMacroErrorTestCase( description="reference_function_in_body", files={ - "macros/sql/bad.sql": 'MACRO (\n description "Bad",\n);\n\nWITH x AS (SELECT * FROM __ref("stg_orders"))\n', + "sql/macros/sql/bad.sql": 'MACRO (\n description "Bad",\n);\n\nWITH x AS (SELECT * FROM __ref("stg_orders"))\n', **orders_model("WITH @sql.bad()\nSELECT 1 AS a\n"), }, expected_code="P016", expected_fragments=( "macro bad() reads model:stg_orders through __ref() in its body", - "macros/sql/bad.sql:5:26", + "sql/macros/sql/bad.sql:5:26", ), ), SqlMacroErrorTestCase( description="macros_calling_each_other", files={ - "macros/sql/a.sql": _X_HEADER.replace("X", "A").format( + "sql/macros/sql/a.sql": _X_HEADER.replace("X", "A").format( args="v BIGINT", returns=", returns BIGINT" ) + "@sql.b(@v) + 1\n", - "macros/sql/b.sql": _X_HEADER.replace("X", "B").format( + "sql/macros/sql/b.sql": _X_HEADER.replace("X", "B").format( args="v BIGINT", returns=", returns BIGINT" ) + "@sql.a(@v) + 1\n", @@ -242,7 +246,7 @@ description="runtime_parameter_forwarded_to_const", files={ **CENTS_TO_DOLLARS, - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="v BIGINT, p INT", returns=", returns DECIMAL(18, 2)" ) + "@sql.cents_to_dollars(@v, @p)\n", @@ -258,7 +262,7 @@ description="wrong_enum", files={ **IS_OPEN_STATUS, - "enums/other.sql": 'ENUM (name other, members (X "x"));\n', + "sql/enums/other.sql": 'ENUM (name other, members (X "x"));\n', **orders_model( 'SELECT order_id FROM __ref("stg_orders") WHERE @sql.is_open_status(status, @enum("other").X)\n' ), @@ -343,7 +347,9 @@ SqlMacroErrorTestCase( description="returns_that_disagrees_with_the_body_is_reported_at_the_macro_file", files={ - "macros/sql/x.sql": _X_HEADER.format(args="v VARCHAR", returns=", returns BIGINT") + "sql/macros/sql/x.sql": _X_HEADER.format( + args="v VARCHAR", returns=", returns BIGINT" + ) + "UPPER(@v)\n", **orders_model("SELECT @sql.x('a') AS a\n"), }, @@ -351,14 +357,14 @@ expected_fragments=( "macro x() declares returns BIGINT, but its body is VARCHAR\n" " model: orders\n" - " --> macros/sql/x.sql:3:1", + " --> sql/macros/sql/x.sql:3:1", "declare returns VARCHAR, CAST the body to BIGINT, or remove returns", ), ), SqlMacroErrorTestCase( description="untyped_argument", files={ - "macros/sql/x.sql": _X_HEADER.format(args="v", returns=", returns BIGINT") + "sql/macros/sql/x.sql": _X_HEADER.format(args="v", returns=", returns BIGINT") + "@v + 1\n", **_CALL_X, }, @@ -368,7 +374,7 @@ SqlMacroErrorTestCase( description="raw_text_argument", files={ - "macros/sql/x.sql": _X_HEADER.format(args="v RAW", returns=", returns BIGINT") + "sql/macros/sql/x.sql": _X_HEADER.format(args="v RAW", returns=", returns BIGINT") + "@v + 1\n", **_CALL_X, }, @@ -380,7 +386,9 @@ SqlMacroErrorTestCase( description="type_the_adapter_cannot_parse", files={ - "macros/sql/x.sql": _X_HEADER.format(args="v FOO BAR", returns=", returns BIGINT") + "sql/macros/sql/x.sql": _X_HEADER.format( + args="v FOO BAR", returns=", returns BIGINT" + ) + "@v + 1\n", **_CALL_X, }, @@ -392,7 +400,7 @@ SqlMacroErrorTestCase( description="list_declared_const", files={ - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="codes LIST VARCHAR CONST", returns=", returns BOOLEAN" ) + "'GB' IN @codes\n", @@ -407,7 +415,7 @@ SqlMacroErrorTestCase( description="array_declared_const", files={ - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="codes VARCHAR[] CONST", returns=", returns BOOLEAN" ) + "len(@codes) > 0\n", @@ -422,7 +430,7 @@ SqlMacroErrorTestCase( description="unnamed_column_list_column", files={ - "macros/sql/x.sql": _X_HEADER.format(args="src RELATION (a BIGINT)", returns="") + "sql/macros/sql/x.sql": _X_HEADER.format(args="src RELATION (a BIGINT)", returns="") + "SELECT @src.a + 1\n", **orders_model("SELECT @sql.x(o) FROM (SELECT 1 AS a) AS o\n"), }, @@ -434,7 +442,9 @@ SqlMacroErrorTestCase( description="cte_macro_declaring_returns", files={ - "macros/sql/x.sql": _X_HEADER.format(args="v BIGINT", returns=", returns BIGINT") + "sql/macros/sql/x.sql": _X_HEADER.format( + args="v BIGINT", returns=", returns BIGINT" + ) + "WITH y AS (SELECT @v AS a)\n", **orders_model("WITH @sql.x(1)\nSELECT * FROM y\n"), }, @@ -446,7 +456,9 @@ SqlMacroErrorTestCase( description="built_in_parameter_name", files={ - "macros/sql/x.sql": _X_HEADER.format(args="enum BIGINT", returns=", returns BIGINT") + "sql/macros/sql/x.sql": _X_HEADER.format( + args="enum BIGINT", returns=", returns BIGINT" + ) + "1\n", **_CALL_X, }, @@ -456,7 +468,9 @@ SqlMacroErrorTestCase( description="undeclared_parameter", files={ - "macros/sql/x.sql": _X_HEADER.format(args="v BIGINT", returns=", returns BIGINT") + "sql/macros/sql/x.sql": _X_HEADER.format( + args="v BIGINT", returns=", returns BIGINT" + ) + "@v + @w\n", **_CALL_X, }, @@ -464,13 +478,13 @@ expected_fragments=( "@w in the body of macro x() names no parameter of the macro", "its parameters are @v", - "macros/sql/x.sql:3:6", + "sql/macros/sql/x.sql:3:6", ), ), SqlMacroErrorTestCase( description="relation_parameter_written_bare", files={ - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="src RELATION (order_id BIGINT)", returns="" ) + "WITH ids AS (SELECT order_id FROM src)\n", @@ -484,7 +498,7 @@ SqlMacroErrorTestCase( description="relation_parameter_qualifier_written_bare", files={ - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="src RELATION (order_id BIGINT)", returns="" ) + "SELECT src.order_id\n", @@ -496,7 +510,7 @@ SqlMacroErrorTestCase( description="runtime_parameter_as_limit", files={ - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="src RELATION (order_id BIGINT), n BIGINT", returns="" ) + "WITH firsts AS (SELECT order_id FROM @src LIMIT @n)\n", @@ -513,7 +527,7 @@ SqlMacroErrorTestCase( description="runtime_parameter_as_interval_unit", files={ - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="at TIMESTAMP, unit VARCHAR", returns=", returns TIMESTAMP" ) + "@at + INTERVAL 1 @unit\n", @@ -528,7 +542,7 @@ SqlMacroErrorTestCase( description="runtime_parameter_as_pivot_value", files={ - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="src RELATION (status VARCHAR, amount_cents BIGINT), first_status VARCHAR", returns="", ) @@ -546,7 +560,7 @@ SqlMacroErrorTestCase( description="runtime_parameter_as_round_precision_on_duckdb", files={ - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="v DECIMAL(18, 4), places INT", returns=", returns DECIMAL(18, 2)" ) + "ROUND(@v, @places)\n", @@ -563,7 +577,7 @@ SqlMacroErrorTestCase( description="runtime_parameter_as_date_trunc_unit", files={ - "macros/sql/x.sql": _X_HEADER.format( + "sql/macros/sql/x.sql": _X_HEADER.format( args="at TIMESTAMP, unit VARCHAR", returns=", returns TIMESTAMP" ) + "DATE_TRUNC(@unit, @at)\n", @@ -580,20 +594,20 @@ SqlMacroErrorTestCase( description="body_constant_not_visible_from_macro_file", files={ - "models/marts/_sqlbuild/_constants/places.sql": "CONSTANT (name price_places, value 2);\n", - "macros/sql/x.sql": _X_HEADER.format( + "sql/models/marts/_sqlbuild/_constants/places.sql": "CONSTANT (name price_places, value 2);\n", + "sql/macros/sql/x.sql": _X_HEADER.format( args="v BIGINT", returns=", returns DECIMAL(18, 2)" ) + 'ROUND(@v / 100, @const("price_places"))\n', **orders_model('SELECT @sql.x(amount_cents) AS a FROM __ref("stg_orders")\n'), }, expected_code="S026", - expected_fragments=("constant price_places is not visible from macros/sql/x.sql",), + expected_fragments=("constant price_places is not visible from sql/macros/sql/x.sql",), ), SqlMacroErrorTestCase( description="scoped_macro_not_visible_from_caller", files={ - "models/staging/_sqlbuild/_macros/sql/x.sql": _X_HEADER.format( + "sql/models/staging/_sqlbuild/_macros/sql/x.sql": _X_HEADER.format( args="v BIGINT", returns=", returns BIGINT" ) + "@v + 1\n", @@ -601,39 +615,41 @@ }, expected_code="S006", expected_fragments=( - "SQL macro x() defined at models/staging/_sqlbuild/_macros/sql/x.sql is not visible from", + "SQL macro x() defined at sql/models/staging/_sqlbuild/_macros/sql/x.sql is not visible from", ), ), SqlMacroErrorTestCase( description="folder_local_macro_called_from_a_subfolder_model", files={ - "models/marts/_sqlbuild/_macros/sql/doubled_inner.sql": _X_HEADER.format( + "sql/models/marts/_sqlbuild/_macros/sql/doubled_inner.sql": _X_HEADER.format( args="v BIGINT", returns=", returns BIGINT" ) + "@v * 2\n", - "models/marts/daily/orders.sql": ( + "sql/models/marts/daily/orders.sql": ( 'MODEL (description "Orders");\n\nSELECT @sql.doubled_inner(order_id) AS d ' 'FROM __ref("stg_orders")\n' ), }, expected_code="S006", expected_fragments=( - "SQL macro doubled_inner() defined at models/marts/_sqlbuild/_macros/sql/doubled_inner.sql is not visible from", + "SQL macro doubled_inner() defined at sql/models/marts/_sqlbuild/_macros/sql/doubled_inner.sql is not visible from", ), ), SqlMacroErrorTestCase( description="sql_and_python_macro_sharing_a_name", files={ - "macros/sql/same.sql": _X_HEADER.format(args="v BIGINT", returns=", returns BIGINT") + "sql/macros/sql/same.sql": _X_HEADER.format( + args="v BIGINT", returns=", returns BIGINT" + ) + "@v + 1\n", - "macros/python/same.py": "def same(v):\n return v\n", + "sql/macros/python/same.py": "def same(v):\n return v\n", **orders_model('SELECT @sql.same(amount_cents) AS a FROM __ref("stg_orders")\n'), }, expected_code="P001", expected_fragments=( "Macro name collision for 'same'", - "macros/python/same.py", - "macros/sql/same.sql", + "sql/macros/python/same.py", + "sql/macros/sql/same.sql", ), ), SqlMacroErrorTestCase( @@ -650,7 +666,7 @@ ), }, expected_code="P017", - expected_fragments=("expects INT CONST", "models/marts/orders.sql:5:3"), + expected_fragments=("expects INT CONST", "sql/models/marts/orders.sql:5:3"), ), SqlMacroErrorTestCase( description="relation_missing_a_declared_column", @@ -663,8 +679,8 @@ expected_code="P017", expected_fragments=( "argument src of macro clean_orders() needs column is_deleted BOOLEAN; orders_raw has no column is_deleted", - "models/marts/orders.sql:4:1", - "macros/sql/clean_orders.sql:3:", + "sql/models/marts/orders.sql:4:1", + "sql/macros/sql/clean_orders.sql:3:", "pass a relation with these columns: order_id BIGINT, updated_at TIMESTAMP, is_deleted BOOLEAN", ), ), @@ -695,7 +711,7 @@ expected_code="P017", expected_fragments=( "argument src of macro clean_orders() needs column is_deleted BOOLEAN; orders_raw.is_deleted is VARCHAR", - "models/marts/orders.sql:4:1", + "sql/models/marts/orders.sql:4:1", ), ), SqlMacroErrorTestCase( @@ -709,8 +725,8 @@ expected_code="P017", expected_fragments=( "slot src.keys groups column email_typo; orders_raw has no column email_typo", - "models/marts/orders.sql:4:1", - "macros/sql/latest_per_key.sql:", + "sql/models/marts/orders.sql:4:1", + "sql/macros/sql/latest_per_key.sql:", ), ), SqlMacroErrorTestCase( @@ -724,8 +740,8 @@ expected_code="P017", expected_fragments=( "argument amount_cents of macro cents_to_dollars() expects BIGINT; o.status is VARCHAR", - "models/marts/orders.sql:4:3", - "macros/sql/cents_to_dollars.sql:3:", + "sql/models/marts/orders.sql:4:3", + "sql/macros/sql/cents_to_dollars.sql:3:", ), ), SqlMacroErrorTestCase( @@ -758,15 +774,15 @@ SqlMacroErrorTestCase( description="same_named_folder_local_macros_in_two_folders", files={ - "models/a/_sqlbuild/_macros/sql/helper.sql": _X_HEADER.format( + "sql/models/a/_sqlbuild/_macros/sql/helper.sql": _X_HEADER.format( args="v BIGINT", returns=", returns BIGINT" ) + "@v * 2\n", - "models/b/_sqlbuild/_macros/sql/helper.sql": _X_HEADER.format( + "sql/models/b/_sqlbuild/_macros/sql/helper.sql": _X_HEADER.format( args="v BIGINT", returns=", returns BIGINT" ) + "@v * 3\n", - "models/a/model_a.sql": ( + "sql/models/a/model_a.sql": ( 'MODEL (description "A");\n\nSELECT @sql.helper(order_id) AS x ' 'FROM __ref("stg_orders")\n' ), @@ -785,7 +801,7 @@ expected_code="P021", expected_fragments=( "column-list macro audit_columns() cannot take an alias", - "models/marts/orders.sql:3:20", + "sql/models/marts/orders.sql:3:20", ), ), ], @@ -814,7 +830,7 @@ def test_given_an_invalid_sql_macro_project_when_compiling_then_the_error_names_ 'SELECT o.order_id, @sql.cents_to_dollars(o.amount_cents) AS d FROM __ref("stg_orders") AS o\n' ), }, - edited_path="macros/sql/cents_to_dollars.sql", + edited_path="sql/macros/sql/cents_to_dollars.sql", replaced_text=("amount_cents BIGINT", "amount_cents BOOLEAN"), expected_code="P017", expected_fragment=( @@ -869,4 +885,4 @@ def test_given_typed_calls_in_every_wave_when_compiling_then_each_model_reports_ assert result.returncode == 1, printed assert printed.count(test_case.expected_finding) == test_case.wave_count, printed for level in range(1, test_case.wave_count + 1): - assert f"models/marts/level_{level}.sql:5:3" in printed, printed + assert f"sql/models/marts/level_{level}.sql:5:3" in printed, printed diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_expansion_text.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_expansion_text.py index a94e146263..6bebfcf8bb 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_expansion_text.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_expansion_text.py @@ -20,7 +20,7 @@ with_rules, ) -_COMPILED: str = "target/compiled/models/marts/orders.sql" +_COMPILED: str = "target/compiled/sql/models/marts/orders.sql" _RULE_FAILURES: tuple[str, ...] = ("L005", "rules-unevaluated", "Native SQL parser") _CHECK_STATUS: dict[str, str] = orders_model( 'SELECT order_id, @sql.check(status) AS checked FROM __ref("stg_orders")\n' @@ -132,7 +132,7 @@ description="spaced_enum_and_constant_references_in_a_body_are_declarations", files={ **with_rules("SQLCLEAN001"), - "constants/fee_divisor.sql": "CONSTANT (name fee_divisor, value 100);\n", + "sql/constants/fee_divisor.sql": "CONSTANT (name fee_divisor, value 100);\n", **check_macro( "value VARCHAR, cents BIGINT", '@value <> @enum ("order_status").CLOSED AND @cents / @const ("fee_divisor") > 1', @@ -188,7 +188,7 @@ description="a_cte_list_body_lints_without_parse_or_unused_cte_findings", files={ **with_rules("SQLCLEAN001", "SQLCLEAN005"), - "macros/sql/live_orders.sql": ( + "sql/macros/sql/live_orders.sql": ( 'MACRO (\n description "Live orders",\n' " arguments (src RELATION (order_id BIGINT, is_deleted BOOLEAN)),\n);\n\n" "WITH live AS (SELECT s.order_id FROM @src AS s WHERE NOT s.is_deleted),\n" @@ -384,7 +384,7 @@ def test_given_a_sql_macro_call_in_python_macro_arguments_when_compiling_then_py }, expected_returncode=1, expected_fragments=(f"--> {CHECK_MACRO_PATH}:",), - unexpected_fragments=("--> models/marts/orders.sql",), + unexpected_fragments=("--> sql/models/marts/orders.sql",), ), SqlMacroCompileTestCase( description="comments_a_python_macro_returns_are_judged_in_the_caller", @@ -399,7 +399,7 @@ def test_given_a_sql_macro_call_in_python_macro_arguments_when_compiling_then_py expected_fragments=( "[SQLCLEAN033]", "(in SQL generated by @py.noted('status'))", - "--> models/marts/orders.sql:3:", + "--> sql/models/marts/orders.sql:3:", ), ), SqlMacroCompileTestCase( @@ -412,7 +412,7 @@ def test_given_a_sql_macro_call_in_python_macro_arguments_when_compiling_then_py ), }, expected_returncode=1, - expected_fragments=("[SQLCLEAN033]", "--> models/marts/orders.sql:3:"), + expected_fragments=("[SQLCLEAN033]", "--> sql/models/marts/orders.sql:3:"), ), ], ids=lambda case: case.description, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_layout_rules.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_layout_rules.py index 0a978ee07d..552bb0de95 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_layout_rules.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_layout_rules.py @@ -1,4 +1,4 @@ -"""E2E coverage for declaration layout Rules over a macro folder's python/ and sql/ kind folders.""" +"""E2E coverage for declaration layout Rules over a macro folder's python/nodes/ and sql/ kind folders.""" from __future__ import annotations @@ -46,7 +46,7 @@ expected_returncode=1, expected_fragments=( "error[SQBRDECLARATION304]", - 'declaration container "macros/sql/normalise" has 11 files', + 'declaration container "sql/macros/sql/normalise" has 11 files', ), ), SqlMacroCommandTestCase( @@ -60,7 +60,7 @@ expected_fragments=( "error[SQBRDECLARATION306]", "2 sibling SQL macro files", - "Move these files into macros/sql/text/name/", + "Move these files into sql/macros/sql/text/name/", "each macro keeps its name", ), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_relation_slots.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_relation_slots.py index eea790a291..3e1dfad346 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_relation_slots.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_relation_slots.py @@ -60,8 +60,8 @@ **BY_HAND, }, compared_paths=( - "target/compiled/models/marts/rates_by_slot.sql", - "target/compiled/models/marts/rates_by_hand.sql", + "target/compiled/sql/models/marts/rates_by_slot.sql", + "target/compiled/sql/models/marts/rates_by_hand.sql", ), expected_fragment=( "ROW_NUMBER() OVER (PARTITION BY product_id, region ORDER BY s.week DESC)" @@ -109,8 +109,8 @@ def test_given_a_columns_slot_at_two_grains_when_building_then_it_matches_per_gr expected_code="P017", expected_fragments=( "error[P017]: slot weekly.order_count needs a BIGINT column; weekly has no column placed", - "--> models/marts/rates.sql:4:1", - "--> macros/sql/weekly_rates.sql:3:14", + "--> sql/models/marts/rates.sql:4:1", + "--> sql/macros/sql/weekly_rates.sql:3:14", "help: map weekly.order_count to columns of weekly", ), ), @@ -195,7 +195,7 @@ def test_given_a_columns_slot_at_two_grains_when_building_then_it_matches_per_gr files={ **WEEKLY_ORDERS, **UNNAMED_COUNT, - "models/marts/rates.sql": ( + "sql/models/marts/rates.sql": ( 'MODEL (description "Order counts");\n\n' "SELECT @sql.order_columns(w, weekly.order_count := orders_placed)\n" 'FROM __seed("weekly_orders") AS w\n' @@ -204,14 +204,14 @@ def test_given_a_columns_slot_at_two_grains_when_building_then_it_matches_per_gr expected_code="P017", expected_fragments=( "error[P017]: slot weekly.order_count of macro order_columns() is mapped to orders_placed, but the macro reads it in a select list without AS, so the output column's name would depend on the mapping", - "help: add AS to @weekly.order_count in macros/sql/order_columns.sql", + "help: add AS to @weekly.order_count in sql/macros/sql/order_columns.sql", ), ), SqlMacroErrorTestCase( description="columns_slot_outside_a_list", files={ **WEEKLY_ORDERS, - "macros/sql/weekly_rates.sql": ( + "sql/macros/sql/weekly_rates.sql": ( 'MACRO (description "Rates", arguments (weekly RELATION (keys COLUMNS)));\n\n' "WITH rated AS (SELECT * FROM @weekly WHERE @weekly.keys IS NOT NULL)\n" ), @@ -220,7 +220,7 @@ def test_given_a_columns_slot_at_two_grains_when_building_then_it_matches_per_gr expected_code="P015", expected_fragments=( "error[P015]: COLUMNS slot weekly.keys is read as @weekly.keys in macro weekly_rates() where a list item cannot stand", - "--> macros/sql/weekly_rates.sql:3:44", + "--> sql/macros/sql/weekly_rates.sql:3:44", ), ), ], @@ -260,12 +260,12 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( **WEEKLY_ORDERS, "sqlbuild_project.toml": BASE_FILES["sqlbuild_project.toml"] + '\n[rules]\nselect = ["SQLCLEAN001"]\n', - "macros/sql/order_columns.sql": ( + "sql/macros/sql/order_columns.sql": ( 'MACRO (\n description "Order count column",\n' " arguments (weekly RELATION (order_count BIGINT)),\n);\n\n" "SELECT @weekly.order_count = NULL AS has_no_orders\n" ), - "models/marts/order_counts.sql": ( + "sql/models/marts/order_counts.sql": ( 'MODEL (description "Order counts");\n\n' "SELECT @sql.order_columns(w, weekly.order_count := orders_placed)\n" 'FROM __seed("weekly_orders") AS w\n' @@ -276,7 +276,7 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( expected_fragments=( "error[SQLCLEAN001]: Comparison with NULL is never true (in SQL generated by " "@sql.order_columns(w, weekly.order_count := orders_placed))", - "--> models/marts/order_counts.sql:3:8", + "--> sql/models/marts/order_counts.sql:3:8", ), ), SqlMacroCommandTestCase( @@ -285,13 +285,13 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( **WEEKLY_ORDERS, "sqlbuild_project.toml": BASE_FILES["sqlbuild_project.toml"] + '\n[rules]\nselect = ["SQLCLEAN016"]\n', - "macros/sql/order_columns.sql": ( + "sql/macros/sql/order_columns.sql": ( 'MACRO (\n description "Order count column",\n' " arguments (weekly RELATION (order_count BIGINT)),\n);\n\n" "WITH counted AS (SELECT s.@weekly.order_count AS order_count FROM @weekly AS s),\n" "named AS (SELECT @weekly.order_count AS order_count FROM @weekly)\n" ), - "models/marts/order_counts.sql": ( + "sql/models/marts/order_counts.sql": ( 'MODEL (description "Order counts");\n\n' 'WITH w AS (SELECT * FROM __seed("weekly_orders")),\n' "@sql.order_columns(w, weekly.order_count := orders_placed)\n" @@ -308,12 +308,12 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( **WEEKLY_ORDERS, "sqlbuild_project.toml": BASE_FILES["sqlbuild_project.toml"] + '\n[rules]\nselect = ["SQLCLEAN016"]\n', - "macros/sql/order_columns.sql": ( + "sql/macros/sql/order_columns.sql": ( 'MACRO (\n description "Order count column",\n' " arguments (weekly RELATION (order_count BIGINT)),\n);\n\n" "WITH counted AS (SELECT s.order_count AS order_count FROM @weekly AS s)\n" ), - "models/marts/order_counts.sql": ( + "sql/models/marts/order_counts.sql": ( 'MODEL (description "Order counts");\n\n' 'WITH w AS (SELECT orders_placed AS order_count FROM __seed("weekly_orders")),\n' "@sql.order_columns(w)\n" @@ -324,14 +324,14 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( expected_returncode=1, expected_fragments=( "SQLCLEAN016]: Expression is aliased to its existing name", - "--> macros/sql/order_columns.sql:6:", + "--> sql/macros/sql/order_columns.sql:6:", ), ), SqlMacroCommandTestCase( description="a_plain_slot_read_ambiguous_in_a_join_fails_like_hand_written_sql", files={ **WEEKLY_ORDERS, - "macros/sql/joined_keys.sql": ( + "sql/macros/sql/joined_keys.sql": ( 'MACRO (\n description "Keys of joined weeks",\n' " arguments (weekly RELATION (keys COLUMNS), other RELATION (week BIGINT)),\n);\n\n" "WITH joined AS (\n" @@ -340,7 +340,7 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( " JOIN @other AS o ON w.week = o.week\n" ")\n" ), - "models/marts/joined.sql": ( + "sql/models/marts/joined.sql": ( 'MODEL (description "Joined weeks");\n\n' 'WITH weekly AS (SELECT * FROM __seed("weekly_orders")),\n' "@sql.joined_keys(weekly, weekly, weekly.keys := (product_id))\n" @@ -351,14 +351,14 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( expected_returncode=1, expected_fragments=( "error[B003]: Ambiguous unqualified column 'product_id' found in 2 referenced tables", - "--> models/marts/joined.sql:4:1", + "--> sql/models/marts/joined.sql:4:1", ), ), SqlMacroCommandTestCase( description="the_same_bare_name_written_by_hand_in_a_join", files={ **WEEKLY_ORDERS, - "models/marts/joined.sql": ( + "sql/models/marts/joined.sql": ( 'MODEL (description "Joined weeks");\n\n' 'WITH weekly AS (SELECT * FROM __seed("weekly_orders")),\n' "joined AS (\n" @@ -373,7 +373,7 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( expected_returncode=1, expected_fragments=( "error[B003]: Ambiguous unqualified column 'product_id' found in 2 referenced tables", - "--> models/marts/joined.sql:5:10", + "--> sql/models/marts/joined.sql:5:10", ), ), SqlMacroCommandTestCase( @@ -391,7 +391,7 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( expected_fragments=( "error[P017]: slot weekly.keys column product_id would bind to refunds in this " "subquery; write alias.@weekly.keys", - "--> models/marts/refunded.sql:5:1", + "--> sql/models/marts/refunded.sql:5:1", ), ), SqlMacroCommandTestCase( @@ -471,7 +471,7 @@ def test_given_slot_reads_when_inspecting_then_tools_see_the_mapped_columns( _RATE_TYPE_MISMATCH, "w.refund_count / NULLIF(w.orders_placed, 0) AS refund_rate", ), - inspected_paths=("target/compiled/models/marts/rates.sql",), + inspected_paths=("target/compiled/sql/models/marts/rates.sql",), ), SqlMacroCompileTestCase( description="the_same_expression_written_by_hand", @@ -484,7 +484,7 @@ def test_given_slot_reads_when_inspecting_then_tools_see_the_mapped_columns( _RATE_TYPE_MISMATCH, "w.refund_count / NULLIF(w.orders_placed, 0) AS refund_rate", ), - inspected_paths=("target/compiled/models/marts/rates.sql",), + inspected_paths=("target/compiled/sql/models/marts/rates.sql",), ), ], ids=lambda case: case.description, @@ -522,8 +522,8 @@ def test_given_slot_reads_when_formatting_then_they_lay_out_like_hand_written_co project_dir, result = run_project( tmp_path=tmp_path, files={ - "macros/sql/slots.sql": test_case.slot_text, - "macros/sql/by_hand.sql": test_case.hand_text, + "sql/macros/sql/slots.sql": test_case.slot_text, + "sql/macros/sql/by_hand.sql": test_case.hand_text, }, command=("format",), ) @@ -532,9 +532,9 @@ def test_given_slot_reads_when_formatting_then_they_lay_out_like_hand_written_co ) assert result.returncode == 0, output(result) - formatted: str = (project_dir / "macros/sql/slots.sql").read_text(encoding="utf-8") + formatted: str = (project_dir / "sql/macros/sql/slots.sql").read_text(encoding="utf-8") assert formatted != test_case.slot_text - assert hand_written(formatted) == (project_dir / "macros/sql/by_hand.sql").read_text( + assert hand_written(formatted) == (project_dir / "sql/macros/sql/by_hand.sql").read_text( encoding="utf-8" ) assert checked.returncode == test_case.expected_check_returncode, output(checked) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_returns.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_returns.py index 429eec1dd8..566f93b3dc 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_returns.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_returns.py @@ -24,20 +24,20 @@ from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import run_sqb _UNTYPED_UPSTREAM: dict[str, str] = { - "models/marts/up.sql": ( + "sql/models/marts/up.sql": ( 'MODEL (description "Up");\n\nSELECT NULL AS s FROM __ref("stg_orders") AS o\n' ), } _UNTYPED_CALL: str = 'SELECT @sql.m(u.s) AS v FROM __ref("up") AS u\n' _FIRST_OF: dict[str, str] = { - "macros/sql/first_of.sql": ( + "sql/macros/sql/first_of.sql": ( 'MACRO (\n description "The first of two values",\n' " arguments (value ANY, other ANY),\n returns TYPE OF value,\n);\n\n" "list_extract([@value, @other], 1)\n" ) } _FIRST_OF_UNTYPED: dict[str, str] = { - "macros/sql/first_of.sql": _FIRST_OF["macros/sql/first_of.sql"].replace( + "sql/macros/sql/first_of.sql": _FIRST_OF["sql/macros/sql/first_of.sql"].replace( " returns TYPE OF value,\n", "" ) } @@ -75,16 +75,16 @@ ) } _ROUNDED: dict[str, str] = { - "macros/sql/rounded.sql": ( + "sql/macros/sql/rounded.sql": ( 'MACRO (\n description "Rounded to places",\n' " arguments (value ANY NUMERIC, places INT CONST DEFAULT 2),\n" " returns TYPE OF value,\n);\n\nROUND(@value, @places)\n" ), - "macros/sql/shouted.sql": ( + "sql/macros/sql/shouted.sql": ( 'MACRO (\n description "Shouted",\n arguments (value ANY TEXT),\n' " returns TYPE OF value,\n);\n\nUPPER(@value)\n" ), - "macros/sql/month_of.sql": ( + "sql/macros/sql/month_of.sql": ( 'MACRO (\n description "Month start",\n arguments (value ANY TEMPORAL),\n' " returns TYPE OF value,\n);\n\nDATE_TRUNC('month', @value)\n" ), @@ -147,7 +147,7 @@ expected_fragments=( "error[P024]: macro m() declares returns BIGINT, but its body is VARCHAR\n" " model: orders\n" - " --> macros/sql/m.sql:7:1", + " --> sql/macros/sql/m.sql:7:1", ), ), SqlMacroCompileTestCase( @@ -466,13 +466,13 @@ def test_given_a_partly_unknown_list_body_when_compiling_then_the_mismatch_is_re expected_returncode=1, expected_fragments=( "error[P015]: returns TYPE OF missing names no argument of macro m()", - "macros/sql/m.sql:4:", + "sql/macros/sql/m.sql:4:", ), ), SqlMacroCompileTestCase( description="returns_type_of_a_list_argument_is_reported_at_the_macro_file", files={ - "macros/sql/m.sql": ( + "sql/macros/sql/m.sql": ( 'MACRO (\n description "Listed",\n arguments (codes LIST VARCHAR),\n' " returns TYPE OF codes,\n);\n\n'GB' IN @codes\n" ), @@ -549,7 +549,7 @@ def test_given_returns_type_of_when_compiling_then_each_call_has_its_argument_ty expected_returncode=1, expected_fragments=( "argument value of macro rounded() expects a number; o.status is VARCHAR", - "models/marts/orders.sql:3:", + "sql/models/marts/orders.sql:3:", ), ), SqlMacroCompileTestCase( @@ -566,7 +566,7 @@ def test_given_returns_type_of_when_compiling_then_each_call_has_its_argument_ty SqlMacroCompileTestCase( description="a_body_wrong_for_its_family_is_reported_at_the_macro_file", files={ - "macros/sql/m.sql": ( + "sql/macros/sql/m.sql": ( 'MACRO (\n description "Shouted number",\n arguments (value ANY NUMERIC),\n' ");\n\nUPPER(@value)\n" ), @@ -577,7 +577,7 @@ def test_given_returns_type_of_when_compiling_then_each_call_has_its_argument_ty expected_returncode=1, expected_fragments=( "error[P025]: body of macro m() does not accept every value of value ANY NUMERIC", - "--> macros/sql/m.sql:6:1", + "--> sql/macros/sql/m.sql:6:1", ), ), ], @@ -604,7 +604,7 @@ def test_given_any_type_families_when_compiling_then_calls_and_bodies_are_checke **_FIRST_OF, **contract_model("orders", "day_value (type DATE)", _TYPE_OF_UNION), }, - edited_path="macros/sql/first_of.sql", + edited_path="sql/macros/sql/first_of.sql", replaced_text=(" returns TYPE OF value,\n", ""), expected_cold_fragment="0 errors, 0 warnings", expected_warm_fragment="warning[K003]: column 'day_value'", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_slot_scopes.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_slot_scopes.py index 62057a7b45..bea6a72616 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_slot_scopes.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_slot_scopes.py @@ -18,7 +18,7 @@ scoped_model, ) -_COMPILED: tuple[str, ...] = ("target/compiled/models/marts/scoped.sql",) +_COMPILED: tuple[str, ...] = ("target/compiled/sql/models/marts/scoped.sql",) _CAPTURED: str = ( "error[P017]: slot weekly.keys column product_id would bind to refunds in this subquery; " "write alias.@weekly.keys" @@ -248,7 +248,7 @@ "SELECT * FROM counted", ), expected_returncode=1, - expected_fragments=(_CAPTURED, "--> models/marts/scoped.sql:5:1"), + expected_fragments=(_CAPTURED, "--> sql/models/marts/scoped.sql:5:1"), ), SqlMacroCompileTestCase( description="plain_group_read_in_a_join_lateral_subquery_that_captures_it", @@ -264,7 +264,7 @@ "SELECT * FROM counted", ), expected_returncode=1, - expected_fragments=(_CAPTURED, "--> models/marts/scoped.sql:5:1"), + expected_fragments=(_CAPTURED, "--> sql/models/marts/scoped.sql:5:1"), ), SqlMacroCompileTestCase( description="plain_group_read_in_a_subquery_over_the_passed_relation", @@ -296,7 +296,7 @@ "SELECT * FROM latest", ), expected_returncode=1, - expected_fragments=(_CAPTURED, "--> models/marts/scoped.sql:5:1"), + expected_fragments=(_CAPTURED, "--> sql/models/marts/scoped.sql:5:1"), ), SqlMacroCompileTestCase( description="aliased_group_read_in_a_column_list_macro", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_types.py index 8bb6725fdc..4d4c9e333e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_types.py @@ -25,7 +25,7 @@ from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import query_duckdb, run_sqb _ORDER_KEY: dict[str, str] = { - "macros/sql/order_key.sql": ( + "sql/macros/sql/order_key.sql": ( 'MACRO (\n description "Order key from the country and the order",\n' " arguments (country_code VARCHAR, order_ref ANY),\n" " returns VARCHAR,\n);\n\n" @@ -126,7 +126,7 @@ def test_given_an_any_argument_when_building_then_callers_pass_values_of_any_typ SqlMacroErrorTestCase( description="any_with_const", files={ - "macros/sql/order_key.sql": ( + "sql/macros/sql/order_key.sql": ( 'MACRO (description "Key", arguments (order_ref ANY CONST), ' "returns VARCHAR);\n\nCAST(@order_ref AS VARCHAR)\n" ), @@ -397,7 +397,7 @@ def test_given_an_any_argument_misused_when_compiling_then_it_fails( files={ **with_rules("SQBRCONTRACT105"), **text_macro("m", "BIGINT", "@value", argument="ANY"), - "models/marts/up.sql": ( + "sql/models/marts/up.sql": ( 'MODEL (description "Up");\n\nSELECT NULL AS s FROM __ref("stg_orders") AS o\n' ), **contract_model( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_typing_matrix.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_typing_matrix.py index 77f1696def..8f3442256b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_typing_matrix.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_typing_matrix.py @@ -29,7 +29,7 @@ from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import run_sqb _FROM: str = 'FROM __ref("stg_orders") AS o' -_COMPILED: str = "target/compiled/models/marts/orders.sql" +_COMPILED: str = "target/compiled/sql/models/marts/orders.sql" _CLEAN: tuple[str, ...] = ("0 errors, 0 warnings",) _MACROS: dict[str, str] = { **text_macro("status_bar", "VARCHAR", "bar(LENGTH(@value), 0, 10)"), @@ -297,7 +297,7 @@ def test_given_a_known_different_body_when_compiling_then_the_inferred_type_stan **orders_model(f"SELECT @sql.status_bar(o.status) AS x, o.missing {_FROM}\n"), }, expected_returncode=1, - expected_fragments=("--> models/marts/orders.sql:3:42",), + expected_fragments=("--> sql/models/marts/orders.sql:3:42",), ), SqlMacroCompileTestCase( description="the_reserved_analysis_function_is_rejected_in_a_model", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_unit_tests.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_unit_tests.py index 6818187a1d..992a890d12 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_unit_tests.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_unit_tests.py @@ -42,7 +42,7 @@ "__macro_expected__ AS (SELECT 1 AS order_id, TIMESTAMP '2026-01-02' AS updated_at)\n" ) _ORDERS_CLEAN: dict[str, str] = { - "models/marts/orders_clean.sql": ( + "sql/models/marts/orders_clean.sql": ( 'MODEL (description "Clean orders");\n\n' 'WITH orders_raw AS (SELECT * FROM __ref("stg_orders")),\n' "@sql.clean_orders(orders_raw)\n" @@ -113,7 +113,7 @@ description="mock_of_a_column_list_call_without_commas_keeps_the_separators", files={ **ALL_MACROS, - "models/marts/orders_audited.sql": ( + "sql/models/marts/orders_audited.sql": ( 'MODEL (description "Audited orders");\n\n' "SELECT o.order_id @sql.audit_columns(o) o.status " 'FROM __ref("stg_orders") AS o\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_test_errors/test_native_sql_test_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_test_errors/test_native_sql_test_errors.py index 240eb28130..0f557c5e60 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_test_errors/test_native_sql_test_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_test_errors/test_native_sql_test_errors.py @@ -13,8 +13,10 @@ from scripts.compiler_differential.constants import FAILURE_BASE_MART, FAILURE_MART_PATH from scripts.compiler_differential.models import FailureCase from tests.e2e.src.sqlbuild.cli.commands.main.compile.helpers import ( + MACRO_CALL_LOG_CODE, CompileReuseRun, lifecycle_error_type, + macro_call_log, run_reuse_compile, write_project_file, ) @@ -22,12 +24,11 @@ NativeSqlTestErrorTestCase, ) -_CALL_LOG: str = "macro_calls.log" _COUNTED_MACRO: str = ( "from pathlib import Path\n\n\n" "def counted(expression: str) -> str:\n" ' """Return the expression, logging each execution."""\n\n' - f" with (Path(__file__).resolve().parents[2] / {_CALL_LOG!r}).open(\n" + f" with {MACRO_CALL_LOG_CODE}.open(\n" ' "a", encoding="utf-8"\n' " ) as log:\n" ' _ = log.write("call\\n")\n' @@ -106,12 +107,12 @@ def test_given_sql_test_error_when_compiling_then_the_error_and_type_are_reporte project_dir: Path = tmp_path / "orders" files: dict[str, str] = { **case.files, - "macros/python/counted.py": _COUNTED_MACRO, + "sql/macros/python/counted.py": _COUNTED_MACRO, FAILURE_MART_PATH: FAILURE_BASE_MART.replace("SUM(amount)", "SUM(@py.counted('amount'))"), - _CALL_LOG: "", } for relative_path, contents in files.items(): write_project_file(project_dir, relative_path, contents) + _ = macro_call_log(project_dir).write_text("", encoding="utf-8") run: CompileReuseRun = run_reuse_compile(project_dir=project_dir) error_type: str = lifecycle_error_type(project_dir=project_dir, monkeypatch=monkeypatch) output: str = run.report + run.stderr diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_bigquery_string_contracts.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_bigquery_string_contracts.py index fb3fe33fb2..c6c1f12f55 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_bigquery_string_contracts.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_bigquery_string_contracts.py @@ -56,7 +56,7 @@ def test_given_bigquery_string_contract_when_compiling_then_text_types_compare_a project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/order_notes.sql": _MODEL.format( + "sql/models/order_notes.sql": _MODEL.format( declared_type=test_case.declared_type, cast_type=test_case.cast_type ), }, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_cache_binding_diagnostics.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_cache_binding_diagnostics.py index 2006bc3461..dad1286a92 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_cache_binding_diagnostics.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_cache_binding_diagnostics.py @@ -40,10 +40,10 @@ def test_given_cached_model_with_binding_diagnostic_when_recompiling_then_diagno project_name="orders", repo_files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders");\n\nSELECT 1 AS order_id, 10 AS quantity\n' ), - "models/order_quantities.sql": ( + "sql/models/order_quantities.sql": ( 'MODEL (description "Order quantities");\n\n' + test_case.query_sql ), }, @@ -51,7 +51,7 @@ def test_given_cached_model_with_binding_diagnostic_when_recompiling_then_diagno cold: dict[str, Any] = compile_with_binding_error(project_dir) # An upstream comment defeats whole-project reuse; the diagnosed model's analysis stays cached. - upstream: Path = project_dir / "models" / "orders.sql" + upstream: Path = project_dir / "sql" / "models" / "orders.sql" upstream.write_text( upstream.read_text(encoding="utf-8") + "\n-- upstream comment\n", encoding="utf-8" ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_cache_invalidation.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_cache_invalidation.py index 76d3165cc8..adefa20d50 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_cache_invalidation.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_cache_invalidation.py @@ -29,14 +29,17 @@ CompileCacheInvalidationTestCase( description="model_sql_body_edit", edit=lambda root: replace_project_text( - root, "models/staging/stg_orders.sql", " quantity,", " quantity + 0 AS quantity," + root, + "sql/models/staging/stg_orders.sql", + " quantity,", + " quantity + 0 AS quantity,", ), ), CompileCacheInvalidationTestCase( description="model_header_metadata_edit", edit=lambda root: replace_project_text( root, - "models/staging/stg_orders.sql", + "sql/models/staging/stg_orders.sql", "customer_id (nullable false, audits [not_null]),", 'customer_id (nullable false, description "Buyer.", audits [not_null, unique]),', ), @@ -44,7 +47,10 @@ CompileCacheInvalidationTestCase( description="model_header_syntax_error", edit=lambda root: replace_project_text( - root, "models/staging/stg_orders.sql", "materialized view,", "materialized view,,((" + root, + "sql/models/staging/stg_orders.sql", + "materialized view,", + "materialized view,,((", ), expected_failure=True, ), @@ -52,26 +58,28 @@ description="model_added", edit=lambda root: write_project_file( root, - "models/marts/order_quantities.sql", + "sql/models/marts/order_quantities.sql", 'MODEL (description "Test model order_quantities.");\n\nSELECT order_id, quantity FROM __ref("stg_orders")\n', ), ), CompileCacheInvalidationTestCase( description="model_deleted", - edit=lambda root: (root / "models/marts/channel_orders.sql").unlink(), + edit=lambda root: (root / "sql/models/marts/channel_orders.sql").unlink(), expected_failure=True, ), CompileCacheInvalidationTestCase( description="model_moved_between_folders", edit=lambda root: move_project_file( - root, "models/staging/stg_payments.sql", "models/staging/payments/stg_payments.sql" + root, + "sql/models/staging/stg_payments.sql", + "sql/models/staging/payments/stg_payments.sql", ), ), CompileCacheInvalidationTestCase( description="source_yaml_column_type_edit", edit=lambda root: replace_project_text( root, - "sources/raw.yml", + "sql/sources/raw.yml", " - name: quantity\n type: INTEGER", " - name: quantity\n type: BIGINT", ), @@ -81,7 +89,7 @@ description="source_yaml_column_rename", edit=lambda root: replace_project_text( root, - "sources/raw.yml", + "sql/sources/raw.yml", " - name: quantity\n type: INTEGER", " - name: item_count\n type: INTEGER", ), @@ -90,7 +98,7 @@ CompileCacheInvalidationTestCase( description="source_yaml_syntax_error", edit=lambda root: replace_project_text( - root, "sources/raw.yml", "sources:", "sources: [\n" + root, "sql/sources/raw.yml", "sources:", "sources: [\n" ), expected_failure=True, ), @@ -123,7 +131,7 @@ description="project_macro_edit", edit=lambda root: replace_project_text( root, - "macros/python/currency.py", + "sql/macros/python/currency.py", 'return f"{price_cents} * {quantity}"', 'return f"({price_cents}) * ({quantity})"', ), @@ -132,7 +140,7 @@ description="scoped_macro_edit", edit=lambda root: replace_project_text( root, - "models/marts/_sqlbuild/_macros/python/currency.py", + "sql/models/marts/_sqlbuild/_macros/python/currency.py", 'return f"ROUND(({column}) / 100.0, 2)"', 'return f"ROUND(({column}) / 100.0, 3)"', ), @@ -140,13 +148,16 @@ CompileCacheInvalidationTestCase( description="enum_member_value_edit", edit=lambda root: replace_project_text( - root, "models/marts/_sqlbuild/_enums/order_channel.sql", 'WEB "web"', 'WEB "online"' + root, + "sql/models/marts/_sqlbuild/_enums/order_channel.sql", + 'WEB "web"', + 'WEB "online"', ), ), CompileCacheInvalidationTestCase( description="constant_value_edit", edit=lambda root: replace_project_text( - root, "models/marts/_sqlbuild/_constants/min_quantity.sql", "value 1", "value 3" + root, "sql/models/marts/_sqlbuild/_constants/min_quantity.sql", "value 1", "value 3" ), ), CompileCacheInvalidationTestCase( @@ -172,7 +183,7 @@ description="python_loader_edit", edit=lambda root: replace_project_text( root, - "python/loaders/waffle_sources.py", + "python/nodes/loaders/waffle_sources/loaders.py", "from sqlbuild.loaders import loader\n", "from sqlbuild.loaders import loader\n\nLOADER_REVISION: int = 2\n", ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_complexity_guard.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_complexity_guard.py index 9ab872411d..ac04130106 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_complexity_guard.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_complexity_guard.py @@ -44,7 +44,7 @@ def test_given_deep_trusted_model_when_compiling_then_sql_analysis_completes( "[targets.dev]\n" 'schema = "dev"\n' ), - "models/deep_expression.sql": ( + "sql/models/deep_expression.sql": ( "MODEL (description 'Test model deep_expression.', columns (resolved_value (type INTEGER)));\n\n" f"SELECT {nested_coalesce_expression(function_depth=test_case.function_depth)} " "AS resolved_value\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_delta.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_delta.py index f560599079..a674d43419 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_delta.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_delta.py @@ -56,7 +56,7 @@ _TEXT_COMPILE: tuple[str, ...] = ("compile",) _UNTYPED_ADAPTER: str = "sqlserver" _SMALL_MODEL_COUNT: int = 30 -_SMALL_MODEL_ROOT: str = "models/sales000/intermediate/clean" +_SMALL_MODEL_ROOT: str = "sql/models/sales000/intermediate/clean" _ANALYSED_MODEL: str = f"{_SMALL_MODEL_ROOT}/batch00000/sales000__int_clean__orders_00001.sql" _SMALL_EDITED_MODEL: str = f"{_SMALL_MODEL_ROOT}/batch00001/sales000__int_clean__orders_00005.sql" _RESHAPED_MODEL: str = f"{_SMALL_MODEL_ROOT}/batch00002/sales000__int_clean__orders_00010.sql" @@ -127,7 +127,7 @@ """, ) _ORDER_QUALITY_FACTORY: tuple[str, str] = ( - "python/factories/quality.py", + "python/nodes/factories/quality.py", """from sqlbuild.audits import AuditCase, AuditSeverity, audit_factory @@ -230,7 +230,7 @@ def order_folder_siblings(*, model: Model, ctx: RuleContext) -> list[Finding]: "delta compile fell back: the set of tracked environment variables changed" ) _EDITED_MODEL: str = ( - "models/sales000/intermediate/clean/batch00000/sales000__int_clean__orders_00003.sql" + "sql/models/sales000/intermediate/clean/batch00000/sales000__int_clean__orders_00003.sql" ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_early_builtin_rules.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_early_builtin_rules.py index c86a335b70..a851f13275 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_early_builtin_rules.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_early_builtin_rules.py @@ -40,7 +40,7 @@ " return []\n" " return [ctx.finding(subject=model)]\n" ) -_STAR_FINDING: tuple[str, str, int, int] = ("SQBRMODEL102", "models/order_totals.sql", 2, 8) +_STAR_FINDING: tuple[str, str, int, int] = ("SQBRMODEL102", "sql/models/order_totals.sql", 2, 8) @pytest.mark.parametrize( @@ -50,8 +50,8 @@ description="clean graph answers built-in rules from the early evaluation", repo_files={ "sqlbuild_project.toml": _BUILTIN_PROJECT_TOML, - "models/orders.sql": _ORDERS_SQL, - "models/order_totals.sql": _STAR_TOTALS_SQL, + "sql/models/orders.sql": _ORDERS_SQL, + "sql/models/order_totals.sql": _STAR_TOTALS_SQL, }, compile_arguments=(), expected_exit_code=1, @@ -63,12 +63,12 @@ description="graph error skips rules and discards the early evaluation", repo_files={ "sqlbuild_project.toml": _BUILTIN_PROJECT_TOML, - "models/orders.sql": _ORDERS_SQL, - "models/order_totals.sql": _BROKEN_TOTALS_SQL, + "sql/models/orders.sql": _ORDERS_SQL, + "sql/models/order_totals.sql": _BROKEN_TOTALS_SQL, }, compile_arguments=(), expected_exit_code=1, - expected_diagnostics=(("B002", "models/order_totals.sql", 2, 18),), + expected_diagnostics=(("B002", "sql/models/order_totals.sql", 2, 18),), expected_early_hits=0, expected_early_misses=0, ), @@ -76,8 +76,8 @@ description="model selection evaluates rules without an early evaluation", repo_files={ "sqlbuild_project.toml": _BUILTIN_PROJECT_TOML, - "models/orders.sql": _ORDERS_SQL, - "models/order_totals.sql": _STAR_TOTALS_SQL, + "sql/models/orders.sql": _ORDERS_SQL, + "sql/models/order_totals.sql": _STAR_TOTALS_SQL, }, compile_arguments=("--select", "order_totals"), expected_exit_code=1, @@ -89,15 +89,15 @@ description="custom rules keep built-in rules in the rules phase", repo_files={ "sqlbuild_project.toml": _CUSTOM_PROJECT_TOML, - "models/orders.sql": _ORDERS_SQL, - "models/order_totals.sql": _STAR_TOTALS_SQL, + "sql/models/orders.sql": _ORDERS_SQL, + "sql/models/order_totals.sql": _STAR_TOTALS_SQL, "rules/naming.py": _LONG_NAME_RULE, }, compile_arguments=(), expected_exit_code=1, expected_diagnostics=( _STAR_FINDING, - ("XSQBRNAME001", "models/order_totals.sql", 1, 1), + ("XSQBRNAME001", "sql/models/order_totals.sql", 1, 1), ), expected_early_hits=0, expected_early_misses=0, @@ -132,7 +132,7 @@ def test_given_rules_project_when_compiling_cold_and_warm_then_early_rules_keep_ ( EarlyBuiltinRulesEditTestCase( description="editing one model reuses the other model's cached findings", - edited_path="models/orders.sql", + edited_path="sql/models/orders.sql", edited_sql='MODEL (description "Orders");\nSELECT 1 AS order_id, 3 AS amount\n', expected_diagnostics=(_STAR_FINDING,), expected_early_outcomes=((1, 0), (1, 0), (1, 0)), @@ -150,8 +150,8 @@ def test_given_early_rules_when_compiling_cold_warm_and_edited_then_rule_cache_s project_name="commerce", repo_files={ "sqlbuild_project.toml": _BUILTIN_PROJECT_TOML, - "models/orders.sql": _ORDERS_SQL, - "models/order_totals.sql": _STAR_TOTALS_SQL, + "sql/models/orders.sql": _ORDERS_SQL, + "sql/models/order_totals.sql": _STAR_TOTALS_SQL, }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_early_lint.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_early_lint.py index 4f29767741..bf544bebd9 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_early_lint.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_early_lint.py @@ -41,7 +41,7 @@ "SELECT order_id FROM totals\n" ), expected_exit_code=1, - expected_diagnostics=(("B002", "models/order_totals.sql", 4, 31),), + expected_diagnostics=(("B002", "sql/models/order_totals.sql", 4, 31),), ), EarlyLintCompileTestCase( description="clean graph reports every lint finding at its authored line", @@ -59,9 +59,9 @@ ), expected_exit_code=1, expected_diagnostics=( - ("SQLCLEAN005", "models/order_totals.sql", 3, 3), - ("SQLCLEAN005", "models/order_totals.sql", 6, 3), - ("SQLCLEAN005", "models/order_totals.sql", 9, 3), + ("SQLCLEAN005", "sql/models/order_totals.sql", 3, 3), + ("SQLCLEAN005", "sql/models/order_totals.sql", 6, 3), + ("SQLCLEAN005", "sql/models/order_totals.sql", 9, 3), ), ), ), @@ -76,8 +76,8 @@ def test_given_rules_enabled_project_when_compiling_cold_and_warm_then_lint_wait project_name="commerce", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": _ORDERS_SQL, - "models/order_totals.sql": test_case.order_totals_sql, + "sql/models/orders.sql": _ORDERS_SQL, + "sql/models/order_totals.sql": test_case.order_totals_sql, }, ) @@ -118,7 +118,7 @@ def test_given_slow_background_lint_when_interrupted_then_compile_stops_promptly project_name="commerce", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": _ORDERS_SQL, + "sql/models/orders.sql": _ORDERS_SQL, **slow_lint_model_files(model_count=test_case.model_count), }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_incremental_edits.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_incremental_edits.py index 4c283db9f6..906771e2a9 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_incremental_edits.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_incremental_edits.py @@ -109,7 +109,7 @@ "model_added", lambda root: write_project_file( root, - "models/marts/order_quantities.sql", + "sql/models/marts/order_quantities.sql", "MODEL (description 'Order quantities.');\n\n" 'SELECT order_id, quantity FROM __ref("stg_orders")\n', ), @@ -119,13 +119,13 @@ "model_renamed", lambda root: move_project_file( root, - "models/marts/order_quantities.sql", - "models/marts/order_quantity_totals.sql", + "sql/models/marts/order_quantities.sql", + "sql/models/marts/order_quantity_totals.sql", ), ), edit_step( "model_removed", - lambda root: (root / "models/marts/order_quantity_totals.sql").unlink(), + lambda root: (root / "sql/models/marts/order_quantity_totals.sql").unlink(), ), edit_step("edit_after_remove", fact_comment), ), @@ -137,7 +137,7 @@ "macro_edit", lambda root: replace_project_text( root, - "macros/python/currency.py", + "sql/macros/python/currency.py", "{price_cents} * {quantity}", "{quantity} * {price_cents}", ), @@ -146,14 +146,14 @@ edit_step( "module_imported_by_macro_edit", lambda root: replace_project_text( - root, "macros/python/_rounding.py", "_SCALE: int = 2", "_SCALE: int = 3" + root, "sql/macros/python/_rounding.py", "_SCALE: int = 2", "_SCALE: int = 3" ), ), edit_step( "scoped_macro_edit", lambda root: replace_project_text( root, - "models/marts/_sqlbuild/_macros/python/currency.py", + "sql/models/marts/_sqlbuild/_macros/python/currency.py", "/ 100.0, 2)", "/ 100.0, 3)", ), @@ -171,7 +171,7 @@ "enum_edit", lambda root: replace_project_text( root, - "models/marts/_sqlbuild/_enums/order_channel.sql", + "sql/models/marts/_sqlbuild/_enums/order_channel.sql", 'WEB "web"', 'WEB "online"', ), @@ -180,7 +180,7 @@ "constant_edit", lambda root: replace_project_text( root, - "models/marts/_sqlbuild/_constants/min_quantity.sql", + "sql/models/marts/_sqlbuild/_constants/min_quantity.sql", "value 1)", "value 2)", ), @@ -189,7 +189,7 @@ "new_scope_folder", lambda root: write_project_file( root, - "models/staging/_sqlbuild/_macros/python/staging_totals.py", + "sql/models/staging/_sqlbuild/_macros/python/staging_totals.py", "def staging_total_cents(price_cents: str, quantity: str) -> str:\n" ' """Calculate a staging line total."""\n' ' return f"({price_cents}) * ({quantity})"\n', @@ -204,14 +204,14 @@ edit_step( "seed_edit", lambda root: replace_project_text( - root, "seeds/waffle_types.csv", "Classic Belgian", "Classic Brussels" + root, "sql/seeds/waffle_types.csv", "Classic Belgian", "Classic Brussels" ), ), edit_step( "source_edit", lambda root: replace_project_text( root, - "sources/raw.yml", + "sql/sources/raw.yml", " - name: quantity\n type: INTEGER", " - name: quantity\n type: BIGINT", ), @@ -222,7 +222,7 @@ "audit_edit", lambda root: replace_project_text( root, - "models/marts/_sqlbuild/_audits/generic/expression_is_true.sql", + "sql/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql", "WHERE NOT (@expression)", "WHERE NOT (@expression) AND 1 = 1", ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_macro_call_store.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_macro_call_store.py index 7bdc94805b..8d3ccfbe34 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_macro_call_store.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_macro_call_store.py @@ -59,7 +59,7 @@ _MACRO_REFERENCE_CALL_MESSAGE: str = ( "__ref(customers) is not a valid __ref() call, returned by macro customer_relation()" ) -_MACRO_REFERENCE_CALL_PATH: str = "models/marts/_sqlbuild/_macros/python/customer_relation.py" +_MACRO_REFERENCE_CALL_PATH: str = "sql/models/marts/_sqlbuild/_macros/python/customer_relation.py" _EDIT_STEPS: tuple[MacroCallStoreEditStep, ...] = ( MacroCallStoreEditStep( description="no_change", @@ -126,21 +126,24 @@ MacroCallStoreEditStep( description="constant_file_edit", edit=lambda root: replace_project_text( - root, "constants/base_rate.sql", "value 1)", "value 5)" + root, "sql/constants/base_rate.sql", "value 1)", "value 5)" ), expected_logged_calls=3, ), MacroCallStoreEditStep( description="enum_edit", edit=lambda root: replace_project_text( - root, "enums/order_status.sql", 'PLACED "placed"', 'PLACED "open"' + root, "sql/enums/order_status.sql", 'PLACED "placed"', 'PLACED "open"' ), expected_logged_calls=3, ), MacroCallStoreEditStep( description="macro_body_edit", edit=lambda root: replace_project_text( - root, "macros/python/common.py", 'return f"{column} * 100"', 'return f"{column} * 1000"' + root, + "sql/macros/python/common.py", + 'return f"{column} * 100"', + 'return f"{column} * 1000"', ), expected_logged_calls=3, ), @@ -154,7 +157,7 @@ edit=lambda root: ( write_project_file( root, - "macros/python/badges.py", + "sql/macros/python/badges.py", 'def badge() -> str:\n """Return a badge literal."""\n return "\'gold\'"\n', ), edit_south_model(root, " @py.label() AS label,\n", " @py.badge() AS badge,\n"), @@ -165,7 +168,7 @@ description="macro_file_removed", edit=lambda root: ( edit_south_model(root, " @py.badge() AS badge,\n", ""), - (root / "macros/python/badges.py").unlink(), + (root / "sql/macros/python/badges.py").unlink(), ), expected_logged_calls=3, ), @@ -183,10 +186,10 @@ _TAGGED_STAGING: dict[str, str] = { - "models/staging/_sqlbuild/_macros/python/tags.py": ( + "sql/models/staging/_sqlbuild/_macros/python/tags.py": ( 'def tagged(ctx, expr: str) -> str:\n """Tag."""\n return expr\n' ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( 'MODEL (\n description "Staged orders",\n);\n\n' "SELECT order_id, customer_id, @py.tagged('amount') AS amount, status\n" 'FROM __source("raw_orders")\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_reuse.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_reuse.py index 2eb25d3eba..5e9c0b5ca3 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_reuse.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_reuse.py @@ -102,14 +102,17 @@ CompileReuseInvalidationTestCase( description="model_sql_edit", edit=lambda root: replace_project_text( - root, "models/staging/stg_orders.sql", " quantity,", " quantity + 0 AS quantity," + root, + "sql/models/staging/stg_orders.sql", + " quantity,", + " quantity + 0 AS quantity,", ), ), CompileReuseInvalidationTestCase( description="model_reference_edit", edit=lambda root: replace_project_text( root, - "models/marts/referenced_orders.sql", + "sql/models/marts/referenced_orders.sql", '__ref("stg_orders")', '__ref("regional_orders")', ), @@ -118,7 +121,7 @@ description="macro_built_reference_edit", edit=lambda root: replace_project_text( root, - "models/marts/_sqlbuild/_macros/python/order_source.py", + "sql/models/marts/_sqlbuild/_macros/python/order_source.py", '"stg_orders"', '"regional_orders"', ), @@ -131,20 +134,20 @@ description="model_added", edit=lambda root: write_project_file( root, - "models/marts/order_quantities.sql", + "sql/models/marts/order_quantities.sql", "MODEL (description 'Order quantities.');\n\n" 'SELECT order_id, quantity FROM __ref("stg_orders")\n', ), ), CompileReuseInvalidationTestCase( description="model_deleted", - edit=lambda root: (root / "models/marts/regional_orders.sql").unlink(), + edit=lambda root: (root / "sql/models/marts/regional_orders.sql").unlink(), ), CompileReuseInvalidationTestCase( description="source_yaml_edit", edit=lambda root: replace_project_text( root, - "sources/raw.yml", + "sql/sources/raw.yml", " - name: quantity\n type: INTEGER", " - name: quantity\n type: BIGINT", ), @@ -152,14 +155,14 @@ CompileReuseInvalidationTestCase( description="seed_csv_edit", edit=lambda root: replace_project_text( - root, "seeds/waffle_types.csv", "Classic Belgian", "Classic Brussels" + root, "sql/seeds/waffle_types.csv", "Classic Belgian", "Classic Brussels" ), ), CompileReuseInvalidationTestCase( description="macro_file_edit", edit=lambda root: replace_project_text( root, - "macros/python/currency.py", + "sql/macros/python/currency.py", "{price_cents} * {quantity}", "{quantity} * {price_cents}", ), @@ -167,14 +170,14 @@ CompileReuseInvalidationTestCase( description="module_imported_by_macro_edit", edit=lambda root: replace_project_text( - root, "macros/python/_rounding.py", "_SCALE: int = 2", "_SCALE: int = 3" + root, "sql/macros/python/_rounding.py", "_SCALE: int = 2", "_SCALE: int = 3" ), ), CompileReuseInvalidationTestCase( description="scoped_macro_edit", edit=lambda root: replace_project_text( root, - "models/marts/_sqlbuild/_macros/python/currency.py", + "sql/models/marts/_sqlbuild/_macros/python/currency.py", 'return f"ROUND(({column}) / 100.0, 2)"', 'return f"ROUND(({column}) / 100.0, 3)"', ), @@ -182,7 +185,10 @@ CompileReuseInvalidationTestCase( description="enum_declaration_edit", edit=lambda root: replace_project_text( - root, "models/marts/_sqlbuild/_enums/order_channel.sql", 'WEB "web"', 'WEB "online"' + root, + "sql/models/marts/_sqlbuild/_enums/order_channel.sql", + 'WEB "web"', + 'WEB "online"', ), ), CompileReuseInvalidationTestCase( @@ -234,14 +240,17 @@ CompileReuseInvalidationTestCase( description="contract_error_replayed_as_failure", edit=lambda root: write_project_file( - root, "models/marts/order_contract.sql", _CONTRACT_ERROR_MODEL + root, "sql/models/marts/order_contract.sql", _CONTRACT_ERROR_MODEL ), expected_returncode=1, ), CompileReuseInvalidationTestCase( description="stopped_compile_is_never_replayed", edit=lambda root: replace_project_text( - root, "models/staging/stg_orders.sql", "materialized view,", "materialized view,,((" + root, + "sql/models/staging/stg_orders.sql", + "materialized view,", + "materialized view,,((", ), expected_returncode=1, expected_rewarm_hit=False, @@ -404,7 +413,7 @@ def test_given_timestamp_only_change_when_it_repeats_then_the_known_content_is_r description="model_reads_run_id", edit=lambda root: write_project_file( root, - "models/marts/stamped_orders.sql", + "sql/models/marts/stamped_orders.sql", "MODEL (description 'Orders stamped by run ${CTX:run.id}.');\n\n" 'SELECT order_id FROM __ref("stg_orders")\n', ), @@ -627,7 +636,7 @@ def test_given_deprecated_setting_alias_when_compile_is_reused_then_the_warning_ "test_case", [ CompileReuseRedirectTestCase( - description="json_report_redirected_into_project_root", + description="json_report_redirected_into_a_gitignored_project_file", report_name="compile-report.json", expected_hit_counts=(0, 1), ) @@ -639,6 +648,8 @@ def test_given_stdout_redirected_into_project_when_rerun_then_it_reuses_the_comp ) -> None: project_dir: Path = compile_reuse_project report_path: Path = project_dir / test_case.report_name + # A file outside the project layout is allowed only when the project ignores it. + _ = (project_dir / ".gitignore").write_text(f"{test_case.report_name}\n", encoding="utf-8") first: subprocess.CompletedProcess[str] = run_reuse_compile_into_file( project_dir=project_dir, report_path=report_path @@ -888,6 +899,13 @@ def test_given_large_data_file_when_storing_and_reusing_then_it_is_read_only_aft test_case: CompileReuseLargeFileTestCase, ) -> None: project_dir: Path = compile_reuse_project + project_file: Path = project_dir / "sqlbuild_project.toml" + # A data folder at the top level is part of the project only when the project lists it. + _ = project_file.write_text( + f'extra_paths = ["{test_case.relative_path.split("/")[0]}/"]\n' + + project_file.read_text(encoding="utf-8"), + encoding="utf-8", + ) data_file: Path = write_large_file( project_dir=project_dir, relative_path=test_case.relative_path, @@ -1014,12 +1032,12 @@ def test_given_cache_files_of_older_releases_when_compiling_then_cached_compile_ CompiledTreeStampTestCase( description="stale_file_beside_compiled_models", edit=add_stale_compiled_file_beside_models, - expected_removed_path="target/compiled/models/marts/stale_mart.sql", + expected_removed_path="target/compiled/sql/models/marts/stale_mart.sql", ), CompiledTreeStampTestCase( description="stale_file_in_compiled_models_root", edit=add_stale_compiled_file, - expected_removed_path="target/compiled/models/stale_model.sql", + expected_removed_path="target/compiled/sql/models/stale_model.sql", ), CompiledTreeStampTestCase( description="stale_file_in_linked_compiled_root", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_rule_empty_input_tests.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_rule_empty_input_tests.py index 4412cbd468..ce9eee782e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_rule_empty_input_tests.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_rule_empty_input_tests.py @@ -41,7 +41,7 @@ ) _ORDERS_MINIMUM: tuple[str, str, str] = ( "SQBRTEST202", - "models/orders.sql", + "sql/models/orders.sql", 'model "orders" has 0 tests; 1 required (1 empty-input-only test not counted; see SQBRTEST203)', ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_selection.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_selection.py index 14a265e4f1..d74a03e4ba 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_selection.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_selection.py @@ -25,7 +25,7 @@ 'schema = "dev"\n' ) _SOURCE_FILES: dict[str, str] = { - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw__orders\n" " description: Raw orders.\n" @@ -35,7 +35,7 @@ " - name: order_id\n" " type: INTEGER\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.');\n\nSELECT order_id FROM __source(\"raw__orders\")\n" ), } @@ -68,7 +68,7 @@ ), CompileSelectionTestCase( description="select file keeps upstream analysis while reporting its downstream", - selection_args=("--select-file", "selectors.txt"), + selection_args=("--select-file", "../selectors.txt"), expected_stdout_fragments=( "Compile ready 1 model", "result", @@ -96,16 +96,16 @@ def test_given_model_selection_when_compiling_then_limits_offline_analysis_and_r "[targets.dev]\n" 'schema = "dev"\n' ), - "models/order_record.sql": "MODEL (description 'Test model order_record.');\n\nSELECT 1 AS order_id\n", - "models/result.sql": ( + "sql/models/order_record.sql": "MODEL (description 'Test model order_record.');\n\nSELECT 1 AS order_id\n", + "sql/models/result.sql": ( 'MODEL (description "Test model result.", columns (order_id ()));\n\nSELECT order_id FROM __ref("order_record")\n' ), - "models/unrelated.sql": ( + "sql/models/unrelated.sql": ( "MODEL (description 'Test model unrelated.', columns (missing_column ()));\n\nSELECT 1 AS present_column\n" ), - "selectors.txt": "result\n", }, ) + _ = (project_dir.parent / "selectors.txt").write_text("result\n", encoding="utf-8") result: subprocess.CompletedProcess[str] = run_sqb( command=( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_type_proof_rules.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_type_proof_rules.py index 27675056a5..adb4df11e1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_type_proof_rules.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_compile_type_proof_rules.py @@ -78,7 +78,7 @@ def test_given_typed_contract_when_compiling_then_type_proof_rules_follow_sql_an project_name="orders", repo_files={ "sqlbuild_project.toml": test_case.project_toml, - "models/orders.sql": _ORDERS_MODEL, + "sql/models/orders.sql": _ORDERS_MODEL, }, ) @@ -127,7 +127,7 @@ def test_given_typed_contract_when_building_without_sql_analysis_then_type_proof project_name="orders", repo_files={ "sqlbuild_project.toml": test_case.project_toml, - "models/orders.sql": _ORDERS_MODEL, + "sql/models/orders.sql": _ORDERS_MODEL, }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_contract_cast_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_contract_cast_types.py index 9492bf3f4e..d289b22a0c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_contract_cast_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_contract_cast_types.py @@ -78,7 +78,7 @@ expected_fragments=( 'error[SQBRCONTRACT105]: output "status_label" has an outer cast to VARCHAR(10),' " which is not its declared contract type VARCHAR", - "--> models/labels.sql:12:3", + "--> sql/models/labels.sql:12:3", "help: Change the outer cast to CAST(... AS VARCHAR).", ), ), @@ -93,9 +93,9 @@ def test_given_outer_cast_on_contract_output_when_compiling_then_types_compare_a project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "macros/sql/status_label.sql": _STATUS_LABEL_MACRO, - "models/orders.sql": _ORDERS_MODEL, - "models/labels.sql": _LABELS_MODEL.format(projection=test_case.projection), + "sql/macros/sql/status_label.sql": _STATUS_LABEL_MACRO, + "sql/models/orders.sql": _ORDERS_MODEL, + "sql/models/labels.sql": _LABELS_MODEL.format(projection=test_case.projection), }, ) @@ -138,7 +138,7 @@ def test_given_outer_cast_on_contract_output_when_compiling_then_types_compare_a expected_fragments=( 'error[SQBRCONTRACT105]: output "status_label" is a call to SQL macro ' "status_label(), which declares returns VARCHAR, but its body isn't cast to it", - "--> models/labels.sql:12:3", + "--> sql/models/labels.sql:12:3", "help: Cast the result in the macro or at the call", ), ), @@ -180,11 +180,11 @@ def test_given_typed_macro_call_on_contract_output_when_compiling_then_only_a_bo project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "macros/sql/status_label.sql": _TYPED_MACRO.format( + "sql/macros/sql/status_label.sql": _TYPED_MACRO.format( returns=test_case.returns, body=test_case.body ), - "models/orders.sql": _ORDERS_MODEL, - "models/labels.sql": _LABELS_MODEL.format(projection=test_case.projection), + "sql/models/orders.sql": _ORDERS_MODEL, + "sql/models/labels.sql": _LABELS_MODEL.format(projection=test_case.projection), }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_deep_header_nesting.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_deep_header_nesting.py index e89c0ab3d4..c5e28792d8 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_deep_header_nesting.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_deep_header_nesting.py @@ -20,7 +20,7 @@ _NESTING_HELP: str = "help: flatten the value so it nests at most 256 levels deep" _CONSTANT_CALL_NESTING: tuple[str, ...] = ( "error[D013]", - "constants/limits.sql:3' contains invalid SQLBuild header syntax: " + "sql/constants/limits.sql:3' contains invalid SQLBuild header syntax: " "values nest deeper than 256 levels", _NESTING_HELP, ) @@ -31,26 +31,26 @@ [ DeepHeaderNestingCompileCase( description="native_model_1k", - path="models/orders.sql", + path="sql/models/orders.sql", prefix="MODEL (\n description 'Orders.',\n tags ", suffix=",\n);\n\nSELECT 1 AS order_id\n", depth=1_000, expected_fragments=( "error[D002]", - "models/orders.sql:3' contains invalid SQLBuild header syntax: " + "sql/models/orders.sql:3' contains invalid SQLBuild header syntax: " "values nest deeper than 256 levels", _NESTING_HELP, ), ), DeepHeaderNestingCompileCase( description="native_constant_20k", - path="constants/limits.sql", + path="sql/constants/limits.sql", prefix="\nCONSTANT (\n name order_limits,\n value ", suffix=",\n);\n", depth=20_000, expected_fragments=( "error[D013]", - "constants/limits.sql:4' contains invalid SQLBuild header syntax: " + "sql/constants/limits.sql:4' contains invalid SQLBuild header syntax: " "values nest deeper than 256 levels", _NESTING_HELP, ), @@ -67,7 +67,7 @@ def test_given_deeply_nested_header_value_when_compiling_then_fails_with_coded_d project_name="orders", repo_files={ "sqlbuild_project.toml": _PROJECT_CONFIG, - "models/orders.sql": _ORDERS_MODEL, + "sql/models/orders.sql": _ORDERS_MODEL, test_case.path: test_case.prefix + nested_value + test_case.suffix, }, ) @@ -119,8 +119,8 @@ def test_given_deeply_nested_constant_calls_when_compiling_then_fails_coded( project_name="orders", repo_files={ "sqlbuild_project.toml": _PROJECT_CONFIG, - "models/orders.sql": _ORDERS_MODEL, - "constants/limits.sql": ( + "sql/models/orders.sql": _ORDERS_MODEL, + "sql/constants/limits.sql": ( "CONSTANT (\n name order_limits,\n value " + "limit(level " * test_case.depth + "1" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dense_compile_performance.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dense_compile_performance.py index bc10c8923f..cd7c868b99 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dense_compile_performance.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dense_compile_performance.py @@ -63,28 +63,28 @@ 1000, 6.0 * _NATIVE_COLD_WALL_ALLOWANCE, 800 * _MIB, - "de23b14d87e954a65c2da91918fce062d158419edd63cc8cf3dc938b3e47cd44", + "ab7743624da2bd0f8fc8ee79b27715fef28a99bfd3034a220bda8921fbb96e2e", ), DenseCompileGuardTestCase( "dense_models_3000_all_rules", 3000, 12.0 * _NATIVE_COLD_WALL_ALLOWANCE, 3 * _GIB // 2, - "196fca3e87989eb3e89e443b7ca93bb094198538d5bde32b9d6fcca58ffc8eed", + "f7f04d2d90c5b4731672461cc1501c363aed2ab81124e46abaf65f4307e7e54e", ), DenseCompileGuardTestCase( "dense_models_5000_all_rules", 5000, 18.0 * _NATIVE_COLD_WALL_ALLOWANCE, 9 * _GIB // 4, - "3477a472fa76d6236ebd0c9758d79c18f67f1bf55e9bbec05b002ba3744cfd22", + "1ef68545e95a6f25d012953ff8841bec0f337831c1f8e0780c29096f87754341", ), DenseCompileGuardTestCase( "dense_models_10000_all_rules", 10000, 35.0 * _NATIVE_COLD_WALL_ALLOWANCE, 15 * _GIB // 4, - "f2a574af6e8068a0634fa3c078b168dff9a475ada5d71502482ad2926c90e1c3", + "8b2ca844331ed66f7d31e023f93c5d59d74105ce4c259140ad28e1427465c968", ), ), ids=lambda case: case.description, @@ -154,7 +154,7 @@ def test_given_dense_project_when_compiling_cold_then_preserves_rules_semantics_ # Each model misses in model rules and SQL lint, the custom rule once, and the Python rules # once per project Python file: the custom rule module and every Python macro. python_files: int = len(list(project_dir.glob("rules/*.py"))) + len( - list(project_dir.glob("models/**/macros/python/**/*.py")) + list(project_dir.glob("sql/models/**/macros/python/**/*.py")) ) assert timings["rule_cache_misses"] == 2 * test_case.model_count + 1 + python_files assert timings["built_in_rules_ms"] > 0 @@ -177,8 +177,8 @@ def test_given_dense_project_when_compiling_cold_then_preserves_rules_semantics_ 6.0, 6.0, 3 * _GIB // 2, - "196fca3e87989eb3e89e443b7ca93bb094198538d5bde32b9d6fcca58ffc8eed", - "1afe754dd8c66bc36e38a40c66e9183ecbaf365fd8d87a784069cd615c3ce64a", + "f7f04d2d90c5b4731672461cc1501c363aed2ab81124e46abaf65f4307e7e54e", + "05ad37a618a558852b60ee4e8bcdf44b5e6c095e287458ccff706a4afbb2b71e", 2, ), DenseWarmEditCompileGuardTestCase( @@ -188,8 +188,8 @@ def test_given_dense_project_when_compiling_cold_then_preserves_rules_semantics_ 9.0, 9.5, 9 * _GIB // 4, - "3477a472fa76d6236ebd0c9758d79c18f67f1bf55e9bbec05b002ba3744cfd22", - "dfbada4c59a3ab8ec7733784890d74c7b64e9b0adcb03364baaabef5bdba5574", + "1ef68545e95a6f25d012953ff8841bec0f337831c1f8e0780c29096f87754341", + "83f7f06af1780a8110f3c56dd05265e4d0743aa3c21ed1bddd885f89d3b75f66", 2, ), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_diagnostic_compile_performance.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_diagnostic_compile_performance.py index 92d5ab0f7c..16ea864193 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_diagnostic_compile_performance.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_diagnostic_compile_performance.py @@ -38,7 +38,7 @@ def test_given_large_invalid_models_when_compiling_then_bounds_diagnostic_work( test_case: DiagnosticPerformanceCase, tmp_path: Path ) -> None: write_diagnostic_project(project_dir=tmp_path, depth=test_case.depth, width=test_case.width) - for path in (tmp_path / "models").glob("large_orders_*.sql"): + for path in (tmp_path / "sql" / "models").glob("large_orders_*.sql"): assert len(path.read_text().splitlines()) >= 3000 elapsed, payload = measure_diagnostic_compile( project_dir=tmp_path, timeout=test_case.expected_timeout_seconds diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dialect_line_comments.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dialect_line_comments.py index 8b71f18374..1e3f4558b7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dialect_line_comments.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dialect_line_comments.py @@ -61,8 +61,8 @@ def test_given_dialect_line_comment_with_quotes_when_compiling_then_model_is_ana project_name="orders_project", repo_files={ "sqlbuild_project.toml": test_case.project_toml, - "models/base_orders.sql": _BASE_ORDERS_SQL, - "models/commented_orders.sql": ( + "sql/models/base_orders.sql": _BASE_ORDERS_SQL, + "sql/models/commented_orders.sql": ( "MODEL (description 'Commented orders.', materialized table);\n\n" f"{test_case.query_sql}\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dollar_quoted_project_vars.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dollar_quoted_project_vars.py index 8c4b49df87..c8cc63e7d2 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dollar_quoted_project_vars.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dollar_quoted_project_vars.py @@ -14,7 +14,7 @@ _PROJECT_TOML: str = 'name = "orders"\nadapter = "duckdb"\n\n[vars]\nregion = "north"\n' _MODEL_HEADER: str = "MODEL (description 'Order region labels.', materialized view);\n\n" -_COMPILED_MODEL: Path = Path("target/compiled/models/order_labels.sql") +_COMPILED_MODEL: Path = Path("target/compiled/sql/models/order_labels.sql") @pytest.mark.parametrize( @@ -42,7 +42,7 @@ def test_given_dollar_quoted_model_sql_when_compiling_then_vars_substitute_insid project_name="orders", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/order_labels.sql": _MODEL_HEADER + test_case.model_sql, + "sql/models/order_labels.sql": _MODEL_HEADER + test_case.model_sql, }, ) @@ -75,7 +75,7 @@ def test_given_unclosed_dollar_quote_with_var_when_compiling_then_interpolation_ project_name="orders", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/order_labels.sql": _MODEL_HEADER + test_case.model_sql, + "sql/models/order_labels.sql": _MODEL_HEADER + test_case.model_sql, }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dynamic_models.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dynamic_models.py index ca307d8ad0..f2f548f5a0 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dynamic_models.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_dynamic_models.py @@ -97,9 +97,9 @@ def test_given_dynamic_models_when_compiling_then_adapter_rules_apply( project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML[test_case.adapter], - "models/orders.sql": _ORDERS, - "models/clean_orders.sql": _CLEAN_ORDERS, - "models/daily_totals.sql": ( + "sql/models/orders.sql": _ORDERS, + "sql/models/clean_orders.sql": _CLEAN_ORDERS, + "sql/models/daily_totals.sql": ( f"MODEL (description 'Daily totals.', {test_case.daily_totals_header});\n" f"{_DAILY_TOTALS_QUERY}" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_fresh_process_compile_cache_performance.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_fresh_process_compile_cache_performance.py index 529eac3886..69888f6696 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_fresh_process_compile_cache_performance.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_fresh_process_compile_cache_performance.py @@ -66,16 +66,16 @@ expected_max_rss_bytes=1152 * _MIB, expected_max_cache_bytes=96 * _MIB, expected_cold_fingerprint=( - "286292a621494a38a59cc7afd76122f44d45f75a7f880dda5f0812bc7f44a96e" + "42453f47298eb1da88c2a4224100a6231ee4527f1e437b822dcf8f1385f85b45" ), expected_leaf_edit_fingerprint=( - "b05559012bba3690a2b080249a6a3003990dad864117e2a776ccb4ce7f924fea" + "5f1c87742eb57170683b95cc95963e5ef2cdcdd68b32158322b6693e295ca818" ), expected_macro_edit_fingerprint=( - "055f337ed937d98535ee527b8b4857bc862fff9abb599e3569fd421efb352069" + "f0e3da7889b0d3f80f35899fd1870934fdab8d83aa49392bdc07a9533c1b0b59" ), expected_project_config_fingerprint=( - "17dccf392d769593c6febbcbdbb53dfbcf39cd681bf57dccdbd601ae7b1ecd8e" + "109c9ca710a6015f5ed4638b88cd435a231a2680b893937b1ac44aa27f3672aa" ), macro_call_interval=6, scoped_macros=True, @@ -102,16 +102,16 @@ expected_max_rss_bytes=1152 * _MIB, expected_max_cache_bytes=96 * _MIB, expected_cold_fingerprint=( - "286292a621494a38a59cc7afd76122f44d45f75a7f880dda5f0812bc7f44a96e" + "42453f47298eb1da88c2a4224100a6231ee4527f1e437b822dcf8f1385f85b45" ), expected_leaf_edit_fingerprint=( - "b05559012bba3690a2b080249a6a3003990dad864117e2a776ccb4ce7f924fea" + "5f1c87742eb57170683b95cc95963e5ef2cdcdd68b32158322b6693e295ca818" ), expected_macro_edit_fingerprint=( - "055f337ed937d98535ee527b8b4857bc862fff9abb599e3569fd421efb352069" + "f0e3da7889b0d3f80f35899fd1870934fdab8d83aa49392bdc07a9533c1b0b59" ), expected_project_config_fingerprint=( - "17dccf392d769593c6febbcbdbb53dfbcf39cd681bf57dccdbd601ae7b1ecd8e" + "109c9ca710a6015f5ed4638b88cd435a231a2680b893937b1ac44aa27f3672aa" ), macro_call_interval=6, scoped_macros=True, @@ -140,16 +140,16 @@ expected_max_rss_bytes=1664 * _MIB, expected_max_cache_bytes=160 * _MIB, expected_cold_fingerprint=( - "a89cdf1a5367f9c939beb1c3d43b70381e6d9ebcc0b2d246f7db9e2051ab6ecb" + "b495a623a346aa797c776385b70a03f09aac73589b417c08d0905e5465efc104" ), expected_leaf_edit_fingerprint=( - "5abf7f05d66a6275cbe3fd11ca75765fc6c565ad8827f28a999a443a59ccde48" + "57d7e3139cfde4be15424eec7c4265db09e6ba38f5baffb3de855c5e64ec5140" ), expected_macro_edit_fingerprint=( - "5a451e1b4ce399600a9fbc736b4f21af5084d6418f826f66eb03b61b37a26145" + "3e6923058b55a7b40af9b0d15beeb5cca25ea65c3bfa471d842a0f289684d7db" ), expected_project_config_fingerprint=( - "a2d57bffbd6cdc1a1bc746371fc3986b17c83044d61465a7e48613dbf6b51b85" + "a222ebd3e36feec420aaeaef5343ed663a1d2bff1b75e9a28a91890ad4b82bb9" ), macro_call_interval=6, scoped_macros=True, @@ -178,16 +178,16 @@ expected_max_rss_bytes=3008 * _MIB, expected_max_cache_bytes=320 * _MIB, expected_cold_fingerprint=( - "176af67b3dea1be84c6009e0fea5558914b849abb58a1f6411e56641c9b2ec80" + "5e0e377f023efa6b964c321e47b14d45ca20297b4a90b33d0f801287278d66ce" ), expected_leaf_edit_fingerprint=( - "c14622c147922edb801ead1a286b1974719141dfcc08cc2d37d3f77d1270672d" + "2ecc38966f7b2a03b242eab924e3d498740f338faf099db9eeedde31f8d8fe65" ), expected_macro_edit_fingerprint=( - "1a8849d8a3c4b2acc69041ba82680f120bf0c91086c9a2a9d8a5cdcd82a7b767" + "3d6af38b935d24391232fcdd601ec3e17361b08d085cc681ba6cf6308e316752" ), expected_project_config_fingerprint=( - "2d6d158dd90ff95dc76a742bd04ffb6d6db309933d6e8826515df548d4b46cb9" + "bcab260b5066810e4fd4c6dba9a3e9fe958b308eadc824eaded106cfff2a17dd" ), macro_call_interval=6, scoped_macros=True, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_fresh_process_compile_performance.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_fresh_process_compile_performance.py index 199387d04e..66a9e152ed 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_fresh_process_compile_performance.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_fresh_process_compile_performance.py @@ -46,7 +46,7 @@ expected_max_wall_seconds=9.9 * _NATIVE_COLD_WALL_ALLOWANCE, expected_max_rss_bytes=1088 * _MIB, expected_semantic_fingerprint=( - "c9e4f4857b6879dbbde2f3ed28bc298124569817958512df4dd01170a537be90" + "5d8d4ea9cf91ad660e95fabf90f0e645bd90fc0fe0c6b82028e91fe82ea0ea1d" ), ), FreshProcessCompilePerformanceGuardTestCase( @@ -62,7 +62,7 @@ expected_max_wall_seconds=15.4 * _NATIVE_COLD_WALL_ALLOWANCE, expected_max_rss_bytes=1664 * _MIB, expected_semantic_fingerprint=( - "c89d8d60e9655dcef4cd01c0fc270a9aa2343cb2d56aae2ab5ca476a9778ec39" + "4549894f456c85028882b142c98f63c2015df30c96bad18fe0148c3e9662e1f4" ), ), FreshProcessCompilePerformanceGuardTestCase( @@ -78,7 +78,7 @@ expected_max_wall_seconds=28.8 * _NATIVE_COLD_WALL_ALLOWANCE, expected_max_rss_bytes=int(2.5 * _GIB), expected_semantic_fingerprint=( - "a5caf9a87baa70eb5f90cbd2d30cc86b41d6b160f6e5eadd23413b153878d9e8" + "e45034fe50c3907e4669ed4cc00bfd44ac9b1544cda2fad6d4bb06f77502c12e" ), ), ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_function_header_keys.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_function_header_keys.py index cfcd54bb24..58bca5e8a1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_function_header_keys.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_function_header_keys.py @@ -20,18 +20,18 @@ description="sql udf header with a removed replay setting", repo_files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "functions/sql/normalize_status.sql": ( + "sql/functions/sql/normalize_status.sql": ( "FUNCTION (description 'Test function normalize_status.',\n arguments (status VARCHAR),\n returns VARCHAR,\n" " replay_on_change full,\n);\n\nlower(status)\n" ), - "models/order_statuses.sql": ( + "sql/models/order_statuses.sql": ( "MODEL (description 'Test model order_statuses.', materialized table);\n\nSELECT __udf(\"normalize_status\")('OPEN') " "AS status\n" ), }, expected_fragments=( "error[D002]", - "functions/sql/normalize_status.sql:4' has unsupported keys: replay_on_change", + "sql/functions/sql/normalize_status.sql:4' has unsupported keys: replay_on_change", ), ) ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_function_name_validation.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_function_name_validation.py index b0fdfb24c8..1977d9b1ed 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_function_name_validation.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_function_name_validation.py @@ -72,7 +72,7 @@ FunctionNameCompileTestCase( description="snowflake derived-table alias named like an alias compiles", project_toml=_SNOWFLAKE_PROJECT - + '\n[[rules.rule_ignores]]\nrules = ["SQLCLEAN039"]\npaths = ["models/**"]\n' + + '\n[[rules.rule_ignores]]\nrules = ["SQLCLEAN039"]\npaths = ["sql/models/**"]\n' + 'reason = "The case names a derived table like a date part."\n', query_sql="SELECT x FROM (VALUES (1)) day_of_week (x)\n", expected_exit_code=0, @@ -125,8 +125,8 @@ def test_given_builtin_spelling_when_compiling_then_dialect_support_is_enforced( project_name="products", repo_files={ "sqlbuild_project.toml": test_case.project_toml, - "functions/sql/starts_with.sql": _STARTS_WITH_FUNCTION, - "models/products.sql": ( + "sql/functions/sql/starts_with.sql": _STARTS_WITH_FUNCTION, + "sql/models/products.sql": ( f"MODEL (description 'Test model products.', database warehouse, schema analytics);\n\n{test_case.query_sql}" ), }, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_layered_production_project.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_layered_production_project.py index 903c4255fd..1b4c6d0db3 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_layered_production_project.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_layered_production_project.py @@ -51,7 +51,7 @@ def test_given_layered_production_project_when_compiling_then_reports_no_diagnos audit_count=test_case.audit_count, ) model_sql: str = "".join( - path.read_text(encoding="utf-8") for path in (project_dir / "models").rglob("*.sql") + path.read_text(encoding="utf-8") for path in (project_dir / "sql" / "models").rglob("*.sql") ) for fragment in ("__seed(", "__udf(", "@py.macro_", "model_schema benchmark_row"): assert fragment in model_sql diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_macro_argument_dict_keys.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_macro_argument_dict_keys.py index 9a8b3717d0..2f65cecfa3 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_macro_argument_dict_keys.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_macro_argument_dict_keys.py @@ -69,8 +69,8 @@ def test_given_macro_dict_key_from_nested_call_when_compiling_then_unhashable_ke 'name = "shop"\nadapter = "duckdb"\n\n[connection]\ndatabase = "shop.duckdb"\n\n' "[scopes]\nenforce_placement = false\n" ), - "macros/python/values.py": _MACROS, - "models/orders.sql": ( + "sql/macros/python/values.py": _MACROS, + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n" f"SELECT @py.show({test_case.argument}) AS shown\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_macro_store_module_edits.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_macro_store_module_edits.py index b0e0ac297f..3a823e4810 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_macro_store_module_edits.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_macro_store_module_edits.py @@ -97,7 +97,7 @@ def test_given_stored_call_reused_when_its_lazily_imported_module_changes_then_o [ StoredMacroDeltaFallbackTestCase( description="a model error found by the delta round", - edited_path="models/staging/stg_customers.sql", + edited_path="sql/models/staging/stg_customers.sql", old=" email,\n", new=" email,\n unknown_column,\n", expected_outcome=(0, 1, False, 1), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_missing_target_database.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_missing_target_database.py index 25598b9427..194d39b74d 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_missing_target_database.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_missing_target_database.py @@ -108,11 +108,11 @@ '[connections.archive]\ndatabase = "archive.duckdb"\n' ), extra_files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized view, " "schema staging);\n\nSELECT 1 AS order_id\n" ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n\n@loader\n" "def raw_orders(ctx: object) -> list[dict[str, object]]:\n" ' """Raw orders."""\n _ = ctx\n return [{"order_id": 1}]\n' @@ -138,11 +138,11 @@ '[connections.archive]\ndatabase = "archive.duckdb"\n' ), extra_files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized view, " "schema staging);\n\nSELECT 1 AS order_id\n" ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n\n@loader\n" "def raw_orders(ctx: object) -> list[dict[str, object]]:\n" ' """Raw orders."""\n _ = ctx\n return [{"order_id": 1}]\n' @@ -169,7 +169,7 @@ '[defaults]\nschema = "analytics"\n\n[targets.dev]\nschema = "preserve"\n' ), extra_files={ - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n\n@loader\n" "def raw_orders(ctx: object) -> list[dict[str, object]]:\n" ' """Raw orders."""\n _ = ctx\n return [{"order_id": 1}]\n' @@ -193,7 +193,7 @@ '[defaults]\nschema = "analytics"\n\n[targets.dev]\nschema = "preserve"\n' ), extra_files={ - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n\n@loader\n" "def raw_orders(ctx: object) -> list[dict[str, object]]:\n" ' """Raw orders."""\n _ = ctx\n return [{"order_id": 1}]\n' @@ -218,12 +218,12 @@ '[targets.dev]\nschema = "analytics"\nloader_schema = "preserve"\n' ), extra_files={ - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" " managed: true\n write_strategy: table\n" " columns:\n - name: order_id\n type: INTEGER\n" ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n\n@loader\n" "def raw_orders(ctx: object) -> list[dict[str, object]]:\n" ' """Raw orders."""\n _ = ctx\n return [{"order_id": 1}]\n' @@ -246,12 +246,12 @@ '[targets.dev]\nschema = "analytics"\nloader_schema = "raw_${CTX:run.id}"\n' ), extra_files={ - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" " managed: true\n write_strategy: table\n" " columns:\n - name: order_id\n type: INTEGER\n" ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n\n@loader\n" "def raw_orders(ctx: object) -> list[dict[str, object]]:\n" ' """Raw orders."""\n _ = ctx\n return [{"order_id": 1}]\n' @@ -272,7 +272,7 @@ def test_given_model_without_location_when_compiling_then_error_names_the_settin project_name="orders", repo_files={ "sqlbuild_project.toml": test_case.project_toml, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized view);\n\n" "SELECT 1 AS order_id\n" ), @@ -329,7 +329,7 @@ def test_given_connection_location_when_compiling_then_models_build_there( project_name="orders", repo_files={ "sqlbuild_project.toml": test_case.project_toml, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized view);\n\n" "SELECT 1 AS order_id\n" ), @@ -432,16 +432,16 @@ def test_given_managed_source_when_loading_then_source_lands_in_its_resolved_sch project_name="orders", repo_files={ "sqlbuild_project.toml": test_case.project_toml, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized view, " 'schema staging);\n\nSELECT order_id FROM __source("raw_orders")\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" f" managed: true\n{test_case.source_schema} write_strategy: table\n" " columns:\n - name: order_id\n type: INTEGER\n" ), - "python/loaders/orders.py": ( + "python/nodes/loaders/orders/loader.py": ( "from sqlbuild.loaders import loader\n\n\n@loader\n" "def raw_orders(ctx: object) -> list[dict[str, object]]:\n" ' """Raw orders."""\n _ = ctx\n return [{"order_id": 1}]\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_namespace_validation.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_namespace_validation.py index ecfeab998f..0c677d0ea9 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_namespace_validation.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_namespace_validation.py @@ -79,7 +79,7 @@ description="model without logical schema fails under preserve", repo_files={ "sqlbuild_project.toml": _PRESERVE_CONFIG, - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=1, expected_stderr_fragment="Model 'orders' has no logical schema", @@ -88,8 +88,8 @@ description="seed without logical schema fails under preserve", repo_files={ "sqlbuild_project.toml": _PRESERVE_CONFIG, - "seeds/schema.yml": _SEED_SCHEMA, - "seeds/countries.csv": "code\nGB\n", + "sql/seeds/schema.yml": _SEED_SCHEMA, + "sql/seeds/countries.csv": "code\nGB\n", }, expected_exit_code=1, expected_stderr_fragment="Seed 'countries' has no logical schema", @@ -98,7 +98,7 @@ description="SQL scalar function without logical schema fails under preserve", repo_files={ "sqlbuild_project.toml": _PRESERVE_CONFIG, - "functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", + "sql/functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", }, expected_exit_code=1, expected_stderr_fragment="SQL function 'answer' has no logical schema", @@ -107,7 +107,7 @@ description="SQL table function without logical schema fails under preserve", repo_files={ "sqlbuild_project.toml": _PRESERVE_CONFIG, - "functions/sql/answers.sql": dedent( + "sql/functions/sql/answers.sql": dedent( """ FUNCTION (description "Test function answers.", returns table ( @@ -127,7 +127,7 @@ description="non inheriting Python UDF without logical schema fails under preserve", repo_files={ "sqlbuild_project.toml": _PRESERVE_CONFIG, - "functions/python/answer.py": dedent( + "sql/functions/python/answer.py": dedent( """ from sqlbuild.functions import udf @@ -146,8 +146,8 @@ def main(): description="managed source without logical schema fails under preserve", repo_files={ "sqlbuild_project.toml": _PRESERVE_CONFIG, - "sources/raw.yml": _MANAGED_SOURCE, - "python/loaders/raw_events.py": _MANAGED_SOURCE_LOADER, + "sql/sources/raw.yml": _MANAGED_SOURCE, + "python/nodes/loaders/raw_events/loader.py": _MANAGED_SOURCE_LOADER, }, expected_exit_code=1, expected_stderr_fragment="Managed source 'raw_events' has no logical schema", @@ -176,11 +176,11 @@ def main(): """ ).strip() + "\n", - "models/marts/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", - "seeds/schema.yml": _SEED_SCHEMA, - "seeds/countries.csv": "code\nGB\n", - "functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", - "functions/python/python_answer.py": dedent( + "sql/models/marts/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/seeds/schema.yml": _SEED_SCHEMA, + "sql/seeds/countries.csv": "code\nGB\n", + "sql/functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", + "sql/functions/python/python_answer.py": dedent( """ from sqlbuild.functions import udf @@ -201,11 +201,11 @@ def main(): "sqlbuild_project.toml": _PRESERVE_CONFIG.replace( 'schema = "preserve"', 'schema = "physical"' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", - "seeds/schema.yml": _SEED_SCHEMA, - "seeds/countries.csv": "code\nGB\n", - "functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", - "functions/python/python_answer.py": dedent( + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/seeds/schema.yml": _SEED_SCHEMA, + "sql/seeds/countries.csv": "code\nGB\n", + "sql/functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", + "sql/functions/python/python_answer.py": dedent( """ from sqlbuild.functions import udf @@ -224,7 +224,7 @@ def main(): description="warehouse model without explicit schema fails offline", repo_files={ "sqlbuild_project.toml": _POSTGRES_CONFIG_WITHOUT_SCHEMA, - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=1, expected_stderr_fragment="Model 'orders' has no explicitly resolved physical write schema", @@ -233,8 +233,8 @@ def main(): description="warehouse seed without explicit schema fails offline", repo_files={ "sqlbuild_project.toml": _POSTGRES_CONFIG_WITHOUT_SCHEMA, - "seeds/schema.yml": _SEED_SCHEMA, - "seeds/countries.csv": "code\nGB\n", + "sql/seeds/schema.yml": _SEED_SCHEMA, + "sql/seeds/countries.csv": "code\nGB\n", }, expected_exit_code=1, expected_stderr_fragment="Seed 'countries' has no explicitly resolved physical write schema", @@ -243,7 +243,7 @@ def main(): description="warehouse SQL scalar function without explicit schema fails offline", repo_files={ "sqlbuild_project.toml": _POSTGRES_CONFIG_WITHOUT_SCHEMA, - "functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", + "sql/functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", }, expected_exit_code=1, expected_stderr_fragment="Function 'answer' has no explicitly resolved physical write schema", @@ -252,7 +252,7 @@ def main(): description="warehouse SQL table function without explicit schema fails offline", repo_files={ "sqlbuild_project.toml": _POSTGRES_CONFIG_WITHOUT_SCHEMA, - "functions/sql/answers.sql": ( + "sql/functions/sql/answers.sql": ( "FUNCTION (description 'Test function answers.', returns table (answer INTEGER));\n\nSELECT 42 AS answer\n" ), }, @@ -263,7 +263,7 @@ def main(): description="warehouse Python UDF without explicit schema fails offline", repo_files={ "sqlbuild_project.toml": _POSTGRES_CONFIG_WITHOUT_SCHEMA, - "functions/python/answer.py": _PYTHON_FUNCTION, + "sql/functions/python/answer.py": _PYTHON_FUNCTION, }, expected_exit_code=1, expected_stderr_fragment="Function 'answer' has no explicitly resolved physical write schema", @@ -272,8 +272,8 @@ def main(): description="warehouse managed source without explicit schema fails offline", repo_files={ "sqlbuild_project.toml": _POSTGRES_CONFIG_WITHOUT_SCHEMA, - "sources/raw.yml": _MANAGED_SOURCE, - "python/loaders/raw_events.py": _MANAGED_SOURCE_LOADER, + "sql/sources/raw.yml": _MANAGED_SOURCE, + "python/nodes/loaders/raw_events/loader.py": _MANAGED_SOURCE_LOADER, }, expected_exit_code=1, expected_stderr_fragment=( @@ -284,7 +284,7 @@ def main(): description="resource schema supplies physical namespace", repo_files={ "sqlbuild_project.toml": _POSTGRES_CONFIG_WITHOUT_SCHEMA, - "models/orders.sql": "MODEL (description 'Test model orders.', schema analytics);\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', schema analytics);\n\nSELECT 1 AS id\n", }, expected_exit_code=0, expected_stderr_fragment="", @@ -295,7 +295,7 @@ def main(): "sqlbuild_project.toml": ( _POSTGRES_CONFIG_WITHOUT_SCHEMA + '\n[defaults]\nschema = "analytics"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=0, expected_stderr_fragment="", @@ -309,7 +309,7 @@ def main(): ) + '\n[targets.dev]\nschema = "analytics"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=0, expected_stderr_fragment="", @@ -320,7 +320,7 @@ def main(): "sqlbuild_project.toml": ( _NAMED_POSTGRES_CONFIG_WITHOUT_SCHEMA + 'schema = "preserve"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.', schema analytics);\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', schema analytics);\n\nSELECT 1 AS id\n", }, expected_exit_code=0, expected_stderr_fragment="", @@ -329,7 +329,7 @@ def main(): description="named target rejects model logical schema as strategy", repo_files={ "sqlbuild_project.toml": _NAMED_POSTGRES_CONFIG_WITHOUT_SCHEMA, - "models/orders.sql": "MODEL (description 'Test model orders.', schema analytics);\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', schema analytics);\n\nSELECT 1 AS id\n", }, expected_exit_code=1, expected_stderr_fragment=( @@ -342,7 +342,7 @@ def main(): "sqlbuild_project.toml": ( _NAMED_POSTGRES_CONFIG_WITHOUT_SCHEMA + '\n[defaults]\nschema = "analytics"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=1, expected_stderr_fragment="Named target 'dev' must explicitly set schema", @@ -354,7 +354,7 @@ def main(): 'database = "analytics"', 'database = "analytics"\nschema = "connection_schema"', ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=1, expected_stderr_fragment="Named target 'dev' must explicitly set schema", @@ -365,7 +365,7 @@ def main(): "sqlbuild_project.toml": ( _POSTGRES_CONFIG_WITHOUT_SCHEMA + 'schema = "analytics"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=0, expected_stderr_fragment="", @@ -379,8 +379,8 @@ def main(): ) + '\n[targets.dev]\nloader_schema = "raw"\n' ), - "sources/raw.yml": _MANAGED_SOURCE, - "python/loaders/raw_events.py": _MANAGED_SOURCE_LOADER, + "sql/sources/raw.yml": _MANAGED_SOURCE, + "python/nodes/loaders/raw_events/loader.py": _MANAGED_SOURCE_LOADER, }, expected_exit_code=1, expected_stderr_fragment="Named target 'dev' must explicitly set schema", @@ -393,12 +393,12 @@ def main(): "[connection]\n" 'database = ":memory:"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", - "seeds/schema.yml": _SEED_SCHEMA, - "seeds/countries.csv": "code\nGB\n", - "functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", - "sources/raw.yml": _MANAGED_SOURCE, - "python/loaders/raw_events.py": _MANAGED_SOURCE_LOADER, + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/seeds/schema.yml": _SEED_SCHEMA, + "sql/seeds/countries.csv": "code\nGB\n", + "sql/functions/sql/answer.sql": "FUNCTION (description 'Test function answer.', returns INTEGER);\n\n42\n", + "sql/sources/raw.yml": _MANAGED_SOURCE, + "python/nodes/loaders/raw_events/loader.py": _MANAGED_SOURCE_LOADER, }, expected_exit_code=0, expected_stderr_fragment="", @@ -412,7 +412,7 @@ def main(): 'database = ":memory:"\n\n' "[targets.dev]\n" ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=0, expected_stderr_fragment="", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_config_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_config_errors.py index abe0b7d627..065769566e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_config_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_config_errors.py @@ -14,18 +14,19 @@ NativeConfigErrorTestCase, ) from tests.e2e.src.sqlbuild.cli.commands.main.compile.helpers import ( + MACRO_CALL_LOG_CODE, CompileReuseRun, fallback_free_preview_compile, + macro_call_log, run_reuse_compile, write_counted_error_project, ) -_CALL_LOG: str = "macro_calls.log" _COUNTED_MACRO: str = ( "from pathlib import Path\n\n\n" "def counted(expression: str) -> str:\n" ' """Return the expression, logging each execution."""\n\n' - f" with (Path(__file__).resolve().parents[2] / {_CALL_LOG!r}).open(\n" + f" with {MACRO_CALL_LOG_CODE}.open(\n" ' "a", encoding="utf-8"\n' " ) as log:\n" ' _ = log.write("call\\n")\n' @@ -35,7 +36,7 @@ _UPSTREAM_MACRO: str = _COUNTED_MACRO.replace( "def counted(expression: str) -> str:", "def upstream() -> str:" ).replace(" return expression\n", " return '__ref(\"ghost\")'\n") -_STAGING_PATH: str = "models/staging/stg_orders.sql" +_STAGING_PATH: str = "sql/models/staging/stg_orders.sql" _STAGING_BODY: str = ( '\n);\n\nSELECT order_id, customer_id, amount, status\nFROM __source("raw_orders")\n' ) @@ -45,9 +46,8 @@ ) _FALLBACKS: tuple[tuple[ModuleType, str], ...] = ((_native, "expand_template_data"),) _PROJECT_FILES: dict[str, str] = { - "macros/python/counted.py": _COUNTED_MACRO, - "models/marts/customer_totals.sql": _COUNTED_MART, - _CALL_LOG: "", + "sql/macros/python/counted.py": _COUNTED_MACRO, + "sql/models/marts/customer_totals.sql": _COUNTED_MART, } @@ -125,8 +125,9 @@ def test_given_config_error_when_compiling_then_the_error_is_reported_without_fa write_counted_error_project( project_dir=project_dir, files={**_PROJECT_FILES, **test_case.project_files} ) + _ = macro_call_log(project_dir).write_text("", encoding="utf-8") run: CompileReuseRun = run_reuse_compile(project_dir=project_dir) - macro_calls: int = len((project_dir / _CALL_LOG).read_text(encoding="utf-8").splitlines()) + macro_calls: int = len(macro_call_log(project_dir).read_text(encoding="utf-8").splitlines()) write_counted_error_project( project_dir=tmp_path / "in_process", files={**_PROJECT_FILES, **test_case.project_files} ) @@ -160,12 +161,11 @@ def test_given_config_error_when_compiling_then_the_error_is_reported_without_fa MacroExpandedValidatorErrorTestCase( description="unknown_model_reference_from_a_macro", project_files={ - "macros/python/upstream.py": _UPSTREAM_MACRO, - "models/marts/customer_totals.sql": ( + "sql/macros/python/upstream.py": _UPSTREAM_MACRO, + "sql/models/marts/customer_totals.sql": ( 'MODEL (\n description "Order totals per customer",\n);\n\n' "SELECT * FROM @py.upstream()\n" ), - _CALL_LOG: "", }, expected_report_text="references unknown model 'ghost'", expected_macro_calls=1, @@ -178,8 +178,9 @@ def test_given_validator_error_from_macro_sql_when_compiling_then_macros_run_onc ) -> None: project_dir: Path = tmp_path / "orders" write_counted_error_project(project_dir=project_dir, files=test_case.project_files) + _ = macro_call_log(project_dir).write_text("", encoding="utf-8") run: CompileReuseRun = run_reuse_compile(project_dir=project_dir) - macro_calls: int = len((project_dir / _CALL_LOG).read_text(encoding="utf-8").splitlines()) + macro_calls: int = len(macro_call_log(project_dir).read_text(encoding="utf-8").splitlines()) assert ( run.returncode, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_declaration_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_declaration_errors.py index d7e5a0f16a..5396ab4426 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_declaration_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_declaration_errors.py @@ -12,31 +12,32 @@ NativeDeclarationErrorTestCase, ) from tests.e2e.src.sqlbuild.cli.commands.main.compile.helpers import ( + MACRO_CALL_LOG_CODE, CompileReuseRun, lifecycle_error_type, + macro_call_log, run_reuse_compile, write_project_file, ) -_CALL_LOG: str = "macro_calls.log" _COUNTED_MACRO: str = ( "from pathlib import Path\n\n\n" "def counted(expression: str) -> str:\n" ' """Return the expression, logging each execution."""\n\n' - f" with (Path(__file__).resolve().parents[2] / {_CALL_LOG!r}).open(\n" + f" with {MACRO_CALL_LOG_CODE}.open(\n" ' "a", encoding="utf-8"\n' " ) as log:\n" ' _ = log.write("call\\n")\n' " return expression\n" ) _COUNTED_MART: str = FAILURE_BASE_MART.replace("SUM(amount)", "SUM(@py.counted('amount'))") -_STAGING_PATH: str = "models/staging/stg_orders.sql" +_STAGING_PATH: str = "sql/models/staging/stg_orders.sql" _STAGING_PREFIX: str = ( 'MODEL (\n description "Staged orders",\n);\n\n' 'SELECT order_id, customer_id, amount, status\nFROM __source("raw_orders")\nWHERE ' ) _STATUS_ENUM: dict[str, str] = { - "enums/order_status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/enums/order_status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", } @@ -71,7 +72,7 @@ NativeDeclarationErrorTestCase( description="inaccessible_local_constant_after_a_macro_ran", project_files={ - "models/marts/_constants/limits.sql": "CONSTANT (name order_cap, value 3);\n", + "sql/models/marts/_constants/limits.sql": "CONSTANT (name order_cap, value 3);\n", _STAGING_PATH: _STAGING_PREFIX + 'amount > @const("order_cap")\n', }, expected_report_text="Constant 'order_cap' is known but inaccessible", @@ -90,7 +91,7 @@ description="duplicate_scoped_enum_before_any_macro_runs", project_files={ **_STATUS_ENUM, - "models/staging/_enums/order_status.sql": ( + "sql/models/staging/_enums/order_status.sql": ( "ENUM (name order_status, members [HELD]);\n" ), }, @@ -99,7 +100,9 @@ ), NativeDeclarationErrorTestCase( description="invalid_enum_declaration_file", - project_files={"enums/order_status.sql": "ENUM (name order_status, members [held]);\n"}, + project_files={ + "sql/enums/order_status.sql": "ENUM (name order_status, members [held]);\n" + }, expected_report_text="member identifiers must be uppercase", expected_macro_calls=0, ), @@ -112,15 +115,16 @@ def test_given_declaration_error_when_compiling_natively_then_error_matches_pyth project_dir: Path = tmp_path / "orders" files: dict[str, str] = { **FAILURE_BASE_FILES, - "macros/python/counted.py": _COUNTED_MACRO, - "models/marts/customer_totals.sql": _COUNTED_MART, + "sql/macros/python/counted.py": _COUNTED_MACRO, + "sql/models/marts/customer_totals.sql": _COUNTED_MART, **test_case.project_files, } - for relative_path, contents in {**files, _CALL_LOG: ""}.items(): + for relative_path, contents in files.items(): write_project_file(project_dir, relative_path, contents) + _ = macro_call_log(project_dir).write_text("", encoding="utf-8") run: CompileReuseRun = run_reuse_compile(project_dir=project_dir) - macro_calls: int = len((project_dir / _CALL_LOG).read_text(encoding="utf-8").splitlines()) + macro_calls: int = len(macro_call_log(project_dir).read_text(encoding="utf-8").splitlines()) assert ( run.returncode, @@ -157,9 +161,8 @@ def test_given_declaration_error_when_compiling_then_lifecycle_error_type_matche project_dir: Path = tmp_path / "orders" for relative_path, contents in { **FAILURE_BASE_FILES, - "macros/python/counted.py": _COUNTED_MACRO, - "models/marts/customer_totals.sql": _COUNTED_MART, - _CALL_LOG: "", + "sql/macros/python/counted.py": _COUNTED_MACRO, + "sql/models/marts/customer_totals.sql": _COUNTED_MART, **test_case.project_files, }.items(): write_project_file(project_dir, relative_path, contents) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_macro_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_macro_errors.py index 647d4cbf74..2c5723245f 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_macro_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_macro_errors.py @@ -12,17 +12,18 @@ NativeMacroErrorTestCase, ) from tests.e2e.src.sqlbuild.cli.commands.main.compile.helpers import ( + MACRO_CALL_LOG_CODE, CompileReuseRun, lifecycle_error_type, + macro_call_log, run_reuse_compile, write_project_file, ) -_CALL_LOG: str = "macro_calls.log" _MACROS: str = ( "from pathlib import Path\n\n\n" "def _log(name: str) -> None:\n" - f" with (Path(__file__).resolve().parents[2] / {_CALL_LOG!r}).open(\n" + f" with {MACRO_CALL_LOG_CODE}.open(\n" ' "a", encoding="utf-8"\n' " ) as log:\n" ' _ = log.write(f"{name}\\n")\n\n\n' @@ -53,8 +54,8 @@ 'def pong(expression: str) -> str:\n """Call ping."""\n return ping(expression)\n' ) _COUNTED_MART: str = FAILURE_BASE_MART.replace("SUM(amount)", "SUM(@py.counted('amount'))") -_STAGING_PATH: str = "models/staging/stg_orders.sql" -_MART_PATH: str = "models/marts/customer_totals.sql" +_STAGING_PATH: str = "sql/models/staging/stg_orders.sql" +_MART_PATH: str = "sql/models/marts/customer_totals.sql" _STAGING_PREFIX: str = ( 'MODEL (\n description "Staged orders",\n);\n\nSELECT order_id, customer_id, ' ) @@ -104,15 +105,15 @@ description="macro_in_a_sibling_scope", project_files={ _STAGING_PATH: _STAGING_PREFIX + "@py.mart_only('amount')" + _STAGING_SUFFIX, - "models/marts/_sqlbuild/macros/python/local.py": _MART_MACROS, + "sql/models/marts/_sqlbuild/macros/python/local.py": _MART_MACROS, }, expected_report_text="stg_orders.sql' is inaccessible", expected_macro_runs=["counted amount"], ), NativeMacroErrorTestCase( description="macro_call_cycle", - project_files={"macros/python/cyclic.py": _CYCLIC_MACROS}, - expected_report_text="Macro call cycle in 'macros/python/cyclic.py': ping -> pong -> ping", + project_files={"sql/macros/python/cyclic.py": _CYCLIC_MACROS}, + expected_report_text="Macro call cycle in 'sql/macros/python/cyclic.py': ping -> pong -> ping", expected_macro_runs=[], ), NativeMacroErrorTestCase( @@ -143,15 +144,15 @@ def test_given_macro_error_when_compiling_then_error_matches_python_once( project_dir: Path = tmp_path / "orders" for relative_path, contents in { **FAILURE_BASE_FILES, - "macros/python/orders.py": _MACROS, + "sql/macros/python/orders.py": _MACROS, _MART_PATH: _COUNTED_MART, - _CALL_LOG: "", **test_case.project_files, }.items(): write_project_file(project_dir, relative_path, contents) + _ = macro_call_log(project_dir).write_text("", encoding="utf-8") run: CompileReuseRun = run_reuse_compile(project_dir=project_dir) - macro_runs: list[str] = (project_dir / _CALL_LOG).read_text(encoding="utf-8").splitlines() + macro_runs: list[str] = macro_call_log(project_dir).read_text(encoding="utf-8").splitlines() assert ( run.returncode, @@ -186,9 +187,8 @@ def test_given_macro_error_when_compiling_then_lifecycle_error_type_matches( project_dir: Path = tmp_path / "orders" for relative_path, contents in { **FAILURE_BASE_FILES, - "macros/python/orders.py": _MACROS, + "sql/macros/python/orders.py": _MACROS, _MART_PATH: _COUNTED_MART, - _CALL_LOG: "", **test_case.project_files, }.items(): write_project_file(project_dir, relative_path, contents) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_reference_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_reference_errors.py index 6c05df61b0..e5dccea82a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_reference_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_reference_errors.py @@ -15,18 +15,19 @@ ReferenceScanErrorTestCase, ) from tests.e2e.src.sqlbuild.cli.commands.main.compile.helpers import ( + MACRO_CALL_LOG_CODE, CompileReuseRun, lifecycle_error_type, + macro_call_log, run_reuse_compile, write_project_file, ) -_CALL_LOG: str = "macro_calls.log" _EMIT_MACRO: str = ( "from pathlib import Path\n\n\n" "def emit(expression: str) -> str:\n" ' """Return the expression, logging each execution."""\n\n' - f" with (Path(__file__).resolve().parents[2] / {_CALL_LOG!r}).open(\n" + f" with {MACRO_CALL_LOG_CODE}.open(\n" ' "a", encoding="utf-8"\n' " ) as log:\n" ' _ = log.write("call\\n")\n' @@ -93,7 +94,7 @@ ReferenceScanErrorTestCase( description="macro_output_fault_before_an_authored_fault_is_unlocated", project_files={ - "macros/python/emit.py": _EMIT_MACRO, + "sql/macros/python/emit.py": _EMIT_MACRO, FAILURE_MART_PATH: _MART_HEADER + "SELECT customer_id, @py.emit('__ref(1') AS total_amount\n" 'FROM __ref("stg_orders"\n', @@ -107,7 +108,7 @@ ReferenceScanErrorTestCase( description="authored_fault_after_a_macro_is_located_natively", project_files={ - "macros/python/emit.py": _EMIT_MACRO, + "sql/macros/python/emit.py": _EMIT_MACRO, FAILURE_MART_PATH: _MART_HEADER + "SELECT customer_id, @py.emit('1') AS total_amount\n" 'FROM __ref("stg_orders"\n', @@ -141,7 +142,7 @@ ReferenceScanErrorTestCase( description="audit_file_header_names_the_file", project_files={ - "audits/generic/positive_total.sql": ( + "sql/audits/generic/positive_total.sql": ( "AUDIT (\n -- totals over 12\" boxes, by customer's orders\n" " severity warn\n);\n\n" 'SELECT * FROM __ref("@model") WHERE note = \'open\n' @@ -151,7 +152,7 @@ ), }, expected_message=( - "audits/generic/positive_total.sql: SQL reference contains an unclosed quoted string" + "sql/audits/generic/positive_total.sql: SQL reference contains an unclosed quoted string" ), expected_macro_calls=0, expected_error_type="CompileInputError", @@ -160,14 +161,14 @@ description="function_file_header_names_the_file", project_files={ "sqlbuild_project.toml": _NO_SQL_ANALYSIS_CONFIG, - "functions/sql/orders_for.sql": ( + "sql/functions/sql/orders_for.sql": ( f'FUNCTION (\n description """{_QUOTED_DESCRIPTION}""",\n' " arguments (p_customer_id INTEGER),\n returns INTEGER\n);\n\n" 'SELECT COUNT(*) FROM __ref("stg_orders" WHERE customer_id = p_customer_id\n' ), }, expected_message=( - "functions/sql/orders_for.sql: SQL reference contains an unclosed parenthesis" + "sql/functions/sql/orders_for.sql: SQL reference contains an unclosed parenthesis" ), expected_macro_calls=0, expected_error_type="CompileInputError", @@ -181,12 +182,12 @@ def test_given_reference_scan_error_when_compiling_then_it_is_located_and_typed( project_dir: Path = tmp_path / "orders" for relative_path, contents in { **FAILURE_BASE_FILES, - _CALL_LOG: "", **test_case.project_files, }.items(): write_project_file(project_dir, relative_path, contents) + _ = macro_call_log(project_dir).write_text("", encoding="utf-8") run: CompileReuseRun = run_reuse_compile(project_dir=project_dir) - macro_calls: int = len((project_dir / _CALL_LOG).read_text(encoding="utf-8").splitlines()) + macro_calls: int = len(macro_call_log(project_dir).read_text(encoding="utf-8").splitlines()) error_type: str = lifecycle_error_type(project_dir=project_dir, monkeypatch=monkeypatch) assert ( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_type_system.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_type_system.py index 08c286aa81..50bac1136b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_type_system.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_native_type_system.py @@ -136,8 +136,8 @@ description="matching spellings pass and a changed precision is reported", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": _ORDERS_MODEL, - "models/order_totals.sql": _ORDER_TOTALS_MODEL, + "sql/models/orders.sql": _ORDERS_MODEL, + "sql/models/order_totals.sql": _ORDER_TOTALS_MODEL, }, expected_exit_code=1, expected_report_text="inferred as numeric(10,2) but declared type is DECIMAL(12,2)", @@ -146,8 +146,8 @@ description="a sized TEXT satisfies a VARCHAR contract of the same length", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": _SIZED_TEXT_ORDERS, - "models/order_statuses.sql": _SIZED_VARCHAR_STATUSES, + "sql/models/orders.sql": _SIZED_TEXT_ORDERS, + "sql/models/order_statuses.sql": _SIZED_VARCHAR_STATUSES, }, expected_exit_code=0, expected_report_text='"has_errors": false', @@ -156,11 +156,11 @@ description="every contract family fails alike under immediate promotion", project_files={ "sqlbuild_project.toml": _IMMEDIATE_PROMOTION_TOML, - "models/contract_orders.sql": _ENFORCED_ORDERS, - "models/contract_totals.sql": _IMPLICIT_TOTALS, - "models/contract_empty.sql": _EMPTY_CONTRACT, - "models/contract_order_amounts.sql": _ORDER_AMOUNTS, - "models/contract_category_pivot.sql": _CATEGORY_PIVOT, + "sql/models/contract_orders.sql": _ENFORCED_ORDERS, + "sql/models/contract_totals.sql": _IMPLICIT_TOTALS, + "sql/models/contract_empty.sql": _EMPTY_CONTRACT, + "sql/models/contract_order_amounts.sql": _ORDER_AMOUNTS, + "sql/models/contract_category_pivot.sql": _CATEGORY_PIVOT, }, expected_exit_code=1, expected_report_text="contract enforced requires staged table promotion", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_parameterised_test_lint.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_parameterised_test_lint.py index b379042ad2..3e8ac870a7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_parameterised_test_lint.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_parameterised_test_lint.py @@ -65,8 +65,8 @@ def test_given_parameterised_test_and_sql_rules_when_compiling_then_the_test_is_ project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML.format(rules=test_case.selected_rules), - "models/orders.sql": _ORDERS_MODEL, - "models/stg_orders.sql": _STAGED_ORDERS_MODEL, + "sql/models/orders.sql": _ORDERS_MODEL, + "sql/models/stg_orders.sql": _STAGED_ORDERS_MODEL, "tests/unit/test_stg_orders_status.sql": _STATUS_TEST, }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_path_defaults.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_path_defaults.py index 07e4f9ad95..85ddb752e0 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_path_defaults.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_path_defaults.py @@ -37,7 +37,7 @@ """ ).strip() + "\n", - "models/commerce/partner_feed/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/commerce/partner_feed/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=0, expected_stderr_fragment="", @@ -61,7 +61,7 @@ """ ).strip() + "\n", - "models/commerce/eu/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/commerce/eu/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, expected_exit_code=1, expected_stderr_fragment=( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_macro_argument_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_macro_argument_errors.py index 53e0b833b0..c16b8bea4b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_macro_argument_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_macro_argument_errors.py @@ -47,8 +47,8 @@ def test_given_invalid_python_macro_arguments_when_compiling_then_error_names_th project_name="order_totals", repo_files={ "sqlbuild_project.toml": build_offline_snowflake_project_toml(), - "models/_macros/python/order_total.py": _ORDER_MACRO, - "models/order_totals.sql": ( + "sql/models/_macros/python/order_total.py": _ORDER_MACRO, + "sql/models/order_totals.sql": ( f'MODEL (description "Order totals.");\nSELECT {test_case.call_sql} AS total\n' ), }, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_project_layout.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_project_layout.py index a5781c31e9..c7fdc9e2ca 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_project_layout.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_project_layout.py @@ -10,27 +10,36 @@ from tests.e2e.src.sqlbuild.cli.commands.main.compile._test_types import ( FactoryModuleNodePlanTestCase, + PythonLayoutBuildTestCase, PythonProjectLayoutCompileTestCase, UnrelatedPythonPackageBuildTestCase, ) from tests.e2e.src.sqlbuild.cli.commands.main.compile.helpers import orders_job_project from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb +_LAYOUT_CONFIG: str = 'name = "python_layout"\nadapter = "duckdb"\n' +_ASSET_MODULE: str = ( + "from sqlbuild.assets import asset\n\n\n" + "@asset\n" + "def orders(ctx):\n" + " '''Test task orders.'''\n return None\n" +) + @pytest.mark.parametrize( "test_case", ( PythonProjectLayoutCompileTestCase( - description="unsupported project Python root", + description="Python inside the models folder", repo_files={ "sqlbuild_project.toml": 'name = "python_layout"\nadapter = "duckdb"\n', - "audit_helpers/measurements.py": "def build_cases(): return []\n", + "sql/models/measurements.py": "def build_cases(): return []\n", }, expected_exit_code=1, expected_stderr_fragments=( "error[D016]", - "Unsupported project Python path(s): audit_helpers/measurements.py", - "Move pipeline Python nodes and the helper modules they import under python/", + "Unsupported project Python path(s): sql/models/measurements.py", + "Move pipeline Python nodes and the helper modules they import under python/nodes/", ), ), PythonProjectLayoutCompileTestCase( @@ -145,8 +154,8 @@ }, expected_exit_code=1, expected_stderr_fragments=( - "error[D016]", - "Unsupported project Python path(s): tasks/orders.py", + "error[D018]", + "'tasks/' is not part of a SQLBuild project", ), ), PythonProjectLayoutCompileTestCase( @@ -157,8 +166,8 @@ }, expected_exit_code=1, expected_stderr_fragments=( - "error[D016]", - "Unsupported project Python path(s): assets/orders.py", + "error[D018]", + "'assets/' is not part of a SQLBuild project", ), ), PythonProjectLayoutCompileTestCase( @@ -169,8 +178,8 @@ }, expected_exit_code=1, expected_stderr_fragments=( - "error[D016]", - "Unsupported project Python path(s): checks/orders.py", + "error[D018]", + "'checks/' is not part of a SQLBuild project", ), ), PythonProjectLayoutCompileTestCase( @@ -181,8 +190,8 @@ }, expected_exit_code=1, expected_stderr_fragments=( - "error[D016]", - "Unsupported project Python path(s): loaders/orders.py", + "error[D018]", + "'loaders/' is not part of a SQLBuild project", ), ), PythonProjectLayoutCompileTestCase( @@ -193,8 +202,8 @@ }, expected_exit_code=1, expected_stderr_fragments=( - "error[D016]", - "Unsupported project Python path(s): factories/orders.py", + "error[D018]", + "'factories/' is not part of a SQLBuild project", ), ), PythonProjectLayoutCompileTestCase( @@ -205,8 +214,8 @@ }, expected_exit_code=1, expected_stderr_fragments=( - "error[D016]", - "Unsupported project Python path(s): libs/cleaning.py", + "error[D018]", + "'libs/' is not part of a SQLBuild project", ), ), PythonProjectLayoutCompileTestCase( @@ -217,8 +226,8 @@ }, expected_exit_code=1, expected_stderr_fragments=( - "error[D016]", - "Unsupported project Python path(s): dagster/definitions.py", + "error[D018]", + "'dagster/' is not part of a SQLBuild project", ), ), PythonProjectLayoutCompileTestCase( @@ -229,8 +238,8 @@ }, expected_exit_code=1, expected_stderr_fragments=( - "error[D016]", - "Unsupported project Python path(s): rivers_pipeline/definitions.py", + "error[D018]", + "'rivers_pipeline/' is not part of a SQLBuild project", ), ), PythonProjectLayoutCompileTestCase( @@ -241,8 +250,8 @@ }, expected_exit_code=1, expected_stderr_fragments=( - "error[D016]", - "Unsupported project Python path(s): definitions.py", + "error[D018]", + "'definitions.py' is not part of a SQLBuild project", ), ), ), @@ -274,7 +283,7 @@ def test_given_python_under_unsupported_root_when_compiling_then_command_fails_w description="custom Rule harness test path", repo_files={ "sqlbuild_project.toml": 'name = "rule_harness_layout"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", "tests/rules/test_order_policy.py": "def test_order_policy(): pass\n", }, expected_exit_code=0, @@ -318,7 +327,7 @@ def test_given_rule_harness_test_when_compiling_then_python_test_path_is_accepte 'connection = "developer"\n' 'schema = "main"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -329,30 +338,30 @@ def test_given_rule_harness_test_when_compiling_then_python_test_path_is_accepte " - name: status\n" " type: VARCHAR\n" ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.', materialized table);\n\n" 'SELECT order_id, status FROM __source("raw_orders")\n' ), - "python/_helpers.py": ( + "python/nodes/_helpers.py": ( "def normalize_status(value):\n return value.strip().lower()\n" ), - "python/orders/__init__.py": "", - "python/orders/utils.py": ( - "from python._helpers import normalize_status\n\n\n" + "python/nodes/orders/__init__.py": "", + "python/nodes/orders/utils.py": ( + "from python.nodes._helpers import normalize_status\n\n\n" "def order_rows():\n" " return [\n" " {'order_id': 1, 'status': normalize_status(' Shipped ')},\n" " {'order_id': 2, 'status': normalize_status('PENDING')},\n" " ]\n" ), - "python/loaders/orders.py": ( - "from python.orders.utils import order_rows\n" + "python/nodes/loaders/raw_orders/loader.py": ( + "from python.nodes.orders.utils import order_rows\n" "from sqlbuild.loaders import loader\n\n\n" "@loader\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return order_rows()\n" ), - "python/orders/exports/assets.py": ( + "python/nodes/orders/exports/asset.py": ( "from sqlbuild.assets import asset\n" "from sqlbuild.refs import model\n\n\n" "@asset(depends_on=model('fact_orders'))\n" @@ -361,8 +370,8 @@ def test_given_rule_harness_test_when_compiling_then_python_test_path_is_accepte " rows = ctx.query(f'SELECT COUNT(*) FROM {relation}').fetchall()\n" " return ctx.result(payload={'order_count': int(rows[0][0])})\n" ), - "python/orders/exports/checks.py": ( - "from python.orders.exports.assets import orders_export\n" + "python/nodes/orders/exports/checks.py": ( + "from python.nodes.orders.exports.asset import orders_export\n" "from sqlbuild.checks import check\n\n\n" "@check(depends_on=orders_export)\n" "def orders_export_not_empty(ctx):\n" @@ -424,7 +433,7 @@ def test_given_python_root_project_when_compiling_and_building_then_nodes_run_wi "sqlbuild_project.toml": ( 'name = "factory_layout"\nadapter = "duckdb"\n\n[connection]\ndatabase = ":memory:"\n' ), - "python/factories/orders.py": ( + "python/nodes/orders/orders/asset.py": ( "from sqlbuild.factories import factory\n" "from sqlbuild.assets import asset\n\n\n" "@asset\n" @@ -443,7 +452,7 @@ def test_given_python_root_project_when_compiling_and_building_then_nodes_run_wi "sqlbuild_project.toml": ( 'name = "factory_layout"\nadapter = "duckdb"\n\n[connection]\ndatabase = ":memory:"\n' ), - "python/factories/orders.py": ( + "python/nodes/orders/orders/assets.py": ( "from sqlbuild.factories import factory\n" "from sqlbuild.assets import asset\n\n\n" "@factory\n" @@ -492,12 +501,15 @@ def test_given_factory_returning_module_node_when_planning_then_node_registers_o "sqlbuild_project.toml": ( 'name = "factory_layout"\nadapter = "duckdb"\n\n[connection]\ndatabase = ":memory:"\n' ), - "python/factories/orders.py": ( - "from sqlbuild.factories import factory\n" + "python/nodes/orders/orders/asset.py": ( "from sqlbuild.assets import asset\n\n\n" "@asset\n" "def orders(ctx):\n" - " '''Test task orders.'''\n return None\n\n\n" + " '''Test task orders.'''\n return None\n" + ), + "python/nodes/orders/generated/assets.py": ( + "from sqlbuild.factories import factory\n" + "from sqlbuild.assets import asset\n\n\n" "@factory\n" "def order_nodes():\n" " @asset(name='orders')\n" @@ -538,23 +550,23 @@ def test_given_factory_returning_distinct_same_name_node_when_planning_then_conf description="project python helpers win over an unrelated python package on PYTHONPATH", unrelated_files={ "python/__init__.py": "UNRELATED = True\n", - "python/helpers.py": "raise RuntimeError('unrelated python package imported')\n", + "python/nodes/helpers.py": "raise RuntimeError('unrelated python package imported')\n", }, repo_files={ "sqlbuild_project.toml": ( 'name = "python_collision"\nadapter = "duckdb"\n\n[connection]\ndatabase = ":memory:"\n' ), - "python/helpers/__init__.py": "", - "python/helpers/values.py": "STATUS = 'shipped'\n", - "python/helpers/clean.py": ( + "python/nodes/helpers/__init__.py": "", + "python/nodes/helpers/values.py": "STATUS = 'shipped'\n", + "python/nodes/helpers/clean.py": ( "from .values import STATUS\n\n\ndef label():\n return STATUS\n" ), - "python/orders.py": ( - "import python.helpers.clean\n" + "python/nodes/orders/orders/asset.py": ( + "import python.nodes.helpers.clean\n" "from sqlbuild.assets import asset\n\n\n" "@asset\n" "def orders(ctx):\n" - " '''Test task orders.'''\n return ctx.result(payload={'status': python.helpers.clean.label()})\n" + " '''Test task orders.'''\n return ctx.result(payload={'status': python.nodes.helpers.clean.label()})\n" ), }, expected_build_fragments=("orders", "\u2713 Completed successfully"), @@ -588,5 +600,229 @@ def test_given_unrelated_python_package_on_path_when_building_then_project_pytho assert all(fragment in output for fragment in test_case.expected_build_fragments) +@pytest.mark.parametrize( + "test_case", + ( + PythonProjectLayoutCompileTestCase( + description="unknown folder inside sql", + repo_files={"sqlbuild_project.toml": _LAYOUT_CONFIG, "sql/notes/readme.md": ""}, + expected_exit_code=1, + expected_stderr_fragments=( + "error[D018]", + "'sql/notes/' is not part of a SQLBuild project", + "move it under one of: sql/models/,", + "or list it in extra_paths in sqlbuild_project.toml", + ), + ), + PythonProjectLayoutCompileTestCase( + description="unknown module inside python", + repo_files={"sqlbuild_project.toml": _LAYOUT_CONFIG, "python/helpers.py": ""}, + expected_exit_code=1, + expected_stderr_fragments=( + "error[D018]", + "'python/helpers.py' is not part of a SQLBuild project", + "move it under one of: python/nodes/,", + ), + ), + PythonProjectLayoutCompileTestCase( + description="several unknown entries are named together", + repo_files={ + "sqlbuild_project.toml": _LAYOUT_CONFIG, + "notes.txt": "", + "models/orders.sql": "", + }, + expected_exit_code=1, + expected_stderr_fragments=( + "error[D018]: 'models/' and 'notes.txt' are not part of a SQLBuild project", + ), + ), + PythonProjectLayoutCompileTestCase( + description="extra_paths allows listed entries", + repo_files={ + "sqlbuild_project.toml": 'extra_paths = ["docs/", "sql/notes"]\n' + _LAYOUT_CONFIG, + "docs/guide.md": "", + "sql/notes/readme.md": "", + }, + expected_exit_code=0, + expected_stderr_fragments=(), + ), + PythonProjectLayoutCompileTestCase( + description="gitignored, hidden and SQLBuild-written entries are allowed", + repo_files={ + "sqlbuild_project.toml": _LAYOUT_CONFIG, + ".gitignore": "scratch/\n*.log\n", + "scratch/notes.md": "", + "build.log": "", + ".env": "", + "README.md": "", + "warehouse.duckdb": "", + "logs/run.log": "", + }, + expected_exit_code=0, + expected_stderr_fragments=(), + ), + PythonProjectLayoutCompileTestCase( + description="an asset in node.py", + repo_files={ + "sqlbuild_project.toml": _LAYOUT_CONFIG, + "python/nodes/orders/export/node.py": _ASSET_MODULE, + }, + expected_exit_code=1, + expected_stderr_fragments=( + "error[D011]: @asset 'orders' is declared in python/nodes/orders/export/node.py; " + "an @asset is declared in asset.py", + ), + ), + PythonProjectLayoutCompileTestCase( + description="an asset in loader.py", + repo_files={ + "sqlbuild_project.toml": _LAYOUT_CONFIG, + "python/nodes/orders/export/loader.py": _ASSET_MODULE, + }, + expected_exit_code=1, + expected_stderr_fragments=( + "error[D011]: @asset 'orders' is declared in python/nodes/orders/export/loader.py; " + "an @asset is declared in asset.py", + ), + ), + PythonProjectLayoutCompileTestCase( + description="a loaders.py factory returning an asset", + repo_files={ + "sqlbuild_project.toml": _LAYOUT_CONFIG, + "python/nodes/orders/export/loaders.py": ( + "from sqlbuild.assets import asset\n" + "from sqlbuild.factories import factory\n\n\n" + "@factory\n" + "def order_nodes():\n" + " @asset(name='orders')\n" + " def orders(ctx):\n" + " '''Test task orders.'''\n return None\n" + " return [orders]\n" + ), + }, + expected_exit_code=1, + expected_stderr_fragments=( + "error[D011]: @factory 'order_nodes' in python/nodes/orders/export/loaders.py " + "makes only assets; a factory that makes only assets is declared in assets.py", + ), + ), + PythonProjectLayoutCompileTestCase( + description="a factory.py making one kind", + repo_files={ + "sqlbuild_project.toml": _LAYOUT_CONFIG, + "python/nodes/orders/export/factory.py": ( + "from sqlbuild.assets import asset\n" + "from sqlbuild.factories import factory\n\n\n" + "@factory\n" + "def order_nodes():\n" + " @asset(name='orders')\n" + " def orders(ctx):\n" + " '''Test task orders.'''\n return None\n" + " return [orders]\n" + ), + }, + expected_exit_code=1, + expected_stderr_fragments=( + "error[D011]: @factory 'order_nodes' in python/nodes/orders/export/factory.py " + "makes only assets; a factory that makes only assets is declared in assets.py", + ), + ), + PythonProjectLayoutCompileTestCase( + description="kind-named files and checks beside an asset compile", + repo_files={ + "sqlbuild_project.toml": _LAYOUT_CONFIG, + "python/nodes/orders/export/asset.py": _ASSET_MODULE, + "python/nodes/orders/export/checks.py": ( + "from python.nodes.orders.export.asset import orders\n" + "from sqlbuild.checks import check\n\n\n" + "@check(depends_on=orders)\n" + "def orders_ok(ctx):\n" + " '''Test check orders_ok.'''\n return ctx.pass_()\n" + ), + }, + expected_exit_code=0, + expected_stderr_fragments=(), + ), + ), + ids=lambda case: case.description, +) +def test_given_project_layout_when_compiling_then_layout_and_node_file_names_are_checked( + test_case: PythonProjectLayoutCompileTestCase, + tmp_path: Path, +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="python_layout", + repo_files=test_case.repo_files, + ) + + result: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "compile"), + project_dir=project_dir, + ) + + assert result.returncode == test_case.expected_exit_code, result.stdout + result.stderr + assert all(fragment in result.stderr for fragment in test_case.expected_stderr_fragments), ( + result.stderr + ) + + +@pytest.mark.parametrize( + "test_case", + ( + PythonLayoutBuildTestCase( + description="a provider imported by its python.providers path keeps its class identity", + repo_files={ + "sqlbuild_project.toml": ( + 'name = "provider_identity"\nadapter = "duckdb"\n\n' + '[connection]\ndatabase = ":memory:"\n' + ), + "python/providers/warehouse/provider.py": ( + "from sqlbuild.providers import Provider\n\n\n" + "class Warehouse(Provider):\n" + " '''Test provider Warehouse.'''\n\n" + " region: str = 'north'\n" + ), + "python/nodes/utils/regions.py": ( + "from python.providers.warehouse.provider import Warehouse\n\n\n" + "def region_of(warehouse: Warehouse) -> str:\n" + " return warehouse.region\n" + ), + "python/nodes/orders/export/asset.py": ( + "from python.nodes.utils.regions import region_of\n" + "from python.providers.warehouse.provider import Warehouse\n" + "from sqlbuild.assets import asset\n\n\n" + "@asset\n" + "def orders_export(ctx, warehouse: Warehouse):\n" + " '''Test task orders_export.'''\n" + " assert isinstance(warehouse, Warehouse)\n" + " return ctx.result(payload={'region': region_of(warehouse)})\n" + ), + }, + expected_build_fragments=("orders_export", "✓ Completed successfully"), + ), + ), + ids=lambda case: case.description, +) +def test_given_provider_imported_by_path_when_building_then_its_type_check_holds( + test_case: PythonLayoutBuildTestCase, + tmp_path: Path, +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="provider_identity", + repo_files=test_case.repo_files, + ) + + result: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "build"), + project_dir=project_dir, + ) + + output: str = result.stdout + result.stderr + assert result.returncode == 0, output + assert all(fragment in output for fragment in test_case.expected_build_fragments) + + if __name__ == "__main__": pytest.main([__file__, "-vv"]) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_sql_graph_boundaries.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_sql_graph_boundaries.py index bb94927713..5f5c4bacc5 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_sql_graph_boundaries.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_python_sql_graph_boundaries.py @@ -35,7 +35,9 @@ GraphBoundaryCompileTestCase( description="a cycle through a task, models, a source and its loader fails compile", project_settings=ALLOW_ROUND_TRIPS, - edited_files={"python/tasks/scoring.py": round_trip_refusal("cycle_task.py")}, + edited_files={ + "python/nodes/tasks/scoring/asset.py": round_trip_refusal("cycle_task.py"), + }, expected_exit_code=1, expected_output_fragments=( "S000", @@ -48,8 +50,8 @@ description="a cycle of model refs alone fails compile with the plan's message", project_settings=ALLOW_ROUND_TRIPS, edited_files={ - "models/order_totals.sql": round_trip_refusal("order_totals.sql"), - "models/order_ranks.sql": round_trip_refusal("order_ranks.sql"), + "sql/models/order_totals.sql": round_trip_refusal("order_totals.sql"), + "sql/models/order_ranks.sql": round_trip_refusal("order_ranks.sql"), }, expected_exit_code=1, expected_output_fragments=( @@ -71,8 +73,10 @@ description="a task depending on a terminal loader instead of its source fails compile", project_settings="", edited_files={ - "python/tasks/scoring.py": round_trip_refusal("unread_task.py"), - "python/tasks/reporting.py": round_trip_refusal("terminal_loader_reader.py"), + "python/nodes/tasks/scoring/asset.py": round_trip_refusal("unread_task.py"), + "python/nodes/tasks/reporting/asset.py": round_trip_refusal( + "terminal_loader_reader.py" + ), }, expected_exit_code=1, expected_output_fragments=( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_reference_call_syntax.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_reference_call_syntax.py index 843069e63e..beee605b6e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_reference_call_syntax.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_reference_call_syntax.py @@ -61,7 +61,7 @@ def test_given_double_quoted_reference_calls_when_building_then_relations_resolv ( "P012", "__ref(stg_orders) is not a valid __ref() call", - "models/marts/order_totals.sql", + "sql/models/marts/order_totals.sql", 4, 6, '__ref() takes exactly one double-quoted name, with no comments or extra spaces inside the parentheses: __ref("stg_orders")', @@ -76,7 +76,7 @@ def test_given_double_quoted_reference_calls_when_building_then_relations_resolv ( "P012", "__ref( /* upstream */ 'stg_orders') is not a valid __ref() call", - "models/marts/order_totals.sql", + "sql/models/marts/order_totals.sql", 4, 6, '__ref() takes exactly one double-quoted name, with no comments or extra spaces inside the parentheses: __ref("stg_orders")', @@ -91,7 +91,7 @@ def test_given_double_quoted_reference_calls_when_building_then_relations_resolv ( "P012", "__source('raw_orders') is not a valid __source() call", - "models/staging/stg_orders.sql", + "sql/models/staging/stg_orders.sql", 3, 36, '__source() takes exactly one double-quoted name, with no comments or extra spaces inside the parentheses: __source("raw_orders")', @@ -106,7 +106,7 @@ def test_given_double_quoted_reference_calls_when_building_then_relations_resolv ( "P012", "__ref(stg_orders) is not a valid __ref() call", - "models/marts/order_totals.sql", + "sql/models/marts/order_totals.sql", 4, 6, '__ref() takes exactly one double-quoted name, with no comments or extra spaces inside the parentheses: __ref("stg_orders")', @@ -114,7 +114,7 @@ def test_given_double_quoted_reference_calls_when_building_then_relations_resolv ( "P012", "__source('raw_orders') is not a valid __source() call", - "models/staging/stg_orders.sql", + "sql/models/staging/stg_orders.sql", 3, 36, '__source() takes exactly one double-quoted name, with no comments or extra spaces inside the parentheses: __source("raw_orders")', diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_relationships_target.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_relationships_target.py index dc1415f9a0..e6f952f363 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_relationships_target.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_relationships_target.py @@ -39,10 +39,10 @@ def test_given_relationships_audit_when_compiling_then_target_must_be_a_referenc project_name="relationships_target", repo_files={ "sqlbuild_project.toml": 'name = "relationships_target"\nadapter = "duckdb"\n', - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Test model customers.');\nSELECT 1 AS id\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', columns (customer_id (\n" f" audits [relationships (to {test_case.target}, field id)])));\n" "SELECT 1 AS order_id, 1 AS customer_id\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_require_sql_analysis.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_require_sql_analysis.py index 668a81a1ff..a04f56b0c1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_require_sql_analysis.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_require_sql_analysis.py @@ -32,11 +32,11 @@ description="a header opt-out on parseable SQL is an error listing its findings", repo_files=( ("sqlbuild_project.toml", REQUIRE_SQL_ANALYSIS_PROJECT), - ("models/order_flags.sql", PARSEABLE_OPT_OUT_MODEL), + ("sql/models/order_flags.sql", PARSEABLE_OPT_OUT_MODEL), ), command=_COMPILE, expected_returncode=1, - expected_diagnostics=(("P009", "models/order_flags.sql", 3),), + expected_diagnostics=(("P009", "sql/models/order_flags.sql", 3),), expected_text_fragments=( "sqlbuild_project.toml sets [settings] require_sql_analysis = true, which only " "allows `sql_analysis false` on SQL that SQLBuild cannot parse; this model " @@ -54,7 +54,7 @@ REQUIRE_SQL_ANALYSIS_PROJECT + '\n[path_defaults."marts"]\nsql_analysis = false\n', ), - ("models/marts/order_epochs.sql", PATH_DEFAULT_MODEL), + ("sql/models/marts/order_epochs.sql", PATH_DEFAULT_MODEL), ), command=_COMPILE, expected_returncode=1, @@ -69,7 +69,7 @@ description="an opt-out on SQL the parser rejects is accepted", repo_files=( ("sqlbuild_project.toml", REQUIRE_SQL_ANALYSIS_PROJECT), - ("models/order_lookup.sql", UNPARSEABLE_OPT_OUT_MODEL), + ("sql/models/order_lookup.sql", UNPARSEABLE_OPT_OUT_MODEL), ), command=_COMPILE, expected_returncode=0, @@ -80,7 +80,7 @@ description="without the setting a parseable opt-out keeps today's behaviour", repo_files=( ("sqlbuild_project.toml", OPTIONAL_SQL_ANALYSIS_PROJECT), - ("models/order_flags.sql", PARSEABLE_OPT_OUT_MODEL), + ("sql/models/order_flags.sql", PARSEABLE_OPT_OUT_MODEL), ), command=_COMPILE, expected_returncode=0, @@ -91,19 +91,19 @@ description="a T-SQL cursor stub after a bracket name holding -- is analysed, not skipped", repo_files=( ("sqlbuild_project.toml", SQLSERVER_REQUIRE_SQL_ANALYSIS_PROJECT), - ("sources/raw.yml", SQLSERVER_EVENTS_SOURCE), - ("models/bracketed_events.sql", SQLSERVER_BRACKETED_CURSOR_MODEL), + ("sql/sources/raw.yml", SQLSERVER_EVENTS_SOURCE), + ("sql/models/bracketed_events.sql", SQLSERVER_BRACKETED_CURSOR_MODEL), ), command=_COMPILE, expected_returncode=0, - expected_diagnostics=(("L007", "models/bracketed_events.sql", 18),), + expected_diagnostics=(("L007", "sql/models/bracketed_events.sql", 18),), expected_text_fragments=(), ), RequireSqlAnalysisCase( description="a single-run --no-sql-analysis still works", repo_files=( ("sqlbuild_project.toml", REQUIRE_SQL_ANALYSIS_PROJECT), - ("models/order_flags.sql", PARSEABLE_OPT_OUT_MODEL), + ("sql/models/order_flags.sql", PARSEABLE_OPT_OUT_MODEL), ), command=("--no-color", "compile", "--json", "--no-cache", "--no-sql-analysis"), expected_returncode=0, @@ -115,7 +115,7 @@ repo_files=( ("sqlbuild_project.toml", REQUIRE_SQL_ANALYSIS_PROJECT), ("sqlbuild_local.toml", "[settings]\nsql_analysis = false\n"), - ("models/order_epochs.sql", PATH_DEFAULT_MODEL), + ("sql/models/order_epochs.sql", PATH_DEFAULT_MODEL), ), command=_COMPILE, expected_returncode=1, @@ -134,7 +134,7 @@ repo_files=( ("sqlbuild_project.toml", REQUIRE_SQL_ANALYSIS_PROJECT), ("sqlbuild_local.toml", "[settings]\nrequire_sql_analysis = false\n"), - ("models/order_epochs.sql", PATH_DEFAULT_MODEL), + ("sql/models/order_epochs.sql", PATH_DEFAULT_MODEL), ), command=_COMPILE, expected_returncode=1, @@ -150,7 +150,7 @@ repo_files=( ("sqlbuild_project.toml", OPTIONAL_SQL_ANALYSIS_PROJECT), ( - "models/order_lookup.sql", + "sql/models/order_lookup.sql", 'MODEL (description "Order lookup");\nSELECT order_id FROM orders WHERE\n', ), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_required_descriptions.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_required_descriptions.py index 2c6fa4ffdc..124d7a26cb 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_required_descriptions.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_required_descriptions.py @@ -50,7 +50,7 @@ " - name: label\n type: VARCHAR\n" ) _ORDER_TOTALS_MODEL: tuple[str, str] = ( - "models/order_totals.sql", + "sql/models/order_totals.sql", 'MODEL (description "Order count");\n\nSELECT COUNT(*) AS order_count FROM __ref("orders")\n', ) _SCENARIO_BODY: str = ( @@ -97,19 +97,19 @@ RequiredDescriptionCase( description="model header", missing_files=( - ("models/order_totals.sql", "MODEL (materialized table);\nSELECT 1 AS id\n"), + ("sql/models/order_totals.sql", "MODEL (materialized table);\nSELECT 1 AS id\n"), ), described_files=( ( - "models/order_totals.sql", + "sql/models/order_totals.sql", 'MODEL (description "Order totals", materialized table);\nSELECT 1 AS id\n', ), ), - expected_diagnostic=("P010", "models/order_totals.sql", 1), + expected_diagnostic=("P010", "sql/models/order_totals.sql", 1), expected_message="model 'order_totals' has no description", expected_help_fragments=( "to describe model 'order_totals', add this to the MODEL header in " - "models/order_totals.sql:\n" + "sql/models/order_totals.sql:\n" " MODEL (\n" ' description "What one row of order_totals represents",\n' " ...\n" @@ -143,21 +143,21 @@ RequiredDescriptionCase( description="seed YAML entry", missing_files=( - ("seeds/product_types.csv", _SEED_CSV), - ("seeds/product_types.yml", "seeds:\n - name: product_types\n" + _SEED_COLUMNS), + ("sql/seeds/product_types.csv", _SEED_CSV), + ("sql/seeds/product_types.yml", "seeds:\n - name: product_types\n" + _SEED_COLUMNS), ), described_files=( - ("seeds/product_types.csv", _SEED_CSV), + ("sql/seeds/product_types.csv", _SEED_CSV), ( - "seeds/product_types.yml", + "sql/seeds/product_types.yml", "seeds:\n - name: product_types\n description: Product type catalogue\n" + _SEED_COLUMNS, ), ), - expected_diagnostic=("P010", "seeds/product_types.yml", 2), + expected_diagnostic=("P010", "sql/seeds/product_types.yml", 2), expected_message="seed 'product_types' has no description", expected_help_fragments=( - "add `description` to its entry in seeds/product_types.yml:\n" + "add `description` to its entry in sql/seeds/product_types.yml:\n" " - name: product_types\n" " description: What one row of product_types represents", ), @@ -166,37 +166,37 @@ description="source YAML entry", missing_files=( ( - "sources/raw.yml", + "sql/sources/raw.yml", "sources:\n - name: raw_customers\n schema: main\n table: customers\n", ), ), described_files=( ( - "sources/raw.yml", + "sql/sources/raw.yml", "sources:\n - name: raw_customers\n description: Customer records\n" " schema: main\n table: customers\n", ), ), - expected_diagnostic=("P010", "sources/raw.yml", 2), + expected_diagnostic=("P010", "sql/sources/raw.yml", 2), expected_message="source 'raw_customers' has no description", expected_help_fragments=( - "add `description` to its entry in sources/raw.yml:\n" + "add `description` to its entry in sql/sources/raw.yml:\n" " - name: raw_customers\n", ), ), RequiredDescriptionCase( description="managed source described by its loader docstring", missing_files=( - ("sources/raw.yml", "sources:\n - name: raw_customers\n managed: true\n"), + ("sql/sources/raw.yml", "sources:\n - name: raw_customers\n managed: true\n"), ( - "python/loaders/raw_customers.py", + "python/nodes/loaders/raw_customers/loader.py", python_node_source(module="loaders", decorator="loader", name="raw_customers"), ), ), described_files=( - ("sources/raw.yml", "sources:\n - name: raw_customers\n managed: true\n"), + ("sql/sources/raw.yml", "sources:\n - name: raw_customers\n managed: true\n"), ( - "python/loaders/raw_customers.py", + "python/nodes/loaders/raw_customers/loader.py", python_node_source( module="loaders", decorator="loader", @@ -205,10 +205,10 @@ ), ), ), - expected_diagnostic=("P010", "sources/raw.yml", 2), + expected_diagnostic=("P010", "sql/sources/raw.yml", 2), expected_message="source 'raw_customers' has no description", expected_help_fragments=( - "or describe its loader 'raw_customers' in python/loaders/raw_customers.py with a " + "or describe its loader 'raw_customers' in python/nodes/loaders/raw_customers/loader.py with a " 'docstring or @loader(description="What one row of raw_customers represents")', ), ), @@ -216,22 +216,22 @@ description="SQL function header", missing_files=( ( - "functions/sql/is_large_order.sql", + "sql/functions/sql/is_large_order.sql", "FUNCTION (\n arguments (amount INTEGER),\n returns BOOLEAN,\n);\n\n" "amount > 100\n", ), ), described_files=( ( - "functions/sql/is_large_order.sql", + "sql/functions/sql/is_large_order.sql", 'FUNCTION (\n description "Whether an order amount is large",\n' " arguments (amount INTEGER),\n returns BOOLEAN,\n);\n\namount > 100\n", ), ), - expected_diagnostic=("P010", "functions/sql/is_large_order.sql", 1), + expected_diagnostic=("P010", "sql/functions/sql/is_large_order.sql", 1), expected_message="function 'is_large_order' has no description", expected_help_fragments=( - "add this to the FUNCTION header in functions/sql/is_large_order.sql:\n" + "add this to the FUNCTION header in sql/functions/sql/is_large_order.sql:\n" " FUNCTION (\n" ' description "What is_large_order returns",', ), @@ -240,20 +240,20 @@ description="table function header", missing_files=( ( - "functions/sql/order_lines.sql", + "sql/functions/sql/order_lines.sql", "FUNCTION (\n arguments (p_order_id INTEGER),\n" " returns table (order_id INTEGER),\n);\n\nSELECT p_order_id AS order_id\n", ), ), described_files=( ( - "functions/sql/order_lines.sql", + "sql/functions/sql/order_lines.sql", 'FUNCTION (\n description "Lines of one order",\n' " arguments (p_order_id INTEGER),\n" " returns table (order_id INTEGER),\n);\n\nSELECT p_order_id AS order_id\n", ), ), - expected_diagnostic=("P010", "functions/sql/order_lines.sql", 1), + expected_diagnostic=("P010", "sql/functions/sql/order_lines.sql", 1), expected_message="function 'order_lines' has no description", expected_help_fragments=('description "What order_lines returns"',), ), @@ -261,7 +261,7 @@ description="Python UDF described by its docstring", missing_files=( ( - "functions/python/is_large_order_py.py", + "sql/functions/python/is_large_order_py.py", "from sqlbuild.functions import udf\n\n\n" '@udf(arguments={"amount": "INTEGER"}, returns="BOOLEAN", runtime_version="3.11")\n' "def main(amount: int) -> bool:\n return amount > 100\n", @@ -269,7 +269,7 @@ ), described_files=( ( - "functions/python/is_large_order_py.py", + "sql/functions/python/is_large_order_py.py", "from sqlbuild.functions import udf\n\n\n" '@udf(arguments={"amount": "INTEGER"}, returns="BOOLEAN", runtime_version="3.11")\n' "def main(amount: int) -> bool:\n" @@ -277,10 +277,10 @@ " return amount > 100\n", ), ), - expected_diagnostic=("P010", "functions/python/is_large_order_py.py", 4), + expected_diagnostic=("P010", "sql/functions/python/is_large_order_py.py", 4), expected_message="function 'is_large_order_py' has no description", expected_help_fragments=( - "give its function in functions/python/is_large_order_py.py a docstring or add " + "give its function in sql/functions/python/is_large_order_py.py a docstring or add " "this to @udf:\n" ' @udf(description="What is_large_order_py returns", ...)', ), @@ -289,7 +289,7 @@ description="Python UDF described by its decorator", missing_files=( ( - "functions/python/is_large_order_py.py", + "sql/functions/python/is_large_order_py.py", "from sqlbuild.functions import udf\n\n\n" '@udf(arguments={"amount": "INTEGER"}, returns="BOOLEAN", runtime_version="3.11")\n' "def main(amount: int) -> bool:\n return amount > 100\n", @@ -297,7 +297,7 @@ ), described_files=( ( - "functions/python/is_large_order_py.py", + "sql/functions/python/is_large_order_py.py", "from sqlbuild.functions import udf\n\n\n" "@udf(\n" ' description="Whether an order amount is large",\n' @@ -308,27 +308,27 @@ "def main(amount: int) -> bool:\n return amount > 100\n", ), ), - expected_diagnostic=("P010", "functions/python/is_large_order_py.py", 4), + expected_diagnostic=("P010", "sql/functions/python/is_large_order_py.py", 4), expected_message="function 'is_large_order_py' has no description", expected_help_fragments=(), ), RequiredDescriptionCase( description="named SQL hook header", missing_files=( - ("hooks/sql/analyze_orders.sql", "HOOK ();\n\nSELECT 1\n"), + ("sql/hooks/sql/analyze_orders.sql", "HOOK ();\n\nSELECT 1\n"), hooked_model_file(model_name="analyzed_orders", hook='sql("analyze_orders")'), ), described_files=( ( - "hooks/sql/analyze_orders.sql", + "sql/hooks/sql/analyze_orders.sql", 'HOOK (description "What analyze_orders does");\n\nSELECT 1\n', ), hooked_model_file(model_name="analyzed_orders", hook='sql("analyze_orders")'), ), - expected_diagnostic=("P010", "hooks/sql/analyze_orders.sql", 1), + expected_diagnostic=("P010", "sql/hooks/sql/analyze_orders.sql", 1), expected_message="hook 'analyze_orders' has no description", expected_help_fragments=( - "add this to the HOOK header in hooks/sql/analyze_orders.sql:\n" + "add this to the HOOK header in sql/hooks/sql/analyze_orders.sql:\n" ' HOOK (description "What analyze_orders does");', ), ), @@ -336,14 +336,14 @@ description="Python hook", missing_files=( ( - "hooks/python/notify_orders.py", + "sql/hooks/python/notify_orders.py", python_node_source(module="hooks", decorator="hook", name="notify_orders"), ), hooked_model_file(model_name="notified_orders", hook='python("notify_orders")'), ), described_files=( ( - "hooks/python/notify_orders.py", + "sql/hooks/python/notify_orders.py", python_node_source( module="hooks", decorator="hook", @@ -353,10 +353,10 @@ ), hooked_model_file(model_name="notified_orders", hook='python("notify_orders")'), ), - expected_diagnostic=("P010", "hooks/python/notify_orders.py", 4), + expected_diagnostic=("P010", "sql/hooks/python/notify_orders.py", 4), expected_message="hook 'notify_orders' has no description", expected_help_fragments=( - "give its function in hooks/python/notify_orders.py a docstring or pass a " + "give its function in sql/hooks/python/notify_orders.py a docstring or pass a " "description to @hook:\n" ' @hook(description="What notify_orders does", ...)', ), @@ -365,13 +365,13 @@ description="loader without a source declaration", missing_files=( ( - "python/loaders/raw_returns.py", + "python/nodes/loaders/raw_returns/loader.py", python_node_source(module="loaders", decorator="loader", name="raw_returns"), ), ), described_files=( ( - "python/loaders/raw_returns.py", + "python/nodes/loaders/raw_returns/loader.py", python_node_source( module="loaders", decorator="loader", @@ -380,7 +380,7 @@ ), ), ), - expected_diagnostic=("P010", "python/loaders/raw_returns.py", 4), + expected_diagnostic=("P010", "python/nodes/loaders/raw_returns/loader.py", 4), expected_message="loader 'raw_returns' has no description", expected_help_fragments=('@loader(description="What raw_returns does", ...)',), ), @@ -388,13 +388,13 @@ description="asset", missing_files=( ( - "python/assets/order_report.py", + "python/nodes/assets/order_report/asset.py", python_node_source(module="assets", decorator="asset", name="order_report"), ), ), described_files=( ( - "python/assets/order_report.py", + "python/nodes/assets/order_report/asset.py", python_node_source( module="assets", decorator="asset", @@ -403,7 +403,7 @@ ), ), ), - expected_diagnostic=("P010", "python/assets/order_report.py", 4), + expected_diagnostic=("P010", "python/nodes/assets/order_report/asset.py", 4), expected_message="asset 'order_report' has no description", expected_help_fragments=('@asset(description="What order_report does", ...)',), ), @@ -411,7 +411,7 @@ description="check", missing_files=( ( - "python/checks/orders_present.py", + "python/nodes/checks/orders_present/checks.py", python_node_source( module="checks", decorator="check", @@ -423,7 +423,7 @@ ), described_files=( ( - "python/checks/orders_present.py", + "python/nodes/checks/orders_present/checks.py", python_node_source( module="checks", decorator="check", @@ -434,18 +434,18 @@ ), ), ), - expected_diagnostic=("P010", "python/checks/orders_present.py", 5), + expected_diagnostic=("P010", "python/nodes/checks/orders_present/checks.py", 5), expected_message="check 'orders_present' has no description", expected_help_fragments=('@check(description="What orders_present does", ...)',), ), RequiredDescriptionCase( description="provider", - missing_files=(("providers/orders_api.py", _PROVIDER_UNDESCRIBED),), - described_files=(("providers/orders_api.py", _PROVIDER_DESCRIBED),), - expected_diagnostic=("P010", "providers/orders_api.py", 4), + missing_files=(("python/providers/orders_api.py", _PROVIDER_UNDESCRIBED),), + described_files=(("python/providers/orders_api.py", _PROVIDER_DESCRIBED),), + expected_diagnostic=("P010", "python/providers/orders_api.py", 4), expected_message="provider 'orders_api' has no description", expected_help_fragments=( - "add a class docstring in providers/orders_api.py:\n" + "add a class docstring in python/providers/orders_api.py:\n" " class OrdersApi(Provider):\n" ' """What orders_api provides."""', ), @@ -462,12 +462,12 @@ _TYPED_NULL_FIXTURE_FILES: tuple[tuple[str, str], ...] = ( - ("models/up.sql", 'MODEL (description "Upstream rows");\n\nSELECT 1 AS a\n'), + ("sql/models/up.sql", 'MODEL (description "Upstream rows");\n\nSELECT 1 AS a\n'), ( - "models/marts/a_model.sql", + "sql/models/marts/a_model.sql", 'MODEL (description "Own description");\n\nSELECT a\nFROM __ref("up")\n', ), - ("models/marts/b_model.sql", _INHERITING_MODEL), + ("sql/models/marts/b_model.sql", _INHERITING_MODEL), ( "tests/unit/test_a_model.sql", 'TEST (description "Null values pass through");\n\n' @@ -479,7 +479,7 @@ _ALL_UNDESCRIBED_FILES: tuple[tuple[str, str], ...] = ( *dict(chain.from_iterable(case.missing_files for case in _CASES)).items(), - ("models/undescribed_orders.sql", "MODEL (materialized view);\n\nSELECT 1 AS id\n"), + ("sql/models/undescribed_orders.sql", "MODEL (materialized view);\n\nSELECT 1 AS id\n"), ) @@ -491,7 +491,7 @@ description="asset docstring", missing_files=( ( - "python/assets/order_report.py", + "python/nodes/assets/order_report/asset.py", python_node_source( module="assets", decorator="asset", @@ -502,7 +502,7 @@ ), described_files=( ( - "python/assets/order_report.py", + "python/nodes/assets/order_report/asset.py", python_node_source( module="assets", decorator="asset", @@ -511,7 +511,7 @@ ), ), ), - expected_diagnostic=("P027", "python/assets/order_report.py", 4), + expected_diagnostic=("P027", "python/nodes/assets/order_report/asset.py", 4), expected_message="asset 'order_report' description exceeds 10 lines", expected_help_fragments=("Shorten the description to 10 lines",), ), @@ -519,7 +519,7 @@ description="asset description argument", missing_files=( ( - "python/assets/order_report.py", + "python/nodes/assets/order_report/asset.py", python_node_source( module="assets", decorator="asset", @@ -530,7 +530,7 @@ ), described_files=( ( - "python/assets/order_report.py", + "python/nodes/assets/order_report/asset.py", python_node_source( module="assets", decorator="asset", @@ -539,7 +539,7 @@ ), ), ), - expected_diagnostic=("P027", "python/assets/order_report.py", 4), + expected_diagnostic=("P027", "python/nodes/assets/order_report/asset.py", 4), expected_message="asset 'order_report' description exceeds 10 lines", expected_help_fragments=("Shorten the description to 10 lines",), ), @@ -636,55 +636,61 @@ def test_given_every_resource_kind_undescribed_when_compiling_then_one_run_repor RequiredDescriptionExactOutputCase( description="seed and source entries located at their outermost declarations", files=( - ("models/order_summary.sql", "MODEL ();\nSELECT 1 AS order_count\n"), - ("seeds/product_types.csv", _SEED_CSV), - ("seeds/product_labels.csv", _SEED_CSV), - ("seeds/products.yml", _TWO_SEEDS_YAML), - ("sources/raw.yml", _SHADOWED_SOURCES_YAML), + ("sql/models/order_summary.sql", "MODEL ();\nSELECT 1 AS order_count\n"), + ("sql/seeds/product_types.csv", _SEED_CSV), + ("sql/seeds/product_labels.csv", _SEED_CSV), + ("sql/seeds/products.yml", _TWO_SEEDS_YAML), + ("sql/sources/raw.yml", _SHADOWED_SOURCES_YAML), ), expected_diagnostics=( ( "P010", "model 'order_summary' has no description", - "models/order_summary.sql", + "sql/models/order_summary.sql", 1, 1, ), - ("P010", "seed 'product_types' has no description", "seeds/products.yml", 2, 1), - ("P010", "seed 'product_labels' has no description", "seeds/products.yml", 8, 1), - ("P010", "source 'raw_orders' has no description", "sources/raw.yml", 2, 1), - ("P010", "source 'raw_refunds' has no description", "sources/raw.yml", 8, 1), - ("P010", "source 'raw_customers' has no description", "sources/raw.yml", 11, 1), + ("P010", "seed 'product_types' has no description", "sql/seeds/products.yml", 2, 1), + ( + "P010", + "seed 'product_labels' has no description", + "sql/seeds/products.yml", + 8, + 1, + ), + ("P010", "source 'raw_orders' has no description", "sql/sources/raw.yml", 2, 1), + ("P010", "source 'raw_refunds' has no description", "sql/sources/raw.yml", 8, 1), + ("P010", "source 'raw_customers' has no description", "sql/sources/raw.yml", 11, 1), ), expected_help=( "to describe model 'order_summary', add this to the MODEL header in " - "models/order_summary.sql:\n" + "sql/models/order_summary.sql:\n" " MODEL (\n" ' description "What one row of order_summary represents",\n' " ...\n" " );", ( - "to describe seed 'product_types', add `description` to its entry in seeds/products.yml:\n" + "to describe seed 'product_types', add `description` to its entry in sql/seeds/products.yml:\n" " - name: product_types\n" " description: What one row of product_types represents" ), ( - "to describe seed 'product_labels', add `description` to its entry in seeds/products.yml:\n" + "to describe seed 'product_labels', add `description` to its entry in sql/seeds/products.yml:\n" " - name: product_labels\n" " description: What one row of product_labels represents" ), ( - "to describe source 'raw_orders', add `description` to its entry in sources/raw.yml:\n" + "to describe source 'raw_orders', add `description` to its entry in sql/sources/raw.yml:\n" " - name: raw_orders\n" " description: What one row of raw_orders represents" ), ( - "to describe source 'raw_refunds', add `description` to its entry in sources/raw.yml:\n" + "to describe source 'raw_refunds', add `description` to its entry in sql/sources/raw.yml:\n" " - name: raw_refunds\n" " description: What one row of raw_refunds represents" ), ( - "to describe source 'raw_customers', add `description` to its entry in sources/raw.yml:\n" + "to describe source 'raw_customers', add `description` to its entry in sql/sources/raw.yml:\n" " - name: raw_customers\n" " description: What one row of raw_customers represents" ), @@ -721,7 +727,7 @@ def test_given_undescribed_yaml_entries_when_compiling_then_reports_exact_ordere model_sql="MODEL (materialized table);\n\nSELECT 1 AS order_id\n", expected_returncode=1, expected_stderr_fragment=( - "[P010] models/orders.sql:1:1: model 'orders' has no description" + "[P010] sql/models/orders.sql:1:1: model 'orders' has no description" ), ), ], @@ -735,7 +741,7 @@ def test_given_undescribed_model_when_planning_then_plan_is_blocked( project_name="orders", repo_files={ "sqlbuild_project.toml": REQUIRED_DESCRIPTIONS_PROJECT, - "models/orders.sql": test_case.model_sql, + "sql/models/orders.sql": test_case.model_sql, }, ) @@ -753,8 +759,8 @@ def test_given_undescribed_model_when_planning_then_plan_is_blocked( PathDefaultDescriptionCase( description="described model sorts before the inheriting model", model_files=( - ("models/marts/a_model.sql", _OWN_DESCRIPTION_MODEL), - ("models/marts/b_model.sql", _INHERITING_MODEL), + ("sql/models/marts/a_model.sql", _OWN_DESCRIPTION_MODEL), + ("sql/models/marts/b_model.sql", _INHERITING_MODEL), ), expected_returncode=0, expected_diagnostics=(), @@ -763,8 +769,8 @@ def test_given_undescribed_model_when_planning_then_plan_is_blocked( PathDefaultDescriptionCase( description="inheriting model sorts before the described model", model_files=( - ("models/marts/a_model.sql", _INHERITING_MODEL), - ("models/marts/b_model.sql", _OWN_DESCRIPTION_MODEL), + ("sql/models/marts/a_model.sql", _INHERITING_MODEL), + ("sql/models/marts/b_model.sql", _OWN_DESCRIPTION_MODEL), ), expected_returncode=0, expected_diagnostics=(), @@ -809,9 +815,11 @@ def test_given_path_default_description_when_compiling_then_every_model_keeps_it ), FormatDescriptionResolutionE2ECase( description="a genuinely missing description is still reported", - extra_files=(("models/bare.sql", "MODEL (materialized table);\n\nSELECT 1 AS id\n"),), + extra_files=( + ("sql/models/bare.sql", "MODEL (materialized table);\n\nSELECT 1 AS id\n"), + ), expected_returncode=1, - expected_faults=(("models/bare.sql", "description-present"),), + expected_faults=(("sql/models/bare.sql", "description-present"),), ), ], ids=lambda case: case.description, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_snowflake_star_contracts.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_snowflake_star_contracts.py index c63bdb4b81..316a4b3ca4 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_snowflake_star_contracts.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_snowflake_star_contracts.py @@ -48,10 +48,10 @@ def test_given_snowflake_star_when_compiling_lowercase_contract_then_folded_name project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": ( + "sql/models/orders.sql": ( f"MODEL (description 'Test model orders.');\nSELECT {test_case.upstream_columns}\n" ), - "models/order_rows.sql": ( + "sql/models/order_rows.sql": ( f"MODEL (description 'Test model order_rows.', {_CONTRACT});\n" 'SELECT o.* FROM __ref("orders") AS o\n' ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_source_semantic_binding.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_source_semantic_binding.py index be9fdc3e92..80833c8adf 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_source_semantic_binding.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_source_semantic_binding.py @@ -37,8 +37,8 @@ def test_given_open_source_when_planning_then_live_columns_reject_missing_refere project_name="source_binding", repo_files={ "sqlbuild_project.toml": 'name = "source_binding"\nadapter = "duckdb"\n[connection]\ndatabase = "orders.duckdb"\n', - "sources/orders.yml": "sources:\n - name: raw_orders\n description: Test source raw_orders.\n table: raw_orders\n", - "models/orders.sql": 'MODEL (description "Test model orders.", materialized table);\nSELECT missing FROM __source("raw_orders")\n', + "sql/sources/orders.yml": "sources:\n - name: raw_orders\n description: Test source raw_orders.\n table: raw_orders\n", + "sql/models/orders.sql": 'MODEL (description "Test model orders.", materialized table);\nSELECT missing FROM __source("raw_orders")\n', }, ) database: Path = project / "orders.duckdb" @@ -52,7 +52,7 @@ def test_given_open_source_when_planning_then_live_columns_reject_missing_refere ) assert planned.returncode != 0 assert f"error[{test_case.expected_code}]" in planned.stdout + planned.stderr - assert "models/orders.sql:2:" in planned.stdout + planned.stderr + assert "sql/models/orders.sql:2:" in planned.stdout + planned.stderr assert not table_exists(db_path=database, table_name="orders") @@ -77,7 +77,7 @@ def test_given_invalid_metadata_when_planning_then_no_warehouse_connection_is_op project_name="metadata_binding", repo_files={ "sqlbuild_project.toml": 'name = "metadata_binding"\nadapter = "duckdb"\n[connection]\ndatabase = "orders.duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table, unique_key [missing]);\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table, unique_key [missing]);\nSELECT 1 AS id\n", }, ) result: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_sql_macro_string_escapes.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_sql_macro_string_escapes.py index b4506dbda6..36a86c4082 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_sql_macro_string_escapes.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_sql_macro_string_escapes.py @@ -62,8 +62,8 @@ def test_given_string_with_backslash_when_compiling_sql_macro_call_then_call_exp project_name="order_notes", repo_files={ "sqlbuild_project.toml": test_case.adapter_config, - "models/_macros/sql/shout.sql": _SHOUT_MACRO, - "models/order_notes.sql": ( + "sql/models/_macros/sql/shout.sql": _SHOUT_MACRO, + "sql/models/order_notes.sql": ( 'MODEL (description "Order notes after an escaped string.");\n' f"SELECT {test_case.string_sql} AS note, @sql.shout('web') AS channel\n" ), @@ -77,7 +77,7 @@ def test_given_string_with_backslash_when_compiling_sql_macro_call_then_call_exp assert compiled.returncode == 0, compiled.stdout + compiled.stderr assert "0 errors" in compiled.stdout, compiled.stdout compiled_sql: str = ( - project_dir / "target" / "compiled" / "models" / "order_notes.sql" + project_dir / "target" / "compiled" / "sql" / "models" / "order_notes.sql" ).read_text(encoding="utf-8") assert test_case.expected_compiled_fragment in compiled_sql, compiled_sql assert test_case.string_sql in compiled_sql, compiled_sql diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_star_beside_cast_constant.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_star_beside_cast_constant.py index 497a58b1d3..5409618bc2 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_star_beside_cast_constant.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_star_beside_cast_constant.py @@ -20,7 +20,7 @@ _PROJECT_TOML: str = ( 'name = "orders"\nadapter = "duckdb"\n[connection]\ndatabase = "orders.duckdb"\n\n' - '[[rules.rule_ignores]]\nrules = ["SQLCLEAN039"]\npaths = ["models/flagged_orders.sql"]\n' + '[[rules.rule_ignores]]\nrules = ["SQLCLEAN039"]\npaths = ["sql/models/flagged_orders.sql"]\n' 'reason = "One case stars over a derived table on purpose."\n' ) _BASE_ORDERS_SQL: str = ( @@ -60,8 +60,8 @@ def test_given_star_beside_cast_constant_when_compiling_and_building_then_starre project_name="orders_project", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/base_orders.sql": _BASE_ORDERS_SQL, - "models/flagged_orders.sql": f"{_FLAGGED_ORDERS_HEADER}{test_case.query_sql}\n", + "sql/models/base_orders.sql": _BASE_ORDERS_SQL, + "sql/models/flagged_orders.sql": f"{_FLAGGED_ORDERS_HEADER}{test_case.query_sql}\n", }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_truth_value_tests.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_truth_value_tests.py index eff30c8b79..9c51e341b7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_truth_value_tests.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_truth_value_tests.py @@ -35,8 +35,8 @@ " database: example_db\n schema: raw\n table: orders\n", " expression: SELECT 'o1' AS order_id, NULL::BOOLEAN AS is_test_order\n", ) -_MODEL_PATH: str = "models/real_orders.sql" -_AUDIT_PATH: str = "audits/generic/test_orders_are_flagged.sql" +_MODEL_PATH: str = "sql/models/real_orders.sql" +_AUDIT_PATH: str = "sql/audits/generic/test_orders_are_flagged.sql" _TEST_PATH: str = "tests/unit/test_real_orders.sql" _MODEL: str = ( "MODEL (\n" @@ -82,7 +82,7 @@ description="snowflake rejects truth-value tests in models, audits and SQL tests", repo_files={ "sqlbuild_project.toml": _SNOWFLAKE_PROJECT, - "sources/raw.yml": _SOURCES, + "sql/sources/raw.yml": _SOURCES, _MODEL_PATH: _MODEL, _AUDIT_PATH: _AUDIT, _TEST_PATH: _SQL_TEST, @@ -120,7 +120,7 @@ description="duckdb accepts truth-value tests", repo_files={ "sqlbuild_project.toml": _DUCKDB_PROJECT, - "sources/raw.yml": _DUCKDB_SOURCES, + "sql/sources/raw.yml": _DUCKDB_SOURCES, _MODEL_PATH: _DUCKDB_MODEL, _AUDIT_PATH: _AUDIT, _TEST_PATH: _SQL_TEST, @@ -162,7 +162,7 @@ def test_given_truth_value_test_when_compiling_then_dialect_support_is_enforced( description="duckdb builds, audits and tests truth-value tests", repo_files={ "sqlbuild_project.toml": _DUCKDB_PROJECT, - "sources/raw.yml": _DUCKDB_SOURCES, + "sql/sources/raw.yml": _DUCKDB_SOURCES, _MODEL_PATH: _DUCKDB_MODEL, _AUDIT_PATH: _AUDIT, _TEST_PATH: _SQL_TEST, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_type_finding_locations.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_type_finding_locations.py index 139daa794c..754ca1fb68 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_type_finding_locations.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_type_finding_locations.py @@ -64,7 +64,7 @@ def test_given_type_findings_without_native_spans_when_compiling_then_each_is_lo project_name="orders", repo_files={ "sqlbuild_project.toml": f'name = "orders"\nadapter = "{test_case.adapter}"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Order epochs", database warehouse, schema analytics);\n\n' + test_case.query_sql ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_undecodable_selector.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_undecodable_selector.py index b874832853..07e4e550be 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_undecodable_selector.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_undecodable_selector.py @@ -42,7 +42,7 @@ def test_given_undecodable_selector_when_compiling_then_unknown_selector_error_i project_name="selectors", repo_files={ "sqlbuild_project.toml": 'name = "selectors"\nadapter = "duckdb"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized view);\n\n" "SELECT 1 AS order_id\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_unknown_config_keys.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_unknown_config_keys.py index dbfbf41d12..3120dfe9e1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_unknown_config_keys.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_unknown_config_keys.py @@ -22,15 +22,15 @@ description="misspelled MODEL key", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS order_id\n", - "models/fct_orders.sql": ( + "sql/models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS order_id\n", + "sql/models/fct_orders.sql": ( 'MODEL (description "Test model fct_orders.",\n materialized table,\n descripton "Orders fact.",\n);\n\n' 'SELECT order_id FROM __ref("stg_orders")\n' ), }, expected_fragments=( "error[D002]", - "models/fct_orders.sql:3' has unsupported keys: descripton", + "sql/models/fct_orders.sql:3' has unsupported keys: descripton", "did you mean 'description'?", ), ), @@ -40,7 +40,7 @@ "sqlbuild_project.toml": ( _PROJECT_TOML + '\n[path_defaults.staging]\nmaterialised = "view"\n' ), - "models/staging/stg_orders.sql": "MODEL (description 'Test model stg_orders.');\n\nSELECT 1 AS order_id\n", + "sql/models/staging/stg_orders.sql": "MODEL (description 'Test model stg_orders.');\n\nSELECT 1 AS order_id\n", }, expected_fragments=( "error[D001]", @@ -52,11 +52,11 @@ description="misspelled source column key", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n expression: SELECT 1 AS order_id\n" " columns:\n - name: order_id\n tpye: INTEGER\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( 'MODEL (description "Test model stg_orders.");\n\nSELECT order_id FROM __source("raw_orders")\n' ), }, @@ -70,7 +70,7 @@ description="unknown on_schema_change in MODEL header", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/fct_orders.sql": ( + "sql/models/fct_orders.sql": ( "MODEL (description 'Test model fct_orders.',\n materialized incremental,\n incremental_strategy append,\n" " on_schema_change append_columns,\n);\n\nSELECT 1 AS order_id\n" ), @@ -88,7 +88,7 @@ "sqlbuild_project.toml": ( _PROJECT_TOML + '\n[defaults]\nreplay_on_change = "everything"\n' ), - "models/fct_orders.sql": ( + "sql/models/fct_orders.sql": ( "MODEL (description 'Test model fct_orders.', materialized incremental, incremental_strategy append);\n\n" "SELECT 1 AS order_id\n" ), @@ -126,13 +126,13 @@ def test_given_unknown_model_config_key_when_compiling_then_fails_naming_key_and description="custom materialization values live under config", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "materializations/order_snapshot.py": ( + "python/materializations/order_snapshot.py": ( "from sqlbuild.executor.custom.models import (\n" " MaterializationContext,\n MaterializationResult,\n)\n\n\n" "def materialize(ctx: MaterializationContext) -> MaterializationResult:\n" " return MaterializationResult(success=True)\n" ), - "models/order_snapshot.sql": ( + "sql/models/order_snapshot.sql": ( "MODEL (description 'Test model order_snapshot.',\n materialized order_snapshot,\n" " config (retention_days 7, partition_column order_id),\n);\n\n" "SELECT 1 AS order_id\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_varied_compile_cache_performance.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_varied_compile_cache_performance.py index 81b1e6cad2..5a8c13c6f6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_varied_compile_cache_performance.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_varied_compile_cache_performance.py @@ -44,10 +44,10 @@ 150, 250, ( - "14849200e2eb5aab0383d7df9d87e3467d821367f7e014d477ee2a39c2820c92", - "84711dadecdeaa909a80bfc75a725ea398e216c495dc38e259a8611f1740e024", - "75e0e244bc74e0e6a5301e594c125cf4b23bacb885058509dc36b06a3292d989", - "4ebfd8ecc67b9d66196d0c79602dcac8660d699821d25ab615fe5e3d00f1c022", + "2e35992518da03ca943baae8d91f1546df37bb58d8ff527a2a4f2bc0bbf30bdc", + "9a75faa84eaa230ec4ef86bf2a653187ba326ea269c1a9f7fdaaefb2bbf9e0c6", + "2832eea0b057413118eed3cd322a6c5e55553d1075d73fc9ba89451d9790884f", + "b05de2bfbfa67f97624731bc7b906ebf0519814f51e05ae9bfa2c2f849f99eee", ), ), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/databricks/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/databricks/helpers.py index e5de4a552f..d55b5aafd6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/databricks/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/databricks/helpers.py @@ -268,7 +268,7 @@ def prepare_databricks_diff_project(*, tmp_path: Path) -> tuple[Path, str, str]: build_databricks_local_config(schema_name=dev_schema), encoding="utf-8", ) - models_dir: Path = project_dir / "models" / "staging" + models_dir: Path = project_dir / "sql" / "models" / "staging" models_dir.mkdir(parents=True, exist_ok=True) (models_dir / "stg_orders.sql").write_text( "MODEL (description 'Test model stg_orders.', " diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/databricks/test_databricks.py b/tests/e2e/src/sqlbuild/cli/commands/main/databricks/test_databricks.py index 8c0a6f278f..8b9a4f9c44 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/databricks/test_databricks.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/databricks/test_databricks.py @@ -66,6 +66,7 @@ build_databricks_connection_config, build_unique_schema_name, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.dbt @@ -162,15 +163,15 @@ def test_given_python_result_when_running_check_on_databricks_then_persists_node project_name="databricks_node_results", schema_name=schema_name, ), - "python/tasks/results.py": ( + "python/nodes/tasks/results/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_result(ctx):\n" " '''Test task produce_result.'''\n return ctx.result(payload={'value': 42}, metadata={'source': 'databricks'})\n" ), - "python/checks/results.py": ( + "python/nodes/checks/results/checks.py": ( "from sqlbuild.checks import check\n" - "from python.tasks.results import produce_result\n\n" + "from python.nodes.tasks.results.asset import produce_result\n\n" "@check(depends_on=produce_result)\n" "def check_produce_result(ctx):\n" " '''Test check check_produce_result.'''\n return ctx.result_of(node_function=produce_result).payload['value'] == 42\n" @@ -246,14 +247,14 @@ def test_given_physical_source_without_freshness_when_running_on_databricks_then project_name="databricks_freshness_metadata", schema_name=schema_name, ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" f" database: {catalog_name}\n" f" schema: {schema_name}\n" " table: raw_orders\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __source("raw_orders")\n' ), }, @@ -404,7 +405,9 @@ def test_given_intermediate_strategy_project_when_loading_twice_on_databricks_th " - name: amount\n" " type: INTEGER\n" ), - loader_py=test_case.loader_py, + node_files={ + **node_module_files("python/nodes/loaders/source_rows.py", test_case.loader_py) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -570,16 +573,16 @@ def test_given_existing_snapshot_targets_when_building_on_databricks_then_apply_ ) assert initial_result.returncode == 0, initial_result.stdout + initial_result.stderr - (project_dir / "models" / "current_check_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_check_customers.sql").write_text( build_current_check_customers_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "current_delete_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_delete_customers.sql").write_text( build_current_delete_customers_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "historical_timestamp_extracts.sql").write_text( + (project_dir / "sql" / "models" / "historical_timestamp_extracts.sql").write_text( build_historical_timestamp_extracts_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "historical_check_daily.sql").write_text( + (project_dir / "sql" / "models" / "historical_check_daily.sql").write_text( build_historical_check_daily_model_sql(changed=True), encoding="utf-8" ) @@ -821,7 +824,7 @@ def test_given_snapshot_project_when_building_on_databricks_then_scd2_history_is expected_historical_check_rows=test_case.expected_historical_check_rows, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="blocked", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -846,7 +849,7 @@ def test_given_snapshot_project_when_building_on_databricks_then_scd2_history_is expected_rows=test_case.expected_current_rows_after_initial_build, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="pro", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -1389,7 +1392,7 @@ def test_given_databricks_invalid_model_when_building_then_underlying_error_is_p project_dir: Path schema_name: str project_dir, schema_name = prepare_databricks_waffle_shop(tmp_path=tmp_path) - broken_model: Path = project_dir / "models" / "marts" / "databricks_broken_model.sql" + broken_model: Path = project_dir / "sql" / "models" / "marts" / "databricks_broken_model.sql" broken_model.write_text( "MODEL (description 'Test model databricks_broken_model.', materialized table);\n\nSELECT missing_column FROM (SELECT 1 AS id)", encoding="utf-8", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/helpers.py index 762d53e2ff..c83b96ed27 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/helpers.py @@ -139,12 +139,12 @@ def write_sqlbuild_defer_target_models(*, project_dir: Path) -> None: + 'schema = "prod"\n', encoding="utf-8", ) - project_dir.joinpath("models", "deferred_upstream.sql").write_text( + project_dir.joinpath("sql", "models", "deferred_upstream.sql").write_text( "MODEL (description 'Test model deferred_upstream.', " "materialized table);\n\nSELECT 42 AS order_id\n", encoding="utf-8", ) - project_dir.joinpath("models", "deferred_consumer.sql").write_text( + project_dir.joinpath("sql", "models", "deferred_consumer.sql").write_text( 'MODEL (description "Test model deferred_consumer.", ' 'materialized table);\n\nSELECT order_id FROM __ref("deferred_upstream")\n', encoding="utf-8", @@ -162,7 +162,7 @@ def declare_missing_origin_requiring_confirmation(*, project_dir: Path) -> None: + '\n[targets.main]\nschema = "main"\nmissing_migration_origin = "require_confirmation"\n', encoding="utf-8", ) - model_path: Path = project_dir / "models" / "local_only.sql" + model_path: Path = project_dir / "sql" / "models" / "local_only.sql" model_path.write_text( model_path.read_text(encoding="utf-8").replace( "MODEL (\n", "MODEL (\n materialized table,\n migrate_from retired_local_orders,\n", 1 @@ -254,7 +254,7 @@ def write_sqlbuild_order_status_snapshot(*, project_dir: Path) -> None: + '\n[snapshots]\ncurrent_state_full_refresh = "require_confirmation"\n', encoding="utf-8", ) - project_dir.joinpath("models", "order_status_history.sql").write_text( + project_dir.joinpath("sql", "models", "order_status_history.sql").write_text( "MODEL (description 'Test model order_status_history.'," "\n materialized snapshot,\n unique_key [order_id],\n" " snapshot_strategy check,\n check_columns [status],\n);\n\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_execute.py b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_execute.py index ed4273cb4f..ca0c1d5fb5 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_execute.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_execute.py @@ -259,7 +259,7 @@ "dbt", "build", "--select", - "+path:models/marts", + "+path:sql/models/marts", "--exclude", "deprecated_orders", "mart_orders", @@ -449,7 +449,7 @@ def test_given_native_defer_to_when_running_dbt_interop_then_reads_deferred_targ "dbt", "build", "--select", - "+path:models/marts", + "+path:sql/models/marts", "--exclude", "deprecated_orders", "mart_orders", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_init.py b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_init.py index 9999bfdeaa..464409b3bc 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_init.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_init.py @@ -127,8 +127,8 @@ def test_given_duckdb_dbt_project_when_running_dbt_init_then_generated_project_b for fragment in test_case.unexpected_toml_fragments: assert fragment not in generated_toml - (sqlbuild_project_dir / "models").mkdir() - (sqlbuild_project_dir / "models" / "local_profile_orders.sql").write_text( + (sqlbuild_project_dir / "sql" / "models").mkdir(parents=True) + (sqlbuild_project_dir / "sql" / "models" / "local_profile_orders.sql").write_text( "MODEL (description 'Test model local_profile_orders.', materialized table);\n\nSELECT 2 AS order_id\n", encoding="utf-8", ) @@ -145,7 +145,7 @@ def test_given_duckdb_dbt_project_when_running_dbt_init_then_generated_project_b sql="SELECT order_id FROM main.local_profile_orders ORDER BY order_id", ) == [(2,)] - (sqlbuild_project_dir / "models" / "downstream_orders.sql").write_text( + (sqlbuild_project_dir / "sql" / "models" / "downstream_orders.sql").write_text( "MODEL (description 'Test model downstream_orders.', materialized table);\n\n" 'SELECT order_id FROM __dbt_ref("analytics", "dbt_orders")\n', encoding="utf-8", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_plan.py b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_plan.py index 729c2b6b7b..f5b8f1c89d 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_plan.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_plan.py @@ -48,7 +48,7 @@ ), DbtPlanCliTestCase( description="routes explicit model path for SQLBuild model paths", - command=("dbt", "plan", "--json", "--select", "path:models/marts"), + command=("dbt", "plan", "--json", "--select", "path:sql/models/marts"), expected_selected_models=( "deprecated_orders", "downstream_orders", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_plan_safety.py b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_plan_safety.py index 7d68725aa6..b121f868dc 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_plan_safety.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/dbt/test_plan_safety.py @@ -45,7 +45,7 @@ def test_given_target_model_limit_when_running_dbt_interop_then_refuses_sqlbuild project_dir=project_dir, target_settings="\n[targets.main.execution_limits]\nmax_models = 1\n", ) - project_dir.joinpath("models", "local_order_ids.sql").write_text( + project_dir.joinpath("sql", "models", "local_order_ids.sql").write_text( "MODEL (description 'Test model local_order_ids.', materialized table);\n\nSELECT 11 AS order_id\n", encoding="utf-8", ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/debug/test_debug.py b/tests/e2e/src/sqlbuild/cli/commands/main/debug/test_debug.py index 8def6304be..db437077f6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/debug/test_debug.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/debug/test_debug.py @@ -16,6 +16,7 @@ prepare_inline_project, run_sqb, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -334,7 +335,7 @@ def test_given_debug_command_with_providers_when_running_then_outputs_provider_s 'name = "debug_provider_project"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "debug_provider.duckdb"\n' ), - "providers/marker.py": dedent( + "python/providers/marker.py": dedent( """ from sqlbuild.providers import Provider @@ -388,7 +389,7 @@ def test_given_debug_json_with_providers_when_running_then_outputs_provider_summ 'name = "debug_provider_json_project"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "debug_provider_json.duckdb"\n' ), - "providers/marker.py": dedent( + "python/providers/marker.py": dedent( """ from sqlbuild.providers import Provider @@ -481,7 +482,7 @@ def test_given_broken_project_nodes_when_debugging_then_only_configuration_and_p 'name = "debug_broken_project"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "debug_broken.duckdb"\n' ), - "providers/marker.py": dedent( + "python/providers/marker.py": dedent( """ from sqlbuild.providers import Provider @@ -492,16 +493,19 @@ class MarkerProvider(Provider): """ ).strip() + "\n", - "models/orders.sql": "MODEL (materialized table; SELECT FROM WHERE\n", - "python/customers.py": dedent( - """ + "sql/models/orders.sql": "MODEL (materialized table; SELECT FROM WHERE\n", + **node_module_files( + "python/nodes/customers.py", + dedent( + """ from pathlib import Path Path(__file__).with_name("imported.marker").write_text("imported") raise AssertionError("debug must not import project nodes") """ - ).strip() - + "\n", + ).strip() + + "\n", + ), }, ) @@ -513,4 +517,4 @@ class MarkerProvider(Provider): assert result.returncode == test_case.expected_returncode, result.stderr assert "Providers:\n providers: 1 of 1 ready [OK secrets set]\n" in result.stdout assert test_case.expected_stdout_fragment in result.stdout - assert not (project_dir / "python/imported.marker").exists() + assert not (project_dir / "python/nodes/imported.marker").exists() diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/diff/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/diff/helpers.py index 9d54225c5c..e143eb395e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/diff/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/diff/helpers.py @@ -46,7 +46,7 @@ def prepare_diff_project(tmp_path: Path) -> Path: """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -60,7 +60,7 @@ def prepare_diff_project(tmp_path: Path) -> Path: """ ).strip() + "\n", - "models/staging/stg_orders.sql": dedent( + "sql/models/staging/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized view); @@ -74,7 +74,7 @@ def prepare_diff_project(tmp_path: Path) -> Path: """ ).strip() + "\n", - "models/intermediate/orders_snapshot.sql": dedent( + "sql/models/intermediate/orders_snapshot.sql": dedent( """ MODEL (description "Test model orders_snapshot.", materialized table, @@ -101,7 +101,7 @@ def prepare_diff_project(tmp_path: Path) -> Path: """ ).strip() + "\n", - "models/intermediate/customer_totals.sql": dedent( + "sql/models/intermediate/customer_totals.sql": dedent( """ MODEL (description "Test model customer_totals.", materialized table, @@ -117,7 +117,7 @@ def prepare_diff_project(tmp_path: Path) -> Path: """ ).strip() + "\n", - "models/intermediate/orders_sparse.sql": dedent( + "sql/models/intermediate/orders_sparse.sql": dedent( """ MODEL (description "Test model orders_sparse.", materialized table, @@ -132,7 +132,7 @@ def prepare_diff_project(tmp_path: Path) -> Path: """ ).strip() + "\n", - "models/marts/daily_revenue.sql": dedent( + "sql/models/marts/daily_revenue.sql": dedent( """ MODEL (description "Test model daily_revenue.", materialized table); diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/diff/test_diff.py b/tests/e2e/src/sqlbuild/cli/commands/main/diff/test_diff.py index 3e0e6b856f..8438494b0e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/diff/test_diff.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/diff/test_diff.py @@ -1130,7 +1130,7 @@ def test_given_unimportable_project_extension_when_running_raw_query_diff_then_i ) -> None: project_dir: Path = prepare_diff_project(tmp_path) build_both_environments(project_dir=project_dir) - sink_path: Path = project_dir / "sinks" / "broken_sink.py" + sink_path: Path = project_dir / "python" / "event_sinks" / "broken_sink.py" sink_path.parent.mkdir(parents=True, exist_ok=True) sink_path.write_text("import package_that_is_not_installed\n", encoding="utf-8") @@ -1247,7 +1247,7 @@ def test_given_layered_sampling_config_when_diffing_then_model_and_cli_precedenc f"row_diff_sample_seed = {test_case.path_seed}\n" ) project_config_path.write_text(project_config, encoding="utf-8") - model_path: Path = project_dir / "models/intermediate/orders_snapshot.sql" + model_path: Path = project_dir / "sql/models/intermediate/orders_snapshot.sql" model_sql: str = model_path.read_text(encoding="utf-8") model_sql = model_sql.replace( " cursor_type timestamp,", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/format/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/format/helpers.py index a456988544..7b09df2557 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/format/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/format/helpers.py @@ -21,14 +21,14 @@ def write_format_performance_project( ) -> None: """Write a deterministic contract-heavy project with unique SQL test fixtures.""" - project_dir.mkdir() + project_dir.mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "format_guard"\nadapter = "duckdb"\n[defaults]\ncontract = "enforced"\n', encoding="utf-8", ) - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" tests_dir: Path = project_dir / "tests" / "unit" / "orders" - models_dir.mkdir() + models_dir.mkdir(parents=True) tests_dir.mkdir(parents=True) for model_index in range(model_count): models_dir.joinpath(f"orders_{model_index:05d}.sql").write_text( @@ -145,7 +145,7 @@ def write_mixed_format_project(*, project_dir: Path, model_count: int) -> None: """Unformatted models plus files that fault, use CRLF line endings or carry a directive.""" write_model_format_project(project_dir=project_dir, model_count=model_count) - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" path: Path for path in sorted(models_dir.glob("*.sql")): _ = path.write_text( @@ -177,7 +177,7 @@ def model_tree(*, project_dir: Path) -> dict[str, bytes]: return { str(path.relative_to(project_dir)): path.read_bytes() - for path in sorted((project_dir / "models").rglob("*.sql")) + for path in sorted((project_dir / "sql" / "models").rglob("*.sql")) } diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/format/test_description_layout.py b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_description_layout.py index 7a56152225..5042a7b812 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/format/test_description_layout.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_description_layout.py @@ -152,7 +152,7 @@ def test_given_model_description_when_formatting_then_layout_is_canonical_and_te project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "models/customers.sql": test_case.header + _BODY, + "sql/models/customers.sql": test_case.header + _BODY, }, ) before: dict[str, str] = stored_descriptions(project_dir) @@ -168,7 +168,7 @@ def test_given_model_description_when_formatting_then_layout_is_canonical_and_te assert formatted.returncode == 0, formatted.stdout + formatted.stderr assert checked.returncode == 0, checked.stdout + checked.stderr assert ", 0 changed)" in checked.stderr - model: str = (project_dir / "models/customers.sql").read_text() + model: str = (project_dir / "sql/models/customers.sql").read_text() assert model == test_case.expected_header + _BODY assert stored_descriptions(project_dir) == before assert stored_column_descriptions(project_dir) == columns_before @@ -180,11 +180,11 @@ def test_given_model_description_when_formatting_then_layout_is_canonical_and_te QuoteFixTestCase( description="model_and_wrapped_macro_descriptions", files={ - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (\n description "Matches a title (\\"Miss\\").",\n);\n' "\nSELECT @sql.title('Miss') AS title\n" ), - "macros/sql/title.sql": ( + "sql/macros/sql/title.sql": ( "MACRO (\n" " description \"True when a name starts with a woman's title: Mme, Mlle, " "Miss, Mrs, Ms. Any case,\n" @@ -197,10 +197,10 @@ def test_given_model_description_when_formatting_then_layout_is_canonical_and_te ("description-quotes", "title.sql", 2, "applied"), ], expected_starts={ - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (\n description """Matches a title ("Miss").""",\n);\n' ), - "macros/sql/title.sql": ( + "sql/macros/sql/title.sql": ( "MACRO (\n" ' description """\n' " True when a name starts with a woman's title: Mme, Mlle, Miss, Mrs, Ms. " @@ -214,11 +214,11 @@ def test_given_model_description_when_formatting_then_layout_is_canonical_and_te QuoteFixTestCase( description="model_and_macro_descriptions_doubling_quotes", files={ - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (\n description "say ""hi"" now",\n);\n' "\nSELECT @sql.title('Miss') AS title\n" ), - "macros/sql/title.sql": ( + "sql/macros/sql/title.sql": ( 'MACRO (\n description "say ""hi"" now",\n' " arguments (value VARCHAR),\n returns VARCHAR,\n);\n\n@value\n" ), @@ -228,8 +228,8 @@ def test_given_model_description_when_formatting_then_layout_is_canonical_and_te ("description-quotes", "title.sql", 2, "applied"), ], expected_starts={ - "models/customers.sql": 'MODEL (\n description """say "hi" now""",\n);\n', - "macros/sql/title.sql": 'MACRO (\n description """say "hi" now""",\n', + "sql/models/customers.sql": 'MODEL (\n description """say "hi" now""",\n);\n', + "sql/macros/sql/title.sql": 'MACRO (\n description """say "hi" now""",\n', }, expected_description='say "hi" now', ), @@ -309,8 +309,8 @@ def test_given_macro_description_when_formatting_then_its_text_survives_and_it_c project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "macros/sql/lowered.sql": test_case.macro, - "models/customers.sql": ( + "sql/macros/sql/lowered.sql": test_case.macro, + "sql/models/customers.sql": ( "MODEL (description \"Customers.\");\n\nSELECT @sql.lowered('Miss') AS title\n" ), }, @@ -324,7 +324,7 @@ def test_given_macro_description_when_formatting_then_its_text_survives_and_it_c ) assert formatted.returncode == 0, formatted.stdout + formatted.stderr - assert (project_dir / "macros/sql/lowered.sql").read_text() == test_case.expected_macro + assert (project_dir / "sql/macros/sql/lowered.sql").read_text() == test_case.expected_macro assert compiled.returncode == 0, compiled.stdout + compiled.stderr @@ -333,7 +333,7 @@ def test_given_macro_description_when_formatting_then_its_text_survives_and_it_c [ RefusedQuoteFixTestCase( description="macro_with_another_header_error", - path="macros/sql/title.sql", + path="sql/macros/sql/title.sql", contents=( 'MACRO (\n description "say \\"hi\\"",\n arguments (value VARCHAR),\n' " returns VARCHAR,\n unknown_key x,\n);\n\n@value\n" @@ -342,7 +342,7 @@ def test_given_macro_description_when_formatting_then_its_text_survives_and_it_c ), RefusedQuoteFixTestCase( description="model_with_another_header_error", - path="models/orders.sql", + path="sql/models/orders.sql", contents=( 'MODEL (\n description "say \\"hi\\"",\n tags ["a" "b",\n);\n' "\nSELECT 1 AS order_id\n" @@ -361,7 +361,7 @@ def test_given_file_still_broken_after_quote_fix_when_format_fix_then_it_is_left repo_files={ "sqlbuild_project.toml": _PROJECT_FILE, test_case.path: test_case.contents, - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (\n description "Matches \\"Miss\\".",\n);\n\nSELECT 1 AS customer_id\n' ), }, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_cache.py b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_cache.py index e9f6a094b1..d8f80f07db 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_cache.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_format_cache.py @@ -99,7 +99,7 @@ def test_given_formatted_project_when_checking_warm_edited_and_damaged_then_resu cold: subprocess.CompletedProcess[str] = run_sqb(project_dir=project_dir, command=check) stored: bytes = store.read_bytes() warm: subprocess.CompletedProcess[str] = run_sqb(project_dir=project_dir, command=check) - _ = (project_dir / "models" / test_case.edited_model).write_text( + _ = (project_dir / "sql" / "models" / test_case.edited_model).write_text( FORMAT_CACHE_UNFORMATTED_ORDERS, encoding="utf-8" ) edited: subprocess.CompletedProcess[str] = run_sqb(project_dir=project_dir, command=check) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/format/test_rule_fixes.py b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_rule_fixes.py index b4da626db9..49754d7ed3 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/format/test_rule_fixes.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_rule_fixes.py @@ -56,8 +56,8 @@ def test_given_rule_fixes_when_running_cli_then_reports_verified_or_refused_chan test_case: RuleFixTestCase, tmp_path: Path ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text(test_case.sql) (model.parent / "customers.sql").write_text( 'MODEL (description "Test model customers."); SELECT 1 AS customer_id' @@ -100,8 +100,8 @@ def test_given_wide_or_deep_unused_ctes_when_fixing_then_work_is_bounded( test_case: RuleFixPerformanceTestCase, tmp_path: Path ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) columns: str = ", ".join(f"{index} AS item_{index}" for index in range(test_case.width)) ctes: list[str] = [f"items_0 AS (SELECT {columns})"] for index in range(1, test_case.depth): diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/format/test_token_preservation.py b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_token_preservation.py index 46c1b88268..36554d176c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/format/test_token_preservation.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/format/test_token_preservation.py @@ -57,8 +57,8 @@ def test_given_case_sensitive_tokens_when_formatting_then_cli_writes_them_exactl test_case: TokenPreservationFormatTestCase, tmp_path: Path ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(test_case.project_toml, encoding="utf-8") - model: Path = tmp_path / "models" / f"{test_case.model_name}.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / f"{test_case.model_name}.sql" + model.parent.mkdir(parents=True) model.write_text(test_case.authored_sql, encoding="utf-8") formatted: subprocess.CompletedProcess[str] = run_sqb( @@ -100,8 +100,8 @@ def test_given_case_and_line_sensitive_tokens_when_formatting_then_build_keeps_t test_case: TokenPreservationBuildTestCase, tmp_path: Path ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_DUCKDB_PROJECT_TOML, encoding="utf-8") - model: Path = tmp_path / "models" / "order_lines.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "order_lines.sql" + model.parent.mkdir(parents=True) model.write_text(test_case.authored_sql, encoding="utf-8") formatted: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/freshness/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/freshness/helpers.py index 66db7920be..1edfacf77c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/freshness/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/freshness/helpers.py @@ -20,12 +20,12 @@ def prepare_freshness_project( "[connection]\n" 'database = "warehouse.duckdb"\n' ), - "sources/raw.yml": freshness_sources_yml( + "sql/sources/raw.yml": freshness_sources_yml( raw_orders_freshness=raw_orders_freshness, include_error_source=include_error_source, include_managed_source=include_managed_source, ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", ' 'materialized table);\n\nSELECT * FROM __source("raw_orders")\n' ), @@ -34,7 +34,7 @@ def prepare_freshness_project( { False: {}, True: { - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_managed(ctx):\n" @@ -61,12 +61,12 @@ def prepare_multi_schema_freshness_project(*, tmp_path: Path) -> Path: "[connection]\n" 'database = "warehouse.duckdb"\n' ), - "sources/raw.yml": freshness_sources_yml(include_error_source=False), - "models/dev_orders.sql": ( + "sql/sources/raw.yml": freshness_sources_yml(include_error_source=False), + "sql/models/dev_orders.sql": ( 'MODEL (description "Test model dev_orders.", ' 'materialized table, schema dev);\n\nSELECT * FROM __source("raw_orders")\n' ), - "models/mart_orders.sql": ( + "sql/models/mart_orders.sql": ( 'MODEL (description "Test model mart_orders.", ' 'materialized table, schema mart);\n\nSELECT * FROM __source("raw_orders")\n' ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/freshness/test_freshness.py b/tests/e2e/src/sqlbuild/cli/commands/main/freshness/test_freshness.py index 476a79a4f9..802d9a7763 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/freshness/test_freshness.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/freshness/test_freshness.py @@ -360,7 +360,7 @@ def test_given_timestamp_freshness_beyond_tolerance_when_state_then_returns_nonz ), ) persist_direct_source_freshness(project_dir=project_dir) - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources" / "raw.yml").write_text( freshness_sources_yml( raw_orders_freshness=( " freshness:\n" @@ -423,7 +423,7 @@ def test_given_timestamp_freshness_moves_backwards_when_state_then_returns_nonze ), ) persist_direct_source_freshness(project_dir=project_dir) - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources" / "raw.yml").write_text( freshness_sources_yml( raw_orders_freshness=( " freshness:\n" @@ -554,7 +554,7 @@ def test_given_changed_source_freshness_when_running_state_fail_on_stale_then_re ) -> None: project_dir: Path = prepare_freshness_project(tmp_path=tmp_path, include_error_source=False) persist_direct_source_freshness(project_dir=project_dir) - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources" / "raw.yml").write_text( freshness_sources_yml( raw_orders_query="SELECT 2 AS data_version", include_error_source=False, @@ -631,7 +631,7 @@ def test_given_timestamp_freshness_within_tolerance_when_running_state_then_repo ), ) persist_direct_source_freshness(project_dir=project_dir) - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources" / "raw.yml").write_text( freshness_sources_yml( raw_orders_freshness=( " freshness:\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/init/test_init.py b/tests/e2e/src/sqlbuild/cli/commands/main/init/test_init.py index e394ac9922..f635b566ee 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/init/test_init.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/init/test_init.py @@ -24,22 +24,22 @@ "sqlbuild_project.toml", ".gitignore", "python", - "python/.gitkeep", - "hooks/sql", - "hooks/sql/.gitkeep", - "hooks/python", - "hooks/python/.gitkeep", - "audits/generic", - "audits/generic/.gitkeep", - "audits/singular", - "audits/singular/.gitkeep", + "python/nodes/.gitkeep", + "sql/hooks/sql", + "sql/hooks/sql/.gitkeep", + "sql/hooks/python", + "sql/hooks/python/.gitkeep", + "sql/audits/generic", + "sql/audits/generic/.gitkeep", + "sql/audits/singular", + "sql/audits/singular/.gitkeep", ), expected_output_fragments=( "SQLBuild project created", - "Add Python loaders, assets, checks, and factories to python/", - "Add SQL hooks to hooks/sql/, Python hooks to hooks/python/", - "reusable audits to audits/generic/", - "standalone audits to audits/singular/", + "Add Python loaders, assets, checks, and factories to python/nodes/", + "Add SQL hooks to sql/hooks/sql/, Python hooks to sql/hooks/python/", + "reusable audits to sql/audits/generic/", + "standalone audits to sql/audits/singular/", ), ) ], @@ -50,7 +50,7 @@ def test_given_empty_project_directory_when_running_init_then_typed_resource_dir tmp_path: Path, ) -> None: project_dir: Path = tmp_path / "init_hooks_project" - project_dir.mkdir() + project_dir.mkdir(parents=True) result: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "init"), @@ -71,19 +71,19 @@ def test_given_empty_project_directory_when_running_init_then_typed_resource_dir InitPythonRootE2ETestCase( description="initialized project builds Python nodes and helpers under python", project_files={ - "models/marts/fact_orders.sql": ( + "sql/models/marts/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.', materialized table);\n\nSELECT 1 AS order_id\n" ), - "python/_helpers.py": "def order_count(rows):\n return len(rows)\n", - "python/tasks/orders.py": ( - "from python._helpers import order_count\n" + "python/nodes/_helpers.py": "def order_count(rows):\n return len(rows)\n", + "python/nodes/tasks/orders/asset.py": ( + "from python.nodes._helpers import order_count\n" "from sqlbuild.assets import asset\n\n\n" "@asset\n" "def count_orders(ctx):\n" " '''Test task count_orders.'''\n return ctx.result(payload={'order_count': order_count([1, 2])})\n" ), - "python/assets/orders_export.py": ( - "from python.tasks.orders import count_orders\n" + "python/nodes/assets/orders_export/asset.py": ( + "from python.nodes.tasks.orders.asset import count_orders\n" "from sqlbuild.assets import asset\n" "from sqlbuild.refs import model\n\n\n" "@asset(depends_on=(model('fact_orders'), count_orders))\n" @@ -107,7 +107,7 @@ def test_given_initialized_project_with_python_root_nodes_when_building_then_nod tmp_path: Path, ) -> None: project_dir: Path = tmp_path / "init_python_root_project" - project_dir.mkdir() + project_dir.mkdir(parents=True) init_result: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "init"), project_dir=project_dir, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/janitor/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/janitor/helpers.py index bba3549902..218c4d4aa6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/janitor/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/janitor/helpers.py @@ -63,7 +63,7 @@ def prepare_janitor_project( project_name=project_name, repo_files={ "sqlbuild_project.toml": project_config, - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders."); @@ -272,6 +272,14 @@ def create_direct_state_history(*, db_path: Path, schema: str = "main") -> None: connection.close() +def janitor_files(project_dir: Path) -> Path: + """The folder beside the project where the test adapters read settings and write logs.""" + + folder: Path = project_dir.parent / f"{project_dir.name}_janitor" + folder.mkdir(parents=True, exist_ok=True) + return folder + + AGED_JANITOR_ADAPTER_NAME: str = "aged_janitor_duckdb" JANITOR_TEST_SETTINGS_FILENAME: str = "janitor_test_settings.json" AGED_JANITOR_ADAPTER_SOURCE: str = """ @@ -285,7 +293,8 @@ def create_direct_state_history(*, db_path: Path, schema: str = "main") -> None: from sqlbuild.adapter.contract.models import RelationInfo from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter -_SETTINGS_PATH = Path(__file__).resolve().parent.parent / "janitor_test_settings.json" +_PROJECT = Path(__file__).resolve().parents[2] +_SETTINGS_PATH = _PROJECT.parent / f"{_PROJECT.name}_janitor" / "janitor_test_settings.json" def _settings() -> dict[str, Any]: @@ -353,11 +362,11 @@ def prepare_archive_janitor_project( 'materialized = "table"\n' ), **{ - f"models/{model_name}.sql": f"MODEL (description 'Test model.');\n\n" + f"sql/models/{model_name}.sql": f"MODEL (description 'Test model.');\n\n" f"SELECT 1 AS {model_name}_id\n" for model_name in model_names }, - f"adapters/{AGED_JANITOR_ADAPTER_NAME}.py": AGED_JANITOR_ADAPTER_SOURCE, + f"python/adapters/{AGED_JANITOR_ADAPTER_NAME}.py": AGED_JANITOR_ADAPTER_SOURCE, **{ False: {}, True: {"sqlbuild_local.toml": f'adapter = "{AGED_JANITOR_ADAPTER_NAME}"\n'}, @@ -386,7 +395,9 @@ def write_janitor_test_settings( "identifier_limit": identifier_limit, "fail_janitor_event_insert": fail_janitor_event_insert, } - (project_dir / JANITOR_TEST_SETTINGS_FILENAME).write_text(json.dumps(payload), encoding="utf-8") + (janitor_files(project_dir) / JANITOR_TEST_SETTINGS_FILENAME).write_text( + json.dumps(payload), encoding="utf-8" + ) def archive_timestamp_text(value: datetime) -> str: @@ -462,7 +473,7 @@ def prepare_two_target_janitor_project( 'materialized = "table"\n' ), **{ - f"models/{model_name}.sql": f"MODEL (description 'Test model.');\n\n" + f"sql/models/{model_name}.sql": f"MODEL (description 'Test model.');\n\n" f"SELECT 1 AS {model_name}_id\n" for model_name in model_names }, @@ -506,7 +517,7 @@ def prepare_cruft_in_both_targets(*, tmp_path: Path, project_name: str) -> Path: command=build_command, project_dir=project_dir ) assert build_result.returncode == 0, build_result.stdout + build_result.stderr - (project_dir / "models" / "customers.sql").unlink() + (project_dir / "sql" / "models" / "customers.sql").unlink() db_path: Path = project_dir / "janitor.duckdb" for schema in ("dev", "prod"): execute_duckdb( @@ -542,7 +553,8 @@ def probe_fingerprint_count(*, db_path: Path, schema: str) -> int: from sqlbuild.adapter.contract.exceptions import AdapterUserError from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter -_ROOT = Path(__file__).resolve().parent.parent +_PROJECT = Path(__file__).resolve().parents[2] +_ROOT = _PROJECT.parent / f"{_PROJECT.name}_janitor" _LOG_LOCK = threading.Lock() @@ -596,7 +608,7 @@ def prepare_probe_janitor_project( """Build a DuckDB project with stale tables and an expired archive in each schema.""" models: dict[str, str] = { - f"models/{schema}_{name}.sql": _probe_model_sql(schema=schema, migrate_from="") + f"sql/models/{schema}_{name}.sql": _probe_model_sql(schema=schema, migrate_from="") for schema, name in product(stale_tables, ("orders", *renamed_models)) } project_dir: Path = prepare_inline_project( @@ -618,7 +630,7 @@ def prepare_probe_janitor_project( "[defaults]\n" 'materialized = "table"\n' ), - f"adapters/{PROBE_JANITOR_ADAPTER_NAME}.py": PROBE_JANITOR_ADAPTER_SOURCE, + f"python/adapters/{PROBE_JANITOR_ADAPTER_NAME}.py": PROBE_JANITOR_ADAPTER_SOURCE, **models, }, ) @@ -646,8 +658,8 @@ def rename_probe_models( schema: str name: str for schema, name in product(schemas, renamed_models): - (project_dir / "models" / f"{schema}_{name}.sql").unlink() - (project_dir / "models" / f"{schema}_{name}_v2.sql").write_text( + (project_dir / "sql" / "models" / f"{schema}_{name}.sql").unlink() + (project_dir / "sql" / "models" / f"{schema}_{name}_v2.sql").write_text( _probe_model_sql(schema=schema, migrate_from=f"{schema}.{schema}_{name}"), encoding="utf-8", ) @@ -673,8 +685,8 @@ def write_probe_settings( (project_dir / "sqlbuild_local.toml").write_text( f'adapter = "{PROBE_JANITOR_ADAPTER_NAME}"\n', encoding="utf-8" ) - (project_dir / PROBE_STATEMENT_LOG_FILENAME).write_text("", encoding="utf-8") - (project_dir / PROBE_JANITOR_SETTINGS_FILENAME).write_text( + (janitor_files(project_dir) / PROBE_STATEMENT_LOG_FILENAME).write_text("", encoding="utf-8") + (janitor_files(project_dir) / PROBE_JANITOR_SETTINGS_FILENAME).write_text( json.dumps( { "log": True, @@ -691,7 +703,9 @@ def read_probe_statements(*, project_dir: Path) -> tuple[str, ...]: """Return every statement the probe adapter logged, in order.""" return tuple( - (project_dir / PROBE_STATEMENT_LOG_FILENAME).read_text(encoding="utf-8").splitlines() + (janitor_files(project_dir) / PROBE_STATEMENT_LOG_FILENAME) + .read_text(encoding="utf-8") + .splitlines() ) @@ -778,7 +792,8 @@ def janitor_end_state(*, db_path: Path, schemas: tuple[str, ...]) -> tuple[tuple from sqlbuild.adapter.contract.models import RelationInfo, RelationUsage, RelationUsageReport from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter -_ROOT = Path(__file__).resolve().parent.parent +_PROJECT = Path(__file__).resolve().parents[2] +_ROOT = _PROJECT.parent / f"{_PROJECT.name}_janitor" def _settings() -> dict[str, Any]: @@ -883,8 +898,8 @@ def prepare_usage_janitor_project( "[defaults]\n" 'materialized = "table"\n' ), - "models/orders.sql": "MODEL (description 'Test model.');\n\nSELECT 1 AS order_id\n", - f"adapters/{USAGE_JANITOR_ADAPTER_NAME}.py": USAGE_JANITOR_ADAPTER_SOURCE, + "sql/models/orders.sql": "MODEL (description 'Test model.');\n\nSELECT 1 AS order_id\n", + f"python/adapters/{USAGE_JANITOR_ADAPTER_NAME}.py": USAGE_JANITOR_ADAPTER_SOURCE, }, ) _build(project_dir) @@ -919,7 +934,7 @@ def write_usage_settings( (project_dir / "sqlbuild_local.toml").write_text( f'adapter = "{USAGE_JANITOR_ADAPTER_NAME}"\n', encoding="utf-8" ) - (project_dir / USAGE_JANITOR_SETTINGS_FILENAME).write_text( + (janitor_files(project_dir) / USAGE_JANITOR_SETTINGS_FILENAME).write_text( json.dumps( { "changed_at": "2026-09-01T08:00:00+00:00", @@ -944,7 +959,9 @@ def write_usage_settings( def read_usage_calls(*, project_dir: Path) -> dict[str, object]: """The relations and window of the usage adapter's last `relation_usage` call.""" - return json.loads((project_dir / USAGE_JANITOR_CALLS_FILENAME).read_text(encoding="utf-8")) + return json.loads( + (janitor_files(project_dir) / USAGE_JANITOR_CALLS_FILENAME).read_text(encoding="utf-8") + ) def count_stale_archives(*, db_path: Path) -> int: diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor.py b/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor.py index 82c8bef1ae..d617b6be8b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor.py @@ -263,9 +263,9 @@ def test_given_source_in_managed_schema_when_running_direct_janitor_then_blocks_ """ ).strip() + "\n", - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS order_id\n", - "models/safe_orders.sql": "MODEL (description 'Test model safe_orders.', schema safe,);\n\nSELECT 1 AS order_id\n", - "sources/raw.yml": dedent( + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS order_id\n", + "sql/models/safe_orders.sql": "MODEL (description 'Test model safe_orders.', schema safe,);\n\nSELECT 1 AS order_id\n", + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor_archive.py b/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor_archive.py index 1b830691c3..db3101ed89 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor_archive.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor_archive.py @@ -96,7 +96,7 @@ def test_given_retired_tracked_relation_past_retention_when_running_janitor_then }, ) for model_name in test_case.retired_model_ages_days: - (project_dir / "models" / f"{model_name}.sql").unlink() + (project_dir / "sql" / "models" / f"{model_name}.sql").unlink() janitor_result: subprocess.CompletedProcess[str] = run_sqb( command=test_case.janitor_command, project_dir=project_dir diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor_targets.py b/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor_targets.py index ee4e9a2603..6648b012bc 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor_targets.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/janitor/test_janitor_targets.py @@ -126,8 +126,8 @@ def test_given_prod_old_name_view_when_previewing_early_drop_as_prod_then_view_i command=("--no-color", "build", "--target", "prod"), project_dir=project_dir ) assert origin_build.returncode == 0, origin_build.stdout + origin_build.stderr - (project_dir / "models" / "revenue.sql").unlink() - (project_dir / "models" / "daily_revenue.sql").write_text( + (project_dir / "sql" / "models" / "revenue.sql").unlink() + (project_dir / "sql" / "models" / "daily_revenue.sql").write_text( "MODEL (description 'Test model daily_revenue.',\n migrate_from revenue,\n);\n\nSELECT 1 AS revenue_id\n", encoding="utf-8", ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/lineage/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/lineage/helpers.py index 0603f89712..a73f7a4837 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/lineage/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/lineage/helpers.py @@ -12,15 +12,15 @@ def prepare_lineage_cache_project(*, tmp_path: Path) -> Path: project_name="lineage_cache_project", repo_files={ "sqlbuild_project.toml": 'name = "lineage_cache_project"\nadapter = "duckdb"\n', - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', " "materialized view);\n\nSELECT 1 AS order_id, 10 AS customer_id\n" ), - "models/stg_customers.sql": ( + "sql/models/stg_customers.sql": ( "MODEL (description 'Test model stg_customers.', " "materialized view);\n\nSELECT 10 AS customer_id\n" ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( 'MODEL (description "Test model fact_orders.", ' 'materialized view);\n\nSELECT * FROM __ref("stg_orders")\n' ), @@ -52,17 +52,17 @@ def prepare_diamond_lineage_project(*, tmp_path: Path) -> Path: files: dict[str, str] = { "sqlbuild_project.toml": 'name = "diamond_lineage"\nadapter = "duckdb"\n', - "models/orders_0.sql": "MODEL (description 'Test model orders_0.', " + "sql/models/orders_0.sql": "MODEL (description 'Test model orders_0.', " "materialized view);\n\nSELECT 1 AS order_id, 10 AS amount\n", } for layer in range(1, DIAMOND_LAYERS + 1): previous: str = f"orders_{layer - 1}" for side in ("left", "right"): - files[f"models/orders_{side}_{layer}.sql"] = ( + files[f"sql/models/orders_{side}_{layer}.sql"] = ( 'MODEL (description "Test model.", ' f'materialized view);\n\nSELECT order_id, amount FROM __ref("{previous}")\n' ) - files[f"models/orders_{layer}.sql"] = ( + files[f"sql/models/orders_{layer}.sql"] = ( "MODEL (description 'Test model.', materialized view);\n\n" "SELECT l.order_id, l.amount + r.amount AS amount\n" f'FROM __ref("orders_left_{layer}") AS l\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/lineage/test_lineage.py b/tests/e2e/src/sqlbuild/cli/commands/main/lineage/test_lineage.py index ac589f5907..7d5fd577ee 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/lineage/test_lineage.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/lineage/test_lineage.py @@ -88,7 +88,7 @@ command=( "lineage", "--select", - "path:models/staging", + "path:sql/models/staging", "--exclude", "tag:finance", "--direction", @@ -109,11 +109,11 @@ def test_given_directional_selectors_when_expanding_then_depth_and_exclusions_ar test_case: LineageCliTestCase, tmp_path: Path ) -> None: project_dir: Path = prepare_lineage_cache_project(tmp_path=tmp_path) - staging_dir: Path = project_dir / "models" / "staging" - staging_dir.mkdir() + staging_dir: Path = project_dir / "sql" / "models" / "staging" + staging_dir.mkdir(parents=True) for name in ("stg_orders.sql", "stg_customers.sql"): - (project_dir / "models" / name).rename(staging_dir / name) - (project_dir / "models" / "fact_orders.sql").write_text( + (project_dir / "sql" / "models" / name).rename(staging_dir / name) + (project_dir / "sql" / "models" / "fact_orders.sql").write_text( 'MODEL (description "Test model fact_orders.", materialized view, tags [finance]);\nSELECT * FROM __ref("stg_orders")\n', encoding="utf-8", ) @@ -344,7 +344,7 @@ def test_given_authored_dependency_change_when_lineage_runs_then_rebuilds_struct project_dir=project_dir, ) assert first.returncode == 0, first.stdout + first.stderr - (project_dir / "models/fact_orders.sql").write_text( + (project_dir / "sql/models/fact_orders.sql").write_text( "MODEL (description 'Test model fact_orders.', materialized view);\n\n" 'SELECT orders.order_id FROM __ref("stg_orders") AS orders\n' 'JOIN __ref("stg_customers") AS customers USING (customer_id)\n', @@ -555,7 +555,7 @@ def test_given_diamond_dependencies_when_rendering_lineage_tree_then_output_stay ( SharedSelectorCliTestCase( description="models-rooted path", - selector="path:models/staging", + selector="path:sql/models/staging", expected_node_ids=("model:stg_customers", "model:stg_orders", "model:stg_payments"), expected_selected_models=3, expected_selected_functions=0, @@ -569,7 +569,7 @@ def test_given_diamond_dependencies_when_rendering_lineage_tree_then_output_stay ), SharedSelectorCliTestCase( description="path and tag intersection", - selector="path:models/marts,tag:acceptance", + selector="path:sql/models/marts,tag:acceptance", expected_node_ids=( "model:daily_activity_rollup", "model:hourly_activity_with_daily_context", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/load/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/load/helpers.py index 86c38f1475..0f2bdbebcc 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/load/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/load/helpers.py @@ -34,32 +34,50 @@ def assert_source_only_ingress_dependency_case( "sources:\n - name: raw_events\n description: Test source raw_events.\n" " managed: true\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n" - "from python.tasks.prepare import prepare_events\n\n" - "@loader(depends_on=[prepare_events], write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - " {'name': 'load_seq', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [\n" - " {'event_id': 1, 'load_seq': 1},\n" - " {'event_id': 2, 'load_seq': 1},\n" - " ]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS " - "SELECT event_id FROM {events.destination}')\n" - ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.tasks.prepare.asset import prepare_events\n" + "\n" + "\n" + "@loader(depends_on=[prepare_events], write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + " {'name': 'load_seq', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " return [\n" + " {'event_id': 1, 'load_seq': 1},\n" + " {'event_id': 2, 'load_seq': 1},\n" + " ]\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.tasks.prepare.asset import prepare_events\n" + "from python.nodes.loaders.source_rows.fetch_events.loader " + "import fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + " ctx.execute_sql(f'CREATE OR REPLACE TABLE " + "{ctx.destination} AS SELECT event_id FROM {events.destination}')\n" + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + }, ), - "python/tasks/prepare.py": ( + "python/nodes/tasks/prepare/asset.py": ( "from pathlib import Path\n" "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_events(ctx):\n" " '''Test task prepare_events.'''\n" - " Path(__file__).parents[2].joinpath('prepared.txt').write_text('prepared')\n" + " Path(__file__).parents[4].joinpath('prepared.txt').write_text('prepared')\n" " return ctx.result()\n" ), }, @@ -151,7 +169,9 @@ def _assert_successful_source_only_result( assert (project_dir / "prepared.txt").exists() is test_case.expected_marker_exists -def build_schema_behavior_project_files(*, source_yaml: str, loader_py: str) -> dict[str, str]: +def build_schema_behavior_project_files( + *, source_yaml: str, node_files: dict[str, str] +) -> dict[str, str]: return { "sqlbuild_project.toml": ( 'name = "source_loader_schema_behavior"\n' @@ -159,8 +179,8 @@ def build_schema_behavior_project_files(*, source_yaml: str, loader_py: str) -> "[connection]\n" 'database = "source_loader_schema_behavior.duckdb"\n' ), - "sources/raw.yml": source_yaml, - "python/loaders/source_rows.py": loader_py, + "sql/sources/raw.yml": source_yaml, + **node_files, } @@ -235,7 +255,7 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - "[defaults]\n" 'materialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -264,8 +284,10 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - " - name: load_seq\n" " type: INTEGER\n" ), - "python/loaders/waffle_loaders.py": ( - "from sqlbuild.loaders import loader\n\n" + "python/nodes/loaders/waffle_loaders/fetch_order_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" "@loader(write_strategy='append', cursor_column='load_seq', columns=[\n" " {'name': 'order_id', 'type': 'INTEGER'},\n" " {'name': 'customer_id', 'type': 'INTEGER'},\n" @@ -274,7 +296,8 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - " {'name': 'load_seq', 'type': 'INTEGER'},\n" "])\n" "def fetch_order_events(ctx):\n" - " '''Test loader fetch_order_events.'''\n if ctx.current_cursor_value is None:\n" + " '''Test loader fetch_order_events.'''\n" + " if ctx.current_cursor_value is None:\n" " next_seq = 1\n" " else:\n" " next_seq = ctx.current_cursor_value + 1\n" @@ -294,7 +317,12 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - " 'quantity': next_seq + 1,\n" " 'load_seq': next_seq,\n" " },\n" - " ]\n\n" + " ]\n" + ), + "python/nodes/loaders/waffle_loaders/fetch_customers/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" "@loader(\n" " write_strategy='merge',\n" " unique_key='customer_id',\n" @@ -305,7 +333,8 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - " {'name': 'load_seq', 'type': 'INTEGER'},\n" "])\n" "def fetch_customers(ctx):\n" - " '''Test loader fetch_customers.'''\n if ctx.current_cursor_value is None:\n" + " '''Test loader fetch_customers.'''\n" + " if ctx.current_cursor_value is None:\n" " return [\n" " {'customer_id': 1, 'plan_name': 'basic', 'load_seq': 1},\n" " {'customer_id': 2, 'plan_name': 'plus', 'load_seq': 1},\n" @@ -313,7 +342,12 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - " return [\n" " {'customer_id': 1, 'plan_name': 'pro', 'load_seq': 2},\n" " {'customer_id': 3, 'plan_name': 'enterprise', 'load_seq': 2},\n" - " ]\n\n" + " ]\n" + ), + "python/nodes/loaders/waffle_loaders/fetch_prices/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" "@loader(write_strategy='delete_insert', cursor_column='load_seq', columns=[\n" " {'name': 'waffle_type', 'type': 'VARCHAR'},\n" " {'name': 'price_cents', 'type': 'INTEGER'},\n" @@ -325,10 +359,19 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - " return [\n" " {'waffle_type': 'classic', 'price_cents': classic_price, 'load_seq': 1},\n" " {'waffle_type': 'blueberry', 'price_cents': 750, 'load_seq': 1},\n" - " ]\n\n" + " ]\n" + ), + "python/nodes/loaders/waffle_loaders/raw_orders/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.waffle_loaders.fetch_order_events.loader " + "import fetch_order_events\n" + "from python.nodes.loaders.waffle_loaders.fetch_prices.loader import fetch_prices\n" + "\n" + "\n" "@loader(depends_on=[fetch_order_events, fetch_prices])\n" "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n events = ctx.loader(fetch_order_events)\n" + " '''Test loader raw_orders.'''\n" + " events = ctx.loader(fetch_order_events)\n" " prices = ctx.loader(fetch_prices)\n" " cursor = ctx.query(\n" " f'SELECT e.order_id, e.customer_id, e.waffle_type, e.quantity, '\n" @@ -346,10 +389,18 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - " 'load_seq': row[5],\n" " }\n" " for row in cursor.fetchall()\n" - " ]\n\n" + " ]\n" + ), + "python/nodes/loaders/waffle_loaders/raw_customers/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.waffle_loaders.fetch_customers.loader " + "import fetch_customers\n" + "\n" + "\n" "@loader(depends_on=[fetch_customers])\n" "def raw_customers(ctx):\n" - " '''Test loader raw_customers.'''\n customers = ctx.loader(fetch_customers)\n" + " '''Test loader raw_customers.'''\n" + " customers = ctx.loader(fetch_customers)\n" " cursor = ctx.query(\n" " f'SELECT customer_id, plan_name, load_seq FROM {customers.destination} '\n" " f'ORDER BY customer_id'\n" @@ -359,7 +410,14 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - " for row in cursor.fetchall()\n" " ]\n" ), - "models/fact_waffle_orders.sql": ( + "python/nodes/loaders/waffle_loaders/__init__.py": ( + "from .fetch_order_events.loader import fetch_order_events\n" + "from .fetch_customers.loader import fetch_customers\n" + "from .fetch_prices.loader import fetch_prices\n" + "from .raw_orders.loader import raw_orders\n" + "from .raw_customers.loader import raw_customers\n" + ), + "sql/models/fact_waffle_orders.sql": ( "MODEL (description 'Test model fact_waffle_orders.', materialized table);\n\n" "SELECT\n" " o.order_id,\n" @@ -373,7 +431,7 @@ def build_loader_waffle_shop_project_files(*, project_toml: str | None = None) - 'FROM __source("raw_orders") o\n' 'LEFT JOIN __source("raw_customers") c ON o.customer_id = c.customer_id\n' ), - "models/customer_revenue.sql": ( + "sql/models/customer_revenue.sql": ( "MODEL (description 'Test model customer_revenue.', materialized table);\n\n" "SELECT\n" " customer_id,\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/load/test_load.py b/tests/e2e/src/sqlbuild/cli/commands/main/load/test_load.py index 98444d09a5..bb510a931e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/load/test_load.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/load/test_load.py @@ -31,6 +31,7 @@ run_sqb, table_exists, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -144,14 +145,17 @@ def test_given_non_contract_loader_when_late_column_appears_then_existing_target " - name: load_seq\n" " type: INTEGER\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n if ctx.current_cursor_value is None:\n" - " return [{'event_id': 1, 'load_seq': 1}]\n" - " return [{'event_id': 2, 'load_seq': 2, 'note': 'late-note'}]\n" - ), + node_files={ + "python/nodes/loaders/source_rows/loader.py": ( + "from sqlbuild.loaders import loader\n\n" + "@loader\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n if ctx.current_cursor_value is None:\n" + " return [{'event_id': 1, 'load_seq': 1}]\n" + " return [{'event_id': 2, 'load_seq': 2, 'note': 'late-note'}]\n" + ), + "python/nodes/loaders/source_rows/__init__.py": "from .loader import raw_events\n", + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -317,33 +321,59 @@ def test_given_two_terminal_sources_when_sharing_intermediate_then_intermediate_ " managed: true\n" " write_strategy: table\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='append', cursor_column='load_seq', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - " {'name': 'load_seq', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_orders(ctx):\n" - " '''Test loader fetch_orders.'''\n if ctx.current_cursor_value is None:\n" - " next_seq = 1\n" - " else:\n" - " next_seq = ctx.current_cursor_value + 1\n" - " return [{'event_id': next_seq, 'load_seq': next_seq}]\n\n" - "@loader(depends_on=[fetch_orders])\n" - "def raw_orders(ctx):\n" - " '''Test loader raw_orders.'''\n orders = ctx.loader(fetch_orders)\n" - " cursor = ctx.query(\n" - " f'SELECT event_id FROM {orders.destination} ORDER BY event_id'\n" - " )\n" - " return [{'event_id': row[0]} for row in cursor.fetchall()]\n\n" - "@loader(depends_on=[fetch_orders])\n" - "def raw_order_metrics(ctx):\n" - " '''Test loader raw_order_metrics.'''\n orders = ctx.loader(fetch_orders)\n" - " cursor = ctx.query(\n" - " f'SELECT event_id FROM {orders.destination} ORDER BY event_id'\n" - " )\n" - " return [{'event_id': row[0]} for row in cursor.fetchall()]\n" - ), + node_files={ + "python/nodes/loaders/source_rows/fetch_orders/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='append', cursor_column='load_seq', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + " {'name': 'load_seq', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_orders(ctx):\n" + " '''Test loader fetch_orders.'''\n" + " if ctx.current_cursor_value is None:\n" + " next_seq = 1\n" + " else:\n" + " next_seq = ctx.current_cursor_value + 1\n" + " return [{'event_id': next_seq, 'load_seq': next_seq}]\n" + ), + "python/nodes/loaders/source_rows/raw_orders/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_orders.loader import " + "fetch_orders\n" + "\n" + "\n" + "@loader(depends_on=[fetch_orders])\n" + "def raw_orders(ctx):\n" + " '''Test loader raw_orders.'''\n" + " orders = ctx.loader(fetch_orders)\n" + " cursor = ctx.query(\n" + " f'SELECT event_id FROM {orders.destination} ORDER BY event_id'\n" + " )\n" + " return [{'event_id': row[0]} for row in cursor.fetchall()]\n" + ), + "python/nodes/loaders/source_rows/raw_order_metrics/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_orders.loader import " + "fetch_orders\n" + "\n" + "\n" + "@loader(depends_on=[fetch_orders])\n" + "def raw_order_metrics(ctx):\n" + " '''Test loader raw_order_metrics.'''\n" + " orders = ctx.loader(fetch_orders)\n" + " cursor = ctx.query(\n" + " f'SELECT event_id FROM {orders.destination} ORDER BY event_id'\n" + " )\n" + " return [{'event_id': row[0]} for row in cursor.fetchall()]\n" + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_orders.loader import fetch_orders\n" + "from .raw_orders.loader import raw_orders\n" + "from .raw_order_metrics.loader import raw_order_metrics\n" + ), + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -401,25 +431,42 @@ def test_given_chained_loader_project_when_loading_source_then_runs_dependencies " - name: status\n" " type: VARCHAR\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', cursor_column='load_seq', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - " {'name': 'load_seq', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n source_cursor = ctx.source('raw_events').max('event_id')\n" - " return [\n" - " {'event_id': 1, 'load_seq': 1},\n" - " {'event_id': 2, 'load_seq': 1},\n" - " ] if source_cursor is None else []\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - "SELECT event_id, 'loaded' AS status, {events.current_cursor_value} AS max_seq " - 'FROM {events.destination}")\n' - ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', cursor_column='load_seq', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + " {'name': 'load_seq', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " source_cursor = ctx.source('raw_events').max('event_id')\n" + " return [\n" + " {'event_id': 1, 'load_seq': 1},\n" + " {'event_id': 2, 'load_seq': 1},\n" + " ] if source_cursor is None else []\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_events.loader import " + "fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} ' + "AS SELECT event_id, 'loaded' AS status, " + '{events.current_cursor_value} AS max_seq FROM {events.destination}")\n' + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -473,22 +520,39 @@ def test_given_chained_loader_project_when_building_source_model_then_runs_loade " - name: status\n" " type: VARCHAR\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - "SELECT event_id, 'loaded' AS status FROM {events.destination}\")\n" - ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}, {'event_id': 2}]\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_events.loader import " + "fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} ' + "AS SELECT event_id, 'loaded' AS status FROM {events.destination}\")\n" + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + }, ) | { - "models/fact_events.sql": ( + "sql/models/fact_events.sql": ( "MODEL (description 'Test model fact_events.', materialized table);\n\n" 'SELECT event_id, status FROM __source("raw_events")\n' ) @@ -552,22 +616,39 @@ def test_given_chained_loader_project_when_running_source_model_then_runs_loader " - name: status\n" " type: VARCHAR\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - "SELECT event_id, 'loaded' AS status FROM {events.destination}\")\n" - ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}, {'event_id': 2}]\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_events.loader import " + "fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} ' + "AS SELECT event_id, 'loaded' AS status FROM {events.destination}\")\n" + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + }, ) | { - "models/fact_events.sql": ( + "sql/models/fact_events.sql": ( "MODEL (description 'Test model fact_events.', materialized table);\n\n" 'SELECT event_id, status FROM __source("raw_events")\n' ) @@ -615,7 +696,10 @@ def test_given_source_loader_reads_unselected_task_payload_when_loading_then_run test_case: SourceOnlyComplexIngressE2ETestCase, ) -> None: assert test_case.expected_error_fragment is not None - dependency_file: str = f"python/{test_case.dependency_dir}/prepare.py" + dependency_module: str = ( + f"python.nodes.{test_case.dependency_dir}.prepare_events.{test_case.decorator_name}" + ) + dependency_file: str = f"{dependency_module.replace('.', '/')}.py" project_dir: Path = prepare_inline_project( tmp_path=tmp_path, project_name="source_loader_schema_behavior", @@ -630,14 +714,18 @@ def test_given_source_loader_reads_unselected_task_payload_when_loading_then_run " - name: event_id\n" " type: INTEGER\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n" - f"from python.{test_case.dependency_dir}.prepare import prepare_events\n\n" - "@loader(depends_on=[prepare_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n payload = ctx.result_of(node_function=prepare_events).payload\n" - " return [{'event_id': payload['event_id']}]\n" - ), + node_files={ + **node_module_files( + "python/nodes/loaders/source_rows.py", + "from sqlbuild.loaders import loader\n" + f"from {dependency_module} import prepare_events\n\n" + "@loader(depends_on=[prepare_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n payload = " + "ctx.result_of(node_function=prepare_events).payload\n" + " return [{'event_id': payload['event_id']}]\n", + ) + }, ), dependency_file: ( f"{test_case.decorator_import}\n" @@ -749,42 +837,92 @@ def test_given_source_only_selection_when_skipping_complex_intermediates_then_va " - name: raw_rollup\n description: Test source raw_rollup.\n" " managed: true\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}]\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'price_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_prices(ctx):\n" - " '''Test loader fetch_prices.'''\n return [{'price_id': 1}]\n\n" - "@loader(depends_on=[fetch_events, fetch_prices])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " prices = ctx.loader(fetch_prices)\n" - " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS " - "SELECT event_id FROM {events.destination} UNION ALL " - "SELECT price_id FROM {prices.destination}')\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'page_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_pages(ctx):\n" - " '''Test loader fetch_pages.'''\n return [{'page_id': 1}]\n\n" - "@loader(depends_on=[fetch_pages], write_strategy='table', " - "columns=[{'name': 'page_id', 'type': 'INTEGER'}])\n" - "def normalize_pages(ctx):\n" - " '''Test loader normalize_pages.'''\n pages = ctx.loader(fetch_pages)\n" - " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS " - "SELECT page_id FROM {pages.destination}')\n\n" - "@loader(depends_on=[normalize_pages])\n" - "def raw_rollup(ctx):\n" - " '''Test loader raw_rollup.'''\n pages = ctx.loader(normalize_pages)\n" - " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS " - "SELECT page_id FROM {pages.destination}')\n" - ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/source_rows/fetch_prices/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'price_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_prices(ctx):\n" + " '''Test loader fetch_prices.'''\n" + " return [{'price_id': 1}]\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_events.loader import " + "fetch_events\n" + "from python.nodes.loaders.source_rows.fetch_prices.loader import " + "fetch_prices\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events, fetch_prices])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + " prices = ctx.loader(fetch_prices)\n" + " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} " + "AS SELECT event_id FROM {events.destination} UNION ALL SELECT " + "price_id FROM {prices.destination}')\n" + ), + "python/nodes/loaders/source_rows/fetch_pages/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'page_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_pages(ctx):\n" + " '''Test loader fetch_pages.'''\n" + " return [{'page_id': 1}]\n" + ), + "python/nodes/loaders/source_rows/normalize_pages/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_pages.loader import fetch_pages\n" + "\n" + "\n" + "@loader(depends_on=[fetch_pages], write_strategy='table', " + "columns=[{'name': 'page_id', 'type': 'INTEGER'}])\n" + "def normalize_pages(ctx):\n" + " '''Test loader normalize_pages.'''\n" + " pages = ctx.loader(fetch_pages)\n" + " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} " + "AS SELECT page_id FROM {pages.destination}')\n" + ), + "python/nodes/loaders/source_rows/raw_rollup/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.normalize_pages.loader " + "import normalize_pages\n" + "\n" + "\n" + "@loader(depends_on=[normalize_pages])\n" + "def raw_rollup(ctx):\n" + " '''Test loader raw_rollup.'''\n" + " pages = ctx.loader(normalize_pages)\n" + " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} " + "AS SELECT page_id FROM {pages.destination}')\n" + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .fetch_prices.loader import fetch_prices\n" + "from .raw_events.loader import raw_events\n" + "from .fetch_pages.loader import fetch_pages\n" + "from .normalize_pages.loader import normalize_pages\n" + "from .raw_rollup.loader import raw_rollup\n" + ), + }, ), ) setup_command: tuple[str, ...] @@ -872,22 +1010,40 @@ def test_given_chained_loader_project_when_selecting_loader_then_expands_expecte project_name="source_loader_schema_behavior", repo_files=build_schema_behavior_project_files( source_yaml=( - "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n" - ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - " {'name': 'load_seq', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1, 'load_seq': 1}, {'event_id': 2, 'load_seq': 1}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - 'SELECT event_id FROM {events.destination}")\n' + "sources:\n - name: raw_events\n description: Test source " + "raw_events.\n managed: true\n" ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + " {'name': 'load_seq', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1, 'load_seq': 1}, {'event_id': 2, 'load_seq': 1}]\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_events.loader import " + "fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} ' + 'AS SELECT event_id FROM {events.destination}")\n' + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -944,21 +1100,39 @@ def test_given_chained_loader_project_when_excluding_dependency_then_prunes_depe project_name="source_loader_schema_behavior", repo_files=build_schema_behavior_project_files( source_yaml=( - "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n" - ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - 'SELECT event_id FROM {events.destination}")\n' + "sources:\n - name: raw_events\n description: Test source " + "raw_events.\n managed: true\n" ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_events.loader import " + "fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} ' + 'AS SELECT event_id FROM {events.destination}")\n' + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -997,22 +1171,40 @@ def test_given_chained_loader_project_when_intermediate_has_custom_target_then_r project_name="source_loader_schema_behavior", repo_files=build_schema_behavior_project_files( source_yaml=( - "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n" - ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(destination='custom_fetch_events', write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - "SELECT event_id, '{events.table_name}' AS source_table " - 'FROM {events.destination}")\n' + "sources:\n - name: raw_events\n description: Test source " + "raw_events.\n managed: true\n" ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(destination='custom_fetch_events', write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_events.loader import " + "fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} ' + "AS SELECT event_id, '{events.table_name}' AS source_table FROM " + '{events.destination}")\n' + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -1047,7 +1239,8 @@ def test_given_chained_loader_project_when_intermediate_has_custom_target_then_r " {'name': 'amount', 'type': 'INTEGER'},\n" "])\n" "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1, 'amount': 100}, {'event_id': 2, 'amount': 200}]\n\n" + " '''Test loader fetch_events.'''\n return [{'event_id': 1, " + "'amount': 100}, {'event_id': 2, 'amount': 200}]\n\n" "@loader(depends_on=[fetch_events])\n" "def raw_events(ctx):\n" " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" @@ -1107,7 +1300,8 @@ def test_given_chained_loader_project_when_intermediate_has_custom_target_then_r " {'name': 'load_seq', 'type': 'INTEGER'},\n" "])\n" "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n if ctx.current_cursor_value is not None:\n" + " '''Test loader fetch_events.'''\n if ctx.current_cursor_value " + "is not None:\n" " return [\n" " {'event_id': 2, 'amount': 250, 'load_seq': 1},\n" " {'event_id': 3, 'amount': 300, 'load_seq': 1},\n" @@ -1151,7 +1345,9 @@ def test_given_chained_loader_project_when_intermediate_uses_strategy_then_appli " - name: amount\n" " type: INTEGER\n" ), - loader_py=test_case.loader_py, + node_files={ + **node_module_files("python/nodes/loaders/source_rows.py", test_case.loader_py) + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -1211,7 +1407,12 @@ def test_given_intermediate_loader_without_write_strategy_when_loading_twice_the project_name="source_loader_schema_behavior", repo_files=build_schema_behavior_project_files( source_yaml=(edge_cases / "intermediate_default_accounts.yml").read_text(), - loader_py=(edge_cases / "intermediate_default_accounts.py").read_text(), + node_files={ + **node_module_files( + "python/nodes/loaders/source_rows.py", + (edge_cases / "intermediate_default_accounts.py").read_text(), + ) + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -1273,22 +1474,45 @@ def test_given_loader_dependency_failure_when_loading_then_only_dependents_skip( " managed: true\n" " write_strategy: table\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_bad(ctx):\n" - " '''Test loader fetch_bad.'''\n raise RuntimeError('boom')\n\n" - "@loader(depends_on=[fetch_bad])\n" - "def raw_bad(ctx):\n" - " '''Test loader raw_bad.'''\n events = ctx.loader(fetch_bad)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - 'SELECT event_id FROM {events.destination}")\n\n' - "@loader\n" - "def raw_ok(ctx):\n" - " '''Test loader raw_ok.'''\n return [{'event_id': 1}]\n" - ), + node_files={ + "python/nodes/loaders/source_rows/fetch_bad/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_bad(ctx):\n" + " '''Test loader fetch_bad.'''\n" + " raise RuntimeError('boom')\n" + ), + "python/nodes/loaders/source_rows/raw_bad/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_bad.loader import fetch_bad\n" + "\n" + "\n" + "@loader(depends_on=[fetch_bad])\n" + "def raw_bad(ctx):\n" + " '''Test loader raw_bad.'''\n" + " events = ctx.loader(fetch_bad)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} ' + 'AS SELECT event_id FROM {events.destination}")\n' + ), + "python/nodes/loaders/source_rows/raw_ok/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader\n" + "def raw_ok(ctx):\n" + " '''Test loader raw_ok.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_bad.loader import fetch_bad\n" + "from .raw_bad.loader import raw_bad\n" + "from .raw_ok.loader import raw_ok\n" + ), + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -1338,29 +1562,54 @@ def test_given_loader_dependency_failure_when_building_then_only_dependents_skip " managed: true\n" " write_strategy: table\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_bad(ctx):\n" - " '''Test loader fetch_bad.'''\n raise RuntimeError('boom')\n\n" - "@loader(depends_on=[fetch_bad])\n" - "def raw_bad(ctx):\n" - " '''Test loader raw_bad.'''\n events = ctx.loader(fetch_bad)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - 'SELECT event_id FROM {events.destination}")\n\n' - "@loader\n" - "def raw_ok(ctx):\n" - " '''Test loader raw_ok.'''\n return [{'event_id': 1}]\n" - ), + node_files={ + "python/nodes/loaders/source_rows/fetch_bad/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_bad(ctx):\n" + " '''Test loader fetch_bad.'''\n" + " raise RuntimeError('boom')\n" + ), + "python/nodes/loaders/source_rows/raw_bad/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_bad.loader import fetch_bad\n" + "\n" + "\n" + "@loader(depends_on=[fetch_bad])\n" + "def raw_bad(ctx):\n" + " '''Test loader raw_bad.'''\n" + " events = ctx.loader(fetch_bad)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} ' + 'AS SELECT event_id FROM {events.destination}")\n' + ), + "python/nodes/loaders/source_rows/raw_ok/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader\n" + "def raw_ok(ctx):\n" + " '''Test loader raw_ok.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_bad.loader import fetch_bad\n" + "from .raw_bad.loader import raw_bad\n" + "from .raw_ok.loader import raw_ok\n" + ), + }, ) | { - "models/bad_model.sql": ( - 'MODEL (description "Test model bad_model.", materialized table);\n\nSELECT event_id FROM __source("raw_bad")\n' + "sql/models/bad_model.sql": ( + 'MODEL (description "Test model bad_model.", materialized ' + 'table);\n\nSELECT event_id FROM __source("raw_bad")\n' ), - "models/ok_model.sql": ( - 'MODEL (description "Test model ok_model.", materialized table);\n\nSELECT event_id FROM __source("raw_ok")\n' + "sql/models/ok_model.sql": ( + 'MODEL (description "Test model ok_model.", materialized ' + 'table);\n\nSELECT event_id FROM __source("raw_ok")\n' ), }, ) @@ -1413,22 +1662,45 @@ def test_given_loader_dependency_failure_when_loading_json_then_reports_skipped_ " managed: true\n" " write_strategy: table\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_bad(ctx):\n" - " '''Test loader fetch_bad.'''\n raise RuntimeError('boom')\n\n" - "@loader(depends_on=[fetch_bad])\n" - "def raw_bad(ctx):\n" - " '''Test loader raw_bad.'''\n events = ctx.loader(fetch_bad)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - 'SELECT event_id FROM {events.destination}")\n\n' - "@loader\n" - "def raw_ok(ctx):\n" - " '''Test loader raw_ok.'''\n return [{'event_id': 1}]\n" - ), + node_files={ + "python/nodes/loaders/source_rows/fetch_bad/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_bad(ctx):\n" + " '''Test loader fetch_bad.'''\n" + " raise RuntimeError('boom')\n" + ), + "python/nodes/loaders/source_rows/raw_bad/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_bad.loader import fetch_bad\n" + "\n" + "\n" + "@loader(depends_on=[fetch_bad])\n" + "def raw_bad(ctx):\n" + " '''Test loader raw_bad.'''\n" + " events = ctx.loader(fetch_bad)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} ' + 'AS SELECT event_id FROM {events.destination}")\n' + ), + "python/nodes/loaders/source_rows/raw_ok/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader\n" + "def raw_ok(ctx):\n" + " '''Test loader raw_ok.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_bad.loader import fetch_bad\n" + "from .raw_bad.loader import raw_bad\n" + "from .raw_ok.loader import raw_ok\n" + ), + }, ), ) db_path: Path = project_dir / "source_loader_schema_behavior.duckdb" @@ -1464,7 +1736,8 @@ def test_given_loader_dependency_failure_when_loading_json_then_reports_skipped_ repo_files=build_schema_behavior_project_files( source_yaml=( "sources:\n" - " - name: raw_contract_events\n description: Test source raw_contract_events.\n" + " - name: raw_contract_events\n description: Test source " + "raw_contract_events.\n" " managed: true\n" " write_strategy: table\n" " contract: enforced\n" @@ -1472,12 +1745,16 @@ def test_given_loader_dependency_failure_when_loading_json_then_reports_skipped_ " - name: event_id\n" " type: INTEGER\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader\n" - "def raw_contract_events(ctx):\n" - " '''Test loader raw_contract_events.'''\n return [{'event_id': 1, 'extra_note': 'not declared'}]\n" - ), + node_files={ + "python/nodes/loaders/source_rows/loader.py": ( + "from sqlbuild.loaders import loader\n\n" + "@loader\n" + "def raw_contract_events(ctx):\n" + " '''Test loader raw_contract_events.'''\n return " + "[{'event_id': 1, 'extra_note': 'not declared'}]\n" + ), + "python/nodes/loaders/source_rows/__init__.py": "from .loader import raw_contract_events\n", + }, ), ), SourceLoaderErrorE2ETestCase( @@ -1487,7 +1764,8 @@ def test_given_loader_dependency_failure_when_loading_json_then_reports_skipped_ repo_files=build_schema_behavior_project_files( source_yaml=( "sources:\n" - " - name: raw_contract_events\n description: Test source raw_contract_events.\n" + " - name: raw_contract_events\n description: Test source " + "raw_contract_events.\n" " managed: true\n" " write_strategy: table\n" " contract: enforced\n" @@ -1497,12 +1775,15 @@ def test_given_loader_dependency_failure_when_loading_json_then_reports_skipped_ " - name: event_name\n" " type: VARCHAR\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader\n" - "def raw_contract_events(ctx):\n" - " '''Test loader raw_contract_events.'''\n return [{'event_id': 1}]\n" - ), + node_files={ + "python/nodes/loaders/source_rows/loader.py": ( + "from sqlbuild.loaders import loader\n\n" + "@loader\n" + "def raw_contract_events(ctx):\n" + " '''Test loader raw_contract_events.'''\n return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/source_rows/__init__.py": "from .loader import raw_contract_events\n", + }, ), ), SourceLoaderErrorE2ETestCase( @@ -1522,14 +1803,18 @@ def test_given_loader_dependency_failure_when_loading_json_then_reports_skipped_ " - name: load_seq\n" " type: INTEGER\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n if ctx.current_cursor_value is None:\n" - " return [{'event_id': 1, 'load_seq': 1, 'amount': 100}]\n" - " return [{'event_id': 2, 'load_seq': 2, 'amount': 'one hundred'}]\n" - ), + node_files={ + "python/nodes/loaders/source_rows/loader.py": ( + "from sqlbuild.loaders import loader\n\n" + "@loader\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n if " + "ctx.current_cursor_value is None:\n" + " return [{'event_id': 1, 'load_seq': 1, 'amount': 100}]\n" + " return [{'event_id': 2, 'load_seq': 2, 'amount': 'one hundred'}]\n" + ), + "python/nodes/loaders/source_rows/__init__.py": "from .loader import raw_events\n", + }, ), ), SourceLoaderErrorE2ETestCase( @@ -1538,21 +1823,39 @@ def test_given_loader_dependency_failure_when_loading_json_then_reports_skipped_ expected_error_fragment="contract has extra columns: extra_note", repo_files=build_schema_behavior_project_files( source_yaml=( - "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n" - ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', contract='enforced', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1, 'extra_note': 'not declared'}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - 'SELECT event_id FROM {events.destination}")\n' + "sources:\n - name: raw_events\n description: Test source " + "raw_events.\n managed: true\n" ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(write_strategy='table', contract='enforced', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1, 'extra_note': 'not declared'}]\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_events.loader " + "import fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE ' + '{ctx.destination} AS SELECT event_id FROM {events.destination}")\n' + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + }, ), ), SourceLoaderErrorE2ETestCase( @@ -1561,19 +1864,37 @@ def test_given_loader_dependency_failure_when_loading_json_then_reports_skipped_ expected_error_fragment="returned no rows and has no destination declared", repo_files=build_schema_behavior_project_files( source_yaml=( - "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n" - ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n ctx.execute_sql('SELECT 1')\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - ' ctx.execute_sql(f"CREATE OR REPLACE TABLE {ctx.destination} AS ' - 'SELECT * FROM {events.destination}")\n' + "sources:\n - name: raw_events\n description: Test source " + "raw_events.\n managed: true\n" ), + node_files={ + "python/nodes/loaders/source_rows/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n" + " ctx.execute_sql('SELECT 1')\n" + ), + "python/nodes/loaders/source_rows/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.source_rows.fetch_events.loader " + "import fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + ' ctx.execute_sql(f"CREATE OR REPLACE TABLE ' + '{ctx.destination} AS SELECT * FROM {events.destination}")\n' + ), + "python/nodes/loaders/source_rows/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" + ), + }, ), ), ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/load/test_load_relation_guard.py b/tests/e2e/src/sqlbuild/cli/commands/main/load/test_load_relation_guard.py index 1cd132172c..70a02b869b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/load/test_load_relation_guard.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/load/test_load_relation_guard.py @@ -13,6 +13,7 @@ LoaderRelationGuardE2ETestCase, ) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _SOURCES: str = ( "sources:\n" @@ -67,8 +68,8 @@ def test_given_loader_hard_codes_a_source_when_loading_then_it_warns_like_build( '[connection]\ndatabase = "warehouse.duckdb"\n\n' f"[references]\nenforce_explicit = {str(test_case.enforce_explicit).lower()}\n" ), - "sources/raw.yml": _SOURCES, - "python/loaders/raw.py": _LOADERS, + "sql/sources/raw.yml": _SOURCES, + **node_module_files("python/nodes/loaders/raw.py", _LOADERS), }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/model_migrations/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/model_migrations/helpers.py index d916c9b809..39701737dd 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/model_migrations/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/model_migrations/helpers.py @@ -50,15 +50,15 @@ def write_orders_project(*, tmp_path: Path, name: str, migrate_from: str) -> Pat project_dir: Path = tmp_path / "orders_project" stale: Path - for stale in (project_dir / "models").glob("*.sql"): + for stale in (project_dir / "sql" / "models").glob("*.sql"): stale.unlink() return prepare_inline_project( tmp_path=tmp_path, project_name="orders_project", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": _SOURCES_YML, - f"models/{name}.sql": orders_sql(migrate_from=migrate_from), + "sql/sources/raw.yml": _SOURCES_YML, + f"sql/models/{name}.sql": orders_sql(migrate_from=migrate_from), }, ) @@ -162,8 +162,8 @@ def write_fct_orders_project(*, tmp_path: Path, model_sql: str) -> Path: project_name="orders_project", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": _SOURCES_YML, - "models/fct_orders.sql": model_sql, + "sql/sources/raw.yml": _SOURCES_YML, + "sql/models/fct_orders.sql": model_sql, }, ) @@ -315,15 +315,15 @@ def write_old_name_project( project_dir: Path = tmp_path / "orders_project" stale: Path - for stale in (project_dir / "models").glob("*.sql"): + for stale in (project_dir / "sql" / "models").glob("*.sql"): stale.unlink() for stale in (project_dir / "python").glob("*.py"): stale.unlink() files: dict[str, str] = { "sqlbuild_project.toml": _OLD_NAME_PROJECT_TOML + project_toml_extra, - "sources/raw.yml": _SOURCES_YML, - **{f"models/{name}.sql": sql for name, sql in models.items()}, - **{f"python/{name}": source for name, source in (python_files or {}).items()}, + "sql/sources/raw.yml": _SOURCES_YML, + **{f"sql/models/{name}.sql": sql for name, sql in models.items()}, + **{f"python/nodes/{name}": source for name, source in (python_files or {}).items()}, } return prepare_inline_project( tmp_path=tmp_path, project_name="orders_project", repo_files=files diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/model_migrations/test_old_name_views.py b/tests/e2e/src/sqlbuild/cli/commands/main/model_migrations/test_old_name_views.py index 0dec764406..5ea026afcb 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/model_migrations/test_old_name_views.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/model_migrations/test_old_name_views.py @@ -458,7 +458,7 @@ def test_given_python_sql_reading_old_name_when_checking_then_p008_rejects_it( materialized="table", extra_config=test_case.header ) }, - python_files={"tasks.py": _REPORT_TASK}, + python_files={"report/asset.py": _REPORT_TASK}, ) result: subprocess.CompletedProcess[str] = sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/motherduck/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/motherduck/helpers.py index d41d8bb80a..c997227a2d 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/motherduck/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/motherduck/helpers.py @@ -44,7 +44,7 @@ def prepare_motherduck_build_project(*, tmp_path: Path) -> tuple[Path, str]: project_name="motherduck_build_project", schema_name=schema_name, ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.', materialized table);\n\n" "SELECT 1 AS order_id, 'classic' AS waffle_name UNION ALL " "SELECT 2 AS order_id, 'liege' AS waffle_name" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/plan/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/plan/helpers.py index 4f0d334c39..be2ca23363 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/plan/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/plan/helpers.py @@ -63,7 +63,7 @@ "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ) -_DIAMOND_ROOT_PATH: str = "models/orders_0.sql" +_DIAMOND_ROOT_PATH: str = "sql/models/orders_0.sql" def _incremental_header(*, extra_config: str) -> str: @@ -94,16 +94,16 @@ def prepare_incremental_diamond_project(*, tmp_path: Path) -> Path: files: dict[str, str] = { "sqlbuild_project.toml": _DIAMOND_PROJECT_TOML, - "sources/raw.yml": _DIAMOND_SOURCES_YML, + "sql/sources/raw.yml": _DIAMOND_SOURCES_YML, _DIAMOND_ROOT_PATH: _diamond_root_sql(amount_offset=0), } for layer in range(1, DIAMOND_LAYERS + 1): for side in ("left", "right"): - files[f"models/orders_{side}_{layer}.sql"] = ( + files[f"sql/models/orders_{side}_{layer}.sql"] = ( _incremental_header(extra_config="") + "SELECT order_id, order_date, amount_cents " f'FROM __ref("orders_{layer - 1}")\n' ) - files[f"models/orders_{layer}.sql"] = ( + files[f"sql/models/orders_{layer}.sql"] = ( _incremental_header( extra_config=( f" cursor_inputs (orders_left_{layer} order_date, " @@ -189,16 +189,16 @@ def prepare_missing_source_tables_project(*, tmp_path: Path) -> Path: "[connection]\n" 'database = "warehouse.duckdb"\n' ), - "sources/raw.yml": _MISSING_SOURCE_TABLES_SOURCES_YML, - "models/orders.sql": ( + "sql/sources/raw.yml": _MISSING_SOURCE_TABLES_SOURCES_YML, + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", ' 'materialized table);\n\nSELECT * FROM __source("raw_orders")\n' ), - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (description "Test model customers.", ' 'materialized table);\n\nSELECT * FROM __source("raw_customers")\n' ), - "models/payments.sql": ( + "sql/models/payments.sql": ( 'MODEL (description "Test model payments.", ' 'materialized table);\n\nSELECT * FROM __source("raw_payments")\n' ), @@ -231,7 +231,7 @@ def prepare_missing_source_tables_project(*, tmp_path: Path) -> Path: "MODEL (description 'Daily revenue.', materialized table, migrate_from revenue);\n\n" "SELECT 1 AS amount\n" ) -RECLAIMED_NAME: dict[str, str] = {"models/revenue.sql": _REVENUE_MODEL} +RECLAIMED_NAME: dict[str, str] = {"sql/models/revenue.sql": _REVENUE_MODEL} REMOVABLE_MIGRATION_WARNING: str = "migrate_from can be removed from 'daily_revenue'" NAME_CLAIM_ERROR: str = "model 'revenue' would replace analytics.revenue" @@ -244,15 +244,17 @@ def migrated_project(tmp_path: Path) -> Path: project_name="plan_exit_codes", repo_files={ "sqlbuild_project.toml": _EXIT_CODE_PROJECT_TOML, - "models/revenue.sql": _REVENUE_MODEL, + "sql/models/revenue.sql": _REVENUE_MODEL, }, ) first: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir ) assert first.returncode == 0, first.stdout + first.stderr - (project_dir / "models/revenue.sql").unlink() - (project_dir / "models/daily_revenue.sql").write_text(_DAILY_REVENUE_MODEL, encoding="utf-8") + (project_dir / "sql/models/revenue.sql").unlink() + (project_dir / "sql/models/daily_revenue.sql").write_text( + _DAILY_REVENUE_MODEL, encoding="utf-8" + ) migrated: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_missing_source_tables.py b/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_missing_source_tables.py index d27385997e..4196be0b10 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_missing_source_tables.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_missing_source_tables.py @@ -31,7 +31,7 @@ "error[S405]", "1 source table read by selected resources does not exist in the warehouse", "source 'raw_payments' (raw.payments), read by payments", - "'raw_payments' at sources/raw.yml:18", + "'raw_payments' at sql/sources/raw.yml:18", ), ) ], @@ -86,7 +86,7 @@ def test_given_missing_source_reference_removed_when_building_then_other_sources tmp_path: Path, ) -> None: project_dir: Path = prepare_missing_source_tables_project(tmp_path=tmp_path) - (project_dir / "models" / "payments.sql").unlink() + (project_dir / "sql" / "models" / "payments.sql").unlink() build_result: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir @@ -176,7 +176,7 @@ def test_given_case_variant_source_declaration_when_planning_then_table_is_found sql="CREATE TABLE raw.payments AS SELECT 1 AS payment_id, " "TIMESTAMP '2026-01-03 00:00:00' AS updated_at", ) - sources_path: Path = project_dir / "sources" / "raw.yml" + sources_path: Path = project_dir / "sql" / "sources" / "raw.yml" sources_path.write_text( sources_path.read_text(encoding="utf-8").replace( "schema: raw\n table: orders", "schema: Raw\n table: Orders" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_physical_binding.py b/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_physical_binding.py index 412e4bfbb8..9fc9b24a61 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_physical_binding.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_physical_binding.py @@ -28,15 +28,15 @@ def test_given_physical_source_shape_when_rebinding_then_rejects_downstream_befo (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "duckdb"\n[connection]\ndatabase = "{database}"\n[rules]\nselect = []\n' ) - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n table: raw_orders\n schema: main\n" ) - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text( 'MODEL (description "Test model orders.", materialized table, schema analytics); SELECT * FROM __source("raw_orders")' ) - (tmp_path / "models/report.sql").write_text( + (tmp_path / "sql/models/report.sql").write_text( 'MODEL (description "Test model report.", materialized table, schema analytics); SELECT missing FROM __ref("orders")' ) result: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_removed_interfaces.py b/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_removed_interfaces.py index c0b04aa5ca..8cac69bdef 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_removed_interfaces.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/plan/test_removed_interfaces.py @@ -97,7 +97,7 @@ def test_given_removed_interface_when_running_cli_then_reports_unknown_argument( "removed unchanged MODEL field", "MODEL (description 'Test model.', materialized table, run_despite_unchanged always); SELECT 1 AS order_id", "run_despite_unchanged", - "models/orders.sql", + "sql/models/orders.sql", "", ), RemovedConfigTestCase( @@ -158,7 +158,7 @@ def test_given_removed_config_when_running_cli_then_explains_direct_mode( ) -> None: files: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.', materialized view);\nSELECT 1 AS order_id", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized view);\nSELECT 1 AS order_id", } files[test_case.filename] = test_case.prefix + test_case.content project: Path = prepare_inline_project( @@ -193,8 +193,8 @@ def test_given_prepare_version_hook_when_running_cli_then_rejects_removed_hook( project_name="removed_hook", repo_files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n[connection]\ndatabase = "orders.duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.', materialized custom_order);\nSELECT 1 AS order_id", - "materializations/custom_order.py": ( + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized custom_order);\nSELECT 1 AS order_id", + "python/materializations/custom_order.py": ( "from sqlbuild.executor.custom.models import PrepareVersionContext\n\n" "def prepare_version(ctx: PrepareVersionContext):\n pass\n\n" "def materialize(ctx):\n pass\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/helpers.py index db3dd20cba..5c7054f4d6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/helpers.py @@ -295,12 +295,18 @@ def prepare_postgres_waffle_shop(*, tmp_path: Path, config: dict[str, object]) - schema_name: str = build_unique_schema_name(prefix="sqb_waffle") project_dir: Path = prepare_waffle_shop(tmp_path) - (project_dir / "functions" / "sql" / "customer_orders.sql").unlink(missing_ok=True) - (project_dir / "functions" / "python" / "is_completed_order_py.py").unlink(missing_ok=True) + (project_dir / "sql" / "functions" / "sql" / "customer_orders.sql").unlink(missing_ok=True) + (project_dir / "sql" / "functions" / "python" / "is_completed_order_py.py").unlink( + missing_ok=True + ) (project_dir / "tests" / "unit" / "test_customer_orders_table_fn.sql").unlink(missing_ok=True) - (project_dir / "models" / "marts" / "daily_order_partitioned.sql").unlink(missing_ok=True) + (project_dir / "sql" / "models" / "marts" / "daily_order_partitioned.sql").unlink( + missing_ok=True + ) (project_dir / "tests" / "unit" / "test_is_completed_order_udf.sql").unlink(missing_ok=True) - is_completed_order_path: Path = project_dir / "functions" / "sql" / "is_completed_order.sql" + is_completed_order_path: Path = ( + project_dir / "sql" / "functions" / "sql" / "is_completed_order.sql" + ) is_completed_order_path.write_text( is_completed_order_path.read_text(encoding="utf-8") .replace("STRING", "TEXT") @@ -308,7 +314,7 @@ def prepare_postgres_waffle_shop(*, tmp_path: Path, config: dict[str, object]) - encoding="utf-8", ) - fact_orders_path: Path = project_dir / "models" / "marts" / "fact_orders.sql" + fact_orders_path: Path = project_dir / "sql" / "models" / "marts" / "fact_orders.sql" fact_orders_path.write_text( fact_orders_path.read_text(encoding="utf-8").replace( '__udf("is_completed_order_py")(o.status) AS is_completed_order_py,', @@ -509,18 +515,18 @@ def write_migration_project( project_name="postgres_model_migrations", schema_name=schema_name, config=config ) + _JANITOR_CONFIG, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" f" schema: {raw_schema_name}\n" " table: raw_orders\n" ), } project_dir: Path = tmp_path / "postgres_model_migrations" - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" stale: Path for stale in models_dir.glob("*.sql"): stale.unlink() - files.update({f"models/{name}.sql": sql for name, sql in models.items()}) + files.update({f"sql/models/{name}.sql": sql for name, sql in models.items()}) return prepare_inline_project( tmp_path=tmp_path, project_name="postgres_model_migrations", repo_files=files ) @@ -887,7 +893,7 @@ def build_long_model_name_project_files( return { "sqlbuild_project.toml": project_toml + 'contract = "enforced"\n', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n" " description: Raw orders.\n" @@ -899,7 +905,7 @@ def build_long_model_name_project_files( " - name: amount\n" " type: INTEGER\n" ), - f"models/{model_name}.sql": ( + f"sql/models/{model_name}.sql": ( "MODEL (\n" " description 'Order totals for a long-named model.',\n" " materialized table,\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_postgres.py b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_postgres.py index c8acd594a2..75fb4c941b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_postgres.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_postgres.py @@ -62,6 +62,7 @@ stringify_warehouse_rows, write_dbt_profile_orders_model, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.dbt @@ -258,15 +259,15 @@ def test_given_python_result_when_running_check_on_postgres_then_persists_node_r schema_name=schema_name, config=postgres_e2e_config, ), - "python/tasks/results.py": ( + "python/nodes/tasks/results/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_result(ctx):\n" " '''Test task produce_result.'''\n return ctx.result(payload={'value': 42}, metadata={'source': 'postgres'})\n" ), - "python/checks/results.py": ( + "python/nodes/checks/results/checks.py": ( "from sqlbuild.checks import check\n" - "from python.tasks.results import produce_result\n\n" + "from python.nodes.tasks.results.asset import produce_result\n\n" "@check(depends_on=produce_result)\n" "def check_produce_result(ctx):\n" " '''Test check check_produce_result.'''\n return ctx.result_of(node_function=produce_result).payload['value'] == 42\n" @@ -388,7 +389,7 @@ def test_given_source_deferral_env_when_building_on_postgres_then_reads_prod_and prod_schema_name=prod_schema_name, config=postgres_e2e_config, ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -399,13 +400,13 @@ def test_given_source_deferral_env_when_building_on_postgres_then_reads_prod_and " - name: status\n" " type: VARCHAR\n" ), - "python/loaders/raw_orders.py": ( + "python/nodes/loaders/raw_orders/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 7, 'status': 'loaded-dev'}]\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT order_id, status FROM __source("raw_orders")' ), }, @@ -483,7 +484,7 @@ def test_given_partial_source_type_enforcement_when_building_on_postgres_then_ca schema_name=schema_name, config=postgres_e2e_config, ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" f" schema: {schema_name}\n" @@ -492,7 +493,7 @@ def test_given_partial_source_type_enforcement_when_building_on_postgres_then_ca " - name: order_id\n" " type: INTEGER\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\n" 'SELECT order_id, status, amount_cents FROM __source("raw_orders")' ), @@ -864,22 +865,25 @@ def test_given_chained_loader_project_when_loading_on_postgres_then_runs_loader_ " - name: status\n" " type: VARCHAR\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " cursor = ctx.query(\n" - " f'SELECT event_id FROM {events.destination} ORDER BY event_id'\n" - " )\n" - " rows = cursor.fetchall()\n" - " return [{'event_id': row[0], 'status': 'loaded'} for row in rows]\n" - ), + node_files={ + **node_module_files( + "python/nodes/loaders/source_rows.py", + "from sqlbuild.loaders import loader\n\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" + " cursor = ctx.query(\n" + " f'SELECT event_id FROM {events.destination} ORDER BY event_id'\n" + " )\n" + " rows = cursor.fetchall()\n" + " return [{'event_id': row[0], 'status': 'loaded'} for row in rows]\n", + ) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -1046,7 +1050,9 @@ def test_given_intermediate_strategy_project_when_loading_twice_on_postgres_then " - name: amount\n" " type: INTEGER\n" ), - loader_py=test_case.loader_py, + node_files={ + **node_module_files("python/nodes/loaders/source_rows.py", test_case.loader_py) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -1159,7 +1165,7 @@ def test_given_snapshot_project_when_building_on_postgres_then_scd2_history_is_v expected_historical_check_rows=test_case.expected_historical_check_rows, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="blocked", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -1183,7 +1189,7 @@ def test_given_snapshot_project_when_building_on_postgres_then_scd2_history_is_v expected_rows=test_case.expected_current_rows_after_initial_build, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="pro", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -1264,16 +1270,16 @@ def test_given_existing_snapshot_targets_when_building_on_postgres_then_apply_sq ) assert initial_result.returncode == 0, initial_result.stdout + initial_result.stderr - (project_dir / "models" / "current_check_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_check_customers.sql").write_text( build_current_check_customers_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "current_delete_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_delete_customers.sql").write_text( build_current_delete_customers_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "historical_timestamp_extracts.sql").write_text( + (project_dir / "sql" / "models" / "historical_timestamp_extracts.sql").write_text( build_historical_timestamp_extracts_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "historical_check_daily.sql").write_text( + (project_dir / "sql" / "models" / "historical_check_daily.sql").write_text( build_historical_check_daily_model_sql(changed=True), encoding="utf-8" ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_temporary_test_functions.py b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_temporary_test_functions.py index d974db8467..4c9f634eb0 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_temporary_test_functions.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_temporary_test_functions.py @@ -17,7 +17,7 @@ ) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb -_FUNCTION_PATH: str = "functions/sql/is_completed_order.sql" +_FUNCTION_PATH: str = "sql/functions/sql/is_completed_order.sql" _FUNCTION_HEADER: str = ( "FUNCTION (description 'Whether an order status counts as completed.', " "arguments (order_status VARCHAR), returns BOOLEAN);\n" @@ -63,11 +63,11 @@ def test_given_edited_function_when_testing_then_option_chooses_the_definition( project_name="orders_temporary_functions", repo_files={ "sqlbuild_project.toml": project_toml, - "models/order_statuses.sql": ( + "sql/models/order_statuses.sql": ( "MODEL (description 'Test model order_statuses.', materialized table);\n" "SELECT 'completed' AS order_status\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n" 'SELECT order_status, __udf("is_completed_order")(order_status) AS is_completed ' 'FROM __ref("order_statuses")\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/providers/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/providers/_test_types.py index f859efd61e..206af7f9e8 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/providers/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/providers/_test_types.py @@ -205,3 +205,10 @@ class ChangedCantRunTestCase: expected_cant_run_nodes: list[str] expected_cant_run_readers: list[str] expected_unchanged: list[str] + + +@dataclass(frozen=True) +class SinkTeardownFailureE2ETestCase: + description: str + teardown_error: str + expected_warning: str diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_env_file.py b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_env_file.py index a040f788e7..4d42cdb34c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_env_file.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_env_file.py @@ -13,6 +13,7 @@ prepare_inline_project, run_sqb, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files TOKEN_VARIABLE: str = "ENVFILE_E2E_TOKEN" REGION_VARIABLE: str = "ENVFILE_E2E_REGION" @@ -21,7 +22,7 @@ PROJECT_HEADER: str = 'name = "env_file_project"\nadapter = "duckdb"\n' CONNECTION_TABLE: str = '\n[connection]\ndatabase = "env_file_project.duckdb"\n' PROVIDER_FILES: dict[str, str] = { - "providers/settings_api.py": dedent( + "python/providers/settings_api.py": dedent( f""" from pydantic import Field, SecretStr from sqlbuild.providers import Provider @@ -34,12 +35,14 @@ class SettingsApi(Provider): """ ).strip() + "\n", - "python/assets/report_region.py": dedent( - """ + **node_module_files( + "python/nodes/assets/report_region.py", + dedent( + """ import os from pathlib import Path - from providers.settings_api import SettingsApi + from python.providers.settings_api import SettingsApi from sqlbuild.assets import asset @@ -48,8 +51,9 @@ def report_region(ctx, settings_api: SettingsApi): '''Test asset report_region.''' Path(os.environ["MARKER_PATH"]).write_text(settings_api.region, encoding="utf-8") """ - ).strip() - + "\n", + ).strip() + + "\n", + ), } ENV_FILE: str = ( f"# provider settings\n{TOKEN_VARIABLE}={TOKEN_VALUE}\n{REGION_VARIABLE}=from-file\n" @@ -111,7 +115,7 @@ def report_region(ctx, settings_api: SettingsApi): ), EnvFileE2ETestCase( description="the selected target's env_file replaces the project default", - project_toml='\n[targets.uat]\nenv_file = "config/uat.env"\n', + project_toml='extra_paths = ["config/"]\n\n[targets.uat]\nenv_file = "config/uat.env"\n', files={ ".env": (ENV_FILE, PRIVATE), "config/uat.env": ( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_event_exporters.py b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_event_exporters.py index 3ccbbb722c..ae8ebabed3 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_event_exporters.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_event_exporters.py @@ -16,10 +16,12 @@ NoExporterCommandE2ETestCase, ReadOnlyProviderE2ETestCase, SharedSinkProviderE2ETestCase, + SinkTeardownFailureE2ETestCase, SlowSinkExitE2ETestCase, SnowflakeKeyWarningE2ETestCase, ) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -57,7 +59,7 @@ def test_given_provider_exporter_when_building_then_receives_redacted_events_bef """ ).strip() + "\n", - "providers/event_sink.py": dedent( + "python/providers/event_sink.py": dedent( """ import json import os @@ -87,10 +89,10 @@ def teardown(self): """ ).strip() + "\n", - "sinks/events.py": dedent( + "python/event_sinks/events.py": dedent( """ - from providers.event_sink import EventSink - from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink + from python.providers.event_sink import EventSink + from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink import os from pathlib import Path @@ -109,7 +111,7 @@ def failing_exporter(event: LifecycleEvent, event_sink: EventSink) -> None: """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table); @@ -177,18 +179,18 @@ def test_given_command_output_sink_when_compiling_then_multiline_chunks_reconstr """ ).strip() + "\n", - "sinks/output.py": dedent( + "python/event_sinks/output.py": dedent( """ import os from pathlib import Path - from sqlbuild.sinks import ( + from sqlbuild.event_sinks import ( CommandOutputRecord, - command_output_sink, + command_output_event_sink, command_output_to_json, ) - @command_output_sink + @command_output_event_sink def export_output(record: CommandOutputRecord) -> None: path = Path(os.environ["COMMAND_OUTPUT_PATH"]) with path.open("a", encoding="utf-8") as stream: @@ -196,7 +198,7 @@ def export_output(record: CommandOutputRecord) -> None: """ ).strip() + "\n", - "models/orders.sql": "MODEL (description 'Test model orders.', materialized view);\n\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized view);\n\nSELECT 1 AS order_id\n", }, ) @@ -238,7 +240,7 @@ def test_given_configured_provider_and_sink_when_lineage_runs_then_skips_extensi project_name="read_only_lineage_project", repo_files={ "sqlbuild_project.toml": 'name = "read_only_lineage_project"\nadapter = "duckdb"\n', - "providers/output.py": ( + "python/providers/output.py": ( "from pathlib import Path\n" "from sqlbuild.providers import Provider\n" "class OutputProvider(Provider):\n" @@ -250,14 +252,14 @@ def test_given_configured_provider_and_sink_when_lineage_runs_then_skips_extensi " def teardown(self):\n" " pass\n" ), - "sinks/output.py": ( - "from providers.output import OutputProvider\n" - "from sqlbuild.sinks import command_output_sink\n" - "@command_output_sink\n" + "python/event_sinks/output.py": ( + "from python.providers.output import OutputProvider\n" + "from sqlbuild.event_sinks import command_output_event_sink\n" + "@command_output_event_sink\n" "def export_output(record, output_provider: OutputProvider):\n" " output_provider.write(record)\n" ), - "models/orders.sql": "MODEL (description 'Test model orders.', materialized view);\n\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized view);\n\nSELECT 1 AS order_id\n", }, ) @@ -298,17 +300,17 @@ def test_given_no_exporters_and_exploding_provider_when_non_provider_command_run database = "no_exporter_project.duckdb" """ ).lstrip(), - "providers/exploding.py": ( + "python/providers/exploding.py": ( "from pathlib import Path\n" f"Path({str(marker_path)!r}).write_text('imported', encoding='utf-8')\n" "raise RuntimeError('provider must not import')\n" ), - "sinks/helpers.py": ( + "python/event_sinks/helpers.py": ( "from pathlib import Path\n" f"Path({str(helper_marker_path)!r}).write_text('imported', encoding='utf-8')\n" "def encode(value):\n return value\n" ), - "models/example.sql": "MODEL (description 'Test model example.', materialized view);\n\nSELECT 1 AS value\n", + "sql/models/example.sql": "MODEL (description 'Test model example.', materialized view);\n\nSELECT 1 AS value\n", }, ) @@ -336,7 +338,7 @@ def test_given_no_exporters_and_exploding_provider_when_non_provider_command_run "Warning: lifecycle event export was incomplete: 0 of {accepted} event " "deliveries dropped, 1 failed (sink 'failing_on_errors'). Check sink health: a " "sink call slower than 1s drops that sink's events until it returns; events " - "still queued at exit need a longer sinks.lifecycle.shutdown_timeout." + "still queued at exit need a longer event_sinks.lifecycle.shutdown_timeout." ), ), ), @@ -348,7 +350,7 @@ def test_given_filtered_and_failing_sinks_when_build_fails_then_delivery_and_war monkeypatch: pytest.MonkeyPatch, ) -> None: output_dir: Path = tmp_path / "filtered" - output_dir.mkdir() + output_dir.mkdir(parents=True) monkeypatch.setenv("FILTERED_EXPORT_DIR", str(output_dir)) project_dir: Path = prepare_inline_project( tmp_path=tmp_path, @@ -362,16 +364,16 @@ def test_given_filtered_and_failing_sinks_when_build_fails_then_delivery_and_war [connection] database = "filtered_sink_project.duckdb" - [sinks.lifecycle.named.errors_only] + [event_sinks.lifecycle.named.errors_only] min_severity = "error" """ ).lstrip(), - "sinks/filtered.py": dedent( + "python/event_sinks/filtered.py": dedent( """ import os from pathlib import Path - from sqlbuild.sinks import LifecycleEvent, LifecycleEventKind, lifecycle_event_sink + from sqlbuild.event_sinks import LifecycleEvent, LifecycleEventKind, lifecycle_event_sink def _record(sink: str, event: LifecycleEvent) -> None: @@ -395,11 +397,11 @@ def failing(event: LifecycleEvent) -> None: raise RuntimeError("destination detail must not be reported") """ ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\n" "SELECT 1 AS order_id\n" ), - "models/broken_orders.sql": ( + "sql/models/broken_orders.sql": ( "MODEL (description 'Test model broken orders.', materialized table);\n\n" 'SELECT missing_column FROM __ref("orders")\n' ), @@ -457,11 +459,11 @@ def test_given_sink_call_in_flight_at_shutdown_when_process_exits_then_teardown_ [connection] database = "slow_sink_exit_project.duckdb" - [sinks.lifecycle] + [event_sinks.lifecycle] shutdown_timeout = "0s" """ ).lstrip(), - "providers/destination.py": dedent( + "python/providers/destination.py": dedent( """ import os import sys @@ -497,10 +499,10 @@ def teardown(self) -> None: stream.write("teardown finished\\n") """ ).lstrip(), - "sinks/publish.py": dedent( + "python/event_sinks/publish.py": dedent( """ - from providers.destination import Destination - from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink + from python.providers.destination import Destination + from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink @lifecycle_event_sink @@ -509,7 +511,7 @@ def publish_lifecycle(event: LifecycleEvent, destination: Destination) -> None: destination.publish() """ ).lstrip(), - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL ( description "Test model orders.", @@ -588,18 +590,18 @@ def test_given_sink_and_task_sharing_a_provider_when_building_then_it_is_set_up_ 'name = "shared_sink_provider_project"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "shared_sink_provider_project.duckdb"\n' ), - f"providers/{test_case.unused_provider_name}.py": SHARED_PROVIDER.format( + f"python/providers/{test_case.unused_provider_name}.py": SHARED_PROVIDER.format( class_name="UnusedProvider", name=test_case.unused_provider_name ) + "\n", - "providers/z_shared.py": SHARED_PROVIDER.format( + "python/providers/z_shared.py": SHARED_PROVIDER.format( class_name="SharedProvider", name="z_shared" ) + "\n", - "sinks/events.py": dedent( + "python/event_sinks/events.py": dedent( """ - from providers.z_shared import SharedProvider - from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink + from python.providers.z_shared import SharedProvider + from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink @lifecycle_event_sink @@ -608,9 +610,11 @@ def export_event(event: LifecycleEvent, shared_provider: SharedProvider) -> None """ ).strip() + "\n", - "python/tasks/uses_shared.py": dedent( - """ - from providers.z_shared import SharedProvider + **node_module_files( + "python/nodes/tasks/uses_shared.py", + dedent( + """ + from python.providers.z_shared import SharedProvider from sqlbuild.assets import asset @@ -619,8 +623,9 @@ def uses_shared(ctx, shared_provider: SharedProvider): '''Test task uses_shared.''' del ctx, shared_provider """ - ).strip() - + "\n", + ).strip() + + "\n", + ), }, ) @@ -654,11 +659,11 @@ def test_given_snowflake_keys_and_a_sink_provider_when_running_then_warns_once( 'name = "snowflake_keys_project"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "snowflake_keys_project.duckdb"\nwarehouse = "orders_wh"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\n" "SELECT 1 AS order_id\n" ), - "providers/probe.py": dedent( + "python/providers/probe.py": dedent( """ from sqlbuild.providers import Provider @@ -671,10 +676,10 @@ def setup(self, ctx): """ ).strip() + "\n", - "sinks/events.py": dedent( + "python/event_sinks/events.py": dedent( """ - from providers.probe import Probe - from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink + from python.providers.probe import Probe + from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink @lifecycle_event_sink @@ -695,3 +700,56 @@ def export_event(event: LifecycleEvent, probe: Probe) -> None: assert (result.stdout + result.stderr).count( "Snowflake-like keys: warehouse." ) == test_case.expected_warnings, result.stderr + + +@pytest.mark.parametrize( + "test_case", + ( + SinkTeardownFailureE2ETestCase( + description="a sink provider whose teardown raises", + teardown_error="flush failed with destination detail", + expected_warning=( + "sink provider teardown failed ('flaky_sink' (FlakySink) raised RuntimeError); " + "events the provider still held may not have been delivered." + ), + ), + ), + ids=lambda case: case.description, +) +def test_given_sink_provider_teardown_raises_when_command_ends_then_the_export_warning_reports_it( + test_case: SinkTeardownFailureE2ETestCase, + tmp_path: Path, +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="sink_teardown_project", + repo_files={ + "sqlbuild_project.toml": ( + 'name = "sink_teardown_project"\nadapter = "duckdb"\n\n' + '[connection]\ndatabase = "sink_teardown_project.duckdb"\n' + ), + "python/providers/flaky_sink.py": ( + "from sqlbuild.providers import Provider\n\n\n" + "class FlakySink(Provider):\n" + ' """Test provider FlakySink."""\n\n' + " def teardown(self):\n" + f' raise RuntimeError("{test_case.teardown_error}")\n' + ), + "python/event_sinks/events.py": ( + "from python.providers.flaky_sink import FlakySink\n" + "from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink\n\n\n" + "@lifecycle_event_sink\n" + "def export_event(event: LifecycleEvent, flaky_sink: FlakySink) -> None:\n" + " del event, flaky_sink\n" + ), + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + }, + ) + + result: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "build"), project_dir=project_dir + ) + + assert result.returncode == 0, result.stdout + result.stderr + assert test_case.expected_warning in result.stderr, result.stderr + assert test_case.teardown_error not in result.stdout + result.stderr diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_provider_secrets.py b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_provider_secrets.py index fcf0bcd574..1fef34ca59 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_provider_secrets.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_provider_secrets.py @@ -25,6 +25,7 @@ prepare_inline_project, run_sqb, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files SECRET_VARIABLE: str = "SECRETS_E2E_API_KEY" @@ -40,7 +41,7 @@ import os from pathlib import Path - from providers.api import ApiProvider + from python.providers.api import ApiProvider from sqlbuild.{decorator}s import {decorator} @@ -58,7 +59,7 @@ def {name}(ctx{parameter}): PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": PROJECT_TOML, - "providers/api.py": dedent( + "python/providers/api.py": dedent( f""" from pydantic import Field, SecretStr from sqlbuild.providers import Provider @@ -71,27 +72,37 @@ class ApiProvider(Provider): """ ).strip() + "\n", - "python/tasks/uses_api.py": MARKING_NODE.format( - decorator="asset", arguments="", name="uses_api", parameter=USES_API, body="" + **node_module_files( + "python/nodes/tasks/uses_api.py", + MARKING_NODE.format( + decorator="asset", arguments="", name="uses_api", parameter=USES_API, body="" + ), ), - "python/tasks/no_api.py": MARKING_NODE.format( - decorator="asset", arguments="", name="no_api", parameter="", body="" + **node_module_files( + "python/nodes/tasks/no_api.py", + MARKING_NODE.format(decorator="asset", arguments="", name="no_api", parameter="", body=""), ), - "python/checks/api_check.py": MARKING_NODE.format( - decorator="check", - arguments="(depends_on=())", - name="api_check", - parameter=USES_API, - body=" return True\n", + **node_module_files( + "python/nodes/checks/api_check.py", + MARKING_NODE.format( + decorator="check", + arguments="(depends_on=())", + name="api_check", + parameter=USES_API, + body=" return True\n", + ), ), - "python/loaders/raw_api_events.py": MARKING_NODE.format( - decorator="loader", - arguments="", - name="raw_api_events", - parameter=USES_API, - body=' return [{"event_id": 1}]\n', + **node_module_files( + "python/nodes/loaders/raw_api_events.py", + MARKING_NODE.format( + decorator="loader", + arguments="", + name="raw_api_events", + parameter=USES_API, + body=' return [{"event_id": 1}]\n', + ), ), - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_api_events @@ -107,7 +118,7 @@ class ApiProvider(Provider): } SECRET_FREE_SINK: dict[str, str] = { - "providers/event_log.py": dedent( + "python/providers/event_log.py": dedent( """ from sqlbuild.providers import Provider @@ -118,10 +129,10 @@ class EventLog(Provider): """ ).strip() + "\n", - "sinks/events.py": dedent( + "python/event_sinks/events.py": dedent( """ - from providers.event_log import EventLog - from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink + from python.providers.event_log import EventLog + from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink @lifecycle_event_sink @@ -132,10 +143,10 @@ def log_event(event: LifecycleEvent, event_log: EventLog) -> None: + "\n", } API_SINK: dict[str, str] = { - "sinks/events.py": dedent( + "python/event_sinks/events.py": dedent( """ - from providers.api import ApiProvider - from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink + from python.providers.api import ApiProvider + from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink @lifecycle_event_sink @@ -146,7 +157,7 @@ def export_event(event: LifecycleEvent, api_provider: ApiProvider) -> None: + "\n", } READING_MODEL: dict[str, str] = { - "models/api_events.sql": ( + "sql/models/api_events.sql": ( "MODEL (description 'Test model api_events.', materialized table);\n\n" 'SELECT event_id FROM __source("raw_api_events")\n' ), @@ -169,7 +180,7 @@ def export_event(event: LifecycleEvent, api_provider: ApiProvider) -> None: SET_SECRET_VALUE: str = "signing-key-canary" # One secret is missing and one is set, and setting up the provider leaves a mark. MARKING_PROVIDER: dict[str, str] = { - "providers/api.py": dedent( + "python/providers/api.py": dedent( f""" import os from pathlib import Path @@ -191,7 +202,7 @@ def setup(self, ctx): + "\n", } REQUIRED_SETTING: dict[str, str] = { - "providers/region.py": ( + "python/providers/region.py": ( "from pydantic import Field\n" "from sqlbuild.providers import Provider\n\n\n" "class RegionProvider(Provider):\n" @@ -200,13 +211,15 @@ def setup(self, ctx): ), } POST_BUILD_CHECK: dict[str, str] = { - "python/checks/no_api_check.py": dedent( - """ + **node_module_files( + "python/nodes/checks/no_api_check.py", + dedent( + """ import os from pathlib import Path - from providers.api import ApiProvider - from python.tasks.no_api import no_api + from python.providers.api import ApiProvider + from python.nodes.tasks.no_api import no_api from sqlbuild.checks import check @@ -217,12 +230,13 @@ def no_api_check(ctx, api_provider: ApiProvider): marker.write("no_api_check\\n") return True """ - ).strip() - + "\n", + ).strip() + + "\n", + ), } MISSING_ERROR: str = ( - f"provider 'api_provider' (providers/api.py) is missing secret {SECRET_VARIABLE}" + f"provider 'api_provider' (python/providers/api.py) is missing secret {SECRET_VARIABLE}" ) ALLOWED_NOTICE: str = "1 provider has missing secrets (allowed): api_provider" SELECTION_ERROR: str = ( @@ -336,7 +350,7 @@ def no_api_check(ctx, api_provider: ApiProvider): extra_repo_files=REQUIRED_SETTING, expected_exit_code=1, expected_output_fragments=( - "provider 'region_provider' (providers/region.py) is missing secret SECRETS_E2E_REGION", + "provider 'region_provider' (python/providers/region.py) is missing secret SECRETS_E2E_REGION", ), expected_marker_entries=(), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_providers.py b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_providers.py index ab7f0b5a33..9cede979e7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_providers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_providers.py @@ -29,6 +29,7 @@ query_duckdb, run_sqb, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files PROVIDER_FAILURE_PROJECT_TOML: str = ( dedent( @@ -119,7 +120,7 @@ def test_given_provider_usages_when_planning_then_text_and_json_include_selected """ ).strip() + "\n", - "providers/marker.py": dedent( + "python/providers/marker.py": dedent( """ from sqlbuild.providers import Provider @@ -130,9 +131,11 @@ class MarkerProvider(Provider): """ ).strip() + "\n", - "python/loaders/raw_orders.py": dedent( - """ - from providers.marker import MarkerProvider + **node_module_files( + "python/nodes/loaders/raw_orders.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.loaders import loader @@ -141,11 +144,14 @@ def raw_orders(marker_provider: MarkerProvider): '''Test loader raw_orders.''' return [{"order_id": 1, "amount": 10}] """ - ).strip() - + "\n", - "python/tasks/publish_orders.py": dedent( - """ - from providers.marker import MarkerProvider + ).strip() + + "\n", + ), + **node_module_files( + "python/nodes/tasks/publish_orders.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.assets import asset @@ -154,11 +160,12 @@ def publish_orders(marker_provider: MarkerProvider): '''Test task publish_orders.''' marker_provider.label """ - ).strip() - + "\n", - "hooks/python/mark_pre.py": dedent( + ).strip() + + "\n", + ), + "sql/hooks/python/mark_pre.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.hooks import hook @@ -169,9 +176,9 @@ def mark_pre(marker_provider: MarkerProvider): """ ).strip() + "\n", - "materializations/copy_table.py": dedent( + "python/materializations/copy_table.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.executor.custom.models import ( MaterializationContext, MaterializationResult, @@ -188,7 +195,7 @@ def materialize( """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -203,7 +210,7 @@ def materialize( """ ).strip() + "\n", - "models/stg_orders.sql": dedent( + "sql/models/stg_orders.sql": dedent( """ MODEL (description "Test model stg_orders.", materialized copy_table, @@ -297,7 +304,7 @@ def test_given_project_with_provider_when_running_commands_then_provider_is_inje """ ).strip() + "\n", - "providers/marker.py": dedent( + "python/providers/marker.py": dedent( """ from pathlib import Path @@ -323,9 +330,11 @@ def mark(self, value): """ ).strip() + "\n", - "python/tasks/provider_task.py": dedent( - """ - from providers.marker import MarkerProvider + **node_module_files( + "python/nodes/tasks/provider_task.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.assets import asset @@ -334,11 +343,14 @@ def provider_task(ctx, marker_provider: MarkerProvider): '''Test task provider_task.''' marker_provider.mark(f"run_task:{marker_provider.label}") """ - ).strip() - + "\n", - "python/assets/provider_asset.py": dedent( - """ - from providers.marker import MarkerProvider + ).strip() + + "\n", + ), + **node_module_files( + "python/nodes/assets/provider_asset.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.assets import asset @@ -347,11 +359,14 @@ def provider_asset(ctx, marker_provider: MarkerProvider): '''Test asset provider_asset.''' marker_provider.mark(f"build_asset:{marker_provider.label}") """ - ).strip() - + "\n", - "python/checks/provider_check.py": dedent( - """ - from providers.marker import MarkerProvider + ).strip() + + "\n", + ), + **node_module_files( + "python/nodes/checks/provider_check.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.checks import check @@ -361,11 +376,14 @@ def provider_check(ctx, marker_provider: MarkerProvider): marker_provider.mark(f"check:{marker_provider.label}") return True """ - ).strip() - + "\n", - "python/loaders/provider_loader.py": dedent( - """ - from providers.marker import MarkerProvider + ).strip() + + "\n", + ), + **node_module_files( + "python/nodes/loaders/provider_loader.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.loaders import loader @@ -375,9 +393,10 @@ def raw_provider_events(ctx, marker_provider: MarkerProvider): marker_provider.mark(f"load:{marker_provider.label}") return [{"event_id": 1, "label": marker_provider.label}] """ - ).strip() - + "\n", - "sources/raw.yml": dedent( + ).strip() + + "\n", + ), + "sql/sources/raw.yml": dedent( """ sources: - name: raw_provider_events @@ -444,10 +463,12 @@ def raw_provider_events(ctx, marker_provider: MarkerProvider): ), repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "python/tasks/failing_task.py": dedent( - """ - from providers.marker import MarkerProvider + "python/providers/marker.py": PROVIDER_MARKER_FILE, + **node_module_files( + "python/nodes/tasks/failing_task.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.assets import asset @@ -457,8 +478,9 @@ def failing_task(ctx, marker_provider: MarkerProvider): marker_provider.mark("task") raise RuntimeError("intentional provider failure") """ - ).strip() - + "\n", + ).strip() + + "\n", + ), }, expected_marker_entries=("setup", "task", "teardown"), ), @@ -467,10 +489,12 @@ def failing_task(ctx, marker_provider: MarkerProvider): command=("--no-color", "build", "--select", "failing_asset"), repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "python/assets/failing_asset.py": dedent( - """ - from providers.marker import MarkerProvider + "python/providers/marker.py": PROVIDER_MARKER_FILE, + **node_module_files( + "python/nodes/assets/failing_asset.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.assets import asset @@ -480,8 +504,9 @@ def failing_asset(ctx, marker_provider: MarkerProvider): marker_provider.mark("asset") raise RuntimeError("intentional provider failure") """ - ).strip() - + "\n", + ).strip() + + "\n", + ), }, expected_marker_entries=("setup", "asset", "teardown"), ), @@ -490,10 +515,12 @@ def failing_asset(ctx, marker_provider: MarkerProvider): command=("--no-color", "check", "--select", "failing_check"), repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "python/checks/failing_check.py": dedent( - """ - from providers.marker import MarkerProvider + "python/providers/marker.py": PROVIDER_MARKER_FILE, + **node_module_files( + "python/nodes/checks/failing_check.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.checks import check @@ -503,8 +530,9 @@ def failing_check(ctx, marker_provider: MarkerProvider): marker_provider.mark("check") raise RuntimeError("intentional provider failure") """ - ).strip() - + "\n", + ).strip() + + "\n", + ), }, expected_marker_entries=("setup", "check", "teardown"), ), @@ -513,10 +541,12 @@ def failing_check(ctx, marker_provider: MarkerProvider): command=("--no-color", "load", "--select", "raw_provider_events"), repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "python/loaders/failing_loader.py": dedent( - """ - from providers.marker import MarkerProvider + "python/providers/marker.py": PROVIDER_MARKER_FILE, + **node_module_files( + "python/nodes/loaders/failing_loader.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.loaders import loader @@ -526,9 +556,10 @@ def raw_provider_events(ctx, marker_provider: MarkerProvider): marker_provider.mark("load") raise RuntimeError("intentional provider failure") """ - ).strip() - + "\n", - "sources/raw.yml": dedent( + ).strip() + + "\n", + ), + "sql/sources/raw.yml": dedent( """ sources: - name: raw_provider_events @@ -595,10 +626,12 @@ def test_given_provider_project_when_running_compile_or_plan_then_provider_setup project_name="provider_side_effect_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "python/tasks/provider_task.py": dedent( - """ - from providers.marker import MarkerProvider + "python/providers/marker.py": PROVIDER_MARKER_FILE, + **node_module_files( + "python/nodes/tasks/provider_task.py", + dedent( + """ + from python.providers.marker import MarkerProvider from sqlbuild.assets import asset @@ -607,9 +640,10 @@ def provider_task(ctx, marker_provider: MarkerProvider): '''Test task provider_task.''' marker_provider.mark("task") """ - ).strip() - + "\n", - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + ).strip() + + "\n", + ), + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, ) @@ -630,7 +664,7 @@ def provider_task(ctx, marker_provider: MarkerProvider): description="alias-imported provider annotation gets CLI diagnostic", command=("--no-color", "build", "--no-tests", "--no-audits", "--select", "alias_task"), expected_error_fragment=( - "Import project providers using the project-root providers package path" + "Import project providers using the project path of the providers package" ), ) ], @@ -646,16 +680,18 @@ def test_given_alias_imported_provider_annotation_when_running_command_then_cli_ project_name="provider_alias_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "python/tasks/alias_task.py": dedent( - """ + "python/providers/marker.py": PROVIDER_MARKER_FILE, + **node_module_files( + "python/nodes/tasks/alias_task.py", + dedent( + """ import importlib.util import sys from pathlib import Path from sqlbuild.assets import asset - provider_path = Path(__file__).parents[2] / "providers" / "marker.py" + provider_path = Path(__file__).parents[3] / "python" / "providers" / "marker.py" spec = importlib.util.spec_from_file_location("alias_marker", provider_path) alias_marker = importlib.util.module_from_spec(spec) sys.modules["alias_marker"] = alias_marker @@ -669,8 +705,9 @@ def alias_task(ctx, marker_provider: AliasMarkerProvider): '''Test task alias_task.''' marker_provider.mark("task") """ - ).strip() - + "\n", + ).strip() + + "\n", + ), }, ) @@ -706,10 +743,10 @@ def test_given_custom_materialization_with_provider_when_it_fails_then_provider_ project_name="provider_custom_materialization_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "materializations/marker_mat.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "python/materializations/marker_mat.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.executor.custom.models import MaterializationContext @@ -723,7 +760,7 @@ def materialize( """ ).strip() + "\n", - "models/orders.sql": "MODEL (description 'Test model orders.', materialized marker_mat);\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized marker_mat);\n\nSELECT 1 AS id\n", }, ) @@ -769,7 +806,7 @@ def test_given_concurrent_provider_backed_nodes_when_running_command_then_share_ """ ).strip() + "\n", - "providers/concurrent_marker.py": dedent( + "python/providers/concurrent_marker.py": dedent( f""" from pathlib import Path from time import sleep @@ -798,9 +835,11 @@ def mark(self, label): """ ).strip() + "\n", - "python/loaders/events.py": dedent( - """ - from providers.concurrent_marker import ConcurrentMarkerProvider + **node_module_files( + "python/nodes/loaders/events.py", + dedent( + """ + from python.providers.concurrent_marker import ConcurrentMarkerProvider from sqlbuild.loaders import loader @@ -817,9 +856,10 @@ def raw_beta(ctx, concurrent_marker_provider: ConcurrentMarkerProvider): concurrent_marker_provider.mark("beta") return [{"event_id": 2}] """ - ).strip() - + "\n", - "sources/raw.yml": dedent( + ).strip() + + "\n", + ), + "sql/sources/raw.yml": dedent( """ sources: - name: raw_alpha @@ -839,10 +879,10 @@ def raw_beta(ctx, concurrent_marker_provider: ConcurrentMarkerProvider): """ ).strip() + "\n", - "models/fact_alpha.sql": ( + "sql/models/fact_alpha.sql": ( 'MODEL (description "Test model fact_alpha.", materialized table);\n\nSELECT * FROM __source("raw_alpha")\n' ), - "models/fact_beta.sql": ( + "sql/models/fact_beta.sql": ( 'MODEL (description "Test model fact_beta.", materialized table);\n\nSELECT * FROM __source("raw_beta")\n' ), }, @@ -895,10 +935,10 @@ def test_given_python_hooks_with_provider_when_building_then_hooks_use_provider_ project_name="provider_hook_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "hooks/python/marker_hooks.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "sql/hooks/python/marker_hooks.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.hooks import hook @@ -917,7 +957,7 @@ def mark_post(hook_context, marker_provider: MarkerProvider): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -965,10 +1005,10 @@ def test_given_view_model_python_hooks_with_provider_when_building_then_hooks_us project_name="provider_view_hook_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "hooks/python/marker_hooks.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "sql/hooks/python/marker_hooks.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.hooks import hook @@ -985,7 +1025,7 @@ def mark_post(ctx, marker_provider: MarkerProvider): """ ).strip() + "\n", - "models/orders_view.sql": dedent( + "sql/models/orders_view.sql": dedent( """ MODEL (description "Test model orders_view.", materialized view, @@ -1017,7 +1057,7 @@ def mark_post(ctx, marker_provider: MarkerProvider): ProviderHookMaterializationE2ETestCase( description="incremental python hooks use provider injection", command=("--no-color", "build", "--select", "+incremental_orders"), - model_relative_path="models/incremental_orders.sql", + model_relative_path="sql/models/incremental_orders.sql", model_sql=dedent( """ MODEL (description "Test model incremental_orders.", @@ -1034,7 +1074,7 @@ def mark_post(ctx, marker_provider: MarkerProvider): ).strip() + "\n", extra_repo_files={ - "models/order_rows.sql": 'MODEL (description "Test model order_rows.");\n\n' + "sql/models/order_rows.sql": 'MODEL (description "Test model order_rows.");\n\n' "SELECT 1 AS order_id\n" }, expected_marker_entries=( @@ -1048,7 +1088,7 @@ def mark_post(ctx, marker_provider: MarkerProvider): ProviderHookMaterializationE2ETestCase( description="microbatch python hooks use provider injection", command=("--no-color", "build", "--select", "+hourly_activity"), - model_relative_path="models/hourly_activity.sql", + model_relative_path="sql/models/hourly_activity.sql", model_sql=dedent( """ MODEL (description "Test model hourly_activity.", @@ -1075,7 +1115,7 @@ def mark_post(ctx, marker_provider: MarkerProvider): ).strip() + "\n", extra_repo_files={ - "models/fact_orders.sql": dedent( + "sql/models/fact_orders.sql": dedent( """ MODEL (description "Test model fact_orders.", materialized table); @@ -1095,7 +1135,7 @@ def mark_post(ctx, marker_provider: MarkerProvider): ProviderHookMaterializationE2ETestCase( description="snapshot python hooks use provider injection", command=("--no-color", "build", "--select", "customer_snapshot"), - model_relative_path="models/customer_snapshot.sql", + model_relative_path="sql/models/customer_snapshot.sql", model_sql=dedent( """ MODEL (description "Test model customer_snapshot.", @@ -1124,7 +1164,7 @@ def mark_post(ctx, marker_provider: MarkerProvider): ProviderHookMaterializationE2ETestCase( description="custom materialization python hooks use provider injection", command=("--no-color", "build", "--select", "custom_orders"), - model_relative_path="models/custom_orders.sql", + model_relative_path="sql/models/custom_orders.sql", model_sql=dedent( """ MODEL (description "Test model custom_orders.", @@ -1138,7 +1178,7 @@ def mark_post(ctx, marker_provider: MarkerProvider): ).strip() + "\n", extra_repo_files={ - "materializations/copy_table.py": dedent( + "python/materializations/copy_table.py": dedent( """ from sqlbuild.executor.custom.models import ( MaterializationContext, @@ -1171,10 +1211,10 @@ def test_given_materialization_hooks_with_provider_when_building_then_hooks_use_ marker_path: Path = tmp_path / "provider-hook-materialization-marker.log" repo_files: dict[str, str] = { "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "hooks/python/marker_hooks.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "sql/hooks/python/marker_hooks.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.hooks import hook @@ -1227,8 +1267,8 @@ def test_given_untyped_python_hook_provider_parameter_when_building_then_provide project_name="provider_hook_untyped_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "hooks/python/marker_hooks.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "sql/hooks/python/marker_hooks.py": dedent( """ from sqlbuild.hooks import hook @@ -1240,7 +1280,7 @@ def mark_pre(ctx, marker_provider): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -1287,10 +1327,10 @@ def test_given_python_hook_with_provider_when_hook_fails_then_provider_tears_dow project_name="provider_hook_failure_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "hooks/python/marker_hooks.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "sql/hooks/python/marker_hooks.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.hooks import hook @@ -1302,7 +1342,7 @@ def failing_pre_hook(ctx, marker_provider: MarkerProvider): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -1349,10 +1389,10 @@ def test_given_python_post_hook_with_provider_when_hook_fails_then_provider_tear project_name="provider_post_hook_failure_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "hooks/python/marker_hooks.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "sql/hooks/python/marker_hooks.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.hooks import hook @@ -1364,7 +1404,7 @@ def failing_post_hook(ctx, marker_provider: MarkerProvider): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -1410,8 +1450,8 @@ def test_given_alias_imported_provider_annotation_on_hook_when_building_then_cli project_name="provider_hook_alias_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "hooks/python/alias_hooks.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "sql/hooks/python/alias_hooks.py": dedent( """ import importlib.util import sys @@ -1419,7 +1459,7 @@ def test_given_alias_imported_provider_annotation_on_hook_when_building_then_cli from sqlbuild.hooks import hook - provider_path = Path(__file__).parents[2] / "providers" / "marker.py" + provider_path = Path(__file__).parents[3] / "python" / "providers" / "marker.py" spec = importlib.util.spec_from_file_location("alias_marker", provider_path) alias_marker = importlib.util.module_from_spec(spec) sys.modules["alias_marker"] = alias_marker @@ -1435,7 +1475,7 @@ def mark_pre(ctx, marker_provider: AliasMarkerProvider): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -1480,8 +1520,8 @@ def test_given_provider_annotation_mismatch_on_hook_when_building_then_cli_print project_name="provider_hook_mismatch_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "providers/other.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "python/providers/other.py": dedent( """ from sqlbuild.providers import Provider @@ -1492,9 +1532,9 @@ class OtherProvider(Provider): """ ).strip() + "\n", - "hooks/python/marker_hooks.py": dedent( + "sql/hooks/python/marker_hooks.py": dedent( """ - from providers.other import OtherProvider + from python.providers.other import OtherProvider from sqlbuild.hooks import hook @@ -1505,7 +1545,7 @@ def mark_pre(ctx, marker_provider: OtherProvider): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -1553,10 +1593,10 @@ def test_given_python_hook_kwarg_matches_provider_when_building_then_cli_prints_ project_name="provider_hook_conflict_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "hooks/python/marker_hooks.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "sql/hooks/python/marker_hooks.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.hooks import hook @@ -1567,7 +1607,7 @@ def mark_pre(ctx, marker_provider: MarkerProvider): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized table, @@ -1639,10 +1679,10 @@ def test_given_python_hook_kwarg_matches_context_when_building_then_cli_prints_c project_name="provider_hook_context_conflict_project", repo_files={ "sqlbuild_project.toml": PROVIDER_FAILURE_PROJECT_TOML, - "providers/marker.py": PROVIDER_MARKER_FILE, - "hooks/python/marker_hooks.py": dedent( + "python/providers/marker.py": PROVIDER_MARKER_FILE, + "sql/hooks/python/marker_hooks.py": dedent( """ - from providers.marker import MarkerProvider + from python.providers.marker import MarkerProvider from sqlbuild.hooks import hook @@ -1653,7 +1693,7 @@ def mark_pre(ctx, marker_provider: MarkerProvider): """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( f""" MODEL (description "Test model orders.", materialized table, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/query/test_query_project_inputs.py b/tests/e2e/src/sqlbuild/cli/commands/main/query/test_query_project_inputs.py index 25872dca8c..22a2a0633f 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/query/test_query_project_inputs.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/query/test_query_project_inputs.py @@ -63,11 +63,11 @@ ( QueryUnrelatedProjectFaultTestCase( description="model without a MODEL header", - repo_files={"models/orders.sql": "SELECT FROM WHERE (\n"}, + repo_files={"sql/models/orders.sql": "SELECT FROM WHERE (\n"}, ), QueryUnrelatedProjectFaultTestCase( description="project Python that fails to import", - repo_files={"python/broken.py": 'raise RuntimeError("broken project python")\n'}, + repo_files={"python/nodes/broken.py": 'raise RuntimeError("broken project python")\n'}, ), QueryUnrelatedProjectFaultTestCase( description="local SQL analysis opt-out the project forbids", @@ -125,7 +125,10 @@ def test_given_project_when_running_command_then_project_discovery_runs_only_whe project_dir: Path = prepare_inline_project( tmp_path=tmp_path, project_name="orders_project", - repo_files={"sqlbuild_project.toml": PROJECT_TOML, "models/orders.sql": VALID_MODEL_SQL}, + repo_files={ + "sqlbuild_project.toml": PROJECT_TOML, + "sql/models/orders.sql": VALID_MODEL_SQL, + }, ) argv: list[str] = ["--project-dir", str(project_dir), *test_case.command] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/helpers.py index da2c79c8ba..1ff784a42a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/helpers.py @@ -79,40 +79,40 @@ def project_toml(*, target_settings: str = "") -> str: ) BASE_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": _SOURCES_YML, - "models/staging/stg_orders.sql": STG_ORDERS, - "models/marts/fact_orders.sql": FACT_ORDERS, - "models/marts/customer_totals.sql": CUSTOMER_TOTALS, + "sql/sources/raw.yml": _SOURCES_YML, + "sql/models/staging/stg_orders.sql": STG_ORDERS, + "sql/models/marts/fact_orders.sql": FACT_ORDERS, + "sql/models/marts/customer_totals.sql": CUSTOMER_TOTALS, "tests/unit/test_fact_orders.sql": FACT_ORDERS_TEST, } UDF_FILE: tuple[str, str] = ( - "functions/sql/udf__is_large_order.sql", + "sql/functions/sql/udf__is_large_order.sql", "FUNCTION (description 'Test function udf__is_large_order.'," "\n arguments (amount INTEGER),\n returns BOOLEAN,\n);\n\namount >= 100\n", ) CENTS_MACRO: dict[str, str] = { - "models/staging/_sqlbuild/_macros/python/cents.py": ( + "sql/models/staging/_sqlbuild/_macros/python/cents.py": ( 'def to_cents(expression: str) -> str:\n return f"({expression}) * 100"\n' ), - "models/staging/stg_order_cents.sql": ( + "sql/models/staging/stg_order_cents.sql": ( "MODEL (description 'Test model stg_order_cents.',\n materialized view,\n);\n\n" 'SELECT\n order_id,\n @py.to_cents("amount") AS amount_cents\nFROM __ref("stg_orders")\n' ), } ORDER_REFUNDS: dict[str, str] = { - "models/staging/stg_order_refunds.sql": ( + "sql/models/staging/stg_order_refunds.sql": ( "MODEL (description 'Test model stg_order_refunds.',\n materialized view,\n);\n\n" 'SELECT\n order_id,\n @py.to_cents("amount") AS refund_cents\nFROM __ref("stg_orders")\n' ), } SPLIT_CENTS_MACROS: dict[str, str] = { **CENTS_MACRO, - "models/staging/_sqlbuild/_macros/python/cents.py": ( - CENTS_MACRO["models/staging/_sqlbuild/_macros/python/cents.py"] + "sql/models/staging/_sqlbuild/_macros/python/cents.py": ( + CENTS_MACRO["sql/models/staging/_sqlbuild/_macros/python/cents.py"] + '\n\ndef to_dollars(expression: str) -> str:\n return f"({expression}) / 100"\n' ), - "models/staging/stg_order_refunds.sql": ORDER_REFUNDS[ - "models/staging/stg_order_refunds.sql" + "sql/models/staging/stg_order_refunds.sql": ORDER_REFUNDS[ + "sql/models/staging/stg_order_refunds.sql" ].replace("to_cents", "to_dollars"), } @@ -124,38 +124,40 @@ def project_toml(*, target_settings: str = "") -> str: def grouped_role_files(*, cents_path: str, labels_path: str) -> dict[str, str]: """Return the cents users with ``cents_path`` and a shared label macro at ``labels_path``. - Both cents users sit in ``models/staging``; the label macro is read there and from - ``models/staging/eu``, so it is descendant-public at ``models/staging``. + Both cents users sit in ``sql/models/staging``; the label macro is read there and from + ``sql/models/staging/eu``, so it is descendant-public at ``sql/models/staging``. """ return { "sqlbuild_project.toml": project_toml() + _LAYOUT_RULES, - cents_path: CENTS_MACRO["models/staging/_sqlbuild/_macros/python/cents.py"], - "models/staging/stg_order_cents.sql": CENTS_MACRO["models/staging/stg_order_cents.sql"], - "models/staging/stg_order_refunds.sql": ORDER_REFUNDS[ - "models/staging/stg_order_refunds.sql" + cents_path: CENTS_MACRO["sql/models/staging/_sqlbuild/_macros/python/cents.py"], + "sql/models/staging/stg_order_cents.sql": CENTS_MACRO[ + "sql/models/staging/stg_order_cents.sql" + ], + "sql/models/staging/stg_order_refunds.sql": ORDER_REFUNDS[ + "sql/models/staging/stg_order_refunds.sql" ].replace( "AS refund_cents\n", "AS refund_cents,\n @py.upper_label(\"'refund'\") AS label\n" ), labels_path: _LABEL_MACRO, - "models/staging/eu/stg_order_labels.sql": _label_model("stg_order_labels"), + "sql/models/staging/eu/stg_order_labels.sql": _label_model("stg_order_labels"), } def shared_cents_with_grouped_global_role() -> dict[str, str]: - """Return two staging users of a direct local cents macro beside a grouped ``macros/`` role. + """Return two staging users of a direct local cents macro beside a grouped ``sql/macros/`` role. - Moving only one user to ``models/finance`` would carry cents to the grouped top-level role, - which a direct file cannot join; moving both leaves it local to ``models/finance``. + Moving only one user to ``sql/models/finance`` would carry cents to the grouped top-level role, + which a direct file cannot join; moving both leaves it local to ``sql/models/finance``. """ return { "sqlbuild_project.toml": project_toml() + _LAYOUT_RULES, **CENTS_MACRO, **ORDER_REFUNDS, - "macros/python/text/labels.py": _LABEL_MACRO, - "models/staging/stg_order_labels.sql": _label_model("stg_order_labels"), - "models/marts/order_labels.sql": _label_model("order_labels"), + "sql/macros/python/text/labels.py": _LABEL_MACRO, + "sql/models/staging/stg_order_labels.sql": _label_model("stg_order_labels"), + "sql/models/marts/order_labels.sql": _label_model("order_labels"), } @@ -163,12 +165,14 @@ def same_named_local_macros() -> dict[str, str]: """Return two models in different folders, each using its own local ``helpers.py`` macro.""" return { - "models/staging/_sqlbuild/_macros/python/helpers.py": CENTS_MACRO[ - "models/staging/_sqlbuild/_macros/python/cents.py" + "sql/models/staging/_sqlbuild/_macros/python/helpers.py": CENTS_MACRO[ + "sql/models/staging/_sqlbuild/_macros/python/cents.py" + ], + "sql/models/staging/stg_order_cents.sql": CENTS_MACRO[ + "sql/models/staging/stg_order_cents.sql" ], - "models/staging/stg_order_cents.sql": CENTS_MACRO["models/staging/stg_order_cents.sql"], - "models/marts/_sqlbuild/_macros/python/helpers.py": _LABEL_MACRO, - "models/marts/order_labels.sql": _label_model("order_labels"), + "sql/models/marts/_sqlbuild/_macros/python/helpers.py": _LABEL_MACRO, + "sql/models/marts/order_labels.sql": _label_model("order_labels"), } @@ -192,12 +196,12 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: """Return a view unioning amount from two models, and a view reading its output.""" return { - "models/marts/order_amounts.sql": ( + "sql/models/marts/order_amounts.sql": ( "MODEL (description 'Test model order_amounts.',\n materialized view,\n);\n\n" f'SELECT amount FROM __ref("{first}")\nUNION ALL\n' f'SELECT amount FROM __ref("{second}")\n' ), - "models/marts/order_amount_reads.sql": ( + "sql/models/marts/order_amount_reads.sql": ( 'MODEL (description "Test model order_amount_reads.",' '\n materialized view,\n);\n\nSELECT amount FROM __ref("order_amounts")\n' ), @@ -205,13 +209,13 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: ORDER_EXPORT: dict[str, str] = { - "models/marts/order_export.sql": ( + "sql/models/marts/order_export.sql": ( 'MODEL (description "Test model order_export.",' '\n materialized view,\n);\n\nSELECT *\nFROM __ref("fact_orders")\n' ), } ORDER_AMOUNT_CHECK: dict[str, str] = { - "python/checks/order_amounts.py": ( + "python/nodes/checks/order_amounts/checks.py": ( "from sqlbuild.checks import check\n" "from sqlbuild.refs import model\n\n\n" '@check(depends_on=model("stg_orders"))\n' @@ -221,8 +225,8 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: ), } CUSTOMER_DECLARATIONS: dict[str, str] = { - "seeds/customers.csv": "customer_id,customer_name\n10,Ada\n11,Bo\n", - "seeds/customers.yml": ( + "sql/seeds/customers.csv": "customer_id,customer_name\n10,Ada\n11,Bo\n", + "sql/seeds/customers.yml": ( "seeds:\n" " - name: customers\n description: Test seed customers.\n" " columns:\n" @@ -235,7 +239,7 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: " - name: customer_name\n" " type: VARCHAR\n" ), - "sources/customers.yml": ( + "sql/sources/customers.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" ' expression: "SELECT 10 AS customer_id UNION ALL SELECT 11"\n' @@ -246,12 +250,12 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: ), } ORDER_SHAPE: dict[str, str] = { - "models/marts/_sqlbuild/_schemas/order_shape.sql": ( + "sql/models/marts/_sqlbuild/_schemas/order_shape.sql": ( "SCHEMA (description 'Test schema.'," "\n name order_shape,\n columns (\n customer_id (audits [relationships " '(to __ref("stg_orders"), field customer_id)]),\n ),\n);\n' ), - "models/marts/fact_orders.sql": FACT_ORDERS.replace( + "sql/models/marts/fact_orders.sql": FACT_ORDERS.replace( "materialized table,", "materialized table,\n model_schema order_shape," ), } @@ -283,14 +287,14 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: "FROM orders\n" ) FLAGGED_CONTRACT: dict[str, str] = { - "models/marts/flagged_orders.sql": FLAGGED_ORDERS, - "models/marts/flagged_order_summary.sql": FLAGGED_ORDER_SUMMARY, + "sql/models/marts/flagged_orders.sql": FLAGGED_ORDERS, + "sql/models/marts/flagged_order_summary.sql": FLAGGED_ORDER_SUMMARY, } FLAGGED_AUDITS: dict[str, str] = { - "models/marts/_sqlbuild/_audits/generic/flag_check.sql": ( + "sql/models/marts/_sqlbuild/_audits/generic/flag_check.sql": ( "AUDIT ();\n\nSELECT *\nFROM @relation\nWHERE @where_condition AND order_id IS NULL\n" ), - "models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( + "sql/models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( "is_flagged (type BOOLEAN)", "is_flagged (type BOOLEAN, audits [flag_check " "(where_condition \"is_flagged = TRUE AND 'is_flagged' <> ''\")])", @@ -298,7 +302,7 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: " ),\n);", ' ),\n audits [flag_check (name "orders_flag", where_condition "NOT is_flagged")],\n);', ), - "models/marts/flagged_order_summary.sql": FLAGGED_ORDER_SUMMARY.replace( + "sql/models/marts/flagged_order_summary.sql": FLAGGED_ORDER_SUMMARY.replace( " materialized table,\n", ' materialized table,\n audits [flag_check (where_condition "is_flagged IS NULL")],\n', ), @@ -307,12 +311,12 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: "AUDIT ();\n\nSELECT *\nFROM @relation\nWHERE @where_condition AND order_id IS NULL\n" ) FLAGGED_SUBQUERY_AUDITS: dict[str, str] = { - "models/marts/_sqlbuild/_audits/generic/flag_check.sql": _FLAG_CHECK, - "models/marts/vip_flags.sql": ( + "sql/models/marts/_sqlbuild/_audits/generic/flag_check.sql": _FLAG_CHECK, + "sql/models/marts/vip_flags.sql": ( 'MODEL (description "VIP flags", materialized table);\n' "SELECT CAST(TRUE AS BOOLEAN) AS is_flagged\n" ), - "models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( + "sql/models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( " ),\n);", " ),\n audits [\n" ' flag_check (name "vip_flag", where_condition ' @@ -324,7 +328,7 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: } FLAGGED_USING_AUDIT: dict[str, str] = { **FLAGGED_SUBQUERY_AUDITS, - "models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( + "sql/models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( " ),\n);", " ),\n audits [\n" ' flag_check (name "joined_flag", where_condition ' @@ -334,8 +338,8 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: ), } FLAGGED_LAMBDA_AUDIT: dict[str, str] = { - "models/marts/_sqlbuild/_audits/generic/flag_check.sql": _FLAG_CHECK, - "models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( + "sql/models/marts/_sqlbuild/_audits/generic/flag_check.sql": _FLAG_CHECK, + "sql/models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( " ),\n);", " ),\n audits [\n" ' flag_check (name "lambda_flag", where_condition ' @@ -344,19 +348,19 @@ def order_amount_union(*, first: str, second: str) -> dict[str, str]: ), } FLAGGED_LITERAL_AUDIT: dict[str, str] = { - "models/marts/_sqlbuild/_audits/generic/prefix_check.sql": ( + "sql/models/marts/_sqlbuild/_audits/generic/prefix_check.sql": ( "AUDIT ();\n\nSELECT *\nFROM @relation\nWHERE @'prefix' = ''\n" ), - "models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( + "sql/models/marts/flagged_orders.sql": FLAGGED_ORDERS.replace( " ),\n);", ' ),\n audits [prefix_check (prefix "is_flagged")],\n);' ), } ORDERS_MACRO: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML + "\n[references]\nenforce_explicit = false\n", - "models/staging/_sqlbuild/_macros/python/orders.py": ( + "sql/models/staging/_sqlbuild/_macros/python/orders.py": ( "def staged_orders() -> str:\n return '__ref(\"stg_orders\")'\n" ), - "models/staging/stg_order_count.sql": ( + "sql/models/staging/stg_order_count.sql": ( "MODEL (description 'Test model stg_order_count.',\n materialized view,\n);\n\n" "SELECT COUNT(*) AS order_count\nFROM @py.staged_orders()\n" ), @@ -389,7 +393,7 @@ def order_history_files(*, materialized: str, udf: bool) -> dict[str, str]: """Return an order_history model, optionally calling a UDF discovery cannot fingerprint.""" return { - "models/marts/order_history.sql": ( + "sql/models/marts/order_history.sql": ( "MODEL (description 'Test model order_history.'," f"\n{_HISTORY_HEADERS[materialized]});\n\n" f"SELECT\n order_id,\n amount,\n order_date{_UDF_COLUMN[udf]}\n" @@ -415,9 +419,9 @@ def order_history_copy() -> dict[str, str]: """Return a second model with exactly the order_history definition.""" return { - "models/marts/order_history_copy.sql": order_history_files( + "sql/models/marts/order_history_copy.sql": order_history_files( materialized="incremental", udf=False - )["models/marts/order_history.sql"] + )["sql/models/marts/order_history.sql"] } @@ -462,7 +466,7 @@ def drop_view_outside_sqlbuild(*, project_dir: Path, name: str) -> None: def declare_missing_column_origin(*, project_dir: Path) -> None: """Add a revenue column that declares migrate_from a column the table never had.""" - path: Path = project_dir / "models/marts/order_history.sql" + path: Path = project_dir / "sql/models/marts/order_history.sql" contents: str = path.read_text(encoding="utf-8") _ = path.write_text( contents.replace( @@ -523,11 +527,11 @@ def project_text(project_dir: Path) -> dict[str, str]: paths: tuple[Path, ...] = ( project_dir / "sqlbuild_project.toml", - *project_dir.glob("sources/*.yml"), - *project_dir.glob("seeds/*.yml"), - *project_dir.glob("models/**/*.sql"), - *project_dir.glob("models/**/*.py"), - *project_dir.glob("functions/**/*.sql"), + *project_dir.glob("sql/sources/*.yml"), + *project_dir.glob("sql/seeds/*.yml"), + *project_dir.glob("sql/models/**/*.sql"), + *project_dir.glob("sql/models/**/*.py"), + *project_dir.glob("sql/functions/**/*.sql"), *project_dir.glob("tests/**/*.sql"), ) return { @@ -606,7 +610,7 @@ def run_printed_command(command: str) -> subprocess.CompletedProcess[str]: ) -CENTS_CHECK: str = "python/checks/order_cents.py" +CENTS_CHECK: str = "python/nodes/checks/order_cents/checks.py" def cents_check(imports: str, body: str = ' assert to_cents("1")\n') -> dict[str, str]: @@ -662,24 +666,24 @@ def layout_view(name: str, source: str = '__ref("stg_orders")') -> str: + "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n", "rules/layout.py": _FOLDER_LIMIT_RULE, **{ - f"models/staging/stg_order_{name}.sql": layout_view(f"stg_order_{name}") + f"sql/models/staging/stg_order_{name}.sql": layout_view(f"stg_order_{name}") for name in ("lines", "refunds", "returns", "notes") }, } _DOMAIN_RULES: str = '\n[rules]\nselect = ["SQBRPROJECT202"]\ndomains = ["orders"]\n' MIXED_OWNER: dict[str, str] = { "sqlbuild_project.toml": project_toml() + _DOMAIN_RULES, - "models/orders/staging/orders__stg__lines.sql": layout_view( + "sql/models/orders/staging/orders__stg__lines.sql": layout_view( "orders__stg__lines", '__source("raw_orders")' ), - "models/orders/staging/orders__stg__refunds.sql": layout_view( + "sql/models/orders/staging/orders__stg__refunds.sql": layout_view( "orders__stg__refunds", '__source("raw_orders")' ), - "models/orders/staging/web/orders__stg__web_lines.sql": layout_view( + "sql/models/orders/staging/web/orders__stg__web_lines.sql": layout_view( "orders__stg__web_lines", '__source("raw_orders")' ), } -MIXED_OWNER_CHILD: str = "models/orders/staging/core/" +MIXED_OWNER_CHILD: str = "sql/models/orders/staging/core/" RESERVED_CTE_FACT_ORDERS: str = ( "MODEL (description 'Test model.',\n materialized table,\n);\n\n" @@ -692,7 +696,7 @@ def layout_view(name: str, source: str = '__ref("stg_orders")') -> str: + '\n[rules]\nselect = ["SQBRPROJECT204"]\ndomains = ["orders"]\n\n' + "[rules.thresholds]\nmin_shared_owner_prefix_directories = 2\n", **{ - f"models/orders/staging/{folder}/orders__stg__{name}.sql": layout_view( + f"sql/models/orders/staging/{folder}/orders__stg__{name}.sql": layout_view( f"orders__stg__{name}", '__source("raw_orders")' ) for folder, name in (("fin_a", "a"), ("fin_b", "b"), ("core", "c")) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_batch_moves.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_batch_moves.py index 50db008993..44d40bdb59 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_batch_moves.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_batch_moves.py @@ -27,21 +27,21 @@ write_orders_project, ) -_CENTS: str = "models/staging/_sqlbuild/_macros/python/cents.py" +_CENTS: str = "sql/models/staging/_sqlbuild/_macros/python/cents.py" _COMPILE_STARTS: tuple[str, ...] = ( "Compiling project...", "Verifying the edited project compiles...", ) _BOTH_USERS: tuple[str, ...] = ( "model:stg_order_cents", - "models/finance/", + "sql/models/finance/", "stg_order_refunds", - "models/finance/", + "sql/models/finance/", ) _EXPECTED_MOVED: dict[str, str] = { - "models/staging/stg_order_cents.sql": "models/finance/stg_order_cents.sql", - "models/staging/stg_order_refunds.sql": "models/finance/stg_order_refunds.sql", - _CENTS: "models/finance/_sqlbuild/_macros/python/cents.py", + "sql/models/staging/stg_order_cents.sql": "sql/models/finance/stg_order_cents.sql", + "sql/models/staging/stg_order_refunds.sql": "sql/models/finance/stg_order_refunds.sql", + _CENTS: "sql/models/finance/_sqlbuild/_macros/python/cents.py", } @@ -60,8 +60,8 @@ arguments=("--from-file", MOVE_FILE_PLACEHOLDER), move_file=( "# move every cents user together\n\n" - "model:stg_order_cents\tmodels/finance/\n" - " stg_order_refunds models/finance/ \n" + "model:stg_order_cents\tsql/models/finance/\n" + " stg_order_refunds sql/models/finance/ \n" ), expected_moved=_EXPECTED_MOVED, expected_compiles=2, @@ -104,9 +104,9 @@ def test_given_moves_invalid_one_at_a_time_when_moved_together_then_one_verifica [ SingleMoveOfBatchE2ETestCase( description="moving one user alone needs a group in the top-level role", - move=("stg_order_cents", "models/finance/"), + move=("stg_order_cents", "sql/models/finance/"), expected_reason=( - "macro:to_cents must move to macros/python/, which keeps its files in group" + "macro:to_cents must move to sql/macros/python/, which keeps its files in group" ), ), ], @@ -137,13 +137,13 @@ def test_given_one_move_of_the_batch_alone_when_moving_then_it_is_refused( description="two models moved to the same file", arguments=( "stg_order_cents", - "models/finance/order_amounts.sql", + "sql/models/finance/order_amounts.sql", "stg_order_refunds", - "models/finance/order_amounts.sql", + "sql/models/finance/order_amounts.sql", ), expected_reason=( "model:stg_order_cents and model:stg_order_refunds both move to " - "models/finance/order_amounts.sql" + "sql/models/finance/order_amounts.sql" ), ), BatchMoveConflictE2ETestCase( @@ -151,9 +151,9 @@ def test_given_one_move_of_the_batch_alone_when_moving_then_it_is_refused( description="one model moved twice", arguments=( "stg_order_cents", - "models/finance/", + "sql/models/finance/", "stg_order_cents", - "models/marts/", + "sql/models/marts/", ), expected_reason="model:stg_order_cents is moved more than once", ), @@ -162,9 +162,9 @@ def test_given_one_move_of_the_batch_alone_when_moving_then_it_is_refused( description="a model taking the name another model gives up", arguments=( "stg_order_refunds", - "models/staging/stg_order_returns.sql", + "sql/models/staging/stg_order_returns.sql", "stg_order_cents", - "models/staging/stg_order_refunds.sql", + "sql/models/staging/stg_order_refunds.sql", ), expected_reason=( "model:stg_order_cents would take the name model:stg_order_refunds gives up" @@ -175,14 +175,14 @@ def test_given_one_move_of_the_batch_alone_when_moving_then_it_is_refused( files=same_named_local_macros(), arguments=( "stg_order_cents", - "models/finance/", + "sql/models/finance/", "order_labels", - "models/finance/", + "sql/models/finance/", ), expected_reason=( - "models/marts/_sqlbuild/_macros/python/helpers.py and " - "models/staging/_sqlbuild/_macros/python/helpers.py would both move to " - "models/finance/_sqlbuild/_macros/python/helpers.py; rename one of them first" + "sql/models/marts/_sqlbuild/_macros/python/helpers.py and " + "sql/models/staging/_sqlbuild/_macros/python/helpers.py would both move to " + "sql/models/finance/_sqlbuild/_macros/python/helpers.py; rename one of them first" ), ), ], @@ -210,9 +210,9 @@ def test_given_conflicting_moves_when_moved_together_then_batch_is_refused_and_n arguments=_BOTH_USERS, expected_lines=( "Move 2 models", - "├── stg_order_cents -> models/finance/stg_order_cents.sql", - "└── stg_order_refunds -> models/finance/stg_order_refunds.sql", - f"├── models/finance/_sqlbuild/_macros/python/cents.py (moved from {_CENTS})", + "├── stg_order_cents -> sql/models/finance/stg_order_cents.sql", + "└── stg_order_refunds -> sql/models/finance/stg_order_refunds.sql", + f"├── sql/models/finance/_sqlbuild/_macros/python/cents.py (moved from {_CENTS})", "Dry run: compiles, 3 files would change; nothing written", ), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_batch_renames.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_batch_renames.py index fea7cd4493..5ad3fee010 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_batch_renames.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_batch_renames.py @@ -30,16 +30,16 @@ "Verifying the edited project compiles...", ) _RENAMED_FILES: tuple[str, ...] = ( - "models/marts/fact_order_lines.sql", - "models/staging/stg_order_lines.sql", + "sql/models/marts/fact_order_lines.sql", + "sql/models/staging/stg_order_lines.sql", ) _RENAMED_FRAGMENTS: dict[str, tuple[str, ...]] = { - "models/marts/fact_order_lines.sql": ( + "sql/models/marts/fact_order_lines.sql": ( '__ref("stg_order_lines")', "migrate_from fact_orders", ), - "models/staging/stg_order_lines.sql": ("migrate_from stg_orders",), - "models/marts/customer_totals.sql": ('__ref("fact_order_lines")',), + "sql/models/staging/stg_order_lines.sql": ("migrate_from stg_orders",), + "sql/models/marts/customer_totals.sql": ('__ref("fact_order_lines")',), "tests/unit/test_fact_order_lines.sql": ( "__ref__stg_order_lines AS (", "__expected__fact_order_lines AS (", @@ -99,8 +99,8 @@ def test_given_several_renames_when_renamed_together_then_one_verification_appli assert existing_files( project_dir=project_dir, paths=( - "models/staging/stg_orders.sql", - "models/marts/fact_orders.sql", + "sql/models/staging/stg_orders.sql", + "sql/models/marts/fact_orders.sql", *test_case.expected_files, ), ) == tuple(sorted(test_case.expected_files)) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_job_selectors.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_job_selectors.py index 9202e5299f..a158a73ed1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_job_selectors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_job_selectors.py @@ -41,20 +41,20 @@ ), JobSelectorRefactorE2ETestCase( description="moving every model out of a folder moves its folder selectors", - command=("mv", "stg_orders", "models/core/"), - job=refresh_job('"models/staging +path:models/staging/ stg_orders"'), - expected_job=refresh_job('"models/core +path:models/core/ stg_orders"'), + command=("mv", "stg_orders", "sql/models/core/"), + job=refresh_job('"sql/models/staging +path:sql/models/staging/ stg_orders"'), + expected_job=refresh_job('"sql/models/core +path:sql/models/core/ stg_orders"'), expected_output=("selector", _JOB), ), JobSelectorRefactorE2ETestCase( description="moving some models out of a folder leaves it and asks for a check", - command=("mv", "fact_orders", "models/finance/"), - job=refresh_job('"+models/marts"'), - expected_job=refresh_job('"+models/marts"'), + command=("mv", "fact_orders", "sql/models/finance/"), + job=refresh_job('"+sql/models/marts"'), + expected_job=refresh_job('"+sql/models/marts"'), expected_output=( "Notes", f"{_JOB}:3:10", - "this job selects folder 'models/marts', and fact_orders moved out of it", + "this job selects folder 'sql/models/marts', and fact_orders moved out of it", ), ), ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_layout_repairs.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_layout_repairs.py index 9727d6ee6f..9c378e87cb 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_layout_repairs.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_layout_repairs.py @@ -33,7 +33,7 @@ LayoutRepairE2ETestCase( description="moving a model out of an over-full folder keeps the reduced failure", files=OVER_FULL_STAGING, - arguments=("stg_order_notes", "models/support/"), + arguments=("stg_order_notes", "sql/models/support/"), expected_status="applied", expected_baseline={"before": 1, "remaining": 1, "resolved": 0}, expected_blocking=(), @@ -43,9 +43,9 @@ files=OVER_FULL_STAGING, arguments=( "stg_order_notes", - "models/support/", + "sql/models/support/", "stg_order_returns", - "models/support/", + "sql/models/support/", ), expected_status="applied", expected_baseline={"before": 1, "remaining": 0, "resolved": 1}, @@ -54,23 +54,25 @@ LayoutRepairE2ETestCase( description="moving a model into the over-full folder worsens it", files=OVER_FULL_STAGING, - arguments=("fact_orders", "models/staging/"), + arguments=("fact_orders", "sql/models/staging/"), expected_status="compile_failed", expected_baseline={"before": 1, "remaining": 0, "resolved": 0}, - expected_blocking=("XSQBRLAYOUT001 models/staging holds 6 models; the maximum is 3",), + expected_blocking=( + "XSQBRLAYOUT001 sql/models/staging holds 6 models; the maximum is 3", + ), ), LayoutRepairE2ETestCase( description="filling another folder past the limit is a new failure", files=OVER_FULL_STAGING, arguments=( "stg_order_notes", - "models/marts/", + "sql/models/marts/", "stg_order_returns", - "models/marts/", + "sql/models/marts/", ), expected_status="compile_failed", expected_baseline={"before": 1, "remaining": 0, "resolved": 1}, - expected_blocking=("XSQBRLAYOUT001 models/marts holds 4 models; the maximum is 3",), + expected_blocking=("XSQBRLAYOUT001 sql/models/marts holds 4 models; the maximum is 3",), ), LayoutRepairE2ETestCase( description="moving every direct model of a mixed owner into a child repairs it", @@ -88,7 +90,7 @@ LayoutRepairE2ETestCase( description="a count that grows at a file nothing moves into blocks", files=SIBLING_OWNERS, - arguments=("orders__stg__c", "models/orders/staging/fin_c/"), + arguments=("orders__stg__c", "sql/models/orders/staging/fin_c/"), expected_status="compile_failed", expected_baseline={"before": 1, "remaining": 0, "resolved": 0}, expected_blocking=("SQBRPROJECT204 3 sibling owner directories",), @@ -145,11 +147,11 @@ def test_given_existing_rule_failures_when_moving_then_only_new_or_worse_failure LayoutRepairDryRunE2ETestCase( description="an over-full folder losing a model", files=OVER_FULL_STAGING, - arguments=("stg_order_notes", "models/support/"), + arguments=("stg_order_notes", "sql/models/support/"), expected_lines=( "Existing rule failures", "The project had 1 rule failure before this change; 0 resolved, 1 still failing.", - "└── XSQBRLAYOUT001 models/staging:1 models/staging holds 4 models; " + "└── XSQBRLAYOUT001 sql/models/staging:1 sql/models/staging holds 4 models; " "the maximum is 3", "Existing rule failures do not block the change; it adds or worsens none.", "Dry run: compiles, 1 file would change; nothing written", @@ -181,15 +183,20 @@ def test_given_existing_rule_failures_when_dry_run_then_baseline_and_result_are_ description="an over-full folder and a reference to a missing model", files={ **OVER_FULL_STAGING, - "models/marts/order_gaps.sql": layout_view("order_gaps", '__ref("missing_orders")'), + "sql/models/marts/order_gaps.sql": layout_view( + "order_gaps", '__ref("missing_orders")' + ), }, - command=("mv", "stg_order_notes", "models/support/"), + command=("mv", "stg_order_notes", "sql/models/support/"), expected_codes=("P001",), ), RefusedBaselineE2ETestCase( description="an over-full folder and a unit test that cannot be planned", - files={**OVER_FULL_STAGING, "models/marts/fact_orders.sql": RESERVED_CTE_FACT_ORDERS}, - command=("mv", "customer_totals", "models/support/"), + files={ + **OVER_FULL_STAGING, + "sql/models/marts/fact_orders.sql": RESERVED_CTE_FACT_ORDERS, + }, + command=("mv", "customer_totals", "sql/models/support/"), expected_codes=("XSQBRLAYOUT001", "P001"), ), ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_move_declarations.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_move_declarations.py index 1d0c0bd566..b36557075f 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_move_declarations.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_move_declarations.py @@ -23,13 +23,13 @@ write_orders_project, ) -_CENTS: str = "models/staging/_sqlbuild/_macros/python/cents.py" -_GROUPED_CENTS: str = "models/staging/_sqlbuild/_macros/python/money/cents.py" +_CENTS: str = "sql/models/staging/_sqlbuild/_macros/python/cents.py" +_GROUPED_CENTS: str = "sql/models/staging/_sqlbuild/_macros/python/money/cents.py" _PRIORITY_ENUM: dict[str, str] = { - "models/marts/_sqlbuild/_enums/priority.sql": ( + "sql/models/marts/_sqlbuild/_enums/priority.sql": ( "ENUM (\n name priority,\n members (LOW 1, HIGH 3),\n);\n" ), - "models/marts/fact_orders.sql": ORDER_SHAPE["models/marts/fact_orders.sql"].replace( + "sql/models/marts/fact_orders.sql": ORDER_SHAPE["sql/models/marts/fact_orders.sql"].replace( "SELECT", 'SELECT\n @enum("priority").LOW AS priority,', 1 ), } @@ -42,13 +42,13 @@ description="declarations only the moved model uses move with it", model="fact_orders", extra_files={**ORDER_SHAPE, **_PRIORITY_ENUM}, - destination="models/reporting/", + destination="sql/models/reporting/", expected_moved={ - "models/marts/_sqlbuild/_schemas/order_shape.sql": ( - "models/reporting/_sqlbuild/_schemas/order_shape.sql" + "sql/models/marts/_sqlbuild/_schemas/order_shape.sql": ( + "sql/models/reporting/_sqlbuild/_schemas/order_shape.sql" ), - "models/marts/_sqlbuild/_enums/priority.sql": ( - "models/reporting/_sqlbuild/_enums/priority.sql" + "sql/models/marts/_sqlbuild/_enums/priority.sql": ( + "sql/models/reporting/_sqlbuild/_enums/priority.sql" ), }, ), @@ -56,26 +56,26 @@ description="a macro still used at the old folder moves up to the shared owner", model="stg_order_cents", extra_files={**CENTS_MACRO, **ORDER_REFUNDS}, - destination="models/staging/eu/", - expected_moved={_CENTS: "models/staging/_sqlbuild/macros/python/cents.py"}, + destination="sql/models/staging/eu/", + expected_moved={_CENTS: "sql/models/staging/_sqlbuild/macros/python/cents.py"}, ), DeclarationMoveE2ETestCase( description="a macro shared across the models root moves to the top-level role", model="stg_order_cents", extra_files={**CENTS_MACRO, **ORDER_REFUNDS}, - destination="models/marts/", - expected_moved={_CENTS: "macros/python/cents.py"}, + destination="sql/models/marts/", + expected_moved={_CENTS: "sql/macros/python/cents.py"}, ), DeclarationMoveE2ETestCase( description="a grouped macro keeps its group in a grouped destination role", model="stg_order_cents", extra_files=grouped_role_files( cents_path=_GROUPED_CENTS, - labels_path="models/staging/_sqlbuild/macros/python/text/labels.py", + labels_path="sql/models/staging/_sqlbuild/macros/python/text/labels.py", ), - destination="models/staging/eu/", + destination="sql/models/staging/eu/", expected_moved={ - _GROUPED_CENTS: "models/staging/_sqlbuild/macros/python/money/cents.py" + _GROUPED_CENTS: "sql/models/staging/_sqlbuild/macros/python/money/cents.py" }, ), DeclarationMoveE2ETestCase( @@ -83,10 +83,10 @@ model="stg_order_cents", extra_files=grouped_role_files( cents_path=_GROUPED_CENTS, - labels_path="models/staging/_sqlbuild/macros/python/labels.py", + labels_path="sql/models/staging/_sqlbuild/macros/python/labels.py", ), - destination="models/staging/eu/", - expected_moved={_GROUPED_CENTS: "models/staging/_sqlbuild/macros/python/cents.py"}, + destination="sql/models/staging/eu/", + expected_moved={_GROUPED_CENTS: "sql/models/staging/_sqlbuild/macros/python/cents.py"}, ), ], ids=lambda case: case.description, @@ -122,11 +122,11 @@ def test_given_scoped_declarations_when_moving_model_then_they_follow_placement_ model="stg_order_cents", extra_files=grouped_role_files( cents_path=_CENTS, - labels_path="models/staging/_sqlbuild/macros/python/text/labels.py", + labels_path="sql/models/staging/_sqlbuild/macros/python/text/labels.py", ), - destination="models/staging/eu/", + destination="sql/models/staging/eu/", expected_message=( - "macro:to_cents must move to models/staging/_sqlbuild/macros/python/, which keeps its " + "macro:to_cents must move to sql/models/staging/_sqlbuild/macros/python/, which keeps its " f"files in group folders, but {_CENTS} is not in a group; move it into a group " "folder of its current role first" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_project_failures.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_project_failures.py index 93c5f9520f..3ec296cf16 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_project_failures.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_project_failures.py @@ -20,11 +20,11 @@ ) _DUPLICATE_MACROS: dict[str, str] = { - "macros/python/cents.py": 'def to_cents(expression: str) -> str:\n return f"({expression}) * 100"\n', - "macros/python/money.py": 'def to_cents(expression: str) -> str:\n return f"({expression}) * 100"\n', + "sql/macros/python/cents.py": 'def to_cents(expression: str) -> str:\n return f"({expression}) * 100"\n', + "sql/macros/python/money.py": 'def to_cents(expression: str) -> str:\n return f"({expression}) * 100"\n', } _UNKNOWN_REFERENCE: dict[str, str] = { - "models/marts/order_gaps.sql": ( + "sql/models/marts/order_gaps.sql": ( "MODEL (description 'Test model order_gaps.',\n materialized view,\n);\n\n" 'SELECT order_id FROM __ref("missing_orders")\n' ), @@ -36,7 +36,7 @@ [ ProjectFailureE2ETestCase( description="mv on a project with a duplicate macro name", - command=("mv", "fact_orders", "models/reporting/"), + command=("mv", "fact_orders", "sql/models/reporting/"), expected_codes=("P001",), ), ProjectFailureE2ETestCase( @@ -86,7 +86,7 @@ def test_given_input_stage_failure_when_refactoring_then_compile_error_is_report ), ProjectFailureE2ETestCase( description="mv on a project with an unknown reference", - command=("mv", "fact_orders", "models/reporting/"), + command=("mv", "fact_orders", "sql/models/reporting/"), expected_codes=("P001",), ), ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_python_import_moves.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_python_import_moves.py index 2db8522fe0..a3c454c1c1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_python_import_moves.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_python_import_moves.py @@ -20,7 +20,7 @@ write_orders_project, ) -_MOVED: str = "models.finance._sqlbuild._macros.python.cents" +_MOVED: str = "sql.models.finance._sqlbuild._macros.python.cents" @pytest.mark.parametrize( @@ -30,9 +30,9 @@ description="direct, aliased and grouped imports of a carried macro module", files={ **cents_check( - "from models.staging._sqlbuild._macros.python.cents import to_cents\n" - "import models.staging._sqlbuild._macros.python.cents as cents_module\n" - "from models.staging._sqlbuild._macros.python.cents import (\n to_cents as cents,\n)", + "from sql.models.staging._sqlbuild._macros.python.cents import to_cents\n" + "import sql.models.staging._sqlbuild._macros.python.cents as cents_module\n" + "from sql.models.staging._sqlbuild._macros.python.cents import (\n to_cents as cents,\n)", body=' assert to_cents("1") == cents_module.to_cents("1") == cents("1")\n', ), }, @@ -48,23 +48,23 @@ description="a relative import from a macro module that stays", files={ **cents_check( - "from models.staging._sqlbuild._macros.python import cents as cents_module", + "from sql.models.staging._sqlbuild._macros.python import cents as cents_module", body=' assert cents_module.to_cents("1")\n', ), - "models/staging/_sqlbuild/_macros/python/totals.py": ( + "sql/models/staging/_sqlbuild/_macros/python/totals.py": ( "from .cents import to_cents\n\n\n" "def order_total(expression: str) -> str:\n" ' return f"SUM({to_cents(expression)})"\n' ), - "models/staging/stg_order_totals.sql": ( + "sql/models/staging/stg_order_totals.sql": ( "MODEL (description 'Test model stg_order_totals.',\n materialized view,\n);\n\n" 'SELECT\n @py.order_total("amount") AS total_cents\nFROM __ref("stg_orders")\n' ), }, expected_fragments={ - CENTS_CHECK: ("from macros.python import cents as cents_module",), - "models/staging/_sqlbuild/_macros/python/totals.py": ( - "from macros.python.cents import to_cents\n", + CENTS_CHECK: ("from sql.macros.python import cents as cents_module",), + "sql/models/staging/_sqlbuild/_macros/python/totals.py": ( + "from sql.macros.python.cents import to_cents\n", ), }, ), @@ -77,7 +77,7 @@ def test_given_python_imports_of_a_moved_macro_when_moving_then_imports_follow_a project_dir: Path = write_orders_project(tmp_path=tmp_path, files=test_case.files) moved: subprocess.CompletedProcess[str] = sqb( - project_dir, "mv", "stg_order_cents", "models/finance/" + project_dir, "mv", "stg_order_cents", "sql/models/finance/" ) compiled: subprocess.CompletedProcess[str] = sqb(project_dir, "compile") checked: subprocess.CompletedProcess[str] = sqb(project_dir, "build") @@ -102,38 +102,40 @@ def test_given_python_imports_of_a_moved_macro_when_moving_then_imports_follow_a description="a dynamic import naming the macro module", files=cents_check( "import importlib\n\n" - 'CENTS = importlib.import_module("models.staging._sqlbuild._macros.python.cents")', + 'CENTS = importlib.import_module("sql.models.staging._sqlbuild._macros.python.cents")', body=' assert CENTS.to_cents("1")\n', ), expected_location=f"{CENTS_CHECK}:6:9", expected_reason=( - "imports models.staging._sqlbuild._macros.python.cents dynamically by name, which " + "imports sql.models.staging._sqlbuild._macros.python.cents dynamically by name, which " "cannot be rewritten safely" ), ), PythonImportRefusalE2ETestCase( description="a star import from the macro module's package", files=cents_check( - "from models.staging._sqlbuild._macros.python.cents import *\n" - "from models.staging._sqlbuild._macros.python import *" + "from sql.models.staging._sqlbuild._macros.python.cents import *\n" + "from sql.models.staging._sqlbuild._macros.python import *" ), expected_location=f"{CENTS_CHECK}:5:1", expected_reason=( - "star-imports the package of models.staging._sqlbuild._macros.python.cents, which moves" + "star-imports the package of sql.models.staging._sqlbuild._macros.python.cents, which moves" ), ), PythonImportRefusalE2ETestCase( description="an import without an alias", files=cents_check( - "import models.staging._sqlbuild._macros.python.cents", - body=' assert models.staging._sqlbuild._macros.python.cents.to_cents("1")\n', + "import sql.models.staging._sqlbuild._macros.python.cents", + body=' assert sql.models.staging._sqlbuild._macros.python.cents.to_cents("1")\n', ), expected_location=f"{CENTS_CHECK}:4:8", - expected_reason="imports models.staging._sqlbuild._macros.python.cents without an alias", + expected_reason="imports sql.models.staging._sqlbuild._macros.python.cents without an alias", ), PythonImportRefusalE2ETestCase( description="a project Python file that is not UTF-8", - files=cents_check("from models.staging._sqlbuild._macros.python.cents import to_cents"), + files=cents_check( + "from sql.models.staging._sqlbuild._macros.python.cents import to_cents" + ), binary_files={"rules/legacy.py": b"LABEL = '\xe9'\n"}, expected_location="rules/legacy.py", expected_reason="this Python file cannot be read as UTF-8", @@ -152,7 +154,7 @@ def test_given_unrewritable_python_import_when_moving_then_move_is_refused_namin check_before: str = (project_dir / CENTS_CHECK).read_text(encoding="utf-8") moved: subprocess.CompletedProcess[str] = sqb( - project_dir, "mv", "stg_order_cents", "models/finance/" + project_dir, "mv", "stg_order_cents", "sql/models/finance/" ) output: str = " ".join(moved.stdout.split()) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_python_named_moves.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_python_named_moves.py index e0bfe88366..ac11b53d1e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_python_named_moves.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_python_named_moves.py @@ -26,21 +26,21 @@ [ PythonNamedMoveE2ETestCase( description="a move to a folder keeps the name and moves", - destination="models/marts/", + destination="sql/models/marts/", expected_exit_code=0, - expected_model_path="models/marts/orders.sql", + expected_model_path="sql/models/marts/orders.sql", ), PythonNamedMoveE2ETestCase( description="a move to a file of the same name moves", - destination="models/marts/orders.sql", + destination="sql/models/marts/orders.sql", expected_exit_code=0, - expected_model_path="models/marts/orders.sql", + expected_model_path="sql/models/marts/orders.sql", ), PythonNamedMoveE2ETestCase( description="a move that renames the model is refused", - destination="models/marts/fct_orders.sql", + destination="sql/models/marts/fct_orders.sql", expected_exit_code=1, - expected_model_path="models/orders.sql", + expected_model_path="sql/models/orders.sql", ), ], ids=lambda case: case.description, @@ -56,8 +56,8 @@ def test_given_model_named_by_python_when_moving_then_only_renames_are_refused( 'name = "shop"\nadapter = "duckdb"\n\n[connection]\ndatabase = "shop.duckdb"\n\n' "[scopes]\nenforce_placement = false\n" ), - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", - "python/checks/orders.py": _CHECK, + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", + "python/nodes/checks/orders/checks.py": _CHECK, }, ) @@ -67,4 +67,6 @@ def test_given_model_named_by_python_when_moving_then_only_renames_are_refused( assert moved.returncode == test_case.expected_exit_code, moved.stdout + moved.stderr assert (project_dir / test_case.expected_model_path).is_file() - assert (project_dir / "python/checks/orders.py").read_text(encoding="utf-8") == _CHECK + assert (project_dir / "python/nodes/checks/orders/checks.py").read_text( + encoding="utf-8" + ) == _CHECK diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_columns.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_columns.py index 9a21276377..3d85296338 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_columns.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_columns.py @@ -49,8 +49,8 @@ description="one step keeps downstream output names", command=("rename", "column:stg_orders.amount", "revenue"), expected_fragments={ - "models/staging/stg_orders.sql": (" amount AS revenue,",), - "models/marts/fact_orders.sql": (" o.revenue AS amount,",), + "sql/models/staging/stg_orders.sql": (" amount AS revenue,",), + "sql/models/marts/fact_orders.sql": (" o.revenue AS amount,",), "tests/unit/test_fact_orders.sql": ("25 AS revenue",), }, expected_columns={ @@ -62,8 +62,8 @@ description="cascade renames pass-through outputs downstream", command=("rename", "column:stg_orders.amount", "revenue", "--cascade"), expected_fragments={ - "models/marts/fact_orders.sql": (" o.revenue,",), - "models/marts/customer_totals.sql": ("SUM(revenue) AS total_amount",), + "sql/models/marts/fact_orders.sql": (" o.revenue,",), + "sql/models/marts/customer_totals.sql": ("SUM(revenue) AS total_amount",), }, expected_columns={ "fact_orders": ("order_id", "customer_id", "revenue", "order_date"), @@ -75,9 +75,9 @@ command=("rename", "column:stg_orders.customer_id", "buyer_id"), extra_files=CUSTOMER_DECLARATIONS, expected_fragments={ - "seeds/customers.yml": ("field: buyer_id",), - "sources/customers.yml": ("field: buyer_id}",), - "models/marts/fact_orders.sql": (" o.buyer_id AS customer_id,",), + "sql/seeds/customers.yml": ("field: buyer_id",), + "sql/sources/customers.yml": ("field: buyer_id}",), + "sql/models/marts/fact_orders.sql": (" o.buyer_id AS customer_id,",), }, expected_columns={ "stg_orders": ("order_id", "buyer_id", "amount", "order_date"), @@ -88,7 +88,7 @@ command=("rename", "column:stg_orders.customer_id", "buyer_id"), extra_files=ORDER_SHAPE, expected_fragments={ - "models/marts/_sqlbuild/_schemas/order_shape.sql": ("field buyer_id)",), + "sql/models/marts/_sqlbuild/_schemas/order_shape.sql": ("field buyer_id)",), }, expected_columns={ "fact_orders": ("order_id", "customer_id", "amount", "order_date"), @@ -99,8 +99,8 @@ command=("rename", "column:fact_orders.amount", "revenue", "--cascade"), extra_files=order_amount_union(first="stg_orders", second="fact_orders"), expected_fragments={ - "models/marts/order_amounts.sql": ('SELECT revenue FROM __ref("fact_orders")',), - "models/marts/order_amount_reads.sql": ("SELECT amount FROM",), + "sql/models/marts/order_amounts.sql": ('SELECT revenue FROM __ref("fact_orders")',), + "sql/models/marts/order_amount_reads.sql": ("SELECT amount FROM",), }, expected_columns={ "order_amounts": ("amount",), @@ -112,11 +112,11 @@ command=("rename", "column:fact_orders.amount", "revenue", "--cascade"), extra_files=order_amount_union(first="fact_orders", second="stg_orders"), expected_fragments={ - "models/marts/order_amounts.sql": ( + "sql/models/marts/order_amounts.sql": ( 'SELECT revenue FROM __ref("fact_orders")', 'SELECT amount FROM __ref("stg_orders")', ), - "models/marts/order_amount_reads.sql": ("SELECT revenue FROM",), + "sql/models/marts/order_amount_reads.sql": ("SELECT revenue FROM",), }, expected_columns={ "order_amounts": ("revenue",), @@ -127,7 +127,7 @@ description="cascade follows SELECT star consumers", command=("rename", "column:fact_orders.amount", "revenue", "--cascade"), extra_files=ORDER_EXPORT, - expected_fragments={"models/marts/customer_totals.sql": ("SUM(revenue)",)}, + expected_fragments={"sql/models/marts/customer_totals.sql": ("SUM(revenue)",)}, expected_columns={ "fact_orders": ("order_id", "customer_id", "revenue", "order_date"), "order_export": ("order_id", "customer_id", "revenue", "order_date"), @@ -138,11 +138,11 @@ command=("rename", "column:flagged_orders.is_flagged", "is_marked", "--cascade"), extra_files=FLAGGED_CONTRACT, expected_fragments={ - "models/marts/flagged_orders.sql": ( + "sql/models/marts/flagged_orders.sql": ( " is_marked (type BOOLEAN)\n", "CAST(TRUE AS BOOLEAN) AS is_marked\n", ), - "models/marts/flagged_order_summary.sql": (" is_marked\nFROM orders",), + "sql/models/marts/flagged_order_summary.sql": (" is_marked\nFROM orders",), }, expected_columns={ "flagged_orders": ("order_id", "is_marked"), @@ -154,11 +154,13 @@ command=("rename", "column:flagged_orders.is_flagged", "is_marked", "--cascade"), extra_files=FLAGGED_AUDITS, expected_fragments={ - "models/marts/flagged_orders.sql": ( + "sql/models/marts/flagged_orders.sql": ( "where_condition \"is_marked = TRUE AND 'is_flagged' <> ''\"", 'where_condition "NOT is_marked"', ), - "models/marts/flagged_order_summary.sql": ('where_condition "is_marked IS NULL"',), + "sql/models/marts/flagged_order_summary.sql": ( + 'where_condition "is_marked IS NULL"', + ), }, expected_columns={ "flagged_orders": ("order_id", "is_marked"), @@ -170,7 +172,7 @@ command=("rename", "column:flagged_orders.is_flagged", "is_marked"), extra_files=FLAGGED_SUBQUERY_AUDITS, expected_fragments={ - "models/marts/flagged_orders.sql": ( + "sql/models/marts/flagged_orders.sql": ( "'is_marked IN (SELECT is_flagged FROM __ref(\"vip_flags\"))'", "'is_marked IN (SELECT is_marked FROM __ref(\"flagged_orders\"))'", ), @@ -185,7 +187,7 @@ command=("rename", "column:flagged_orders.is_flagged", "is_marked"), extra_files=FLAGGED_LAMBDA_AUDIT, expected_fragments={ - "models/marts/flagged_orders.sql": ( + "sql/models/marts/flagged_orders.sql": ( "'len(list_filter([is_marked], lambda is_flagged: is_flagged)) > 0'", ), }, @@ -225,11 +227,11 @@ def test_given_column_rename_when_applied_then_project_tests_and_builds( [ RefusedRefactorE2ETestCase( description="move needing to split a declaration file", - command=("mv", "model:stg_order_cents", "models/marts/"), + command=("mv", "model:stg_order_cents", "sql/models/marts/"), extra_files=SPLIT_CENTS_MACROS, expected_status="refused", expected_reason="would take macro:to_dollars along, which must stay in", - expected_paths=("models/staging/_sqlbuild/_macros/python/cents.py",), + expected_paths=("sql/models/staging/_sqlbuild/_macros/python/cents.py",), ), RefusedRefactorE2ETestCase( description="column named in Python SQL text needs a manual check", @@ -237,7 +239,7 @@ def test_given_column_rename_when_applied_then_project_tests_and_builds( extra_files=ORDER_AMOUNT_CHECK, expected_status="refused", expected_reason="Python SQL may read column amount of stg_orders", - expected_paths=("python/checks/order_amounts.py",), + expected_paths=("python/nodes/checks/order_amounts/checks.py",), ), RefusedRefactorE2ETestCase( description="rename onto an existing model", @@ -245,7 +247,7 @@ def test_given_column_rename_when_applied_then_project_tests_and_builds( extra_files={}, expected_status="refused", expected_reason="model:fact_orders already exists", - expected_paths=("models/marts/fact_orders.sql",), + expected_paths=("sql/models/marts/fact_orders.sql",), ), RefusedRefactorE2ETestCase( description="column used inside macro-generated SQL", @@ -253,7 +255,7 @@ def test_given_column_rename_when_applied_then_project_tests_and_builds( extra_files=CENTS_MACRO, expected_status="refused", expected_reason="referenced in SQL a macro generates", - expected_paths=("models/staging/stg_order_cents.sql",), + expected_paths=("sql/models/staging/stg_order_cents.sql",), ), RefusedRefactorE2ETestCase( description="SELECT star consumer without cascade", @@ -261,7 +263,7 @@ def test_given_column_rename_when_applied_then_project_tests_and_builds( extra_files=ORDER_EXPORT, expected_status="refused", expected_reason="rerun with --cascade", - expected_paths=("models/marts/order_export.sql",), + expected_paths=("sql/models/marts/order_export.sql",), ), RefusedRefactorE2ETestCase( description="model reference produced by a macro", @@ -269,7 +271,7 @@ def test_given_column_rename_when_applied_then_project_tests_and_builds( extra_files=ORDERS_MACRO, expected_status="refused", expected_reason="reference to stg_orders produced by a macro", - expected_paths=("models/staging/stg_order_count.sql",), + expected_paths=("sql/models/staging/stg_order_count.sql",), ), RefusedRefactorE2ETestCase( description="audit argument the audit quotes as a string needs a manual check", @@ -277,7 +279,7 @@ def test_given_column_rename_when_applied_then_project_tests_and_builds( extra_files=FLAGGED_LITERAL_AUDIT, expected_status="refused", expected_reason="audit prefix_check quotes argument prefix as a string", - expected_paths=("models/marts/flagged_orders.sql",), + expected_paths=("sql/models/marts/flagged_orders.sql",), ), RefusedRefactorE2ETestCase( description="audit argument joining on the column with USING needs a manual edit", @@ -285,7 +287,7 @@ def test_given_column_rename_when_applied_then_project_tests_and_builds( extra_files=FLAGGED_USING_AUDIT, expected_status="refused", expected_reason="USING or NATURAL join on is_flagged in this audit argument", - expected_paths=("models/marts/flagged_orders.sql",), + expected_paths=("sql/models/marts/flagged_orders.sql",), ), ], ids=lambda case: case.description, @@ -340,7 +342,7 @@ def test_given_built_incremental_when_renaming_column_then_build_keeps_history( result: subprocess.CompletedProcess[str] = sqb( project_dir, "rename", "column:order_history.amount", "revenue" ) - header: str = (project_dir / "models/marts/order_history.sql").read_text(encoding="utf-8") + header: str = (project_dir / "sql/models/marts/order_history.sql").read_text(encoding="utf-8") load_raw_orders(project_dir=project_dir, order_ids=(3, 4)) second: subprocess.CompletedProcess[str] = sqb(project_dir, "build") @@ -384,7 +386,7 @@ def test_given_renamed_table_when_renaming_its_column_then_build_keeps_both( column: subprocess.CompletedProcess[str] = sqb( project_dir, "rename", "column:order_ledger.amount", "revenue" ) - header: str = (project_dir / "models/marts/order_ledger.sql").read_text(encoding="utf-8") + header: str = (project_dir / "sql/models/marts/order_ledger.sql").read_text(encoding="utf-8") second: subprocess.CompletedProcess[str] = sqb(project_dir, "build") assert first.returncode == 0, first.stdout + first.stderr diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_layer_refusals.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_layer_refusals.py index 97a117219c..081ecd313d 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_layer_refusals.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_layer_refusals.py @@ -28,10 +28,10 @@ f"[rules]\n{_LAYER_RULES}\n" ) _CLEAN_WEB_PATH: str = ( - "models/orders/intermediate/clean/web/orders__int_clean__order_lines__web.sql" + "sql/models/orders/intermediate/clean/web/orders__int_clean__order_lines__web.sql" ) -_UNLAYERED_WEB_PATH: str = "models/orders/web/order_lines_web.sql" -_MART_PATH: str = "models/orders/mart/orders__mart__order_lines.sql" +_UNLAYERED_WEB_PATH: str = "sql/models/orders/web/order_lines_web.sql" +_MART_PATH: str = "sql/models/orders/mart/orders__mart__order_lines.sql" _ENRICHED_NAME: str = "orders__int_enriched__order_lines__web" _STAGING: str = ( 'MODEL (\n description "Staged order lines",\n materialized table,\n);\n\n' @@ -47,13 +47,13 @@ ) _LAYERED_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders/staging/orders__stg__order_lines.sql": _STAGING, + "sql/models/orders/staging/orders__stg__order_lines.sql": _STAGING, _CLEAN_WEB_PATH: _WEB_LINES, _MART_PATH: _MART.format(upstream="orders__int_clean__order_lines__web"), } _UNLAYERED_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders/staging/orders__stg__order_lines.sql": _STAGING, + "sql/models/orders/staging/orders__stg__order_lines.sql": _STAGING, _UNLAYERED_WEB_PATH: _WEB_LINES, _MART_PATH: _MART.format(upstream="order_lines_web"), } @@ -68,14 +68,14 @@ old_name="orders__int_clean__order_lines__web", new_name=_ENRICHED_NAME, expected_hint=( - f"{_ENRICHED_NAME} belongs under models/orders/intermediate/enriched/", + f"{_ENRICHED_NAME} belongs under sql/models/orders/intermediate/enriched/", " Rename and move in one step:", " sqb mv orders__int_clean__order_lines__web " - f"models/orders/intermediate/enriched/web/{_ENRICHED_NAME}.sql " + f"sql/models/orders/intermediate/enriched/web/{_ENRICHED_NAME}.sql " "--project-dir {project_dir}", " (change the folder if you want it somewhere else)", ), - expected_moved_file=f"models/orders/intermediate/enriched/web/{_ENRICHED_NAME}.sql", + expected_moved_file=f"sql/models/orders/intermediate/enriched/web/{_ENRICHED_NAME}.sql", ), ], ids=lambda case: case.description, @@ -147,7 +147,7 @@ def test_given_rename_into_another_layer_when_refused_then_printed_mv_renames_an expected_hint=( f"{_ENRICHED_NAME} belongs under a layer folder named intermediate/enriched/", " Rename and move in one step:", - f" sqb mv order_lines_web 'models//{_ENRICHED_NAME}.sql' " + f" sqb mv order_lines_web 'sql/models//{_ENRICHED_NAME}.sql' " "--project-dir {project_dir}", " (replace / with the folder the model should live in)", ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_models.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_models.py index e7e790d8fc..82733ba3ed 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_models.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_rename_models.py @@ -46,10 +46,10 @@ ModelRefactorE2ETestCase( description="rename keeps the folder and rewrites refs and fixtures", command=("rename", "model:stg_orders", "stg_order_lines"), - expected_removed="models/staging/stg_orders.sql", - expected_file="models/staging/stg_order_lines.sql", + expected_removed="sql/models/staging/stg_orders.sql", + expected_file="sql/models/staging/stg_order_lines.sql", expected_fragments={ - "models/marts/fact_orders.sql": ('__ref("stg_order_lines")',), + "sql/models/marts/fact_orders.sql": ('__ref("stg_order_lines")',), "tests/unit/test_fact_orders.sql": ("__ref__stg_order_lines AS (",), }, expected_relation="stg_order_lines", @@ -57,12 +57,12 @@ ModelRefactorE2ETestCase( description="rename rewrites seed and source relationships audits", command=("rename", "model:stg_orders", "stg_order_lines"), - expected_removed="models/staging/stg_orders.sql", - expected_file="models/staging/stg_order_lines.sql", + expected_removed="sql/models/staging/stg_orders.sql", + expected_file="sql/models/staging/stg_order_lines.sql", expected_fragments={ - "seeds/customers.yml": ('to: __ref("stg_order_lines")',), - "sources/customers.yml": ("to: '__ref(\"stg_order_lines\")'",), - "models/staging/stg_order_lines.sql": ("migrate_from stg_orders",), + "sql/seeds/customers.yml": ('to: __ref("stg_order_lines")',), + "sql/sources/customers.yml": ("to: '__ref(\"stg_order_lines\")'",), + "sql/models/staging/stg_order_lines.sql": ("migrate_from stg_orders",), }, expected_relation="stg_order_lines", extra_files=CUSTOMER_DECLARATIONS, @@ -70,19 +70,19 @@ ModelRefactorE2ETestCase( description="rename keeps tagged sources after quoted values holding ' # '", command=("rename", "model:stg_orders", "stg_order_lines"), - expected_removed="models/staging/stg_orders.sql", - expected_file="models/staging/stg_order_lines.sql", - expected_fragments={"sources/archived.yml": (_TAGGED_SOURCES,)}, + expected_removed="sql/models/staging/stg_orders.sql", + expected_file="sql/models/staging/stg_order_lines.sql", + expected_fragments={"sql/sources/archived.yml": (_TAGGED_SOURCES,)}, expected_relation="stg_order_lines", - extra_files={"sources/archived.yml": _TAGGED_SOURCES}, + extra_files={"sql/sources/archived.yml": _TAGGED_SOURCES}, ), ModelRefactorE2ETestCase( description="rename rewrites reusable schema relationships audits", command=("rename", "model:stg_orders", "stg_order_lines"), - expected_removed="models/staging/stg_orders.sql", - expected_file="models/staging/stg_order_lines.sql", + expected_removed="sql/models/staging/stg_orders.sql", + expected_file="sql/models/staging/stg_order_lines.sql", expected_fragments={ - "models/marts/_sqlbuild/_schemas/order_shape.sql": ( + "sql/models/marts/_sqlbuild/_schemas/order_shape.sql": ( '(to __ref("stg_order_lines"), field customer_id)', ), }, @@ -92,10 +92,10 @@ ModelRefactorE2ETestCase( description="rename rewrites cursor_inputs keys of incremental consumers", command=("rename", "model:stg_orders", "stg_order_lines"), - expected_removed="models/staging/stg_orders.sql", - expected_file="models/staging/stg_order_lines.sql", + expected_removed="sql/models/staging/stg_orders.sql", + expected_file="sql/models/staging/stg_order_lines.sql", expected_fragments={ - "models/marts/order_history.sql": ( + "sql/models/marts/order_history.sql": ( "stg_order_lines order_date,", '__ref("stg_order_lines")', ), @@ -105,20 +105,20 @@ ), ModelRefactorE2ETestCase( description="move to a new file renames the model after the file", - command=("mv", "model:fact_orders", "models/reporting/order_facts.sql"), - expected_removed="models/marts/fact_orders.sql", - expected_file="models/reporting/order_facts.sql", + command=("mv", "model:fact_orders", "sql/models/reporting/order_facts.sql"), + expected_removed="sql/models/marts/fact_orders.sql", + expected_file="sql/models/reporting/order_facts.sql", expected_fragments={ - "models/marts/customer_totals.sql": ('__ref("order_facts")',), + "sql/models/marts/customer_totals.sql": ('__ref("order_facts")',), "tests/unit/test_order_facts.sql": ("__expected__order_facts AS (",), }, expected_relation="order_facts", ), ModelRefactorE2ETestCase( description="move into a folder keeps the model name", - command=("mv", "model:customer_totals", "models/reporting/"), - expected_removed="models/marts/customer_totals.sql", - expected_file="models/reporting/customer_totals.sql", + command=("mv", "model:customer_totals", "sql/models/reporting/"), + expected_removed="sql/models/marts/customer_totals.sql", + expected_file="sql/models/reporting/customer_totals.sql", expected_fragments={}, expected_relation="customer_totals", ), @@ -155,8 +155,8 @@ def test_given_model_refactor_when_applied_then_project_tests_and_builds( command=("rename", "model:stg_orders", "stg_order_lines", "--dry-run"), expected_paths=frozenset( { - "models/staging/stg_order_lines.sql", - "models/marts/fact_orders.sql", + "sql/models/staging/stg_order_lines.sql", + "sql/models/marts/fact_orders.sql", "tests/unit/test_fact_orders.sql", } ), @@ -222,7 +222,7 @@ def test_given_dry_run_json_when_refactoring_then_nothing_is_written( expected_old_name_type="VIEW", expected_order_ids=(1, 2, 3, 4), extra_files=order_history_copy(), - removed_files=("models/marts/order_history_copy.sql",), + removed_files=("sql/models/marts/order_history_copy.sql",), ), ModelMigrationE2ETestCase( description="incremental built before rename matching", @@ -255,7 +255,7 @@ def test_given_built_model_when_renamed_then_build_migrates_its_relation( project_dir, "rename", "model:order_history", "order_ledger" ) remove_files(project_dir=project_dir, paths=test_case.removed_files) - header: str = (project_dir / "models/marts/order_ledger.sql").read_text(encoding="utf-8") + header: str = (project_dir / "sql/models/marts/order_ledger.sql").read_text(encoding="utf-8") load_raw_orders(project_dir=project_dir, order_ids=(3, 4)) second: subprocess.CompletedProcess[str] = sqb(project_dir, "build") @@ -274,16 +274,16 @@ def test_given_built_model_when_renamed_then_build_migrates_its_relation( [ PendingMigrationRefactorE2ETestCase( description="move to another folder under the same name carries migrate_from", - command=("mv", "model:order_ledger", "models/reporting/"), + command=("mv", "model:order_ledger", "sql/models/reporting/"), expected_returncode=0, - expected_file="models/reporting/order_ledger.sql", + expected_file="sql/models/reporting/order_ledger.sql", expected_output="Compiled: ok", ), PendingMigrationRefactorE2ETestCase( description="rename on top of an undeployed migration is refused", command=("rename", "model:order_ledger", "order_journal"), expected_returncode=1, - expected_file="models/marts/order_ledger.sql", + expected_file="sql/models/marts/order_ledger.sql", expected_output="still declares migrate_from", ), ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_unit_tests_follow_models.py b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_unit_tests_follow_models.py index e320171f48..c025bc8750 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_unit_tests_follow_models.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_unit_tests_follow_models.py @@ -71,7 +71,7 @@ ), FollowedUnitTestE2ETestCase( description="move to another folder moves the test to the mirrored folder", - command=("mv", "model:fact_orders", "models/reporting/"), + command=("mv", "model:fact_orders", "sql/models/reporting/"), expected_fragments={ "tests/unit/reporting/test_fact_orders__keeps_orders.sql": ( 'TEST (name "fact_orders__keeps_orders");', @@ -81,7 +81,7 @@ ), FollowedUnitTestE2ETestCase( description="move with a new name moves and renames the test", - command=("mv", "model:fact_orders", "models/reporting/order_facts.sql"), + command=("mv", "model:fact_orders", "sql/models/reporting/order_facts.sql"), expected_fragments={ "tests/unit/reporting/test_order_facts__keeps_orders.sql": ( 'TEST (name "order_facts__keeps_orders");', @@ -167,8 +167,8 @@ def test_given_dry_run_when_renaming_model_with_unit_test_then_reports_move_and_ ScopedUnitTestMoveE2ETestCase( description="a project-wide constant lets the test move", extra_files={ - "constants/orders.sql": "CONSTANT (name sample_amount, value 25);\n", - "models/marts/customer_totals.sql": CUSTOMER_TOTALS.replace( + "sql/constants/orders.sql": "CONSTANT (name sample_amount, value 25);\n", + "sql/models/marts/customer_totals.sql": CUSTOMER_TOTALS.replace( "GROUP BY customer_id\n", 'GROUP BY customer_id\nHAVING SUM(amount) >= @const("sample_amount")\n', ), @@ -198,7 +198,7 @@ def test_given_scoped_declarations_when_moving_model_then_test_moves_only_if_the remove_files(project_dir=project_dir, paths=("tests/unit/test_fact_orders.sql",)) result: subprocess.CompletedProcess[str] = sqb( - project_dir, "mv", "model:fact_orders", "models/reporting/order_facts.sql" + project_dir, "mv", "model:fact_orders", "sql/models/reporting/order_facts.sql" ) tested: subprocess.CompletedProcess[str] = sqb(project_dir, "test") diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/review/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/review/helpers.py index 9785341dec..491d925273 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/review/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/review/helpers.py @@ -20,9 +20,9 @@ DATABASE_FILE: str = "review_orders.duckdb" DATABASE_NAME: str = "review_orders" REVIEW_SCHEMA_PREFIX: str = "review_" -STAGING: str = "models/stg_orders.sql" -ORDER_TOTALS: str = "models/order_totals.sql" -CUSTOMER_ORDERS: str = "models/customer_orders.sql" +STAGING: str = "sql/models/stg_orders.sql" +ORDER_TOTALS: str = "sql/models/order_totals.sql" +CUSTOMER_ORDERS: str = "sql/models/customer_orders.sql" DROP_FAILURE_PLUGIN: str = "sitecustomize.py" @@ -66,7 +66,7 @@ def build_review_project_files() -> dict[str, str]: """ ).lstrip(), ".gitignore": "target/\nlogs/\n*.duckdb\n*.duckdb.wal\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -89,11 +89,11 @@ def build_review_project_files() -> dict[str, str]: "SELECT order_id, amount_cents / 100.0 AS amount\n" 'FROM __ref("stg_orders")\n' ), - "models/open_orders.sql": ( + "sql/models/open_orders.sql": ( "MODEL (description 'Open orders.', unique_key order_id);\n\n" "SELECT order_id FROM __ref(\"stg_orders\") WHERE status = 'open'\n" ), - "models/order_ledger.sql": ( + "sql/models/order_ledger.sql": ( "MODEL (\n" " description 'Every order once.',\n" " materialized incremental,\n" @@ -143,8 +143,8 @@ def order_statuses_seed(*, rows: str) -> dict[str, str]: """A seed of order statuses and its column types.""" return { - "seeds/order_statuses.csv": "status,label\n" + rows, - "seeds/order_statuses.yml": dedent( + "sql/seeds/order_statuses.csv": "status,label\n" + rows, + "sql/seeds/order_statuses.yml": dedent( """ seeds: - name: order_statuses diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/review/test_review.py b/tests/e2e/src/sqlbuild/cli/commands/main/review/test_review.py index f0e3ca3f3a..3c21b08bd7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/review/test_review.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/review/test_review.py @@ -57,8 +57,8 @@ _HOOKED_TOTALS: str = edited_order_totals( before="critical true);", after='critical true, post_hooks [inline_sql("SELECT 1")]);' ) -_EXPORT_TASK: str = "python/tasks/exports.py" -_OWN_DATABASE_ORDERS: str = "models/own_database_orders.sql" +_EXPORT_TASK: str = "python/nodes/export_totals/asset.py" +_OWN_DATABASE_ORDERS: str = "sql/models/own_database_orders.sql" @pytest.mark.parametrize( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/_test_types.py index e32769cf54..668907f59d 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/_test_types.py @@ -54,7 +54,7 @@ class SharedDepthModelRuleCase: rule: str expected_evaluated_models: int expected_unevaluated_resources: int - path: str = "models/staging/orders.sql" + path: str = "sql/models/staging/orders.sql" extra_files: tuple[tuple[str, str], ...] = () diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/helpers.py index e81e88bcd6..1e857740a2 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/helpers.py @@ -24,7 +24,7 @@ def write_unevaluated_rules_project( configuration: str = "", adapter: str = "duckdb", selected_rules: tuple[str, ...] = ("SQLCLEAN035",), - resource_path: str = "models/staging/orders.sql", + resource_path: str = "sql/models/staging/orders.sql", resource_template: str = ( "MODEL (description 'Test model orders.', {options});\nSELECT {expression} AS order_id" ), @@ -35,7 +35,7 @@ def write_unevaluated_rules_project( f'name = "orders"\nadapter = "{adapter}"\n[rules]\nselect = {json.dumps(selected_rules)}\n' + configuration ) - models: Path = project_dir / "models/staging" + models: Path = project_dir / "sql/models/staging" models.mkdir(parents=True) (models / "orders.sql").write_text( "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n" @@ -86,7 +86,7 @@ def write_custom_rule_project( "\n[rules.thresholds]\nmin_custom_rule_test_cases = 0\n" + configuration, encoding="utf-8", ) - orders: Path = project_dir / "models" / "orders.sql" + orders: Path = project_dir / "sql" / "models" / "orders.sql" orders.parent.mkdir(parents=True, exist_ok=True) orders.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") relative_path: str @@ -157,10 +157,13 @@ def pin_to_one_cpu() -> None: def split_model_files(model_count: int) -> tuple[tuple[str, str], ...]: - """Return numbered order models beside the project's `models/orders.sql`.""" + """Return numbered order models beside the project's `sql/models/orders.sql`.""" return tuple( - (f"models/orders_{index:03d}.sql", 'MODEL (description "Orders");\nSELECT 1 AS order_id\n') + ( + f"sql/models/orders_{index:03d}.sql", + 'MODEL (description "Orders");\nSELECT 1 AS order_id\n', + ) for index in range(model_count) ) @@ -169,12 +172,13 @@ def split_expected_findings(model_count: int) -> tuple[tuple[str, str], ...]: """Return what one host reports for the duplicate-parity and flagged-suffix order rules.""" names: tuple[str, ...] = tuple(f"orders_{index:03d}" for index in range(model_count)) - # `models/orders.sql` sorts first and is the first odd model; `orders_000` is the first even. + # `sql/models/orders.sql` sorts first and is the first odd model; + # `orders_000` is the first even. duplicates: tuple[tuple[str, str], ...] = tuple( - ("XSQBRSPLIT001", f"models/{name}.sql") for name in names[1:] + ("XSQBRSPLIT001", f"sql/models/{name}.sql") for name in names[1:] ) suffixes: tuple[tuple[str, str], ...] = tuple( - ("XSQBRSPLIT002", f"models/{name}.sql") + ("XSQBRSPLIT002", f"sql/models/{name}.sql") for name in filter(lambda name: name.endswith(("3", "7")), names) ) return tuple(sorted(duplicates + suffixes)) @@ -273,8 +277,8 @@ def write_quality_project(*, project_dir: Path, toml: str, upstream: str, summar """Write a two-model project: `raw_orders` and the `order_summary` model under test.""" (project_dir / "sqlbuild_project.toml").write_text(toml, encoding="utf-8") - models: Path = project_dir / "models" - models.mkdir() + models: Path = project_dir / "sql" / "models" + models.mkdir(parents=True) (models / "raw_orders.sql").write_text(upstream, encoding="utf-8") (models / "order_summary.sql").write_text(summary, encoding="utf-8") @@ -332,21 +336,21 @@ def long_literal_hints(result: subprocess.CompletedProcess[str]) -> dict[str, st INCREMENTAL_RULES_PROJECT: dict[str, str] = { "sqlbuild_project.toml": ( - 'name = "orders"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' + 'name = "orders"\nadapter = "duckdb"\ndefault_target = "dev"\nextra_paths = ["config"]\n\n' '[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.dev]\nschema = "dev"\n\n[targets.prod]\nschema = "prod"\n\n' '[vars]\ndiscount_rate = "0.1"\n\n' '[rules]\nselect = ["SQBR", "SQLCLEAN", "XSQBR"]\n\n' "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n" ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.',\n materialized view,\n" " contract enforced,\n columns (\n" " order_id (type INTEGER, nullable false, audits [not_null]),\n" " amount (type DOUBLE),\n ),\n);\n\n" "SELECT CAST(1 AS INTEGER) AS order_id, CAST(10.5 AS DOUBLE) AS amount\n" ), - "models/marts/order_totals.sql": ( + "sql/models/marts/order_totals.sql": ( "MODEL (description 'Test model order_totals.',\n columns (\n" " order_id (type INTEGER, nullable false, audits [not_null]),\n" " net_amount (type DOUBLE),\n ),\n);\n\n" @@ -355,7 +359,7 @@ def long_literal_hints(result: subprocess.CompletedProcess[str]) -> dict[str, st " AS net_amount\n" 'FROM __ref("stg_orders") AS o\n' ), - "models/marts/_sqlbuild/_macros/python/amounts.py": ( + "sql/models/marts/_sqlbuild/_macros/python/amounts.py": ( 'def discounted(amount: str) -> str:\n return f"({amount}) * 0.9"\n' ), "tests/unit/test_order_totals.sql": ( @@ -435,18 +439,18 @@ def flagged_values(*, model: Model, ctx: RuleContext) -> list[Finding]: '[rules]\nselect = ["SQBR"]\ndomains = ["commerce"]\n\n' "[rules.thresholds]\nmin_tests_per_model = 1\n" ), - "models/commerce/staging/commerce__stg__orders.sql": ( + "sql/models/commerce/staging/commerce__stg__orders.sql": ( 'MODEL (description "Staged orders");\n\n' "SELECT CAST(1 AS INTEGER) AS order_id, CAST(10.5 AS DOUBLE) AS amount, " "'paid' AS status\n" ), - "models/commerce/mart/commerce__mart__order_totals.sql": ( + "sql/models/commerce/mart/commerce__mart__order_totals.sql": ( 'MODEL (description "Order totals");\n\n' 'WITH orders AS (\n SELECT * FROM __ref("commerce__stg__orders")\n)\n' "SELECT order_id, amount * 2 AS doubled_amount FROM orders " "WHERE status = 'paid' AND amount > 7\n" ), - "models/commerce/mart/commerce__mart__customers.sql": ( + "sql/models/commerce/mart/commerce__mart__customers.sql": ( 'MODEL (description "Customers");\n\nSELECT customer_id FROM warehouse.raw.customers\n' ), "tests/unit/test_commerce__mart__order_totals.sql": ( @@ -466,7 +470,7 @@ def flagged_values(*, model: Model, ctx: RuleContext) -> list[Finding]: '[rules]\nselect = ["XSQBR"]\n\n' "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Raw orders.\n" ' expression: "(SELECT 1 AS id, CAST(10.5 AS DOUBLE) AS amount, 1 AS customer_id)"\n' @@ -475,20 +479,20 @@ def flagged_values(*, model: Model, ctx: RuleContext) -> list[Finding]: " - name: raw_products\n description: Raw products.\n" ' expression: "(SELECT 1 AS product_id)"\n' ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( 'MODEL (description "Staged orders");\n\n' 'SELECT id AS order_id, amount, customer_id FROM __source("raw_orders")\n' ), - "models/staging/stg_customers.sql": ( + "sql/models/staging/stg_customers.sql": ( 'MODEL (description "Staged customers");\n\n' 'SELECT customer_id FROM __source("raw_customers")\n' ), - "models/marts/order_totals.sql": ( + "sql/models/marts/order_totals.sql": ( 'MODEL (description "Order totals");\n\n' 'SELECT order_id, amount * 2 AS doubled_amount FROM __ref("stg_orders") WHERE amount > 7\n' ), **{ - f"models/intermediate/orders_{index:03d}.sql": ( + f"sql/models/intermediate/orders_{index:03d}.sql": ( f'MODEL (description "Order slice {index}");\n\n' 'SELECT order_id FROM __ref("stg_orders")\n' ) @@ -524,7 +528,7 @@ def approved_sources(*, project: Project, ctx: RuleContext) -> list[Finding]: approved: set[str] = set(ctx.project.tree.read_text("rules/approved_sources.yaml").split()) names: list[str] = sorted(str(getattr(source, "name")) for source in ctx.project.sources) return [ - ctx.finding(subject="sources/raw.yml", message=f"Source {name} is not approved") + ctx.finding(subject="sql/sources/raw.yml", message=f"Source {name} is not approved") for name in names if name not in approved ] @@ -557,7 +561,7 @@ def few_marts(*, project: Project, ctx: RuleContext) -> list[Finding]: ' return [ctx.finding(subject=model)] if "SELECT 3 " in source else []\n' ), **{ - f"models/orders_{index:03d}.sql": ( + f"sql/models/orders_{index:03d}.sql": ( f'MODEL (description "Orders {index}");\n\nSELECT {index} AS order_id\n' ) for index in range(ONE_MODEL_EDIT_MODEL_COUNT) @@ -653,7 +657,7 @@ def move_order_totals_description_to_path_defaults(root: Path) -> None: replace_project_text( root, - "models/marts/order_totals.sql", + "sql/models/marts/order_totals.sql", "MODEL (description 'Test model order_totals.',\n", "MODEL (\n", ) @@ -707,7 +711,7 @@ def write_one_row_cross_join_project( path: Path = project_dir / relative path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") - seed: Path = project_dir / "seeds" / "order_policy.csv" + seed: Path = project_dir / "sql" / "seeds" / "order_policy.csv" seed.write_text("max_amount\n" + "".join(f"{row}\n" for row in seed_rows), encoding="utf-8") return seed diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_clickhouse_comments.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_clickhouse_comments.py index ba1ee05735..5ee33ea70a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_clickhouse_comments.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_clickhouse_comments.py @@ -25,12 +25,12 @@ ClickHouseCommentE2ETestCase( description="a hash comment with an apostrophe is skipped, reported unavailable until SQLBuild parses the dialect", comment="# don't keep the star", - expected_location="models/orders.sql:1:1 [L007]", + expected_location="sql/models/orders.sql:1:1 [L007]", ), ClickHouseCommentE2ETestCase( description="a double-slash comment with an apostrophe is skipped, reported unavailable until SQLBuild parses the dialect", comment="// don't keep the star", - expected_location="models/orders.sql:1:1 [L007]", + expected_location="sql/models/orders.sql:1:1 [L007]", ), ], ids=lambda case: case.description, @@ -43,7 +43,7 @@ def test_given_clickhouse_line_comment_when_running_rules_then_it_is_not_scanned project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n" f"WITH o AS (SELECT 1 AS id)\n{test_case.comment}\nSELECT * FROM o\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_cross_join_one_row.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_cross_join_one_row.py index 9289e03b24..c698faec6c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_cross_join_one_row.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_cross_join_one_row.py @@ -79,8 +79,8 @@ ) -_SEED_YAML_FILE: tuple[str, str] = ("seeds/order_policy.yml", _SEED_YAML) -_RAW_ORDERS_FILE: tuple[str, str] = ("models/raw_orders.sql", _RAW_ORDERS_SQL) +_SEED_YAML_FILE: tuple[str, str] = ("sql/seeds/order_policy.yml", _SEED_YAML) +_RAW_ORDERS_FILE: tuple[str, str] = ("sql/models/raw_orders.sql", _RAW_ORDERS_SQL) @pytest.mark.parametrize( @@ -135,7 +135,7 @@ def test_given_cross_join_when_compiling_then_only_multiplying_joins_are_reporte files=( _SEED_YAML_FILE, _RAW_ORDERS_FILE, - ("models/checked_orders.sql", test_case.model_sql), + ("sql/models/checked_orders.sql", test_case.model_sql), ), ) @@ -171,7 +171,7 @@ def test_given_one_row_seed_when_a_row_is_added_then_the_cached_compile_reports_ files=( _SEED_YAML_FILE, _RAW_ORDERS_FILE, - ("models/checked_orders.sql", test_case.model_sql), + ("sql/models/checked_orders.sql", test_case.model_sql), ), ) first: subprocess.CompletedProcess[str] = run_compile_cli(tmp_path) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rule_hermeticity.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rule_hermeticity.py index 0773c8b483..465cbb724c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rule_hermeticity.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rule_hermeticity.py @@ -146,12 +146,12 @@ def test_given_hermetic_rule_when_compiling_then_rule_is_evaluated( code="XSQBROPEN001", body=( ' reader = getattr(pathlib, "__builtins__")["op" + "en"]\n' - ' reader("models/orders.sql").close()\n' + ' reader("sql/models/orders.sql").close()\n' " return []\n" ), ), expected_line=9, - expected_action="opening 'models/orders.sql'", + expected_action="opening 'sql/models/orders.sql'", ), NonHermeticRuleCase( description="file read through an aliased method is rejected even when caught", @@ -161,14 +161,14 @@ def test_given_hermetic_rule_when_compiling_then_rule_is_evaluated( body=( " reader = pathlib.Path.read_text\n" " try:\n" - ' reader(pathlib.Path("models/orders.sql"))\n' + ' reader(pathlib.Path("sql/models/orders.sql"))\n' " except Exception:\n" " pass\n" " return []\n" ), ), expected_line=10, - expected_action="opening 'models/orders.sql'", + expected_action="opening 'sql/models/orders.sql'", ), NonHermeticRuleCase( description="file existence probe through pathlib is rejected", @@ -189,12 +189,12 @@ def test_given_hermetic_rule_when_compiling_then_rule_is_evaluated( source=custom_rule_source( code="XSQBRMETA002", body=( - ' modified = pathlib.Path("models/orders.sql").stat().st_mtime\n' + ' modified = pathlib.Path("sql/models/orders.sql").stat().st_mtime\n' " return [ctx.finding(subject=model)] * int(modified < 0)\n" ), ), expected_line=8, - expected_action="reading file metadata for 'models/orders.sql'", + expected_action="reading file metadata for 'sql/models/orders.sql'", ), NonHermeticRuleCase( description="command run through an allowed module is rejected", @@ -316,14 +316,14 @@ def test_given_rule_iterating_a_string_set_when_compiling_then_order_uses_fixed_ code="XSQBRTREE001", body=( ' policy = ctx.project.tree.read_text("rules/orders_policy.yaml")\n' - ' models = ctx.project.tree.glob("models/*.sql")\n' + ' models = ctx.project.tree.glob("sql/models/*.sql")\n' ' required = "required: true" in policy and len(models) > 1\n' " return [ctx.finding(subject=model)] * int(required)\n" ), ), policy_path="rules/orders_policy.yaml", - added_model_path="models/customers.sql", - expected_paths_after_glob_change=("models/customers.sql", "models/orders.sql"), + added_model_path="sql/models/customers.sql", + expected_paths_after_glob_change=("sql/models/customers.sql", "sql/models/orders.sql"), expected_minimum_cache_hits=1, ) ], @@ -418,7 +418,7 @@ def test_given_rule_observing_cwd_when_invoked_from_different_directories_then_v tmp_path: Path, test_case: WorkingDirectoryCase ) -> None: project_dir: Path = tmp_path / "project" - project_dir.mkdir() + project_dir.mkdir(parents=True) write_custom_rule_project( project_dir=project_dir, selected_rules=(test_case.code,), @@ -553,7 +553,7 @@ def test_given_stateful_and_stateless_rules_when_split_across_hosts_then_finding single_dir: Path = tmp_path / "single" split_dir: Path = tmp_path / "split" for project_dir in (single_dir, split_dir): - project_dir.mkdir() + project_dir.mkdir(parents=True) write_custom_rule_project( project_dir=project_dir, selected_rules=test_case.selected_rules, files=test_case.files ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rule_timings.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rule_timings.py index b47ec59e4b..77ee21e8a7 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rule_timings.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rule_timings.py @@ -138,7 +138,7 @@ def test_given_custom_rules_when_compiling_then_timings_and_no_cache_report_each ), *split_model_files(_MODEL_COUNT), ), - edited_model="models/orders_001.sql", + edited_model="sql/models/orders_001.sql", expected_misses_after_edit={ "XSQBRSTATE001": _MODEL_COUNT + 1, "XSQBRSTATE002": 0, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rules_incremental_sequence.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rules_incremental_sequence.py index 7e49d93a05..0357cc2e9d 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rules_incremental_sequence.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_custom_rules_incremental_sequence.py @@ -25,8 +25,8 @@ ) CONFIG: str = "sqlbuild_project.toml" -ORDER_TOTALS: str = "models/marts/order_totals.sql" -SOURCES: str = "sources/raw.yml" +ORDER_TOTALS: str = "sql/models/marts/order_totals.sql" +SOURCES: str = "sql/sources/raw.yml" APPROVED: str = "rules/approved_sources.yaml" CUSTOM_EDIT_SEQUENCE: tuple[RulesCacheEditCase, ...] = ( RulesCacheEditCase( @@ -47,14 +47,14 @@ "mart_added", lambda root: write_project_file( root, - "models/marts/customer_totals.sql", + "sql/models/marts/customer_totals.sql", 'MODEL (description "Customer totals");\n\n' 'SELECT customer_id FROM __ref("stg_customers")\n', ), ), RulesCacheEditCase( "model_removed", - lambda root: (root / "models/intermediate/orders_007.sql").unlink(), + lambda root: (root / "sql/models/intermediate/orders_007.sql").unlink(), ), RulesCacheEditCase( "rules_cache_disabled", @@ -112,7 +112,7 @@ def test_given_warm_custom_rules_when_applying_edit_chain_then_every_compile_equ ( OneModelCustomRuleEditCase( description="edit_adds_a_finding", - edited_model="models/orders_002.sql", + edited_model="sql/models/orders_002.sql", before="SELECT 2 AS", after="SELECT 3 AS", expected_warm_counts=(ONE_MODEL_EDIT_CACHED_RESULTS, 0), @@ -121,7 +121,7 @@ def test_given_warm_custom_rules_when_applying_edit_chain_then_every_compile_equ ), OneModelCustomRuleEditCase( description="edit_removes_the_finding", - edited_model="models/orders_003.sql", + edited_model="sql/models/orders_003.sql", before="SELECT 3 AS", after="SELECT 30 AS", expected_warm_counts=(ONE_MODEL_EDIT_CACHED_RESULTS, 0), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_default_rule_selection.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_default_rule_selection.py index 5261589d0b..a3d1082bab 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_default_rule_selection.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_default_rule_selection.py @@ -97,7 +97,7 @@ def test_given_rule_selection_when_running_commands_then_defaults_and_notice_fol project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML + test_case.rules_section, - "models/orders.sql": _HEADER + test_case.sql, + "sql/models/orders.sql": _HEADER + test_case.sql, }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_published_layer_rules.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_published_layer_rules.py index 6e71507791..67622c14c9 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_published_layer_rules.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_published_layer_rules.py @@ -22,18 +22,18 @@ 'allowed_qualifiers = [{ domain = "sales", qualifier = "finance", ' 'reason = "Finance reads a reviewed published variant." }]\n' ) -_FINANCE_PATH: str = "models/sales/mart/sales__mart__orders__finance.sql" +_FINANCE_PATH: str = "sql/models/sales/mart/sales__mart__orders__finance.sql" _INTERMEDIATE: tuple[str, str] = ( - "models/sales/intermediate/clean/sales__int_clean__orders.sql", + "sql/models/sales/intermediate/clean/sales__int_clean__orders.sql", "MODEL (description 'Clean orders.');\nSELECT 1 AS order_id\n", ) _ORDERS: tuple[str, str] = ( - "models/sales/mart/sales__mart__orders.sql", + "sql/models/sales/mart/sales__mart__orders.sql", "MODEL (description 'Published orders.');\n" 'SELECT o.order_id FROM __ref("sales__int_clean__orders") AS o\n', ) _CUSTOMERS: tuple[str, str] = ( - "models/sales/mart/sales__mart__customers.sql", + "sql/models/sales/mart/sales__mart__customers.sql", "MODEL (description 'Published customers.');\n" 'SELECT o.order_id FROM __ref("sales__int_clean__orders") AS o\n', ) @@ -43,17 +43,17 @@ 'SELECT o.order_id FROM __ref("sales__mart__orders") AS o\n', ) _FINANCE_STAGING: tuple[str, str] = ( - "models/finance/staging/finance__stg_v__orders.sql", + "sql/models/finance/staging/finance__stg_v__orders.sql", "MODEL (description 'Finance view of orders.');\n" 'SELECT o.order_id FROM __ref("sales__mart__orders__finance") AS o\n', ) _ORDERS_VIEW: tuple[str, str] = ( - "models/sales/mart/sales__mart_v__orders.sql", + "sql/models/sales/mart/sales__mart_v__orders.sql", "MODEL (description 'Orders view.');\n" 'SELECT o.order_id FROM __ref("sales__mart__orders") AS o\n', ) _FINANCE_FROM_PUBLISHED: tuple[str, str] = ( - "models/finance/staging/finance__stg_v__orders.sql", + "sql/models/finance/staging/finance__stg_v__orders.sql", "MODEL (description 'Finance view of orders.');\n" 'SELECT o.order_id FROM __ref("sales__mart__orders") AS o\n', ) @@ -64,12 +64,12 @@ ) _REGIONAL_PATHS: str = ( "\n[rules.rule_options.SQBRPROJECT107]\n" - 'allowed_qualifiers = [{ paths = ["models/sales/mart/regional/*"], ' + 'allowed_qualifiers = [{ paths = ["sql/models/sales/mart/regional/*"], ' 'reason = "Published once per country." }]\n' ) _COUNTRIES: tuple[tuple[str, str], ...] = tuple( ( - f"models/sales/mart/regional/sales__mart__orders__{country}.sql", + f"sql/models/sales/mart/regional/sales__mart__orders__{country}.sql", f"MODEL (description 'Orders published for {country}.');\n" 'SELECT o.order_id FROM __ref("sales__int_clean__orders") AS o\n', ) @@ -112,8 +112,8 @@ files=_PER_COUNTRY, rules_toml="", expected_findings=( - ("SQBRPROJECT107", "models/sales/mart/sales__mart__customers.sql"), - ("SQBRPROJECT107", "models/sales/mart/sales__mart__orders.sql"), + ("SQBRPROJECT107", "sql/models/sales/mart/sales__mart__customers.sql"), + ("SQBRPROJECT107", "sql/models/sales/mart/sales__mart__orders.sql"), ), expected_exit=1, ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rule_exception_config.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rule_exception_config.py index b23a1409ee..3beb5298db 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rule_exception_config.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rule_exception_config.py @@ -16,7 +16,7 @@ ) _PROJECT_TOML: str = 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN038"]\n' -_MODEL_PATH: str = "models/order_checks.sql" +_MODEL_PATH: str = "sql/models/order_checks.sql" _CUSTOMERS: str = ( "CROSS JOIN with `customers` in CTE `order_checks` creates an explicit cartesian product" ) @@ -62,12 +62,12 @@ 'SELECT o.order_id, u.n FROM __ref("orders") AS o CROSS JOIN UNNEST([1, 2]) AS u(n)\n' ) _UPSTREAM_FILES: tuple[tuple[str, str], ...] = ( - ("models/orders.sql", "MODEL (description 'Sample orders.');\nSELECT 1 AS order_id\n"), + ("sql/models/orders.sql", "MODEL (description 'Sample orders.');\nSELECT 1 AS order_id\n"), ( - "models/customers.sql", + "sql/models/customers.sql", "MODEL (description 'Sample customers.');\nSELECT 1 AS customer_id\n", ), - ("models/regions.sql", "MODEL (description 'Sample regions.');\nSELECT 1 AS region_id\n"), + ("sql/models/regions.sql", "MODEL (description 'Sample regions.');\nSELECT 1 AS region_id\n"), ) @@ -101,7 +101,7 @@ expected_exit=1, expected_fragments=( "stale rule exception suppresses no finding: SQLCLEAN038 at " - "models/order_checks.sql (relation shipments)", + "sql/models/order_checks.sql (relation shipments)", ), ), RuleExceptionConfigCase( @@ -113,7 +113,7 @@ expected_fragments=( "Inline Rule suppressions are not supported", '[[rules.rule_exceptions]]\n rule = "SQLCLEAN038"\n' - ' path = "models/order_checks.sql"\n' + ' path = "sql/models/order_checks.sql"\n' ' relation = "customers"\n' ' reason = "every order meets every customer"', ), @@ -145,7 +145,7 @@ ), expected_fragments=( '[[rules.rule_exceptions]]\n rule = "SQLCLEAN038"\n' - ' path = "models/order_checks.sql"\n', + ' path = "sql/models/order_checks.sql"\n', ), ), RuleExceptionConfigCase( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rule_positions.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rule_positions.py index d4c2714153..e79d362d0a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rule_positions.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rule_positions.py @@ -25,7 +25,7 @@ " columns (a (type VARCHAR), b (type VARCHAR), c (type VARCHAR)),\n);\n" ) _BLANK_TO_NULL: dict[str, str] = { - "macros/sql/blank_to_null.sql": ( + "sql/macros/sql/blank_to_null.sql": ( 'MACRO (description "Blank to null.", arguments (x VARCHAR), returns VARCHAR);\n\n' "CASE\n WHEN TRIM(@x) = ''\n THEN NULL\n ELSE\n TRIM(@x)\nEND\n" ) @@ -82,17 +82,17 @@ RulePositionE2ETestCase( description="a query on the header's line is offset by the header", model_sql=f"{_HEADER} WITH o AS (SELECT 1 AS id) SELECT * FROM o\n", - expected_location="models/orders.sql:1:97 [SQBRMODEL102]", + expected_location="sql/models/orders.sql:1:97 [SQBRMODEL102]", ), RulePositionE2ETestCase( description="a query starting on the header's line keeps later lines unshifted", model_sql=f"{_HEADER} WITH o AS (SELECT 1 AS id)\nSELECT * FROM o\n", - expected_location="models/orders.sql:2:8 [SQBRMODEL102]", + expected_location="sql/models/orders.sql:2:8 [SQBRMODEL102]", ), RulePositionE2ETestCase( description="a query below the header counts file lines", model_sql=f"{_HEADER}\n-- orders\nWITH o AS (SELECT 1 AS id) SELECT * FROM o\n", - expected_location="models/orders.sql:3:35 [SQBRMODEL102]", + expected_location="sql/models/orders.sql:3:35 [SQBRMODEL102]", ), RulePositionE2ETestCase( description="a star below multi-line macro expansions points at its authored line", @@ -101,7 +101,7 @@ " @sql.blank_to_null('b') AS b\n)\nSELECT * FROM o\n" ), macro_files=_BLANK_TO_NULL, - expected_location="models/orders.sql:7:8 [SQBRMODEL102]", + expected_location="sql/models/orders.sql:7:8 [SQBRMODEL102]", ), RulePositionE2ETestCase( description="a star after a macro call on its line points at its authored column", @@ -110,7 +110,7 @@ "SELECT @sql.blank_to_null('a') AS x, * FROM o\n" ), macro_files=_BLANK_TO_NULL, - expected_location="models/orders.sql:3:38 [SQBRMODEL102]", + expected_location="sql/models/orders.sql:3:38 [SQBRMODEL102]", ), RulePositionE2ETestCase( description="the third of three macro call outputs points at its authored line", @@ -120,7 +120,7 @@ ), rule="SQBRCONTRACT105", macro_files=_BLANK_TO_NULL, - expected_location="models/orders.sql:10:3 [SQBRCONTRACT105]", + expected_location="sql/models/orders.sql:10:3 [SQBRCONTRACT105]", ), ], ids=lambda case: case.description, @@ -136,7 +136,7 @@ def test_given_model_query_layout_when_running_rules_then_findings_use_file_posi 'name = "shop"\nadapter = "duckdb"\n\n[connection]\ndatabase = "shop.duckdb"\n\n' "[scopes]\nenforce_placement = false\n" ), - "models/orders.sql": test_case.model_sql, + "sql/models/orders.sql": test_case.model_sql, **test_case.macro_files, }, ) @@ -196,11 +196,11 @@ def test_given_custom_rule_over_the_syntax_tree_when_compiling_then_nodes_point_ selected_rules=("XSQBRTREE001",), files=( ("rules/tree.py", _TREE_RULE), - *((f"models/{name}.sql", sql) for name, sql in test_case.other_models.items()), + *((f"sql/models/{name}.sql", sql) for name, sql in test_case.other_models.items()), ), adapter=test_case.adapter, ) - (tmp_path / "models" / "orders.sql").write_text(test_case.model_sql, encoding="utf-8") + (tmp_path / "sql" / "models" / "orders.sql").write_text(test_case.model_sql, encoding="utf-8") result: subprocess.CompletedProcess[str] = run_compile_cli(tmp_path) @@ -252,11 +252,11 @@ def test_given_custom_rule_reading_node_facts_when_compiling_then_it_sees_the_au selected_rules=("XSQBRTREE002",), files=( ("rules/facts.py", _FACTS_RULE), - *((f"models/{name}.sql", sql) for name, sql in test_case.other_models.items()), + *((f"sql/models/{name}.sql", sql) for name, sql in test_case.other_models.items()), ), adapter=test_case.adapter, ) - (tmp_path / "models" / "orders.sql").write_text(test_case.model_sql, encoding="utf-8") + (tmp_path / "sql" / "models" / "orders.sql").write_text(test_case.model_sql, encoding="utf-8") result: subprocess.CompletedProcess[str] = run_compile_cli(tmp_path) @@ -298,7 +298,7 @@ def test_given_custom_rule_finding_at_a_node_when_compiling_then_it_points_at_th configuration="\n[scopes]\nenforce_placement = false\n", adapter=test_case.adapter, ) - (tmp_path / "models" / "orders.sql").write_text(test_case.model_sql, encoding="utf-8") + (tmp_path / "sql" / "models" / "orders.sql").write_text(test_case.model_sql, encoding="utf-8") cold: subprocess.CompletedProcess[str] = run_compile_cli(tmp_path) warm: subprocess.CompletedProcess[str] = run_compile_cli(tmp_path) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rules_cache_invalidation.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rules_cache_invalidation.py index 34b706d80f..e9359bcc1b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rules_cache_invalidation.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rules_cache_invalidation.py @@ -26,7 +26,7 @@ "model_sql_edit", lambda root: replace_project_text( root, - "models/staging/stg_orders.sql", + "sql/models/staging/stg_orders.sql", "CAST(10.5 AS DOUBLE)", "CAST(12.5 AS DOUBLE)", ), @@ -34,14 +34,14 @@ RulesCacheEditCase( "model_contract_edit", lambda root: replace_project_text( - root, "models/staging/stg_orders.sql", " contract enforced,\n", "" + root, "sql/models/staging/stg_orders.sql", " contract enforced,\n", "" ), ), RulesCacheEditCase( "model_description_edited", lambda root: replace_project_text( root, - "models/staging/stg_orders.sql", + "sql/models/staging/stg_orders.sql", "Test model stg_orders.", "Staged order rows.", ), @@ -50,7 +50,7 @@ "model_description_removed", lambda root: replace_project_text( root, - "models/marts/order_totals.sql", + "sql/models/marts/order_totals.sql", "MODEL (description 'Test model order_totals.',\n", "MODEL (\n", ), @@ -64,7 +64,7 @@ "model_added", lambda root: write_project_file( root, - "models/marts/order_counts.sql", + "sql/models/marts/order_counts.sql", 'MODEL (description "Test model order_counts.");\n\nSELECT order_id FROM __ref("stg_orders")\n', ), ), @@ -72,7 +72,7 @@ "consumer_removed", lambda root: replace_project_text( root, - "models/marts/order_totals.sql", + "sql/models/marts/order_totals.sql", 'FROM __ref("stg_orders") AS o\n', "FROM (SELECT 1 AS order_id, 1.0 AS amount) AS o\n", ), @@ -89,7 +89,7 @@ RulesCacheEditCase( "macro_edit", lambda root: replace_project_text( - root, "models/marts/_sqlbuild/_macros/python/amounts.py", "* 0.9", "* 0.8" + root, "sql/models/marts/_sqlbuild/_macros/python/amounts.py", "* 0.9", "* 0.8" ), ), RulesCacheEditCase( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rules_incremental_sequence.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rules_incremental_sequence.py index c4c373c8bc..3345440435 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rules_incremental_sequence.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_rules_incremental_sequence.py @@ -23,8 +23,8 @@ ) _CONFIG: str = "sqlbuild_project.toml" -_ORDER_TOTALS: str = "models/commerce/mart/commerce__mart__order_totals.sql" -_PRODUCTS: str = "models/commerce/mart/commerce__mart__products.sql" +_ORDER_TOTALS: str = "sql/models/commerce/mart/commerce__mart__order_totals.sql" +_PRODUCTS: str = "sql/models/commerce/mart/commerce__mart__products.sql" EDIT_SEQUENCE: tuple[RulesCacheEditCase, ...] = ( RulesCacheEditCase( @@ -41,12 +41,12 @@ ), RulesCacheEditCase( "model_removed", - lambda root: (root / "models/commerce/mart/commerce__mart__customers.sql").unlink(), + lambda root: (root / "sql/models/commerce/mart/commerce__mart__customers.sql").unlink(), ), RulesCacheEditCase( "model_renamed", lambda root: move_project_file( - root, _PRODUCTS, "models/commerce/mart/commerce__mart__catalog_products.sql" + root, _PRODUCTS, "sql/models/commerce/mart/commerce__mart__catalog_products.sql" ), ), RulesCacheEditCase( @@ -62,7 +62,7 @@ _CONFIG, "[rules.thresholds]", '[[rules.rule_ignores]]\nrules = ["SQBRTEST201"]\n' - 'paths = ["models/commerce/staging/commerce__stg__orders.sql"]\n' + 'paths = ["sql/models/commerce/staging/commerce__stg__orders.sql"]\n' 'reason = "Audits arrive with the source contract"\n\n[rules.thresholds]', ), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_selected_project_wide_rules.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_selected_project_wide_rules.py index 45cb90150b..219e1d1452 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_selected_project_wide_rules.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_selected_project_wide_rules.py @@ -26,14 +26,14 @@ ) _FINDING_LINE: re.Pattern[str] = re.compile(r"^(\S+):\d+:\d+ \[(X?SQBR\w+)\] ", re.MULTILINE) -_RETURNS_PATH: str = "models/sales/mart/sales__mart__returns__finance.sql" -_REFUNDS_PATH: str = "models/sales/mart/sales__mart__refunds__audit.sql" -_ORDERS_PATH: str = "models/sales/mart/sales__mart__orders.sql" -_CUSTOMERS_PATH: str = "models/sales/mart/sales__mart__customers.sql" -_CONSUMER_PATH: str = "models/finance/staging/finance__stg_v__orders.sql" +_RETURNS_PATH: str = "sql/models/sales/mart/sales__mart__returns__finance.sql" +_REFUNDS_PATH: str = "sql/models/sales/mart/sales__mart__refunds__audit.sql" +_ORDERS_PATH: str = "sql/models/sales/mart/sales__mart__orders.sql" +_CUSTOMERS_PATH: str = "sql/models/sales/mart/sales__mart__customers.sql" +_CONSUMER_PATH: str = "sql/models/finance/staging/finance__stg_v__orders.sql" _FILES: tuple[tuple[str, str], ...] = ( ( - "models/sales/intermediate/clean/sales__int_clean__orders.sql", + "sql/models/sales/intermediate/clean/sales__int_clean__orders.sql", "MODEL (description 'Clean orders.');\nSELECT 1 AS order_id\n", ), (_ORDERS_PATH, "MODEL (description 'Published orders.');\nSELECT 1 AS order_id\n"), @@ -43,7 +43,7 @@ 'SELECT o.order_id FROM __ref("sales__int_clean__orders") AS o\n', ), ( - "models/sales/mart/sales__mart__products.sql", + "sql/models/sales/mart/sales__mart__products.sql", "MODEL (description 'Published products.');\nSELECT 1 AS order_id\n", ), ( @@ -60,7 +60,7 @@ 'JOIN __ref("sales__mart__orders") AS o ON r.order_id = o.order_id\n', ), ) -_PRODUCTS_PATH: str = "models/sales/mart/sales__mart__products.sql" +_PRODUCTS_PATH: str = "sql/models/sales/mart/sales__mart__products.sql" _CACHE_FILES: tuple[tuple[str, str], ...] = ( (_ORDERS_PATH, "MODEL (description 'Published orders.');\nSELECT 1 AS order_id\n"), (_CUSTOMERS_PATH, "MODEL (description 'Published customers.');\nSELECT 1 AS customer_id\n"), @@ -73,7 +73,7 @@ 'reason = "Reviewed qualified variants."\n' ) -_ORDERS_BASE_PATH: str = "models/orders_base.sql" +_ORDERS_BASE_PATH: str = "sql/models/orders_base.sql" _PUBLISHED_VIEW_RULE: str = custom_rule_source( code="XSQBRPUB001", body=( @@ -237,12 +237,12 @@ def test_given_selection_when_planning_then_graph_reading_model_rules_see_whole_ ("rules/published.py", _PUBLISHED_VIEW_RULE), (_ORDERS_BASE_PATH, "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n"), ( - "models/orders_report.sql", + "sql/models/orders_report.sql", "MODEL (description 'Order report.');\n" 'SELECT order_id FROM __ref("orders_base")\n', ), ( - "models/orders_published.sql", + "sql/models/orders_published.sql", "MODEL (description 'Published orders.', materialized view);\n" + test_case.view_sql, ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_quality_rules.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_quality_rules.py index 7c40868fbb..9df0ae4c46 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_quality_rules.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_quality_rules.py @@ -170,8 +170,8 @@ def test_given_quality_rule_violations_when_compiling_and_fixing_then_findings_a test_case: SqlQualityRuleCase, tmp_path: Path ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_PROJECT_TOML, encoding="utf-8") - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "raw_orders.sql").write_text(test_case.upstream_header + _UPSTREAM_SQL) (models / "order_summary.sql").write_text(_SUMMARY_HEADER + test_case.query_sql) @@ -211,7 +211,7 @@ def test_given_quality_rule_violations_when_compiling_and_fixing_then_findings_a upstream_sql=_CURSOR_INCREMENTAL_SQL, query_sql=_RENAMED_CHAIN_SQL, expected_codes=(), - extra_files=(("sources/landing_events.yml", _CURSOR_SOURCE_YML),), + extra_files=(("sql/sources/landing_events.yml", _CURSOR_SOURCE_YML),), ), RankingKeyProofCase( description="a key-matched delete_insert unique_key proves the order", @@ -239,7 +239,7 @@ def test_given_quality_rule_violations_when_compiling_and_fixing_then_findings_a upstream_sql=_CURSOR_INCREMENTAL_SQL, query_sql=_RENAMED_CHAIN_SQL, expected_codes=("SQLCLEAN018",), - extra_files=(("sources/landing_events.yml", _CURSOR_SOURCE_YML),), + extra_files=(("sql/sources/landing_events.yml", _CURSOR_SOURCE_YML),), ), RankingKeyProofCase( description="a snapshot unique_key identifies entities, not versions", @@ -273,7 +273,7 @@ def test_given_quality_rule_violations_when_compiling_and_fixing_then_findings_a '__ref("raw_orders")', '__source("landing_orders")' ), expected_codes=(), - extra_files=(("sources/landing.yml", _KEYED_SOURCE_YML),), + extra_files=(("sql/sources/landing.yml", _KEYED_SOURCE_YML),), ), RankingKeyProofCase( description="a QUALIFY window cannot prove its own order", @@ -494,40 +494,40 @@ def test_given_long_value_as_constant_or_literal_when_compiling_then_only_litera DuplicateLiteralCase( description="two models in one folder share a literal", literals=( - ("models/sales/orders.sql", _SHARED_LITERAL), - ("models/sales/refunds.sql", _SHARED_LITERAL), - ("models/support/tickets.sql", _OTHER_LITERAL), + ("sql/models/sales/orders.sql", _SHARED_LITERAL), + ("sql/models/sales/refunds.sql", _SHARED_LITERAL), + ("sql/models/support/tickets.sql", _OTHER_LITERAL), ), expected_hints=( ( - "models/sales/orders.sql", - "The identical literal also appears in models/sales/refunds.sql; their " - "nearest common folder is `models/sales`, so declare it once in " - "`models/sales/_sqlbuild/_constants/` and reference it with `@const` in " + "sql/models/sales/orders.sql", + "The identical literal also appears in sql/models/sales/refunds.sql; their " + "nearest common folder is `sql/models/sales`, so declare it once in " + "`sql/models/sales/_sqlbuild/_constants/` and reference it with `@const` in " "each file.", ), ( - "models/sales/refunds.sql", - "The identical literal also appears in models/sales/orders.sql; their " - "nearest common folder is `models/sales`, so declare it once in " - "`models/sales/_sqlbuild/_constants/` and reference it with `@const` in " + "sql/models/sales/refunds.sql", + "The identical literal also appears in sql/models/sales/orders.sql; their " + "nearest common folder is `sql/models/sales`, so declare it once in " + "`sql/models/sales/_sqlbuild/_constants/` and reference it with `@const` in " "each file.", ), - ("models/support/tickets.sql", None), + ("sql/models/support/tickets.sql", None), ), ), DuplicateLiteralCase( description="a subfolder use moves the declaration to the inherited role", literals=( - ("models/sales/orders.sql", _SHARED_LITERAL), - ("models/sales/east/refunds.sql", _SHARED_LITERAL), + ("sql/models/sales/orders.sql", _SHARED_LITERAL), + ("sql/models/sales/east/refunds.sql", _SHARED_LITERAL), ), expected_hints=( ( - "models/sales/orders.sql", - "The identical literal also appears in models/sales/east/refunds.sql; their " - "nearest common folder is `models/sales`, so declare it once in " - "`models/sales/_sqlbuild/constants/` and reference it with `@const` in " + "sql/models/sales/orders.sql", + "The identical literal also appears in sql/models/sales/east/refunds.sql; their " + "nearest common folder is `sql/models/sales`, so declare it once in " + "`sql/models/sales/_sqlbuild/constants/` and reference it with `@const` in " "each file.", ), ), @@ -535,15 +535,15 @@ def test_given_long_value_as_constant_or_literal_when_compiling_then_only_litera DuplicateLiteralCase( description="uses in different top folders need a project-wide constant", literals=( - ("models/sales/orders.sql", _SHARED_LITERAL), - ("models/support/tickets.sql", _SHARED_LITERAL), + ("sql/models/sales/orders.sql", _SHARED_LITERAL), + ("sql/models/support/tickets.sql", _SHARED_LITERAL), ), expected_hints=( ( - "models/sales/orders.sql", - "The identical literal also appears in models/support/tickets.sql; no " + "sql/models/sales/orders.sql", + "The identical literal also appears in sql/models/support/tickets.sql; no " "folder below the project roots holds every use, so declare it once in " - "top-level `constants/` and reference it with `@const` in each file.", + "top-level `sql/constants/` and reference it with `@const` in each file.", ), ), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_rule_paths.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_rule_paths.py index 35561375d0..496974baff 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_rule_paths.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_rule_paths.py @@ -22,18 +22,18 @@ "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN"]\n' ), - "models/staging/orders.sql": ( + "sql/models/staging/orders.sql": ( 'MODEL (description "Orders");\n' "WITH unused_orders AS (SELECT 1 AS order_id), " "kept AS (SELECT 2 AS order_id)\n" 'SELECT kept.order_id FROM kept WHERE @py.order_filter("kept.order_id")\n' ), - "models/staging/customers.sql": ( + "sql/models/staging/customers.sql": ( 'MODEL (description "Customers");\r\n' "WITH spare AS (SELECT 1 AS customer_id)\r\n" "SELECT 1 AS customer_id\r\n" ), - "models/staging/_sqlbuild/_macros/python/order_filter.py": ( + "sql/models/staging/_sqlbuild/_macros/python/order_filter.py": ( 'def order_filter(column: str) -> str:\n return f"{column} > 0"\n' ), "tests/unit/test_orders.sql": ( @@ -44,13 +44,13 @@ ), }, expected_findings=( - ("models/staging/customers.sql", 2, 6, "SQLCLEAN005"), - ("models/staging/customers.sql", 2, 6, "SQLCLEAN041"), - ("models/staging/customers.sql", 3, 1, "SQLCLEAN035"), - ("models/staging/orders.sql", 2, 6, "SQLCLEAN005"), - ("models/staging/orders.sql", 2, 47, "SQLCLEAN041"), - ("models/staging/orders.sql", 3, 1, "SQLCLEAN034"), - ("models/staging/orders.sql", 3, 1, "SQLCLEAN035"), + ("sql/models/staging/customers.sql", 2, 6, "SQLCLEAN005"), + ("sql/models/staging/customers.sql", 2, 6, "SQLCLEAN041"), + ("sql/models/staging/customers.sql", 3, 1, "SQLCLEAN035"), + ("sql/models/staging/orders.sql", 2, 6, "SQLCLEAN005"), + ("sql/models/staging/orders.sql", 2, 47, "SQLCLEAN041"), + ("sql/models/staging/orders.sql", 3, 1, "SQLCLEAN034"), + ("sql/models/staging/orders.sql", 3, 1, "SQLCLEAN035"), ("tests/unit/test_orders.sql", 4, 1, "SQLCLEAN005"), ("tests/unit/test_orders.sql", 5, 59, "SQLCLEAN004"), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_rule_target_vars.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_rule_target_vars.py index 12a7bde3a6..2465b7c0ab 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_rule_target_vars.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_sql_rule_target_vars.py @@ -16,20 +16,20 @@ '[vars]\nprobe = "1"\n\n[targets.dev]\n\n[targets.prod]\n\n' '[targets.prod.vars]\nprobe = "NULL"\nregion = "us"\n' ) -_MODEL_PATH: str = "models/orders.sql" +_MODEL_PATH: str = "sql/models/orders.sql" _MODEL_SQL: str = ( "MODEL (description 'Test model orders.');\n" 'SELECT o.id FROM __ref("raw_orders") AS o WHERE o.id = @@probe\n' ) _UPSTREAM_FILES: dict[str, str] = { - "models/raw_orders.sql": "MODEL (description 'Test model raw orders.');\nSELECT 1 AS id\n" + "sql/models/raw_orders.sql": "MODEL (description 'Test model raw orders.');\nSELECT 1 AS id\n" } _PROD_ONLY_MODEL: dict[str, str] = { - "models/regions.sql": ( + "sql/models/regions.sql": ( "MODEL (description 'Test model regions.');\nSELECT '@@region' AS region\n" ) } -_AUDIT_PATH: str = "audits/singular/orders_have_ids.sql" +_AUDIT_PATH: str = "sql/audits/singular/orders_have_ids.sql" _AUDIT_BODY: str = ( 'SELECT o.id\nFROM __ref("orders") AS o\n' 'INNER JOIN __ref("raw_orders") AS r ON o.id = r.id\nWHERE o.id = NULL\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_unevaluated.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_unevaluated.py index e795e8c815..8714f9d33f 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_unevaluated.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_unevaluated.py @@ -34,7 +34,7 @@ [ UnevaluatedResourceCase( "model guard", - "models/staging/orders.sql", + "sql/models/staging/orders.sql", "MODEL (description 'Test model orders.');\nSELECT {expression} AS order_id", 0, ), @@ -103,10 +103,10 @@ def test_given_guarded_resource_when_running_rules_then_reports_failure_and_cove "SQLCLEAN035", expected_evaluated_models=2, expected_unevaluated_resources=0, - path="models/staging/_sqlbuild/audits/singular/orders.sql", + path="sql/models/staging/_sqlbuild/audits/singular/orders.sql", extra_files=( ( - "models/staging/customers.sql", + "sql/models/staging/customers.sql", "MODEL (description 'Test model customers.');\nSELECT 1 AS order_id\n", ), ), @@ -168,7 +168,7 @@ def test_given_model_only_polyglot_parses_when_running_rules_then_reports_model_ ) -> None: write_unevaluated_rules_project( project_dir=tmp_path, - resource_path="models/staging/orders.sql", + resource_path="sql/models/staging/orders.sql", resource_template="MODEL (description 'Test model orders.');\n" + test_case.sql, selected_rules=test_case.rules, ) @@ -215,7 +215,7 @@ def test_given_prefix_not_like_when_running_rules_then_evaluates_the_complete_mo ) -> None: write_unevaluated_rules_project( project_dir=tmp_path, - resource_path="models/staging/orders.sql", + resource_path="sql/models/staging/orders.sql", resource_template="MODEL (description 'Test model orders.', database warehouse, schema analytics);\n" + test_case.sql, adapter="snowflake", @@ -256,7 +256,7 @@ def test_given_prefix_not_like_when_running_rules_then_evaluates_the_complete_mo ), UnevaluatedRuleCase( "explicit scoped rule ignore", - configuration='\n[[rules.rule_ignores]]\nrules = ["SQLCLEAN035"]\npaths = ["models/staging/orders.sql"]\nreason = "External SQL syntax"\n', + configuration='\n[[rules.rule_ignores]]\nrules = ["SQLCLEAN035"]\npaths = ["sql/models/staging/orders.sql"]\nreason = "External SQL syntax"\n', expected_exit=0, ), ], @@ -305,7 +305,7 @@ def test_given_explicit_escape_hatch_when_running_rules_then_honors_policy( ("compile", "--json", "--no-cache"), "diagnostics", ("SQLCLEAN034",), - '\n[[rules.rule_ignores]]\nrules = ["SQLCLEAN035"]\npaths = ["models/staging/orders.sql"]\nreason = "External SQL syntax"\n', + '\n[[rules.rule_ignores]]\nrules = ["SQLCLEAN035"]\npaths = ["sql/models/staging/orders.sql"]\nreason = "External SQL syntax"\n', ), ], ids=lambda case: case.description, @@ -340,13 +340,13 @@ def test_given_one_failed_resource_and_multiple_rules_when_running_cli_then_grou "scalar function expression body", ( ( - "functions/sql/next_quantity.sql", + "sql/functions/sql/next_quantity.sql", "FUNCTION (\n description 'Next order quantity.',\n" " arguments (quantity INTEGER),\n returns INTEGER,\n" " database warehouse,\n schema analytics,\n);\n\nquantity + 1\n", ), ( - "models/orders.sql", + "sql/models/orders.sql", "MODEL (description 'Orders.', database warehouse, schema analytics);\n\n" 'SELECT __udf("next_quantity")(2) AS quantity\n', ), @@ -356,14 +356,14 @@ def test_given_one_failed_resource_and_multiple_rules_when_running_cli_then_grou "table function body opening with a parenthesis", ( ( - "functions/sql/open_orders.sql", + "sql/functions/sql/open_orders.sql", "FUNCTION (\n description 'Open orders.',\n" " returns table (order_id INTEGER),\n" " database warehouse,\n schema analytics,\n);\n\n" "(\n SELECT 1 AS order_id\n)\n", ), ( - "models/orders.sql", + "sql/models/orders.sql", "MODEL (description 'Orders.', database warehouse, schema analytics);\n\n" 'SELECT o.order_id\nFROM __table_fn("open_orders")() AS o\n', ), @@ -373,7 +373,7 @@ def test_given_one_failed_resource_and_multiple_rules_when_running_cli_then_grou "partitioned python table function call in a model and its test", ( ( - "functions/python/smooth_payments.py", + "sql/functions/python/smooth_payments.py", "import polars as pl\nfrom sqlbuild.functions import table_fn\n\n\n" "@table_fn(\n" ' arguments={"customer_id": "INTEGER", "amount": "FLOAT"},\n' @@ -387,12 +387,12 @@ def test_given_one_failed_resource_and_multiple_rules_when_running_cli_then_grou ' return payments.rename({"amount": "amount_smoothed"})\n', ), ( - "models/payments.sql", + "sql/models/payments.sql", "MODEL (description 'Payments.', database warehouse, schema analytics);\n\n" "SELECT\n 1 AS customer_id,\n 10.0::FLOAT AS amount\n", ), ( - "models/smoothed_payments.sql", + "sql/models/smoothed_payments.sql", "MODEL (description 'Smoothed payments.', database warehouse, schema analytics);\n\n" "SELECT\n s.customer_id,\n s.amount_smoothed\n" 'FROM __ref("payments") AS p, __table_fn("smooth_payments")(p.customer_id, p.amount)\n' @@ -414,12 +414,12 @@ def test_given_one_failed_resource_and_multiple_rules_when_running_cli_then_grou "quoted hook argument where a string is required", ( ( - "hooks/sql/comment_on_relation.sql", + "sql/hooks/sql/comment_on_relation.sql", "HOOK (description 'Comment on a relation.');\n\n" "COMMENT ON TABLE @relation IS @'comment'\n", ), ( - "models/orders.sql", + "sql/models/orders.sql", "MODEL (\n description 'Orders.',\n database warehouse,\n schema analytics,\n" " post_hooks [\n" ' sql("comment_on_relation", relation: "@@CTX:destination.qualified", ' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_unused_cte_contexts.py b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_unused_cte_contexts.py index 36048d3422..94dfd519b0 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_unused_cte_contexts.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/rules/test_unused_cte_contexts.py @@ -20,7 +20,7 @@ UnusedCteContextTestCase( description="table function argument keeps its input CTE reachable", files={ - "functions/sql/customer_orders.sql": dedent( + "sql/functions/sql/customer_orders.sql": dedent( """ FUNCTION (description "Test function customer_orders.", arguments (customer_id INTEGER), @@ -31,7 +31,7 @@ """ ).strip() + "\n", - "models/order_summary.sql": dedent( + "sql/models/order_summary.sql": dedent( """ MODEL (description "Test model order_summary.", materialized table); @@ -57,13 +57,13 @@ UnusedCteContextTestCase( description="generic audit argument may reference its local base CTE", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n materialized table,\n audits [\n order_group_rate (\n" ' evaluation_sql "SELECT 1 AS is_ok FROM base",\n' " thresholds (error (below 0.5)),\n" " ),\n ],\n);\n\nSELECT 1 AS order_id\n" ), - "audits/generic/order_group_rate.sql": dedent( + "sql/audits/generic/order_group_rate.sql": dedent( """ AUDIT ( evaluation measurement, @@ -92,13 +92,13 @@ UnusedCteContextTestCase( description="opaque audit SQL does not hide a later dead CTE", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n materialized table,\n audits [\n order_group_rate (\n" ' evaluation_sql "SELECT 1 AS is_ok FROM base",\n' " thresholds (error (below 0.5)),\n" " ),\n ],\n);\n\nSELECT 1 AS order_id\n" ), - "audits/generic/order_group_rate.sql": dedent( + "sql/audits/generic/order_group_rate.sql": dedent( """ AUDIT ( evaluation measurement, @@ -128,10 +128,10 @@ UnusedCteContextTestCase( description="test harness output keeps its helper CTE reachable", files={ - "models/raw_orders.sql": ( + "sql/models/raw_orders.sql": ( "MODEL (description 'Test model raw_orders.', materialized table);\n\nSELECT 7 AS order_id, 25 AS amount\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT * FROM __ref("raw_orders")\n' ), "tests/unit/orders_test.sql": dedent( @@ -156,10 +156,10 @@ UnusedCteContextTestCase( description="ordinary audit parameters do not hide a dead CTE", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table, audits [order_rows]);\n\nSELECT 1 AS order_id\n" ), - "audits/generic/order_rows.sql": dedent( + "sql/audits/generic/order_rows.sql": dedent( """ AUDIT (); @@ -184,7 +184,7 @@ def test_given_framework_cte_context_when_running_rule_then_live_cte_is_not_repo test_case: UnusedCteContextTestCase, ) -> None: project_dir: Path = tmp_path / "project" - project_dir.mkdir() + project_dir.mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "unused_cte_contexts"\nadapter = "duckdb"\n', encoding="utf-8", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/helpers.py index daa26ee567..acf0a88fc6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/helpers.py @@ -86,18 +86,18 @@ def build_scenario_project_files() -> dict[str, str]: "[defaults]\n" 'materialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\n" "SELECT\n" " id AS order_id,\n" " amount\n" 'FROM __source("raw_orders")\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Test model order_totals.', materialized table);\n\n" "SELECT\n" " SUM(amount) AS total_amount\n" @@ -151,7 +151,7 @@ def build_partial_fixture_scenario_project_files() -> dict[str, str]: "[connection]\n" 'database = "partial_fixture_scenario.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -160,7 +160,7 @@ def build_partial_fixture_scenario_project_files() -> dict[str, str]: " - name: order_id\n type: INTEGER\n nullable: false\n" " - name: status\n type: VARCHAR\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\n' 'SELECT order_id, status FROM __source("raw_orders")\n' ), @@ -180,7 +180,7 @@ def build_scenario_python_hooks_project_files() -> dict[str, str]: """Build an inline scenario project with a Python lifecycle hook.""" repo_files: dict[str, str] = build_scenario_project_files() - repo_files["hooks/python/scenario_hooks.py"] = ( + repo_files["sql/hooks/python/scenario_hooks.py"] = ( "from sqlbuild.hooks import hook\n\n" "@hook\n" "def log_scenario_model(ctx):\n" @@ -189,7 +189,7 @@ def build_scenario_python_hooks_project_files() -> dict[str, str]: " f\"SELECT '{ctx.model_name}' AS model_name, '{ctx.phase}' AS phase\"\n" " )\n" ) - repo_files["models/orders.sql"] = ( + repo_files["sql/models/orders.sql"] = ( 'MODEL (description "Test model orders.", ' 'materialized table, post_hooks [python("log_scenario_model")]);\n\n' "SELECT\n" @@ -204,11 +204,11 @@ def build_scenario_dependency_chain_project_files() -> dict[str, str]: """Build a three-model scenario with partial source fixtures and final checks.""" repo_files: dict[str, str] = build_partial_fixture_scenario_project_files() - repo_files["models/orders_summary.sql"] = ( + repo_files["sql/models/orders_summary.sql"] = ( 'MODEL (description "Summarize fixture orders.", materialized table);\n' 'SELECT order_id, status FROM __ref("orders")\n' ) - repo_files["models/orders_final.sql"] = ( + repo_files["sql/models/orders_final.sql"] = ( 'MODEL (description "Final scenario output.", materialized table);\n' 'SELECT order_id, status FROM __ref("orders_summary")\n' ) @@ -248,11 +248,11 @@ def build_real_warehouse_local_replay_project_files( return { "sqlbuild_project.toml": project_toml, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_events\n description: Test source raw_events.\n" " schema: raw\n table: raw_events\n" ), - "models/event_rollup.sql": model_sql, + "sql/models/event_rollup.sql": model_sql, f"tests/scenarios/{scenario_name}.sql": scenario_sql, } @@ -262,17 +262,17 @@ def build_real_warehouse_remote_scenario_project_files(*, project_toml: str) -> return { "sqlbuild_project.toml": project_toml, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_events\n description: Test source raw_events.\n" " schema: raw\n table: raw_events\n" ), - "models/stg_events.sql": ( + "sql/models/stg_events.sql": ( "MODEL (description 'Test model stg_events.', materialized view);\n\n" "SELECT customer_id, amount_cents\n" 'FROM __source("raw_events")\n' "WHERE amount_cents >= 1000\n" ), - "models/event_rollup.sql": ( + "sql/models/event_rollup.sql": ( "MODEL (description 'Test model event_rollup.', materialized table);\n\n" "SELECT\n" " customer_id,\n" @@ -622,7 +622,7 @@ def build_promotion_project_files(test_case: ScenarioPromotionE2ETestCase) -> di f"{test_case.defaults_config}\n" f"{test_case.settings_config}" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n" " description: Raw orders.\n" @@ -634,7 +634,7 @@ def build_promotion_project_files(test_case: ScenarioPromotionE2ETestCase) -> di " - name: amount\n" " type: INTEGER\n" ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (\n" " description 'Order totals.',\n" " materialized table,\n" @@ -685,7 +685,7 @@ def build_empty_fixture_scenario_project_files(*, customer_columns_yaml: str) -> "[rules]\n" 'select = ["SQLCLEAN021"]\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n" " description: Raw orders.\n" @@ -702,7 +702,7 @@ def build_empty_fixture_scenario_project_files(*, customer_columns_yaml: str) -> " table: raw_customers\n" f"{customer_columns_yaml}" ), - "models/customer_orders.sql": ( + "sql/models/customer_orders.sql": ( "MODEL (description 'Orders joined to known customers.', materialized table);\n\n" "SELECT o.id AS order_id, c.name AS customer_name\n" 'FROM __source("raw_orders") AS o\n' @@ -743,7 +743,7 @@ class InterruptedScenarioRun(NamedTuple): _POST_HOOKS: dict[bool, str] = {True: ', post_hooks [python("pause_after_build")]', False: ""} _HOOK_FILES: dict[bool, dict[str, str]] = { True: { - "hooks/python/slow_hooks.py": ( + "sql/hooks/python/slow_hooks.py": ( "import os\n" "import time\n\n" "from sqlbuild.hooks import hook\n\n\n" @@ -782,14 +782,14 @@ def build_interrupt_project_files( "[defaults]\n" 'materialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n" " description: Raw orders.\n" " schema: main\n" " table: raw_orders\n" ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals.', materialized table, sql_analysis false" f"{_POST_HOOKS[slow_hook]});\n\n" f"SELECT {_MODEL_TOTALS[long_model]} AS total_amount " @@ -887,12 +887,12 @@ def run_reusable_compile(*, project_dir: Path) -> subprocess.CompletedProcess[st 'name = "scenario_expected_columns"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "warehouse.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders", materialized table);\n\n' "SELECT order_id, status\n" "FROM (VALUES ('o1', 'placed')) AS t(order_id, status)\n" ), - "models/order_flags.sql": ( + "sql/models/order_flags.sql": ( 'MODEL (description "Orders with a flag", materialized table);\n\n' 'WITH orders AS (SELECT * FROM __ref("orders"))\n\n' "SELECT order_id, status, status = 'cancelled' AS is_cancelled\n" @@ -950,24 +950,24 @@ def build_unmocked_input_scenario_project_files() -> dict[str, str]: 'name = "unmocked_inputs"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "unmocked_inputs.duckdb"\n' ), - "sources/raw.yml": "sources:\n" + "sql/sources/raw.yml": "sources:\n" + "".join( f" - name: {name}\n description: Test source {name}.\n" f" schema: main\n table: {name}\n" for name in ("raw_orders", *_UNMOCKED_REP_SOURCES) ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( 'MODEL (description "Test model stg_orders.");\n\n' 'SELECT order_id, rep_id FROM __source("raw_orders")\n' ), - "models/stg_sales_reps.sql": ( + "sql/models/stg_sales_reps.sql": ( 'MODEL (description "Test model stg_sales_reps.");\n\n' + "\nUNION ALL\n".join( f'SELECT rep_id, rep_name FROM __source("{name}")' for name in _UNMOCKED_REP_SOURCES ) + "\n" ), - "models/order_reps.sql": ( + "sql/models/order_reps.sql": ( 'MODEL (description "Test model order_reps.");\n\n' "SELECT o.order_id, r.rep_name\n" 'FROM __ref("stg_orders") AS o\n' @@ -1000,19 +1000,19 @@ def build_lambda_scenario_project_files() -> dict[str, str]: 'name = "lambda_scenario"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "lambda_scenario.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_sessions\n description: Test source raw_sessions.\n" " schema: main\n table: raw_sessions\n" ), - "models/sessions.sql": ( + "sql/models/sessions.sql": ( "MODEL (description 'Test model sessions.');\n" 'SELECT * FROM __source("raw_sessions")\n' ), - "models/carts.sql": ( + "sql/models/carts.sql": ( "MODEL (description 'Test model carts.');\n" "SELECT 1 AS session_id, [1, 2, 3] AS quantities\n" ), - "models/cart_totals.sql": ( + "sql/models/cart_totals.sql": ( "MODEL (description 'Test model cart_totals.');\n" 'WITH sess AS (SELECT * FROM __ref("sessions")),\n' 'crt AS (SELECT c.session_id, c.quantities FROM __ref("carts") AS c)\n' @@ -1041,19 +1041,19 @@ def build_contracted_star_empty_fixture_project_files() -> dict[str, str]: 'name = "contracted_star"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "contracted_star.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n table: raw_customers\n" ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Test model customers.', contract enforced,\n" " columns (id (type INTEGER), name (type VARCHAR)));\n" 'SELECT * FROM __source("raw_customers")\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\nSELECT 1 AS id, 7 AS customer_id\n" ), - "models/customer_orders.sql": ( + "sql/models/customer_orders.sql": ( "MODEL (description 'Test model customer_orders.');\n" "SELECT o.id AS order_id, c.name AS customer_name\n" 'FROM __ref("orders") AS o\nJOIN __ref("customers") AS c ON c.id = o.customer_id\n' @@ -1079,11 +1079,11 @@ def build_cursor_intrinsic_scenario_project_files() -> dict[str, str]: 'name = "cursor_scenario"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "cursor_scenario.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n" "SELECT 1 AS order_id, TIMESTAMP '2026-01-02 10:00:00' AS ordered_at\n" ), - "models/hourly_orders.sql": ( + "sql/models/hourly_orders.sql": ( "MODEL (\n description 'Test model hourly_orders.',\n materialized incremental,\n" " incremental_strategy delete_insert,\n cursor ordered_at,\n" " cursor_type timestamp,\n cursor_grain hour,\n cursor_inputs (orders ordered_at),\n" @@ -1111,12 +1111,12 @@ def build_connect_by_scenario_project_files() -> dict[str, str]: '[targets.dev]\ndatabase = "warehouse"\nschema = "analytics"\n\n' "[scopes]\nenforce_placement = false\n" ), - "models/categories.sql": ( + "sql/models/categories.sql": ( "MODEL (description 'Test model categories.');\n" "SELECT CAST(1 AS INTEGER) AS category_id, CAST(NULL AS INTEGER) AS parent_id,\n" " CAST('root' AS VARCHAR) AS name\n" ), - "models/category_paths.sql": ( + "sql/models/category_paths.sql": ( "MODEL (description 'Test model category_paths.');\n" 'WITH categories AS (SELECT * FROM __ref("categories")),\n' "tree AS (\n" @@ -1150,12 +1150,12 @@ def build_local_variant_scenario_project_files( 'name = "local_variant"\nadapter = "duckdb"\n\n[connection]\ndatabase = ":memory:"\n\n' "[scopes]\nenforce_placement = false\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n columns:\n" " - {name: order_id, type: INTEGER}\n - {name: payload, type: VARIANT}\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.');\n" f"SELECT o.order_id, {output}\n" 'FROM __source("raw_orders") AS o\n' @@ -1179,12 +1179,12 @@ def build_helper_fixture_scenario_project_files() -> dict[str, str]: 'name = "helper_fixture"\nadapter = "duckdb"\n\n[connection]\ndatabase = ":memory:"\n\n' "[scopes]\nenforce_placement = false\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n columns:\n" " - {name: order_id, type: INTEGER}\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.');\n" 'SELECT o.order_id FROM __source("raw_orders") AS o\n' ), @@ -1209,14 +1209,14 @@ def build_snowflake_variant_scenario_project_files(*, expected_payload_json: str return { "sqlbuild_project.toml": build_offline_snowflake_project_toml(), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" " schema: main\n table: raw_orders\n columns:\n" ' - {name: order_id, type: "NUMBER(38,0)"}\n' " - {name: status, type: VARCHAR}\n" " - {name: payload, type: VARIANT}\n" ), - "models/stg_payloads.sql": ( + "sql/models/stg_payloads.sql": ( 'MODEL (description "Order payloads.");\n' 'SELECT order_id, payload FROM __source("raw_orders")\n' ), @@ -1294,12 +1294,12 @@ def build_snowflake_lambda_scenario_project_files() -> dict[str, str]: return { "sqlbuild_project.toml": build_offline_snowflake_project_toml(), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" " schema: main\n table: raw_orders\n columns:\n" ' - {name: order_id, type: "NUMBER(38,0)"}\n' ), - "models/order_quantities.sql": ( + "sql/models/order_quantities.sql": ( 'MODEL (description "Quantities above each order id.");\n' "SELECT order_id,\n" " FILTER(ARRAY_CONSTRUCT(1, 2, 3), x -> x > order_id) AS big_quantities\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_concurrency.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_concurrency.py index fae577bdcb..f6b37b0911 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_concurrency.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_concurrency.py @@ -139,7 +139,7 @@ def test_given_retained_artifact_of_another_type_when_rerunning_then_replaces_an command=(*test_case.command, "--retain"), project_dir=project_dir ) assert retained.returncode == 0, retained.stdout + retained.stderr - orders_model: Path = project_dir / "models/orders.sql" + orders_model: Path = project_dir / "sql/models/orders.sql" orders_model.write_text( orders_model.read_text(encoding="utf-8").replace("materialized table", "materialized view"), encoding="utf-8", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_escaped_quotes.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_escaped_quotes.py index cd1c42e1c4..6a56525525 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_escaped_quotes.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_escaped_quotes.py @@ -25,23 +25,23 @@ ) _PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": build_offline_snowflake_project_toml() + '\n[vars]\nregion = "EU"\n', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" " schema: main\n table: raw_orders\n columns:\n" ' - {name: order_id, type: "NUMBER(38,0)"}\n' ), - "models/_constants/start_date.sql": 'CONSTANT (name start_date, value "2025-01-01");\n', - "models/_enums/channel.sql": 'ENUM (name channel, members (WEB "web", APP "app"));\n', - "models/_macros/sql/shout.sql": ( + "sql/models/_constants/start_date.sql": 'CONSTANT (name start_date, value "2025-01-01");\n', + "sql/models/_enums/channel.sql": 'ENUM (name channel, members (WEB "web", APP "app"));\n', + "sql/models/_macros/sql/shout.sql": ( 'MACRO (description "Upper case.", arguments (v VARCHAR), returns VARCHAR);\n\nUPPER(@v)\n' ), - "models/_macros/python/tag.py": ( + "sql/models/_macros/python/tag.py": ( '"""Order tag macros."""\n\n\n' "def tag() -> str:\n" ' """Return the order tag literal."""\n' " return \"'tag'\"\n" ), - "models/order_notes.sql": ( + "sql/models/order_notes.sql": ( 'MODEL (description "Order notes holding backslash escapes.");\n' "SELECT\n" " o.order_id,\n" @@ -109,7 +109,7 @@ def test_given_snowflake_backslash_escapes_when_compiling_and_replaying_locally_ assert compiled.returncode == 0, compiled.stdout + compiled.stderr compiled_sql: str = ( - project_dir / "target" / "compiled" / "models" / "order_notes.sql" + project_dir / "target" / "compiled" / "sql" / "models" / "order_notes.sql" ).read_text() for fragment in test_case.expected_compiled_fragments: assert fragment in compiled_sql, compiled_sql diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_namespace.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_namespace.py index 2ce20bfabd..ffa6f18e1c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_namespace.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_namespace.py @@ -172,7 +172,7 @@ def test_given_namespaced_leftovers_when_running_janitor_then_all_namespaces_are test_case: ScenarioNamespaceE2ETestCase, tmp_path: Path ) -> None: project: Path = prepare_namespace_project(tmp_path) - source: Path = project / "sources/raw.yml" + source: Path = project / "sql/sources/raw.yml" source.write_text(source.read_text().replace("schema: main", "schema: raw")) config: Path = project / "sqlbuild_project.toml" config.write_text(config.read_text() + "\n[janitor]\nenabled = true\nretention_days = 0\n") diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_promotion.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_promotion.py index 1da1d0a7da..fb25e63a23 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_promotion.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_promotion.py @@ -31,7 +31,7 @@ _ENFORCED_DEFAULTS: str = 'contract = "enforced"\n' _CONFLICT_FRAGMENTS: tuple[str, ...] = ( "error[K011]", - "models/order_totals.sql", + "sql/models/order_totals.sql", "model 'order_totals': contract enforced requires staged table promotion", 'sqlbuild_project.toml sets [settings] table_promotion_mode = "immediate"', "remove that line to use the default staged promotion, or set this in sqlbuild_project.toml:", @@ -113,7 +113,7 @@ def test_given_promotion_configuration_when_running_scenario_then_matches_build_ for fragment in test_case.unexpected_stdout_fragments: assert fragment not in output model_sql: str = ( - project_dir / "target/run/scenarios/order_totals_pass/models/order_totals.sql" + project_dir / "target/run/scenarios/order_totals_pass/sql/models/order_totals.sql" ).read_text(encoding="utf-8") assert ("__staging" in model_sql) is test_case.expect_staged_promotion, model_sql assert list_scenario_relation_names(db_path=project_dir / "scenario_promotion.duckdb") == () diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_scenario.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_scenario.py index fd7d13169f..e25ad2f19b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_scenario.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_scenario.py @@ -203,7 +203,7 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n expected_count=1, additional_project_files=( ( - "models/local_model_error_rows.sql", + "sql/models/local_model_error_rows.sql", "MODEL (description 'Test model local_model_error_rows.', materialized table);\n\n" "SELECT CAST('not_a_number_' || amount AS INTEGER) AS bad_value\n" 'FROM __source("raw_orders")\n', @@ -239,11 +239,11 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n expected_count=2, additional_project_files=( ( - "functions/sql/is_large_order.sql", + "sql/functions/sql/is_large_order.sql", "FUNCTION (description 'Test function is_large_order.', arguments (amount INTEGER), returns BOOLEAN);\n\namount > 9\n", ), ( - "models/local_sql_function_pass_rows.sql", + "sql/models/local_sql_function_pass_rows.sql", "MODEL (description 'Test model local_sql_function_pass_rows.', materialized table);\n\n" 'SELECT id, __udf("is_large_order")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -287,11 +287,11 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n expected_count=1, additional_project_files=( ( - "functions/sql/bad_sql_function.sql", + "sql/functions/sql/bad_sql_function.sql", "FUNCTION (description 'Test function bad_sql_function.', arguments (amount INTEGER), returns BOOLEAN);\n\nmissing_col > 9\n", ), ( - "models/local_sql_function_setup_error_rows.sql", + "sql/models/local_sql_function_setup_error_rows.sql", "MODEL (description 'Test model local_sql_function_setup_error_rows.', materialized table);\n\n" 'SELECT id, __udf("bad_sql_function")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -342,11 +342,11 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n corrupt_capture_dialect=True, additional_project_files=( ( - "functions/sql/bad_transpile_function.sql", + "sql/functions/sql/bad_transpile_function.sql", "FUNCTION (description 'Test function bad_transpile_function.', arguments (amount INTEGER), returns BOOLEAN);\n\namount > 9\n", ), ( - "models/local_sql_function_transpile_error_rows.sql", + "sql/models/local_sql_function_transpile_error_rows.sql", "MODEL (description 'Test model local_sql_function_transpile_error_rows.', materialized table);\n\n" 'SELECT id, __udf("bad_transpile_function")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -385,12 +385,12 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n expected_count=1, additional_project_files=( ( - "functions/sql/sql_runtime_error.sql", + "sql/functions/sql/sql_runtime_error.sql", "FUNCTION (description 'Test function sql_runtime_error.', arguments (amount INTEGER), returns INTEGER);\n\n" "CAST('bad' AS INTEGER)\n", ), ( - "models/local_sql_function_runtime_error_rows.sql", + "sql/models/local_sql_function_runtime_error_rows.sql", "MODEL (description 'Test model local_sql_function_runtime_error_rows.', materialized table);\n\n" 'SELECT id, __udf("sql_runtime_error")(amount) AS bad_value\n' 'FROM __source("raw_orders")\n', @@ -426,7 +426,7 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n expected_count=2, additional_project_files=( ( - "functions/python/is_large_order_py.py", + "sql/functions/python/is_large_order_py.py", "from sqlbuild.functions import udf\n\n\n" "@udf(\n" ' arguments={"amount": "INTEGER"},\n' @@ -437,7 +437,7 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n " '''Test function main.'''\n return amount is not None and amount > 9\n", ), ( - "models/local_python_function_pass_rows.sql", + "sql/models/local_python_function_pass_rows.sql", "MODEL (description 'Test model local_python_function_pass_rows.', materialized table);\n\n" 'SELECT id, __udf("is_large_order_py")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -480,7 +480,7 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n expected_count=1, additional_project_files=( ( - "functions/python/is_large_order_py.py", + "sql/functions/python/is_large_order_py.py", "from sqlbuild.functions import udf\n\n\n" "@udf(\n" ' arguments={"amount": "INTEGER"},\n' @@ -492,7 +492,7 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n " '''Test function main.'''\n return amount is not None and amount > 9\n", ), ( - "models/local_python_function_error_rows.sql", + "sql/models/local_python_function_error_rows.sql", "MODEL (description 'Test model local_python_function_error_rows.', materialized table);\n\n" 'SELECT id, __udf("is_large_order_py")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -542,7 +542,7 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n expected_count=1, additional_project_files=( ( - "functions/python/python_runtime_error.py", + "sql/functions/python/python_runtime_error.py", "from sqlbuild.functions import udf\n\n\n" "@udf(\n" ' arguments={"amount": "INTEGER"},\n' @@ -553,7 +553,7 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n ' """Test function main."""\n raise ValueError("python udf exploded")\n', ), ( - "models/local_python_function_runtime_error_rows.sql", + "sql/models/local_python_function_runtime_error_rows.sql", "MODEL (description 'Test model local_python_function_runtime_error_rows.', materialized table);\n\n" 'SELECT id, __udf("python_runtime_error")(amount) AS bad_value\n' 'FROM __source("raw_orders")\n', @@ -911,7 +911,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte expected_count=1, additional_project_files=( ( - "models/local_model_error_rows.sql", + "sql/models/local_model_error_rows.sql", "MODEL (description 'Test model local_model_error_rows.', materialized table);\n\n" "SELECT CAST('not_a_number_' || amount AS INTEGER) AS bad_value\n" 'FROM __source("raw_orders")\n', @@ -947,11 +947,11 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte expected_count=2, additional_project_files=( ( - "functions/sql/is_large_order.sql", + "sql/functions/sql/is_large_order.sql", "FUNCTION (description 'Test function is_large_order.', arguments (amount INTEGER), returns BOOLEAN);\n\namount > 9\n", ), ( - "models/local_sql_function_pass_rows.sql", + "sql/models/local_sql_function_pass_rows.sql", "MODEL (description 'Test model local_sql_function_pass_rows.', materialized table);\n\n" 'SELECT id, __udf("is_large_order")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -995,11 +995,11 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte expected_count=1, additional_project_files=( ( - "functions/sql/bad_sql_function.sql", + "sql/functions/sql/bad_sql_function.sql", "FUNCTION (description 'Test function bad_sql_function.', arguments (amount INTEGER), returns BOOLEAN);\n\nmissing_col > 9\n", ), ( - "models/local_sql_function_setup_error_rows.sql", + "sql/models/local_sql_function_setup_error_rows.sql", "MODEL (description 'Test model local_sql_function_setup_error_rows.', materialized table);\n\n" 'SELECT id, __udf("bad_sql_function")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -1050,11 +1050,11 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte corrupt_capture_dialect=True, additional_project_files=( ( - "functions/sql/bad_transpile_function.sql", + "sql/functions/sql/bad_transpile_function.sql", "FUNCTION (description 'Test function bad_transpile_function.', arguments (amount INTEGER), returns BOOLEAN);\n\namount > 9\n", ), ( - "models/local_sql_function_transpile_error_rows.sql", + "sql/models/local_sql_function_transpile_error_rows.sql", "MODEL (description 'Test model local_sql_function_transpile_error_rows.', materialized table);\n\n" 'SELECT id, __udf("bad_transpile_function")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -1104,12 +1104,12 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte expected_count=1, additional_project_files=( ( - "functions/sql/sql_runtime_error.sql", + "sql/functions/sql/sql_runtime_error.sql", "FUNCTION (description 'Test function sql_runtime_error.', arguments (amount INTEGER), returns INTEGER);\n\n" "CAST('bad' AS INTEGER)\n", ), ( - "models/local_sql_function_runtime_error_rows.sql", + "sql/models/local_sql_function_runtime_error_rows.sql", "MODEL (description 'Test model local_sql_function_runtime_error_rows.', materialized table);\n\n" 'SELECT id, __udf("sql_runtime_error")(amount) AS bad_value\n' 'FROM __source("raw_orders")\n', @@ -1145,7 +1145,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte expected_count=2, additional_project_files=( ( - "functions/python/is_large_order_py.py", + "sql/functions/python/is_large_order_py.py", "from sqlbuild.functions import udf\n\n\n" "@udf(\n" ' arguments={"amount": "INTEGER"},\n' @@ -1156,7 +1156,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte " '''Test function main.'''\n return amount is not None and amount > 9\n", ), ( - "models/local_python_function_pass_rows.sql", + "sql/models/local_python_function_pass_rows.sql", "MODEL (description 'Test model local_python_function_pass_rows.', materialized table);\n\n" 'SELECT id, __udf("is_large_order_py")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -1199,7 +1199,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte expected_count=1, additional_project_files=( ( - "functions/python/is_large_order_py.py", + "sql/functions/python/is_large_order_py.py", "from sqlbuild.functions import udf\n\n\n" "@udf(\n" ' arguments={"amount": "INTEGER"},\n' @@ -1211,7 +1211,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte " '''Test function main.'''\n return amount is not None and amount > 9\n", ), ( - "models/local_python_function_error_rows.sql", + "sql/models/local_python_function_error_rows.sql", "MODEL (description 'Test model local_python_function_error_rows.', materialized table);\n\n" 'SELECT id, __udf("is_large_order_py")(amount) AS is_large_order\n' 'FROM __source("raw_orders")\n', @@ -1261,7 +1261,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte expected_count=1, additional_project_files=( ( - "functions/python/python_runtime_error.py", + "sql/functions/python/python_runtime_error.py", "from sqlbuild.functions import udf\n\n\n" "@udf(\n" ' arguments={"amount": "INTEGER"},\n' @@ -1272,7 +1272,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte ' """Test function main."""\n raise ValueError("python udf exploded")\n', ), ( - "models/local_python_function_runtime_error_rows.sql", + "sql/models/local_python_function_runtime_error_rows.sql", "MODEL (description 'Test model local_python_function_runtime_error_rows.', materialized table);\n\n" 'SELECT id, __udf("python_runtime_error")(amount) AS bad_value\n' 'FROM __source("raw_orders")\n', @@ -1936,7 +1936,7 @@ def test_given_waffle_shop_fixture_when_running_with_retain_then_keeps_scenario_ command=("--no-color", "scenario", "test", "order_totals_pass"), expected_exit_code=0, artifact_relative_path=Path( - "target/run/scenarios/order_totals_pass/models/order_totals.sql" + "target/run/scenarios/order_totals_pass/sql/models/order_totals.sql" ), expected_artifact_fragments=( "CREATE", @@ -2015,7 +2015,7 @@ def test_given_scenario_project_when_running_scenario_test_then_writes_runtime_a command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), expected_exit_code=0, artifact_relative_path=Path( - "target/run/scenarios/order_totals_pass/local/models/order_totals.sql" + "target/run/scenarios/order_totals_pass/local/sql/models/order_totals.sql" ), expected_artifact_fragments=( "SUM(amount) AS total_amount", @@ -2044,7 +2044,7 @@ def test_given_scenario_project_when_running_scenario_test_then_writes_runtime_a command=("--no-color", "scenario", "test", "local_sql_function_pass", "--local"), expected_exit_code=0, artifact_relative_path=Path( - "target/run/scenarios/local_sql_function_pass/local/functions/sql/is_large_order.sql" + "target/run/scenarios/local_sql_function_pass/local/sql/functions/sql/is_large_order.sql" ), expected_artifact_fragments=( "CREATE OR REPLACE MACRO", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scope/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/scope/helpers.py index ece4988eb2..5119d4cfd8 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scope/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scope/helpers.py @@ -52,8 +52,8 @@ def write_scope_performance_project( next_model_index: int = (domain + 1) * model_count // domain_count models_in_domain: int = next_model_index - first_model_index root_model_count: int = min(10, models_in_domain) - domain_dir: Path = project_dir / "models" / f"domain_{domain:03d}" - macros_dir: Path = domain_dir / "macros" / "python" + domain_dir: Path = project_dir / "sql" / "models" / f"domain_{domain:03d}" + macros_dir: Path = domain_dir / "sql" / "macros" / "python" macros_dir.mkdir(parents=True) macro_source: str = "\n\n".join( f"def domain_{domain:03d}_identity_{offset:02d}(expression: str) -> str:\n" @@ -69,7 +69,7 @@ def write_scope_performance_project( macro_name=f"domain_{domain:03d}_identity_{offset:02d}", ) detail_dir: Path = domain_dir / "detail" - detail_dir.mkdir() + detail_dir.mkdir(parents=True) for offset in range(root_model_count, models_in_domain): model_index = first_model_index + offset _write_scope_model( @@ -82,18 +82,20 @@ def write_scope_performance_project( def write_unicode_macro_project(*, project_dir: Path, macro_names: tuple[str, ...]) -> None: """Write one model and a global macro file defining each named macro.""" - (project_dir / "models").mkdir(parents=True) - (project_dir / "macros" / "python").mkdir(parents=True) + (project_dir / "sql" / "models").mkdir(parents=True) + (project_dir / "sql" / "macros" / "python").mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "scope_unicode"\nadapter = "duckdb"\n', encoding="utf-8" ) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( 'MODEL(description "Test model orders.");\nSELECT 1 AS id\n', encoding="utf-8" ) macro_source: str = "\n\n".join( f"def {name}(expression: str) -> str:\n return expression\n" for name in macro_names ) - (project_dir / "macros" / "python" / "names.py").write_text(macro_source, encoding="utf-8") + (project_dir / "sql" / "macros" / "python" / "names.py").write_text( + macro_source, encoding="utf-8" + ) def _write_scope_model(*, model_dir: Path, model_index: int, macro_name: str) -> None: diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scope/test_scope.py b/tests/e2e/src/sqlbuild/cli/commands/main/scope/test_scope.py index 228fa41698..99dce66af4 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scope/test_scope.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scope/test_scope.py @@ -26,11 +26,11 @@ def test_given_minimal_project_when_running_scope_aliases_then_outputs_are_offli tmp_path: Path, test_case: ScopeE2eCase ) -> None: project_dir: Path = tmp_path / "project" - (project_dir / "models").mkdir(parents=True) + (project_dir / "sql" / "models").mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "scope_e2e"\nadapter = "duckdb"\n', encoding="utf-8" ) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( "MODEL(description 'Test model orders.');\nSELECT 1 AS id\n", encoding="utf-8" ) @@ -44,10 +44,12 @@ def test_given_minimal_project_when_running_scope_aliases_then_outputs_are_offli alias="sqlbuild", project_dir=project_dir, args=("model:orders",) ) prospective: subprocess.CompletedProcess[str] = run_scope_alias( - alias="sqb", project_dir=project_dir, args=("--at", "models/new/") + alias="sqb", project_dir=project_dir, args=("--at", "sql/models/new/") + ) + (project_dir / "sql" / "macros" / "python").mkdir(parents=True) + (project_dir / "sql" / "macros" / "python" / "broken.py").write_text( + "def broken(:\n", encoding="utf-8" ) - (project_dir / "macros" / "python").mkdir(parents=True) - (project_dir / "macros" / "python" / "broken.py").write_text("def broken(:\n", encoding="utf-8") broken: subprocess.CompletedProcess[str] = run_scope_alias( alias="sqb", project_dir=project_dir, args=("model:orders", "--json", "--no-cache") ) @@ -73,11 +75,11 @@ def test_given_bare_model_name_when_running_scope_then_matches_the_prefixed_repo tmp_path: Path, test_case: ScopeE2eCase ) -> None: project_dir: Path = tmp_path / "project" - (project_dir / "models").mkdir(parents=True) + (project_dir / "sql" / "models").mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "scope_e2e"\nadapter = "duckdb"\n', encoding="utf-8" ) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( "MODEL(description 'Test model orders.');\nSELECT 1 AS id\n", encoding="utf-8" ) @@ -114,15 +116,15 @@ def test_given_bare_name_that_is_not_a_resource_when_running_scope_then_fails_cl tmp_path: Path, test_case: ScopeBareTargetE2eCase ) -> None: project_dir: Path = tmp_path / "project" - (project_dir / "models").mkdir(parents=True) - (project_dir / "macros" / "python").mkdir(parents=True) + (project_dir / "sql" / "models").mkdir(parents=True) + (project_dir / "sql" / "macros" / "python").mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "scope_e2e"\nadapter = "duckdb"\n', encoding="utf-8" ) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( "MODEL(description 'Test model orders.');\nSELECT 1 AS id\n", encoding="utf-8" ) - (project_dir / "macros" / "python" / "cents.py").write_text( + (project_dir / "sql" / "macros" / "python" / "cents.py").write_text( "def cents(expression: str) -> str:\n return expression\n", encoding="utf-8" ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/seed/test_seed.py b/tests/e2e/src/sqlbuild/cli/commands/main/seed/test_seed.py index fdfdc81dd2..c0a9334353 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/seed/test_seed.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/seed/test_seed.py @@ -102,7 +102,7 @@ def test_given_empty_typed_seed_fields_when_loading_then_persists_nulls( "[targets.dev.connection]\n" 'database = "warehouse.duckdb"\n' ), - "seeds/schema.yml": ( + "sql/seeds/schema.yml": ( "seeds:\n" " - name: nullable_mappings\n description: Test seed nullable_mappings.\n" " columns:\n" @@ -111,7 +111,7 @@ def test_given_empty_typed_seed_fields_when_loading_then_persists_nulls( " - name: mapping_name\n" " type: VARCHAR\n" ), - "seeds/nullable_mappings.csv": "mapping_id,mapping_name\n1,mapped\n,\n", + "sql/seeds/nullable_mappings.csv": "mapping_id,mapping_name\n1,mapped\n,\n", }, ) @@ -159,7 +159,7 @@ def test_given_standalone_seeds_when_writing_json_file_then_assets_are_complete_ "[targets.dev.connection]\n" 'database = "warehouse.duckdb"\n' ), - "seeds/schema.yml": ( + "sql/seeds/schema.yml": ( "seeds:\n" " - name: first_seed\n description: Test seed first_seed.\n" " columns:\n" @@ -170,8 +170,8 @@ def test_given_standalone_seeds_when_writing_json_file_then_assets_are_complete_ " - name: id\n" " type: INTEGER\n" ), - "seeds/first_seed.csv": "id\n1\n", - "seeds/second_seed.csv": "id\n2\n", + "sql/seeds/first_seed.csv": "id\n1\n", + "sql/seeds/second_seed.csv": "id\n2\n", }, ) output_path: Path = project_dir / "seed-results.json" @@ -223,14 +223,14 @@ def test_given_failing_standalone_seed_when_writing_json_file_then_failure_is_ho "[targets.dev.connection]\n" 'database = "warehouse.duckdb"\n' ), - "seeds/schema.yml": ( + "sql/seeds/schema.yml": ( "seeds:\n" " - name: invalid_seed\n description: Test seed invalid_seed.\n" " columns:\n" " - name: id\n" " type: INTEGER\n" ), - "seeds/invalid_seed.csv": "id\nnot-an-integer\n", + "sql/seeds/invalid_seed.csv": "id\nnot-an-integer\n", }, ) output_path: Path = project_dir / "seed-results.json" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/seed/test_seed_yaml_audits.py b/tests/e2e/src/sqlbuild/cli/commands/main/seed/test_seed_yaml_audits.py index 19271f26cf..99b1a8341a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/seed/test_seed_yaml_audits.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/seed/test_seed_yaml_audits.py @@ -61,7 +61,7 @@ seed_csv="waffle_type_id,price_cents\n1,450\n", expected_exit_code=1, expected_output_fragments=( - "seeds/waffle_types.yml is missing argument 'model' for generic audit " + "sql/seeds/waffle_types.yml is missing argument 'model' for generic audit " "'expression_is_true'; a seed audit receives 'seed' and 'relation', not 'model', " "so read the attached relation with @relation", ), @@ -81,9 +81,9 @@ def test_given_documented_seed_yaml_audits_when_building_then_audits_run_on_the_ 'name = "waffle_seed_audits"\nadapter = "duckdb"\n' '[connection]\ndatabase = "waffles.duckdb"\n' ), - "seeds/waffle_types.csv": test_case.seed_csv, - "seeds/waffle_types.yml": _SEED_YAML, - "audits/generic/expression_is_true.sql": test_case.audit_sql, + "sql/seeds/waffle_types.csv": test_case.seed_csv, + "sql/seeds/waffle_types.yml": _SEED_YAML, + "sql/audits/generic/expression_is_true.sql": test_case.audit_sql, }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/helpers.py index 4faf5f6b84..ea0f4764c6 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/helpers.py @@ -238,17 +238,17 @@ def prepare_snowflake_diff_project(*, tmp_path: Path) -> tuple[Path, str, str]: "allow_as_clone_destination = false\n\n" "[defaults]\n" 'materialized = "table"\n\n' - "models/staging/stg_orders.sql: invalid\n" + "sql/models/staging/stg_orders.sql: invalid\n" ) project_dir.mkdir(parents=True, exist_ok=True) (project_dir / "sqlbuild_project.toml").write_text( project_contents.replace( - "models/staging/stg_orders.sql: invalid\n", + "sql/models/staging/stg_orders.sql: invalid\n", "", ), encoding="utf-8", ) - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" staging_dir: Path = models_dir / "staging" staging_dir.mkdir(parents=True, exist_ok=True) (staging_dir / "stg_orders.sql").write_text( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/test_snowflake.py b/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/test_snowflake.py index b7f212dbf9..82e910b4b4 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/test_snowflake.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/test_snowflake.py @@ -77,6 +77,7 @@ build_snowflake_connection_config, build_unique_schema_name, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.dbt @@ -177,15 +178,15 @@ def test_given_python_result_when_running_check_on_snowflake_then_persists_node_ project_name="snowflake_node_results", schema_name=schema_name, ), - "python/tasks/results.py": ( + "python/nodes/tasks/results/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_result(ctx):\n" " '''Test task produce_result.'''\n return ctx.result(payload={'value': 42}, metadata={'source': 'snowflake'})\n" ), - "python/checks/results.py": ( + "python/nodes/checks/results/checks.py": ( "from sqlbuild.checks import check\n" - "from python.tasks.results import produce_result\n\n" + "from python.nodes.tasks.results.asset import produce_result\n\n" "@check(depends_on=produce_result)\n" "def check_produce_result(ctx):\n" " '''Test check check_produce_result.'''\n return ctx.result_of(node_function=produce_result).payload['value'] == 42\n" @@ -260,13 +261,13 @@ def test_given_physical_source_without_freshness_when_running_on_snowflake_then_ project_name="snowflake_freshness_metadata", schema_name=schema_name, ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" f" schema: {schema_name}\n" " table: raw_orders\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __source("raw_orders")\n' ), }, @@ -393,7 +394,7 @@ def test_given_source_deferral_env_when_building_on_snowflake_then_reads_prod_an prod_schema_name=prod_schema_name, ), "sqlbuild_local.toml": build_snowflake_local_config(schema_name=dev_schema_name), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -404,13 +405,13 @@ def test_given_source_deferral_env_when_building_on_snowflake_then_reads_prod_an " - name: status\n" " type: VARCHAR\n" ), - "python/loaders/raw_orders.py": ( + "python/nodes/loaders/raw_orders/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 7, 'status': 'loaded-dev'}]\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT order_id, status FROM __source("raw_orders")' ), }, @@ -511,16 +512,16 @@ def test_given_existing_snapshot_targets_when_building_on_snowflake_then_apply_s ) assert initial_result.returncode == 0, initial_result.stdout + initial_result.stderr - (project_dir / "models" / "current_check_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_check_customers.sql").write_text( build_current_check_customers_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "current_delete_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_delete_customers.sql").write_text( build_current_delete_customers_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "historical_timestamp_extracts.sql").write_text( + (project_dir / "sql" / "models" / "historical_timestamp_extracts.sql").write_text( build_historical_timestamp_extracts_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "historical_check_daily.sql").write_text( + (project_dir / "sql" / "models" / "historical_check_daily.sql").write_text( build_historical_check_daily_model_sql(changed=True), encoding="utf-8" ) @@ -861,7 +862,7 @@ def test_given_snapshot_project_when_building_on_snowflake_then_scd2_history_is_ expected_historical_check_rows=test_case.expected_historical_check_rows, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="blocked", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -890,7 +891,7 @@ def test_given_snapshot_project_when_building_on_snowflake_then_scd2_history_is_ expected_rows=test_case.expected_current_rows_after_initial_build, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( build_current_customers_model_sql(plan="pro", updated_at="2026-01-02 00:00:00"), encoding="utf-8", ) @@ -1189,14 +1190,17 @@ def test_given_loader_schema_evolution_project_when_loading_twice_on_snowflake_t " - name: load_seq\n" " type: INTEGER\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n if ctx.current_cursor_value is None:\n" - " return [{'event_id': 1, 'load_seq': 1}]\n" - " return [{'event_id': 2, 'load_seq': 2, 'note': 'late-note'}]\n" - ), + node_files={ + **node_module_files( + "python/nodes/loaders/source_rows.py", + "from sqlbuild.loaders import loader\n\n" + "@loader\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n if ctx.current_cursor_value is None:\n" + " return [{'event_id': 1, 'load_seq': 1}]\n" + " return [{'event_id': 2, 'load_seq': 2, 'note': 'late-note'}]\n", + ) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -1267,22 +1271,25 @@ def test_given_chained_loader_project_when_loading_on_snowflake_then_runs_loader " - name: status\n" " type: VARCHAR\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " cursor = ctx.query(\n" - " f'SELECT event_id FROM {events.destination} ORDER BY event_id'\n" - " )\n" - " rows = cursor.fetchall()\n" - " return [{'event_id': row[0], 'status': 'loaded'} for row in rows]\n" - ), + node_files={ + **node_module_files( + "python/nodes/loaders/source_rows.py", + "from sqlbuild.loaders import loader\n\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" + " cursor = ctx.query(\n" + " f'SELECT event_id FROM {events.destination} ORDER BY event_id'\n" + " )\n" + " rows = cursor.fetchall()\n" + " return [{'event_id': row[0], 'status': 'loaded'} for row in rows]\n", + ) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -1443,7 +1450,9 @@ def test_given_intermediate_strategy_project_when_loading_twice_on_snowflake_the " - name: amount\n" " type: INTEGER\n" ), - loader_py=test_case.loader_py, + node_files={ + **node_module_files("python/nodes/loaders/source_rows.py", test_case.loader_py) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/helpers.py index 8fc04a71a0..36c3f35ab9 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/helpers.py @@ -67,7 +67,7 @@ """ _MODELS: dict[str, str] = { - "models/staging/stg_orders.sql": """MODEL ( + "sql/models/staging/stg_orders.sql": """MODEL ( materialized view, description "Latest event per order.", columns ( @@ -83,7 +83,7 @@ FROM ranked WHERE event_rank = 1 """, - "models/marts/customer_totals.sql": """MODEL ( + "sql/models/marts/customer_totals.sql": """MODEL ( materialized table, description "Order totals per customer.", columns ( @@ -97,7 +97,7 @@ LEFT JOIN __ref("stg_orders") AS o ON o.customer_id = c.customer_id GROUP BY c.customer_id, c.customer_name """, - "models/marts/orders_appended.sql": """MODEL ( + "sql/models/marts/orders_appended.sql": """MODEL ( materialized incremental, incremental_strategy append, cursor order_id, @@ -107,7 +107,7 @@ SELECT order_id, customer_id FROM __ref("stg_orders") """, - "models/marts/orders_merged.sql": """MODEL ( + "sql/models/marts/orders_merged.sql": """MODEL ( materialized incremental, incremental_strategy merge, unique_key [order_id], @@ -116,7 +116,7 @@ SELECT order_id, status, amount_cents FROM __ref("stg_orders") """, - "models/marts/orders_replaced.sql": """MODEL ( + "sql/models/marts/orders_replaced.sql": """MODEL ( materialized incremental, incremental_strategy delete_insert, unique_key [order_id], @@ -174,21 +174,21 @@ def build_orders_project_files(*, adapter: str) -> dict[str, str]: 'materialized = "table"\n\n' "[[rules.rule_ignores]]\n" 'rules = ["SQLCLEAN018"]\n' - 'paths = ["models/staging/stg_orders.sql"]\n' + 'paths = ["sql/models/staging/stg_orders.sql"]\n' 'reason = "Seed event_seq is unique by construction; seeds declare no keys."\n' ), - "seeds/customers.csv": _CUSTOMERS_CSV, - "seeds/orders.csv": "event_seq,order_id,customer_id,amount_cents,ordered_at,status\n" + "sql/seeds/customers.csv": _CUSTOMERS_CSV, + "sql/seeds/orders.csv": "event_seq,order_id,customer_id,amount_cents,ordered_at,status\n" + "\n".join(_ORDER_ROWS) + "\n", - "seeds/seeds.yml": _SEEDS_YML, + "sql/seeds/seeds.yml": _SEEDS_YML, "tests/unit/test_customer_totals.sql": _UNIT_TEST, **_MODELS, } def append_late_orders(*, project_dir: Path) -> None: - orders_path: Path = project_dir / "seeds" / "orders.csv" + orders_path: Path = project_dir / "sql" / "seeds" / "orders.csv" with orders_path.open("a", encoding="utf-8") as orders_file: orders_file.write("\n".join(LATE_ORDER_ROWS) + "\n") @@ -256,10 +256,16 @@ def _duckdb_model_rows( f'schema = "{SCHEMA}"\n' ) +_CURRENT_ORDERS_SQL: str = """MODEL (description "Current order state.", materialized table); + +SELECT order_id, amount_cents, ordered_at AS updated_at FROM __seed("order_events") +""" + + STRATEGY_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _SQLITE_TOML, - "seeds/order_events.csv": FIRST_EVENTS_CSV, - "seeds/seeds.yml": """seeds: + "sql/seeds/order_events.csv": FIRST_EVENTS_CSV, + "sql/seeds/seeds.yml": """seeds: - name: order_events description: Order events. columns: @@ -270,7 +276,7 @@ def _duckdb_model_rows( - name: ordered_at type: TIMESTAMP """, - "models/daily_revenue.sql": """MODEL ( + "sql/models/daily_revenue.sql": """MODEL ( description "Daily revenue in sequential microbatches.", materialized incremental, incremental_strategy delete_insert, @@ -290,7 +296,7 @@ def _duckdb_model_rows( WHERE ordered_at >= __cursor_start() AND ordered_at < __cursor_end() GROUP BY 1 """, - "models/orders_window.sql": """MODEL ( + "sql/models/orders_window.sql": """MODEL ( description "Orders replaced by daily cursor window.", materialized incremental, incremental_strategy delete_insert, @@ -303,11 +309,8 @@ def _duckdb_model_rows( SELECT order_id, amount_cents, ordered_at FROM __seed("order_events") """, - "models/current_orders.sql": """MODEL (description "Current order state.", materialized table); - -SELECT order_id, amount_cents, ordered_at AS updated_at FROM __seed("order_events") -""", - "models/order_history.sql": """MODEL ( + "sql/models/current_orders.sql": _CURRENT_ORDERS_SQL, + "sql/models/order_history.sql": """MODEL ( description "Order history by update time.", materialized snapshot, unique_key [order_id], @@ -318,7 +321,7 @@ def _duckdb_model_rows( SELECT order_id, amount_cents, updated_at FROM __ref("current_orders") """, - "models/order_amount_history.sql": """MODEL ( + "sql/models/order_amount_history.sql": """MODEL ( description "Order amount history by checked columns.", materialized snapshot, unique_key [order_id], @@ -332,7 +335,7 @@ def _duckdb_model_rows( CONTRACT_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _SQLITE_TOML, - "models/order_amounts.sql": """MODEL ( + "sql/models/order_amounts.sql": """MODEL ( description "Order amounts with an exact decimal contract.", contract enforced, columns ( @@ -348,7 +351,7 @@ def _duckdb_model_rows( FUNCTION_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _SQLITE_TOML, - "functions/sql/is_large.sql": """FUNCTION ( + "sql/functions/sql/is_large.sql": """FUNCTION ( description "Whether an amount is large.", arguments (amount INTEGER), returns BOOLEAN, @@ -356,7 +359,7 @@ def _duckdb_model_rows( amount > 10 """, - "models/large_orders.sql": """MODEL (description "Large orders.", materialized table); + "sql/models/large_orders.sql": """MODEL (description "Large orders.", materialized table); SELECT 1 AS order_id """, @@ -364,9 +367,9 @@ def _duckdb_model_rows( CONCURRENT_MICROBATCH_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _SQLITE_TOML + "\n[settings]\nmicrobatch_concurrency = true\n", - "seeds/order_events.csv": FIRST_EVENTS_CSV, - "seeds/seeds.yml": STRATEGY_PROJECT_FILES["seeds/seeds.yml"], - "models/daily_revenue.sql": STRATEGY_PROJECT_FILES["models/daily_revenue.sql"].replace( + "sql/seeds/order_events.csv": FIRST_EVENTS_CSV, + "sql/seeds/seeds.yml": STRATEGY_PROJECT_FILES["sql/seeds/seeds.yml"], + "sql/models/daily_revenue.sql": STRATEGY_PROJECT_FILES["sql/models/daily_revenue.sql"].replace( " batch_size 1d,\n", " batch_size 1d,\n batch_concurrency 4,\n" ), } @@ -375,16 +378,24 @@ def _duckdb_model_rows( "sqlbuild_project.toml": _SQLITE_TOML.replace( f'path = "{SQLITE_FILE}"\n', f'path = "{SQLITE_FILE}"\nbusy_timeout = 0.5\n' ), - "models/order_ids.sql": """MODEL (description "Order ids.", materialized table); + "sql/models/order_ids.sql": """MODEL (description "Order ids.", materialized table); SELECT 1 AS order_id """, } +_CUSTOMER_TOTALS_SQL: str = """MODEL (description 'Totals per customer.', materialized table); + +SELECT customer_id, SUM(amount) AS total_amount, COUNT(*) AS order_count +FROM __ref("orders") +GROUP BY customer_id +""" + + SCENARIO_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _SQLITE_TOML, - "sources/raw.yml": """sources: + "sql/sources/raw.yml": """sources: - name: raw_orders description: Raw orders. schema: main @@ -399,17 +410,12 @@ def _duckdb_model_rows( - name: ordered_at type: TIMESTAMP """, - "models/orders.sql": """MODEL (description 'Orders.', materialized table); + "sql/models/orders.sql": """MODEL (description 'Orders.', materialized table); SELECT id AS order_id, customer_id, amount, ordered_at FROM __source("raw_orders") """, - "models/customer_totals.sql": """MODEL (description 'Totals per customer.', materialized table); - -SELECT customer_id, SUM(amount) AS total_amount, COUNT(*) AS order_count -FROM __ref("orders") -GROUP BY customer_id -""", - "models/daily_orders.sql": """MODEL ( + "sql/models/customer_totals.sql": _CUSTOMER_TOTALS_SQL, + "sql/models/daily_orders.sql": """MODEL ( description 'Orders by day, incremental.', materialized incremental, incremental_strategy delete_insert, @@ -590,9 +596,9 @@ def execute_sqlite_script(*, db_path: Path, sql: str) -> None: """ DECIMAL_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _SQLITE_TOML, - "sources/raw.yml": _PAYMENT_SOURCES, - "models/payments.sql": _PAYMENTS_MODEL, - "models/payment_ledger.sql": """MODEL ( + "sql/sources/raw.yml": _PAYMENT_SOURCES, + "sql/models/payments.sql": _PAYMENTS_MODEL, + "sql/models/payment_ledger.sql": """MODEL ( description "Payments computed from numbers under the same contract.", materialized table, contract enforced, @@ -606,7 +612,7 @@ def execute_sqlite_script(*, db_path: Path, sql: str) -> None: """, } EVOLVED_DECIMAL_PROJECT_FILES: dict[str, str] = { - "models/payments.sql": _PAYMENTS_MODEL.replace( + "sql/models/payments.sql": _PAYMENTS_MODEL.replace( " amount (type DECIMAL(10,2)),\n", " amount (type DECIMAL(10,2)),\n fee (type DECIMAL(10,2)),\n", ).replace("SELECT payment_id, amount FROM", "SELECT payment_id, amount, 0.1 AS fee FROM"), @@ -649,9 +655,9 @@ def build_cursor_window_files(*, adapter: str, events_csv: str) -> dict[str, str "[targets.dev]\n" f'schema = "{SCHEMA}"\n' ), - "seeds/order_events.csv": events_csv, - "seeds/seeds.yml": STRATEGY_PROJECT_FILES["seeds/seeds.yml"], - "models/hourly_orders.sql": """MODEL ( + "sql/seeds/order_events.csv": events_csv, + "sql/seeds/seeds.yml": STRATEGY_PROJECT_FILES["sql/seeds/seeds.yml"], + "sql/models/hourly_orders.sql": """MODEL ( description "Orders in hourly microbatches.", materialized incremental, incremental_strategy delete_insert, @@ -709,17 +715,20 @@ def model_order_ids(*, adapter: str, project_dir: Path) -> tuple[tuple[object, . ) STAGING_ORDERS_FILES: dict[str, str] = { "sqlbuild_project.toml": _SCHEMA_PER_MODEL_TOML, - "models/orders.sql": """MODEL (description "Staged.", materialized table, schema "staging"); + "sql/models/orders.sql": """MODEL (description "Staged.", materialized table, schema "staging"); SELECT 1 AS order_id """, } -MAIN_STAGING_ORDERS_FILES: dict[str, str] = { - "sqlbuild_project.toml": _SCHEMA_PER_MODEL_TOML, - "models/staging__orders.sql": """MODEL (description "Orders kept in main.", materialized table); +_STAGING_ORDERS_SQL: str = """MODEL (description "Orders kept in main.", materialized table); SELECT 2 AS order_id -""", +""" + + +MAIN_STAGING_ORDERS_FILES: dict[str, str] = { + "sqlbuild_project.toml": _SCHEMA_PER_MODEL_TOML, + "sql/models/staging__orders.sql": _STAGING_ORDERS_SQL, } @@ -750,26 +759,26 @@ def run_sqb_commands( 'materialized = "view"\n' ) _WAFFLE_SQLITE_UNSUPPORTED_FILES: tuple[str, ...] = ( - "functions/sql/customer_orders.sql", - "functions/sql/is_completed_order.sql", - "functions/python/is_completed_order_py.py", + "sql/functions/sql/customer_orders.sql", + "sql/functions/sql/is_completed_order.sql", + "sql/functions/python/is_completed_order_py.py", "tests/unit/test_customer_orders_table_fn.sql", "tests/unit/test_is_completed_order_udf.sql", - "models/marts/daily_order_partitioned.sql", + "sql/models/marts/daily_order_partitioned.sql", ) _WAFFLE_SQLITE_REWRITES: tuple[tuple[str, str, str], ...] = ( ( - "models/marts/fact_orders.sql", + "sql/models/marts/fact_orders.sql", '__udf("is_completed_order")(o.status) AS is_completed_order,', "o.status = 'completed' AS is_completed_order,", ), ( - "models/marts/fact_orders.sql", + "sql/models/marts/fact_orders.sql", '__udf("is_completed_order_py")(o.status) AS is_completed_order_py,', "o.status = 'completed' AS is_completed_order_py,", ), ( - "models/marts/_macros/python/time.py", + "sql/models/marts/_macros/python/time.py", " return f\"DATE_TRUNC('{grain}', {expression})\"", ' if ctx.adapter_name == "sqlite" and grain == "day":\n' " return f\"datetime({expression}, 'start of day')\"\n" @@ -778,7 +787,7 @@ def run_sqb_commands( "strftime('+%H hours', {expression}))\"\n" " return f\"DATE_TRUNC('{grain}', {expression})\"", ), - ("models/marts/daily_revenue.sql", "CAST(o.ordered_at AS DATE)", "date(o.ordered_at)"), + ("sql/models/marts/daily_revenue.sql", "CAST(o.ordered_at AS DATE)", "date(o.ordered_at)"), ) _TIMESTAMP_LITERAL_CAST: re.Pattern[str] = re.compile(r"CAST\(('[^']*') AS TIMESTAMP\)") WAFFLE_ROW_COUNT_RELATIONS: tuple[str, ...] = ( @@ -820,7 +829,7 @@ def prepare_sqlite_waffle_shop(*, tmp_path: Path) -> Path: new: str for relative_path, old, new in _WAFFLE_SQLITE_REWRITES: _replace_in_file(path=project_dir / relative_path, old=old, new=new) - sources_path: Path = project_dir / "sources" / "raw.yml" + sources_path: Path = project_dir / "sql" / "sources" / "raw.yml" sources_path.write_text( _TIMESTAMP_LITERAL_CAST.sub(r"\1", sources_path.read_text(encoding="utf-8")), encoding="utf-8", @@ -865,7 +874,7 @@ def _duckdb_waffle_row_count(project_dir: Path, relation: str) -> int: LOADER_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _SQLITE_TOML, - "sources/raw.yml": """sources: + "sql/sources/raw.yml": """sources: - name: raw_events description: Order events from a loader. managed: true @@ -881,7 +890,8 @@ def _duckdb_waffle_row_count(project_dir: Path, relation: str) -> int: - name: logged_at type: TIMESTAMP """, - "python/loaders/events.py": '''from datetime import date, datetime, timedelta, timezone + "python/nodes/loaders/events/loader.py": ( + '''from datetime import date, datetime, timedelta, timezone from sqlbuild.loaders import loader @@ -904,8 +914,9 @@ def raw_events(ctx: object) -> list[dict[str, object]]: "logged_at": None, }, ] -''', - "models/events.sql": """MODEL (description "Events from the source.", materialized table); +''' + ), + "sql/models/events.sql": """MODEL (description "Events from the source.", materialized table); SELECT event_id, happened_at, event_day, logged_at FROM __source("raw_events") """, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_decimal_contracts.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_decimal_contracts.py index c11008d650..7c77c46447 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_decimal_contracts.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_decimal_contracts.py @@ -48,7 +48,7 @@ ), SqliteDecimalContractE2ETestCase( description="a numeric DECIMAL(10,2) warehouse column is enforced to contract text", - source_files={"sources/raw.yml": UNDECLARED_PAYMENT_SOURCES}, + source_files={"sql/sources/raw.yml": UNDECLARED_PAYMENT_SOURCES}, expected_payment_rows=_EXPECTED_PAYMENT_ROWS, expected_agreeing_rows=2, expected_evolved_rows=_EXPECTED_EVOLVED_ROWS, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_sqlite.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_sqlite.py index 21f1a162ca..5558916bf9 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_sqlite.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_sqlite.py @@ -196,7 +196,7 @@ def test_given_cloned_target_when_diffing_then_sqlite_reports_changed_rows( SqliteProjectE2ETestCase( description="sequential microbatches rewrite each day without state tables", files=STRATEGY_PROJECT_FILES, - changed_files={"seeds/order_events.csv": CHANGED_EVENTS_CSV}, + changed_files={"sql/seeds/order_events.csv": CHANGED_EVENTS_CSV}, query="SELECT * FROM analytics__daily_revenue ORDER BY 1", expected_rows=(("2026-01-02 00:00:00", 2, 550), ("2026-01-03 00:00:00", 1, 400)), absent_tables=("analytics___sqlbuild_microbatches", "_sqlbuild_microbatches"), @@ -204,7 +204,7 @@ def test_given_cloned_target_when_diffing_then_sqlite_reports_changed_rows( SqliteProjectE2ETestCase( description="keyed cursor delete_insert replaces the window and changed keys", files=STRATEGY_PROJECT_FILES, - changed_files={"seeds/order_events.csv": CHANGED_EVENTS_CSV}, + changed_files={"sql/seeds/order_events.csv": CHANGED_EVENTS_CSV}, query="SELECT * FROM analytics__orders_window ORDER BY 1, 3", expected_rows=( (1, 100, "2026-01-01 10:00:00"), @@ -216,7 +216,7 @@ def test_given_cloned_target_when_diffing_then_sqlite_reports_changed_rows( SqliteProjectE2ETestCase( description="timestamp snapshot closes updated and hard-deleted versions", files=STRATEGY_PROJECT_FILES, - changed_files={"seeds/order_events.csv": CHANGED_EVENTS_CSV}, + changed_files={"sql/seeds/order_events.csv": CHANGED_EVENTS_CSV}, query=( "SELECT order_id, amount_cents, valid_from, valid_to IS NULL " "FROM analytics__order_history ORDER BY 1, 3" @@ -232,7 +232,7 @@ def test_given_cloned_target_when_diffing_then_sqlite_reports_changed_rows( SqliteProjectE2ETestCase( description="check snapshot versions a changed amount", files=STRATEGY_PROJECT_FILES, - changed_files={"seeds/order_events.csv": CHANGED_EVENTS_CSV}, + changed_files={"sql/seeds/order_events.csv": CHANGED_EVENTS_CSV}, query=( "SELECT order_id, amount_cents, valid_to IS NULL " "FROM analytics__order_amount_history ORDER BY 1, 2" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_temporal_casts.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_temporal_casts.py index b8dc12dc73..74698af15b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_temporal_casts.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_temporal_casts.py @@ -47,11 +47,11 @@ def test_given_sqlite_temporal_cast_when_compiling_then_b104_warns( 'name = "shop"\nadapter = "sqlite"\n\n[connection]\npath = "shop.sqlite"\n\n' "[scopes]\nenforce_placement = false\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n" "SELECT 1 AS order_id, '2026-01-01 10:00:00' AS ordered_at\n" ), - "models/order_times.sql": ( + "sql/models/order_times.sql": ( "MODEL (description 'Test model order_times.');\n" f'SELECT o.order_id, {test_case.expression} AS ordered_at FROM __ref("orders") AS o\n' ), @@ -67,7 +67,7 @@ def test_given_sqlite_temporal_cast_when_compiling_then_b104_warns( located: list[tuple[str, str, int, int]] = [ (item["code"], item["path"], item["line"], item["column"]) for item in report["diagnostics"] ] - assert located.count(("B104", "models/order_times.sql", 2, 20)) == ( + assert located.count(("B104", "sql/models/order_times.sql", 2, 20)) == ( test_case.expected_warning_count ), test_case.description assert [item[0] for item in located].count("B104") == test_case.expected_warning_count diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_text_cursors.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_text_cursors.py index e97a7139db..ab2fe62f10 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_text_cursors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_text_cursors.py @@ -56,8 +56,8 @@ def test_given_text_timestamp_cursor_when_building_twice_then_only_sqlite_accept f"[connection]\n{test_case.connection}\n\n" '[defaults]\nmaterialized = "table"\n\n[scopes]\nenforce_placement = false\n' ), - "models/orders.sql": _TWO_ORDERS, - "models/daily_orders.sql": ( + "sql/models/orders.sql": _TWO_ORDERS, + "sql/models/daily_orders.sql": ( "MODEL (description 'Test model daily_orders.', materialized incremental,\n" " incremental_strategy delete_insert, cursor order_day, cursor_type timestamp,\n" " cursor_grain day, cursor_inputs (orders ordered_at));\n" @@ -69,7 +69,7 @@ def test_given_text_timestamp_cursor_when_building_twice_then_only_sqlite_accept first: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir ) - _ = (project_dir / "models/orders.sql").write_text(_THREE_ORDERS, encoding="utf-8") + _ = (project_dir / "sql/models/orders.sql").write_text(_THREE_ORDERS, encoding="utf-8") second: subprocess.CompletedProcess[str] = run_sqb( command=("--no-color", "build"), project_dir=project_dir diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/helpers.py index 4bc2203fab..d3f566dcd3 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/helpers.py @@ -276,14 +276,18 @@ def prepare_sqlserver_waffle_shop(*, tmp_path: Path, config: dict[str, object]) schema_name: str = build_unique_schema_name(prefix="sqb_waffle") project_dir: Path = prepare_waffle_shop(tmp_path) - (project_dir / "functions" / "sql" / "customer_orders.sql").unlink(missing_ok=True) - (project_dir / "functions" / "python" / "is_completed_order_py.py").unlink(missing_ok=True) + (project_dir / "sql" / "functions" / "sql" / "customer_orders.sql").unlink(missing_ok=True) + (project_dir / "sql" / "functions" / "python" / "is_completed_order_py.py").unlink( + missing_ok=True + ) (project_dir / "tests" / "unit" / "test_customer_orders_table_fn.sql").unlink(missing_ok=True) (project_dir / "tests" / "unit" / "test_fact_orders.sql").unlink(missing_ok=True) - (project_dir / "models" / "marts" / "daily_order_partitioned.sql").unlink(missing_ok=True) + (project_dir / "sql" / "models" / "marts" / "daily_order_partitioned.sql").unlink( + missing_ok=True + ) (project_dir / "tests" / "unit" / "test_is_completed_order_udf.sql").unlink(missing_ok=True) - macro_path: Path = project_dir / "models" / "marts" / "_macros" / "python" / "time.py" + macro_path: Path = project_dir / "sql" / "models" / "marts" / "_macros" / "python" / "time.py" _rewrite( macro_path, ( @@ -300,7 +304,9 @@ def prepare_sqlserver_waffle_shop(*, tmp_path: Path, config: dict[str, object]) " return f\"DATE_TRUNC('{grain}', {expression})\"", ), ) - is_completed_order_path: Path = project_dir / "functions" / "sql" / "is_completed_order.sql" + is_completed_order_path: Path = ( + project_dir / "sql" / "functions" / "sql" / "is_completed_order.sql" + ) _rewrite(is_completed_order_path, ("STRING", "NVARCHAR")) _rewrite(is_completed_order_path, ("BOOLEAN", "BIT")) _rewrite( @@ -310,7 +316,7 @@ def prepare_sqlserver_waffle_shop(*, tmp_path: Path, config: dict[str, object]) "CAST(CASE WHEN order_status = 'completed' THEN 1 ELSE 0 END AS BIT)", ), ) - fact_orders_path: Path = project_dir / "models" / "marts" / "fact_orders.sql" + fact_orders_path: Path = project_dir / "sql" / "models" / "marts" / "fact_orders.sql" _rewrite( fact_orders_path, ( @@ -331,9 +337,9 @@ def prepare_sqlserver_waffle_shop(*, tmp_path: Path, config: dict[str, object]) ), encoding="utf-8", ) - lookups_path: Path = project_dir / "seeds" / "lookups.yml" + lookups_path: Path = project_dir / "sql" / "seeds" / "lookups.yml" _rewrite(lookups_path, ("type: VARCHAR", "type: NVARCHAR(100)")) - raw_sources_path: Path = project_dir / "sources" / "raw.yml" + raw_sources_path: Path = project_dir / "sql" / "sources" / "raw.yml" adapt_sqlserver_text_file(raw_sources_path) _rewrite( raw_sources_path, @@ -366,12 +372,12 @@ def prepare_sqlserver_source_loader_strategies( config=config, ), ) - source_path: Path = project_dir / "sources" / "raw.yml" + source_path: Path = project_dir / "sql" / "sources" / "raw.yml" source_path.write_text( source_path.read_text(encoding="utf-8").replace("type: TIMESTAMP", "type: DATETIME2"), encoding="utf-8", ) - loader_path: Path = project_dir / "python" / "loaders" / "strategy_sources.py" + loader_path: Path = project_dir / "python" / "nodes" / "loaders" / "strategy_sources.py" old_sql: str = ( 'f"CREATE TABLE {ctx.destination} AS "\n' " \"SELECT 1 AS status_id, 'loaded' AS status_name, " diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/test_sqlserver.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/test_sqlserver.py index 1b50f67e26..3844f2d9bb 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/test_sqlserver.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/test_sqlserver.py @@ -61,6 +61,7 @@ run_sqb, stringify_warehouse_rows, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -114,13 +115,13 @@ def test_given_managed_source_when_cloning_sqlserver_then_source_precedes_depend "[targets.prod.clone]\n" "allow_as_clone_destination = true\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_customers(ctx):\n" " '''Test loader raw_customers.'''\n return []\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" " managed: true\n" @@ -131,7 +132,7 @@ def test_given_managed_source_when_cloning_sqlserver_then_source_precedes_depend " - name: first_name\n" " type: VARCHAR\n" ), - "models/stg_customers.sql": ( + "sql/models/stg_customers.sql": ( "MODEL (description 'Test model stg_customers.', materialized view);\n\n" 'SELECT customer_id, first_name FROM __source("raw_customers")\n' ), @@ -293,7 +294,7 @@ def test_given_sqlserver_targets_when_running_diff_then_all_modes_execute_end_to "[targets.dev]\n" f'schema = "{dev_schema}"\n' ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.',\n" " materialized table,\n" " unique_key [order_id],\n" @@ -432,15 +433,15 @@ def test_given_python_result_when_running_check_on_sqlserver_then_persists_node_ schema_name=schema_name, config=config, ), - "python/tasks/results.py": ( + "python/nodes/tasks/results/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def produce_result(ctx):\n" " '''Test task produce_result.'''\n return ctx.result(payload={'value': 42}, metadata={'source': 'sqlserver'})\n" ), - "python/checks/results.py": ( + "python/nodes/checks/results/checks.py": ( "from sqlbuild.checks import check\n" - "from python.tasks.results import produce_result\n\n" + "from python.nodes.tasks.results.asset import produce_result\n\n" "@check(depends_on=produce_result)\n" "def check_produce_result(ctx):\n" " '''Test check check_produce_result.'''\n return ctx.result_of(node_function=produce_result).payload['value'] == 42\n" @@ -707,7 +708,7 @@ def test_given_source_loader_project_when_building_on_sqlserver_then_model_reads schema_name=schema_name, config=config, ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -718,13 +719,13 @@ def test_given_source_loader_project_when_building_on_sqlserver_then_model_reads " - name: status\n" " type: NVARCHAR(100)\n" ), - "python/loaders/raw_orders.py": ( + "python/nodes/loaders/raw_orders/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 7, 'status': 'loaded-dev'}]\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT order_id, status FROM __source("raw_orders")' ), }, @@ -779,7 +780,7 @@ def test_given_source_deferral_env_when_building_on_sqlserver_then_reads_prod_an prod_schema_name=prod_schema_name, config=config, ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " managed: true\n" @@ -790,13 +791,13 @@ def test_given_source_deferral_env_when_building_on_sqlserver_then_reads_prod_an " - name: status\n" " type: NVARCHAR(100)\n" ), - "python/loaders/raw_orders.py": ( + "python/nodes/loaders/raw_orders/loader.py": ( "from sqlbuild.loaders import loader\n\n" "@loader\n" "def raw_orders(ctx):\n" " '''Test loader raw_orders.'''\n return [{'order_id': 7, 'status': 'loaded-dev'}]\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT order_id, status FROM __source("raw_orders")' ), }, @@ -1040,22 +1041,25 @@ def test_given_chained_loader_project_when_loading_on_sqlserver_then_runs_loader " - name: status\n" " type: NVARCHAR(100)\n" ), - loader_py=( - "from sqlbuild.loaders import loader\n\n" - "@loader(write_strategy='table', columns=[\n" - " {'name': 'event_id', 'type': 'INTEGER'},\n" - "])\n" - "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" - "@loader(depends_on=[fetch_events])\n" - "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " cursor = ctx.query(\n" - " f'SELECT event_id FROM {events.destination} ORDER BY event_id'\n" - " )\n" - " rows = cursor.fetchall()\n" - " return [{'event_id': row[0], 'status': 'loaded'} for row in rows]\n" - ), + node_files={ + **node_module_files( + "python/nodes/loaders/source_rows.py", + "from sqlbuild.loaders import loader\n\n" + "@loader(write_strategy='table', columns=[\n" + " {'name': 'event_id', 'type': 'INTEGER'},\n" + "])\n" + "def fetch_events(ctx):\n" + " '''Test loader fetch_events.'''\n return [{'event_id': 1}, {'event_id': 2}]\n\n" + "@loader(depends_on=[fetch_events])\n" + "def raw_events(ctx):\n" + " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" + " cursor = ctx.query(\n" + " f'SELECT event_id FROM {events.destination} ORDER BY event_id'\n" + " )\n" + " rows = cursor.fetchall()\n" + " return [{'event_id': row[0], 'status': 'loaded'} for row in rows]\n", + ) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -1222,7 +1226,9 @@ def test_given_intermediate_strategy_project_when_loading_twice_on_sqlserver_the " - name: amount\n" " type: INTEGER\n" ), - loader_py=test_case.loader_py, + node_files={ + **node_module_files("python/nodes/loaders/source_rows.py", test_case.loader_py) + }, ), ) (project_dir / "sqlbuild_project.toml").write_text( @@ -1337,7 +1343,7 @@ def test_given_snapshot_project_when_building_on_sqlserver_then_scd2_history_is_ expected_historical_check_rows=test_case.expected_historical_check_rows, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( adapt_sqlserver_sql( build_current_customers_model_sql(plan="blocked", updated_at="2026-01-02 00:00:00") ), @@ -1363,7 +1369,7 @@ def test_given_snapshot_project_when_building_on_sqlserver_then_scd2_history_is_ expected_rows=test_case.expected_current_rows_after_initial_build, ) - (project_dir / "models" / "current_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_customers.sql").write_text( adapt_sqlserver_sql( build_current_customers_model_sql(plan="pro", updated_at="2026-01-02 00:00:00") ), @@ -1448,18 +1454,18 @@ def test_given_existing_snapshot_targets_when_building_on_sqlserver_then_apply_s ) assert initial_result.returncode == 0, initial_result.stdout + initial_result.stderr - (project_dir / "models" / "current_check_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_check_customers.sql").write_text( build_current_check_customers_model_sql(changed=True), encoding="utf-8" ) - (project_dir / "models" / "current_delete_customers.sql").write_text( + (project_dir / "sql" / "models" / "current_delete_customers.sql").write_text( adapt_sqlserver_sql(build_current_delete_customers_model_sql(changed=True)), encoding="utf-8", ) - (project_dir / "models" / "historical_timestamp_extracts.sql").write_text( + (project_dir / "sql" / "models" / "historical_timestamp_extracts.sql").write_text( adapt_sqlserver_sql(build_historical_timestamp_extracts_model_sql(changed=True)), encoding="utf-8", ) - (project_dir / "models" / "historical_check_daily.sql").write_text( + (project_dir / "sql" / "models" / "historical_check_daily.sql").write_text( adapt_sqlserver_sql(build_historical_check_daily_model_sql(changed=True)), encoding="utf-8", ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py index 7c37e193f1..c1a750a6ac 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py @@ -23,10 +23,10 @@ '[connection]\ndatabase = "optional_ceremony.duckdb"\n\n' '[defaults]\nmaterialized = "table"\n' ), - "macros/python/status.py": ( + "sql/macros/python/status.py": ( 'def normalize_status(value: str) -> str:\n return f"LOWER(TRIM({value}))"\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -35,7 +35,7 @@ " - name: order_id\n type: INTEGER\n" " - name: status\n type: VARCHAR\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\n" 'SELECT order_id, @py.normalize_status("status") AS status FROM __source("raw_orders")\n' ), @@ -52,7 +52,7 @@ def build_dynamic_pivot_test_project_files() -> dict[str, str]: "[defaults]\n" 'contract = "enforced"\n' ), - "models/stg_order_amounts.sql": ( + "sql/models/stg_order_amounts.sql": ( "MODEL (description 'Test model stg_order_amounts.',\n" " database analytics,\n" " schema staging,\n" @@ -68,7 +68,7 @@ def build_dynamic_pivot_test_project_files() -> dict[str, str]: "CAST(10.25 AS DECIMAL(12,2)) AS amount, " "CAST('US' AS VARCHAR) AS country\n" ), - "models/customer_category_amounts.sql": ( + "sql/models/customer_category_amounts.sql": ( "MODEL (description 'Test model customer_category_amounts.',\n" " database analytics,\n" " schema mart,\n" @@ -124,7 +124,7 @@ def build_chain_test_project_files(*, sql_analysis_enabled: bool) -> dict[str, s "[settings]\n" f"sql_analysis = {sql_analysis_value}\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\n" "SELECT\n" " id,\n" @@ -134,7 +134,7 @@ def build_chain_test_project_files(*, sql_analysis_enabled: bool) -> dict[str, s " @py.real_status() AS status\n" 'FROM __source("raw")' ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.', materialized table);\n\n" "SELECT\n" " id,\n" @@ -144,7 +144,7 @@ def build_chain_test_project_files(*, sql_analysis_enabled: bool) -> dict[str, s " status\n" 'FROM __ref("stg_orders")' ), - "models/_macros/python/test_macros.py": ( + "sql/models/_macros/python/test_macros.py": ( "def mocked_amount() -> str:\n" ' return "0"\n\n' "def mocked_country() -> str:\n" @@ -154,7 +154,7 @@ def build_chain_test_project_files(*, sql_analysis_enabled: bool) -> dict[str, s "def real_status() -> str:\n" " return \"'active'\"\n" ), - "sources/raw.yml": "sources:\n - name: raw\n description: Test source raw.\n" + "sql/sources/raw.yml": "sources:\n - name: raw\n description: Test source raw.\n" " schema: main\n table: raw\n", "tests/unit/test_chain.sql": ( "TEST();\n\n" @@ -186,15 +186,15 @@ def build_parameterized_test_project_files() -> dict[str, str]: "[connection]\n" 'database = "parameter_case_demo.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\n' 'SELECT status FROM __source("raw_orders")\n' ), - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (description "Test model customers.");\n\n' 'SELECT status FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), @@ -227,14 +227,14 @@ def build_table_function_fixture_project_files() -> dict[str, str]: "[connection]\n" 'database = "table_function_fixture_demo.duckdb"\n' ), - "functions/sql/customer_orders.sql": ( + "sql/functions/sql/customer_orders.sql": ( "FUNCTION (description 'Test function customer_orders.',\n" " arguments (customer_id INTEGER),\n" " returns table (order_id INTEGER)\n" ");\n\n" "SELECT customer_id * 100 AS order_id\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', columns (order_id (type INTEGER)));\n\n" 'SELECT order_id FROM __table_fn("customer_orders")(7)\n' ), @@ -259,13 +259,13 @@ def build_mock_boundary_test_project_files() -> dict[str, str]: "[connection]\n" 'database = "mock_boundary_demo.duckdb"\n' ), - "models/stg_orders.sql": "MODEL (description 'Test model stg_orders.');\n\n" + "sql/models/stg_orders.sql": "MODEL (description 'Test model stg_orders.');\n\n" "SELECT 1 AS order_id\n", - "models/int_orders.sql": ( + "sql/models/int_orders.sql": ( 'MODEL (description "Test model int_orders.");\n\n' 'SELECT order_id FROM __ref("stg_orders")\n' ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( 'MODEL (description "Test model fact_orders.");\n\n' 'SELECT order_id FROM __ref("int_orders")\n' ), @@ -295,7 +295,7 @@ def build_unsatisfied_leaf_test_project_files() -> dict[str, str]: """Build a test that omits the source mock required by its real model chain.""" files: dict[str, str] = build_chain_test_project_files(sql_analysis_enabled=True) - files["sources/raw.yml"] = ( + files["sql/sources/raw.yml"] = ( "sources:\n" " - name: raw\n description: Test source raw.\n schema: main\n table: raw\n" " - name: unused\n description: Test source unused.\n" @@ -324,11 +324,11 @@ def build_missing_mock_columns_project_files() -> dict[str, str]: "[connection]\n" 'database = "missing_fixture_columns.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\n' 'SELECT customer_id, status FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -357,11 +357,11 @@ def build_partial_source_fixture_project_files() -> dict[str, str]: "[connection]\n" 'database = "partial_source_fixture.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\n' 'SELECT order_id, status FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -386,7 +386,7 @@ def build_unspecified_nullability_fixture_project_files() -> dict[str, str]: """Build a typed partial source fixture whose nullability is unspecified.""" files: dict[str, str] = build_partial_source_fixture_project_files() - files["sources/raw_orders.yml"] = files["sources/raw_orders.yml"].replace( + files["sql/sources/raw_orders.yml"] = files["sql/sources/raw_orders.yml"].replace( " type: VARCHAR\n nullable: true\n", " type: VARCHAR\n", ) @@ -403,11 +403,11 @@ def build_partial_ref_fixture_project_files() -> dict[str, str]: "[connection]\n" 'database = "partial_ref_fixture.duckdb"\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.');\n\n" "SELECT CAST(1 AS INTEGER) AS order_id, CAST(NULL AS VARCHAR) AS status\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\n' 'SELECT order_id, status FROM __ref("stg_orders")\n' ), @@ -433,7 +433,7 @@ def build_open_schema_ref_fixture_project_files() -> dict[str, str]: "[connection]\n" 'database = "open_schema_ref_fixture.duckdb"\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.',\n" " columns (\n" " order_id (type INTEGER),\n" @@ -441,11 +441,11 @@ def build_open_schema_ref_fixture_project_files() -> dict[str, str]: ");\n\n" 'SELECT * FROM __source("raw_orders")\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\n' 'SELECT order_id, status FROM __ref("stg_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), @@ -469,7 +469,7 @@ def build_recursive_ref_fixture_project_files() -> dict[str, str]: "[connection]\n" 'database = "recursive_ref_fixture.duckdb"\n' ), - "models/stg_order_links.sql": ( + "sql/models/stg_order_links.sql": ( "MODEL (description 'Test model stg_order_links.',\n" " contract enforced,\n" " columns (\n" @@ -479,7 +479,7 @@ def build_recursive_ref_fixture_project_files() -> dict[str, str]: ");\n\n" 'SELECT order_id, parent_order_id FROM __source("raw_order_links")\n' ), - "models/order_roots.sql": ( + "sql/models/order_roots.sql": ( "MODEL (description 'Test model order_roots.',\n" " contract enforced,\n" " columns (\n" @@ -501,7 +501,7 @@ def build_recursive_ref_fixture_project_files() -> dict[str, str]: ")\n" "SELECT order_id, root_order_id, link_depth FROM order_chain\n" ), - "sources/raw_order_links.yml": ( + "sql/sources/raw_order_links.yml": ( "sources:\n" " - name: raw_order_links\n description: Test source raw_order_links.\n" " schema: main\n" @@ -534,12 +534,12 @@ def build_partial_seed_fixture_project_files() -> dict[str, str]: "[connection]\n" 'database = "partial_seed_fixture.duckdb"\n' ), - "models/countries.sql": ( + "sql/models/countries.sql": ( 'MODEL (description "Test model countries.");\n\n' 'SELECT country_code, country_name FROM __seed("country_codes")\n' ), - "seeds/country_codes.csv": "country_code,country_name\nUS,United States\n", - "seeds/schema.yml": ( + "sql/seeds/country_codes.csv": "country_code,country_name\nUS,United States\n", + "sql/seeds/schema.yml": ( "seeds:\n" " - name: country_codes\n description: Test seed country_codes.\n" " columns:\n" @@ -562,7 +562,7 @@ def build_irrelevant_omitted_column_project_files() -> dict[str, str]: """Build a fixture omitting a known nullable column outside the compiled closure.""" files: dict[str, str] = build_partial_source_fixture_project_files() - files["models/orders.sql"] = ( + files["sql/models/orders.sql"] = ( 'MODEL (description "Test model orders.");\n\nSELECT order_id FROM __source("raw_orders")\n' ) files["tests/unit/test_orders.sql"] = ( @@ -579,7 +579,7 @@ def build_cte_partial_source_fixture_project_files() -> dict[str, str]: """Build a partial source fixture read through an import CTE.""" files: dict[str, str] = build_partial_source_fixture_project_files() - files["models/orders.sql"] = ( + files["sql/models/orders.sql"] = ( "MODEL (description 'Test model orders.');\n\n" "WITH staged AS (\n" ' SELECT order_id, status FROM __source("raw_orders")\n' @@ -593,7 +593,7 @@ def build_clause_partial_source_fixture_project_files() -> dict[str, str]: """Build a partial source fixture whose omitted column is read only by a filter.""" files: dict[str, str] = build_partial_source_fixture_project_files() - files["models/orders.sql"] = ( + files["sql/models/orders.sql"] = ( 'MODEL (description "Test model orders.");\n\n' 'SELECT order_id FROM __source("raw_orders") WHERE status IS NULL\n' ) @@ -611,10 +611,10 @@ def build_star_partial_fixture_project_files() -> dict[str, str]: """Build a contracted star model requiring the complete known source shape.""" files: dict[str, str] = build_partial_source_fixture_project_files() - files["sources/raw_orders.yml"] = files["sources/raw_orders.yml"].replace( + files["sql/sources/raw_orders.yml"] = files["sql/sources/raw_orders.yml"].replace( " columns:\n", " contract: enforced\n columns:\n" ) - files["models/orders.sql"] = ( + files["sql/models/orders.sql"] = ( 'MODEL (description "Test model orders.");\n\nSELECT * FROM __source("raw_orders")\n' ) return files @@ -664,7 +664,7 @@ def build_untyped_null_fixture_project_files() -> dict[str, str]: "[connection]\n" 'database = "untyped_null_fixture.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " contract enforced,\n" " columns (order_year (type BIGINT)),\n" @@ -672,7 +672,7 @@ def build_untyped_null_fixture_project_files() -> dict[str, str]: "SELECT EXTRACT(YEAR FROM ordered_at) AS order_year\n" 'FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -697,7 +697,7 @@ def build_contract_empty_fixture_project_files() -> dict[str, str]: """Build empty input and expected fixtures whose shapes come from contracts.""" files: dict[str, str] = build_partial_source_fixture_project_files() - files["models/orders.sql"] = ( + files["sql/models/orders.sql"] = ( "MODEL (description 'Test model orders.',\n" " contract enforced,\n" " columns (\n" @@ -707,7 +707,7 @@ def build_contract_empty_fixture_project_files() -> dict[str, str]: ");\n\n" 'SELECT order_id, status FROM __source("raw_orders")\n' ) - files["sources/raw_orders.yml"] = files["sources/raw_orders.yml"].replace( + files["sql/sources/raw_orders.yml"] = files["sql/sources/raw_orders.yml"].replace( " table: raw_orders\n", " table: raw_orders\n contract: enforced\n", ) @@ -741,7 +741,7 @@ def build_open_expected_empty_fixture_project_files() -> dict[str, str]: """Build an empty expected fixture without an authoritative model shape.""" files: dict[str, str] = build_partial_source_fixture_project_files() - files["models/orders.sql"] = ( + files["sql/models/orders.sql"] = ( 'MODEL (description "Test model orders.");\n\nSELECT * FROM __source("raw_orders")\n' ) files["tests/unit/test_orders.sql"] = ( @@ -766,15 +766,15 @@ def build_qualified_star_other_relation_project_files() -> dict[str, str]: "[connection]\n" 'database = "qualified_star_other_relation.duckdb"\n' ), - "models/stg_orders.sql": "MODEL (description 'Test model stg_orders.');\n\n" + "sql/models/stg_orders.sql": "MODEL (description 'Test model stg_orders.');\n\n" "SELECT 1 AS stg_id\n", - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\n" "SELECT stg.*, raw.status\n" 'FROM __ref("stg_orders") stg\n' 'JOIN __source("raw_orders") raw ON TRUE\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -799,11 +799,11 @@ def build_mixed_case_partial_fixture_project_files() -> dict[str, str]: """Build a completed fixture with an as-written mixed-case unquoted alias.""" files: dict[str, str] = build_partial_source_fixture_project_files() - files["models/orders.sql"] = ( + files["sql/models/orders.sql"] = ( 'MODEL (description "Test model orders.");\n\n' 'SELECT status, note FROM __source("raw_orders")\n' ) - files["sources/raw_orders.yml"] = ( + files["sql/sources/raw_orders.yml"] = ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -834,7 +834,7 @@ def build_upper_case_star_import_partial_fixture_project_files() -> dict[str, st "[connection]\n" 'database = "partial_source_fixture.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw__orders\n description: Raw order records\n" " schema: raw\n" @@ -844,7 +844,7 @@ def build_upper_case_star_import_partial_fixture_project_files() -> dict[str, st " - name: customer_id\n type: VARCHAR\n" " - name: status\n type: VARCHAR\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders with their status", materialized table);\n\n' "WITH raw__orders AS (\n" " SELECT *\n" @@ -882,7 +882,7 @@ def build_invalid_partial_fixture_project_files( """Build one partial source fixture that cannot be completed safely.""" files: dict[str, str] = build_partial_source_fixture_project_files() - files["sources/raw_orders.yml"] = ( + files["sql/sources/raw_orders.yml"] = ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -918,11 +918,11 @@ def build_incompatible_fixture_type_project_files(*, adapter_name: str) -> dict[ 'database = "incompatible_fixture_type.duckdb"\n' 'schema = "main"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", database "fixture_db", schema "main");\n\n' 'SELECT item_ids FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -955,11 +955,11 @@ def build_complex_values_fixture_project_files(*, adapter_name: str) -> dict[str 'paths = ["tests/unit/test_orders.sql"]\n' 'reason = "The fixtures cover complex strings in a VALUES relation on every dialect."\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", database "fixture_db", schema "main");\n\n' 'SELECT order_id, mapping_text FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -1014,11 +1014,11 @@ def build_union_distinct_expected_project_files() -> dict[str, str]: "[connection]\n" 'database = "union_distinct_expected.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\n' 'SELECT DISTINCT order_id FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -1052,11 +1052,11 @@ def build_transformed_collection_project_files() -> dict[str, str]: "[connection]\n" 'database = "transformed_collection.duckdb"\n' ), - "models/order_statuses.sql": ( + "sql/models/order_statuses.sql": ( 'MODEL (description "Test model order_statuses.");\n\n' 'SELECT list(status) AS statuses FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -1084,7 +1084,7 @@ def build_cte_derived_output_fixture_project_files() -> dict[str, str]: "[connection]\n" 'database = "cte_derived_output_fixture.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\n" "WITH raw_orders AS (\n" ' SELECT * FROM __source("raw_orders")\n' @@ -1099,7 +1099,7 @@ def build_cte_derived_output_fixture_project_files() -> dict[str, str]: ")\n" "SELECT order_id, normalized_status, loaded_at FROM final\n" ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), @@ -1150,11 +1150,11 @@ def build_assertion_test_project_files(*, failing: bool) -> dict[str, str]: "[defaults]\n" 'materialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\n" "SELECT\n" " id AS order_id,\n" @@ -1185,10 +1185,10 @@ def build_macro_test_project_files() -> dict[str, str]: "[defaults]\n" 'materialized = "table"\n' ), - "macros/python/status.py": ( + "sql/macros/python/status.py": ( 'def normalize_status(value: str) -> str:\n return f"LOWER(TRIM({value}))"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', " "materialized table);\n\nSELECT @py.normalize_status(\"' PAID '\") AS status\n" ), @@ -1220,26 +1220,26 @@ def build_diamond_chain_test_project_files(*, sql_analysis_enabled: bool) -> dic "[defaults]\n" 'materialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\n" 'SELECT id AS order_id, customer_id, amount FROM __source("raw_orders")\n' ), - "models/large_orders.sql": ( + "sql/models/large_orders.sql": ( "MODEL (description 'Test model large_orders.', materialized table);\n\n" 'SELECT order_id, customer_id, amount FROM __ref("stg_orders") WHERE amount >= 10\n' ), - "models/small_orders.sql": ( + "sql/models/small_orders.sql": ( "MODEL (description 'Test model small_orders.', materialized table);\n\n" "WITH picked AS (\n" ' SELECT order_id, customer_id, amount FROM __ref("stg_orders") WHERE amount < 10\n' ")\n" "SELECT * FROM picked -- small orders only\n" ), - "models/customer_order_mix.sql": ( + "sql/models/customer_order_mix.sql": ( "MODEL (description 'Test model customer_order_mix.', materialized table);\n\n" 'WITH customers AS (SELECT DISTINCT customer_id FROM __ref("stg_orders"))\n' "SELECT customer_id,\n" @@ -1292,20 +1292,20 @@ def build_deep_shared_missing_mock_project_files(*, layers: int) -> dict[str, st "[defaults]\n" 'materialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" " - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n table: raw_customers\n" ), - "models/orders_00_left.sql": ( + "sql/models/orders_00_left.sql": ( "MODEL (description 'Test model orders_00_left.', materialized table);\n\n" "SELECT o.order_id, o.amount\n" 'FROM __source("raw_orders") AS o\n' 'JOIN __source("raw_customers") AS c ON c.customer_id = o.customer_id\n' ), - "models/orders_00_right.sql": ( + "sql/models/orders_00_right.sql": ( 'MODEL (description "Test model orders_00_right.", ' 'materialized table);\n\nSELECT order_id, amount FROM __ref("orders_00_left")\n' ), @@ -1314,7 +1314,7 @@ def build_deep_shared_missing_mock_project_files(*, layers: int) -> dict[str, st previous_left: str = f"orders_{layer - 1:02d}_left" previous_right: str = f"orders_{layer - 1:02d}_right" for side in ("left", "right"): - files[f"models/orders_{layer:02d}_{side}.sql"] = ( + files[f"sql/models/orders_{layer:02d}_{side}.sql"] = ( "MODEL (description 'Test model.', materialized table);\n\n" "SELECT a.order_id, a.amount + b.amount AS amount\n" f'FROM __ref("{previous_left}") AS a\n' @@ -1347,11 +1347,11 @@ def build_expected_column_subset_project_files( "[defaults]\n" 'materialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\n" "SELECT id AS order_id, customer_id, status, amount * 2 AS amount\n" 'FROM __source("raw_orders")\n' @@ -1437,15 +1437,15 @@ def build_helper_scope_project_files() -> dict[str, str]: "[defaults]\n" 'materialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\n" 'SELECT id AS order_id, amount FROM __source("raw_orders")\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\n" 'SELECT order_id, amount * 2 AS amount FROM __ref("stg_orders")\n' ), @@ -1541,14 +1541,14 @@ def build_cursor_window_project_files(*, tests: dict[str, str]) -> dict[str, str "[connection]\n" 'database = "cursor_window_demo.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" " - name: raw_events\n description: Test source raw_events.\n" " schema: main\n table: raw_events\n" ), - "models/daily_orders.sql": ( + "sql/models/daily_orders.sql": ( "MODEL (description 'Test model daily_orders.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -1562,7 +1562,7 @@ def build_cursor_window_project_files(*, tests: dict[str, str]) -> dict[str, str 'FROM __source("raw_orders")\n' "WHERE order_date >= __cursor_start() AND order_date < __cursor_end()\n" ), - "models/order_lookback.sql": ( + "sql/models/order_lookback.sql": ( "MODEL (description 'Test model order_lookback.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -1578,7 +1578,7 @@ def build_cursor_window_project_files(*, tests: dict[str, str]) -> dict[str, str 'FROM __source("raw_orders")\n' "WHERE order_date >= CAST(__cursor_start() AS DATE) - INTERVAL 7 DAY\n" ), - "models/event_totals.sql": ( + "sql/models/event_totals.sql": ( "MODEL (description 'Test model event_totals.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -1591,11 +1591,11 @@ def build_cursor_window_project_files(*, tests: dict[str, str]) -> dict[str, str "WHERE event_id >= __cursor_start() AND event_id < __cursor_end()\n" " AND event_id - 1 < __cursor_end() + 1\n" ), - "models/plain_orders.sql": ( + "sql/models/plain_orders.sql": ( 'MODEL (description "Test model plain_orders.", ' 'materialized table);\n\nSELECT amount FROM __source("raw_orders")\n' ), - "models/hourly_orders.sql": ( + "sql/models/hourly_orders.sql": ( "MODEL (description 'Test model hourly_orders.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -1639,7 +1639,7 @@ def build_cte_scope_project_files(*, queries: tuple[str, ...], expected: str) -> "sqlbuild_project.toml": ( 'name = "cte_scope"\nadapter = "duckdb"\n[connection]\ndatabase = "orders.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), @@ -1650,7 +1650,7 @@ def build_cte_scope_project_files(*, queries: tuple[str, ...], expected: str) -> ), } for index, query in enumerate(queries): - files[f"models/orders_{index}.sql"] = f"MODEL (description 'Test model.');\n{query}" + files[f"sql/models/orders_{index}.sql"] = f"MODEL (description 'Test model.');\n{query}" return files @@ -1681,14 +1681,14 @@ def build_shared_cte_name_chain_project_files( 'database = "model_inlining.duckdb"\n\n[settings]\n' f"sql_analysis = {sql_analysis_value}\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/order_lines.sql": ( + "sql/models/order_lines.sql": ( f"MODEL (description 'Order lines.');\n\n{ORDER_LINES_MODEL_SQL}\n" ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( f"MODEL (description 'Order totals.');\n\n{ORDER_TOTALS_MODEL_SQL}\n" ), "tests/unit/order_chain.sql": ( @@ -1745,17 +1745,17 @@ def build_lookup_project_files(*, sql_analysis_enabled: bool) -> dict[str, str]: 'database = "lookup.duckdb"\n\n[settings]\n' f"sql_analysis = {sql_analysis_value}\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/matched_orders.sql": ( + "sql/models/matched_orders.sql": ( "MODEL (description 'Orders found in the lookup table.');\n\n" "WITH lookup_rows AS (SELECT order_id FROM main.lookup_rows)\n" 'SELECT o.order_id FROM __source("raw_orders") AS o\n' "INNER JOIN lookup_rows AS l ON l.order_id = o.order_id\n" ), - "models/listed_orders.sql": ( + "sql/models/listed_orders.sql": ( "MODEL (description 'Orders listed in the physical lookup table.');\n\n" 'SELECT o.order_id FROM __source("raw_orders") AS o\n' "INNER JOIN lookup_rows AS l ON l.order_id = o.order_id\n" @@ -1972,21 +1972,21 @@ def build_helper_reference_project_files( 'paths = ["tests/unit/**"]\n' 'reason = "These SQL tests leave helpers unread to cover reference detection."\n' ), - "sources/item_returns.yml": ( + "sql/sources/item_returns.yml": ( "sources:\n" " - name: item_returns\n" " description: Returned items\n" " expression: SELECT 1 AS item_id\n" ), - "models/item_extras.sql": ( + "sql/models/item_extras.sql": ( "MODEL (description 'Extra item amounts', materialized table);\n\n" 'SELECT item_id, amount FROM __ref("items")\n' ), - "models/items.sql": ( + "sql/models/items.sql": ( "MODEL (description 'Base items', materialized table);\n\n" "SELECT 1 AS item_id, 10 AS amount\n" ), - "models/item_totals.sql": ( + "sql/models/item_totals.sql": ( "MODEL (description 'Doubled item amounts', materialized table);\n\n" 'SELECT item_id, amount * 2 AS amount_doubled FROM __ref("items")\n' ), @@ -2026,14 +2026,14 @@ def build_order_chain_files(*, chain_length: int) -> dict[str, str]: files: dict[str, str] = { "sqlbuild_project.toml": COST_GUARD_PROJECT_TOML, - "sources/raw_orders.yml": COST_GUARD_RAW_ORDERS_SOURCE, - "models/order_step_1.sql": ( + "sql/sources/raw_orders.yml": COST_GUARD_RAW_ORDERS_SOURCE, + "sql/models/order_step_1.sql": ( "MODEL (description 'Order step 1.', materialized table);\n\n" 'SELECT order_id, amount FROM __source("raw_orders")\n' ), } for step in range(2, chain_length + 1): - files[f"models/order_step_{step}.sql"] = ( + files[f"sql/models/order_step_{step}.sql"] = ( f"MODEL (description 'Order step {step}.', materialized table);\n\n" f'SELECT order_id, amount + 1 AS amount FROM __ref("order_step_{step - 1}")\n' ) @@ -2061,16 +2061,16 @@ def slow_model_files(*, max_duration: str) -> dict[str, str]: return { "sqlbuild_project.toml": COST_GUARD_PROJECT_TOML, - "models/order_scans.sql": ( + "sql/models/order_scans.sql": ( "MODEL (description 'Order scans.', materialized table, " f'max_duration "{max_duration}");\n\n' f"SELECT 1 AS order_id, {SLOW_SCALAR_SQL} AS scanned\n" ), - "models/order_scan_summary.sql": ( + "sql/models/order_scan_summary.sql": ( "MODEL (description 'Order scan summary.', materialized table);\n\n" 'SELECT COUNT(*) AS orders FROM __ref("order_scans")\n' ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Customers.', materialized table);\n\nSELECT 100 AS customer_id\n" ), } @@ -2097,13 +2097,13 @@ def slow_promotion_files( "sqlbuild_project.toml": COST_GUARD_PROJECT_TOML.replace( 'adapter = "duckdb"', 'adapter = "duckdb_slow_swap"' ).replace('database = "warehouse.duckdb"', f'database = "{database}"'), - "adapters/duckdb_slow_swap.py": SLOW_SWAP_ADAPTER, - "models/order_totals.sql": ( + "python/adapters/duckdb_slow_swap.py": SLOW_SWAP_ADAPTER, + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals.', materialized table, " f'max_duration "{max_duration}");\n\n' f"SELECT 1 AS order_id, {order_total} AS total\n" ), - "models/z_customers.sql": ( + "sql/models/z_customers.sql": ( "MODEL (description 'Customers.', materialized table);\n\n" f"SELECT {customer_id} AS customer_id\n" ), @@ -2114,7 +2114,7 @@ def order_totals_test_files(total_sql: str) -> dict[str, str]: """Return an order_totals model computing ``total_sql`` and a test expecting both models.""" return { - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Test model order_totals.');\n\n" f'SELECT order_id, {total_sql} AS total FROM __ref("orders")\n' ), @@ -2137,15 +2137,15 @@ def build_shared_partial_fixture_project_files( 'name = "shared_partial_fixture"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "shared_partial_fixture.duckdb"\n' ), - "models/order_lines.sql": ( + "sql/models/order_lines.sql": ( 'MODEL (description "Test model order_lines.");\n\n' "SELECT 1 AS order_id, CAST(1.5 AS DOUBLE) AS amount, CAST(2.5 AS DOUBLE) AS discount\n" ), - "models/enriched_lines.sql": ( + "sql/models/enriched_lines.sql": ( 'MODEL (description "Test model enriched_lines.");\n\n' f'SELECT order_id, amount, {enriched_column} FROM __ref("order_lines")\n' ), - "models/line_report.sql": ( + "sql/models/line_report.sql": ( 'MODEL (description "Test model line_report.");\n\n' f"SELECT e.order_id, e.amount, l.{report_column} AS line_discount\n" 'FROM __ref("enriched_lines") AS e\n' @@ -2174,11 +2174,11 @@ def build_since_project_files() -> dict[str, str]: '[defaults]\nmaterialized = "table"\n' ), ".gitignore": "target/\n*.duckdb\n*.duckdb.wal\n", - "models/_macros/python/money.py": ( + "sql/models/_macros/python/money.py": ( "def cents_to_dollars(expression: str) -> str:\n" ' return f"CAST({expression} AS DOUBLE) / 100"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Raw orders.\n" " schema: main\n table: raw_orders\n" @@ -2187,16 +2187,16 @@ def build_since_project_files() -> dict[str, str]: " - name: status\n type: VARCHAR\n" " - name: amount_cents\n type: INTEGER\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Cleaned orders.');\n\n" 'SELECT order_id, status, amount_cents FROM __source("raw_orders")\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals in dollars.');\n\n" 'SELECT order_id, @py.cents_to_dollars("amount_cents") AS amount\n' 'FROM __ref("stg_orders")\n' ), - "models/open_orders.sql": ( + "sql/models/open_orders.sql": ( "MODEL (description 'Open orders.');\n\n" "SELECT order_id FROM __ref(\"stg_orders\") WHERE status = 'open'\n" ), @@ -2236,17 +2236,17 @@ def build_since_sql_macro_files() -> dict[str, str]: """Build a model whose scoped SQL macro calls another scoped SQL macro, and its test.""" return { - "models/_macros/sql/round_cents.sql": ( + "sql/models/_macros/sql/round_cents.sql": ( "MACRO (\n description 'Cents rounded to whole dollars.',\n" " arguments (cents INTEGER),\n returns DOUBLE,\n);\n\n" "ROUND(CAST(@cents AS DOUBLE) / 100, 0)\n" ), - "models/_macros/sql/net_dollars.sql": ( + "sql/models/_macros/sql/net_dollars.sql": ( "MACRO (\n description 'Net dollars after a fixed fee.',\n" " arguments (cents INTEGER),\n returns DOUBLE,\n);\n\n" "@sql.round_cents(@cents) - 1\n" ), - "models/order_net.sql": ( + "sql/models/order_net.sql": ( "MODEL (description 'Net order amounts.');\n\n" "SELECT order_id, @sql.net_dollars(amount_cents) AS net\n" 'FROM __ref("stg_orders")\n' @@ -2268,35 +2268,35 @@ def build_since_indirect_files() -> dict[str, str]: base["sqlbuild_project.toml"] + '\n[vars]\nmin_amount = "100"\n\n[scopes]\nenforce_placement = false\n' ), - "python/_rates.py": 'DIVISOR = "100"\n', - "models/_macros/python/currency.py": ( + "python/nodes/_rates.py": 'DIVISOR = "100"\n', + "sql/models/_macros/python/currency.py": ( 'def whole_cents(expression: str) -> str:\n return f"({expression} * 1)"\n' ), - "models/_macros/python/money.py": ( - "from models._macros.python.currency import whole_cents\n" - "from python._rates import DIVISOR\n\n\n" + "sql/models/_macros/python/money.py": ( + "from sql.models._macros.python.currency import whole_cents\n" + "from python.nodes._rates import DIVISOR\n\n\n" "def cents_to_dollars(expression: str) -> str:\n" ' return f"CAST({whole_cents(expression)} AS DOUBLE) / {DIVISOR}"\n' ), - "macros/python/taxes.py": ( + "sql/macros/python/taxes.py": ( 'def with_tax(expression: str) -> str:\n return f"({expression} + 0)"\n' ), - "macros/python/pricing.py": ( - "from macros.python.taxes import with_tax\n\n\n" + "sql/macros/python/pricing.py": ( + "from sql.macros.python.taxes import with_tax\n\n\n" "def gross(expression: str) -> str:\n return with_tax(expression)\n" ), - "macros/python/fixture_values.py": "def suffix() -> str:\n return \"''\"\n", - "models/stg_orders.sql": ( + "sql/macros/python/fixture_values.py": "def suffix() -> str:\n return \"''\"\n", + "sql/models/stg_orders.sql": ( "MODEL (\n description 'Cleaned orders.',\n" " columns (order_id (type INTEGER), status (type VARCHAR), " "amount_cents (type INTEGER)),\n);\n\n" 'SELECT order_id, status, amount_cents FROM __source("raw_orders")\n' ), - "models/order_gross.sql": ( + "sql/models/order_gross.sql": ( "MODEL (description 'Gross order amounts.');\n\n" 'SELECT order_id, @py.gross("amount_cents") AS gross_cents FROM __ref("stg_orders")\n' ), - "models/order_day.sql": ( + "sql/models/order_day.sql": ( "MODEL (description 'The UTC day of a fixed timestamp.');\n\n" "SELECT order_id, CAST(TIMESTAMPTZ '2024-01-01 23:30:00+00' AS DATE) AS day\n" 'FROM __ref("stg_orders")\n' @@ -2320,48 +2320,48 @@ def build_since_indirect_files() -> dict[str, str]: "__expected__stg_orders AS (\n" ' SELECT 1 AS order_id, @param("status") || @py.suffix() AS status\n)\nSELECT 1\n' ), - "audits/generic/at_least.sql": ( + "sql/audits/generic/at_least.sql": ( 'AUDIT ();\n\nSELECT *\nFROM __ref("@model")\nWHERE @column < @minimum\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (\n description 'Order totals in dollars.',\n" " audits [at_least (column amount, minimum 0)],\n);\n\n" 'SELECT order_id, @py.cents_to_dollars("amount_cents") AS amount\n' 'FROM __ref("stg_orders")\n' ), - "models/big_orders.sql": ( + "sql/models/big_orders.sql": ( "MODEL (description 'Large orders.');\n\n" 'SELECT order_id FROM __ref("stg_orders") WHERE amount_cents >= @@min_amount\n' ), - "models/marts/order_counts.sql": ( + "sql/models/marts/order_counts.sql": ( "MODEL (description 'Order counts.');\n\n" 'SELECT COUNT(*) AS order_count FROM __ref("stg_orders")\n' ), - "seeds/regions.csv": "region_id,region_name\n1,north\n", - "seeds/regions.yml": ( + "sql/seeds/regions.csv": "region_id,region_name\n1,north\n", + "sql/seeds/regions.yml": ( "seeds:\n - name: regions\n description: Sales regions.\n columns:\n" " - name: region_id\n type: INTEGER\n" " - name: region_name\n type: VARCHAR\n" ), - "functions/sql/is_open.sql": ( + "sql/functions/sql/is_open.sql": ( "FUNCTION (\n description 'Whether an order is open.',\n" " arguments (order_status VARCHAR),\n returns BOOLEAN,\n);\n\n" "order_status = 'open'\n" ), - "models/regional_orders.sql": ( + "sql/models/regional_orders.sql": ( "MODEL (description 'Orders with their region.');\n\n" "SELECT o.order_id, r.region_id\n" 'FROM __ref("stg_orders") o CROSS JOIN __seed("regions") r\n' ), - "models/order_flags.sql": ( + "sql/models/order_flags.sql": ( "MODEL (description 'Whether each order is open.');\n\n" 'SELECT order_id, __udf("is_open")(status) AS is_open FROM __ref("stg_orders")\n' ), - "models/order_archive.sql": ( + "sql/models/order_archive.sql": ( "MODEL (description 'Archived orders.');\n\n" 'SELECT order_id FROM __ref("stg_orders")\n' ), - "models/archive_counts.sql": ( + "sql/models/archive_counts.sql": ( "MODEL (description 'Archived order count.');\n\n" 'SELECT COUNT(*) AS archived FROM __ref("order_archive")\n' ), @@ -2372,7 +2372,7 @@ def build_since_indirect_files() -> dict[str, str]: "),\n" "__expected__archive_counts AS (SELECT 1 AS archived)\nSELECT 1\n" ), - "python/tasks/report.py": ( + "python/nodes/tasks/report/asset.py": ( "from sqlbuild.assets import asset\n\n\n" "@asset()\ndef report_orders(ctx):\n" ' """Report orders."""\n\n' @@ -2511,12 +2511,12 @@ def partitioned_call_fixture_files(*, query: str, expected_rows: str) -> dict[st 'name = "payments_fixtures"\nadapter = "duckdb"\n' '[connection]\ndatabase = "payments.duckdb"\n' ), - "functions/python/smooth_payments.py": _PARTITIONED_FUNCTION, - "models/payments.sql": ( + "sql/functions/python/smooth_payments.py": _PARTITIONED_FUNCTION, + "sql/models/payments.sql": ( "MODEL (description 'Payments.', materialized table);\n" "SELECT 1 AS customer_id, 10.0::DOUBLE AS amount\n" ), - "models/smoothed_payments.sql": ( + "sql/models/smoothed_payments.sql": ( f"MODEL (description 'Smoothed payments.', materialized table);\n{query}\n" ), "tests/unit/test_smoothed_payments.sql": ( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_commented_fixtures.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_commented_fixtures.py index c04f9332ce..891be0c860 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_commented_fixtures.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_commented_fixtures.py @@ -22,10 +22,10 @@ '[connection]\ndatabase = "commented_fixtures.duckdb"\n\n' '[defaults]\nmaterialized = "table"\n' ), - "macros/python/status.py": ( + "sql/macros/python/status.py": ( 'def normalize_status(value: str) -> str:\n return f"LOWER(TRIM({value}))"\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -34,11 +34,11 @@ " - name: order_id\n type: INTEGER\n" " - name: status\n type: VARCHAR\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\n" 'SELECT order_id, @py.normalize_status("status") AS status FROM __source("raw_orders")\n' ), - "models/order_counts.sql": ( + "sql/models/order_counts.sql": ( "MODEL (description 'Test model order_counts.');\n\n" 'SELECT status, COUNT(*) AS order_count FROM __ref("orders") GROUP BY status\n' ), @@ -89,8 +89,8 @@ CommentedFixtureE2ETestCase( description="bounded CTE casts joins and unions execute with mocked sources", test_files={ - "macros/python/status.py": "", - "models/orders.sql": ( + "sql/macros/python/status.py": "", + "sql/models/orders.sql": ( "MODEL (description 'Orders through projected CTEs.');\n" 'WITH imported AS (SELECT * FROM __source("raw_orders")),\n' "projected AS (SELECT CAST(COALESCE(b.order_id, 0) + 0 AS INTEGER) AS order_id,\n" @@ -114,9 +114,11 @@ CommentedFixtureE2ETestCase( description="nested model CTEs and marker lookalikes preserve mocked source results", test_files={ - "macros/python/status.py": "", - "models/_macros/python/status.py": _PROJECT_FILES["macros/python/status.py"], - "models/orders.sql": ( + "sql/macros/python/status.py": "", + "sql/models/_macros/python/status.py": _PROJECT_FILES[ + "sql/macros/python/status.py" + ], + "sql/models/orders.sql": ( "MODEL (description 'Orders through nested CTEs.');\n" 'WITH "recent" AS (\n' " WITH nested AS (SELECT order_id, status, '__ref(\"ignored\")''s' AS note\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_cost_guards.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_cost_guards.py index 1c840f8858..b38cc41097 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_cost_guards.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_cost_guards.py @@ -36,23 +36,23 @@ _ORDER_FILES: dict[str, str] = { "sqlbuild_project.toml": COST_GUARD_PROJECT_TOML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n\n" "SELECT * FROM (VALUES (1, 100, 5)) AS t(order_id, customer_id, amount)\n" ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals.', materialized table);\n\n" 'SELECT order_id, customer_id, amount * 2 AS total FROM __ref("stg_orders")\n' ), } _SLOW_FILES: dict[str, str] = { "sqlbuild_project.toml": COST_GUARD_PROJECT_TOML, - "sources/raw_orders.yml": COST_GUARD_RAW_ORDERS_SOURCE, - "models/stg_orders.sql": ( + "sql/sources/raw_orders.yml": COST_GUARD_RAW_ORDERS_SOURCE, + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n\n" f'SELECT order_id, {SLOW_SCALAR_SQL} AS scanned FROM __source("raw_orders")\n' ), - "models/order_scans.sql": ( + "sql/models/order_scans.sql": ( "MODEL (description 'Order scans.', materialized table);\n\n" 'SELECT order_id, scanned FROM __ref("stg_orders")\n' ), @@ -458,7 +458,7 @@ def test_given_model_limit_expiring_in_promotion_when_building_then_published_ta database=database, max_duration=test_case.max_duration, order_total=20, customer_id=200 ) relative_path: str - for relative_path in ("models/order_totals.sql", "models/z_customers.sql"): + for relative_path in ("sql/models/order_totals.sql", "sql/models/z_customers.sql"): (project_dir / relative_path).write_text(changed_files[relative_path]) result: subprocess.CompletedProcess[str] = run_sqb( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_dialect_string_escapes.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_dialect_string_escapes.py index db31ac7f17..0ba8d94d1c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_dialect_string_escapes.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_dialect_string_escapes.py @@ -15,8 +15,8 @@ 'name = "escape_strings"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "escape_strings.duckdb"\n' ), - "models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT 1 AS order_id\n", - "models/order_names.sql": ( + "sql/models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT 1 AS order_id\n", + "sql/models/order_names.sql": ( "MODEL (description 'Test model order_names.', materialized table);\n\n" "SELECT E'O\\'Brien' AS customer_name, 'C:\\' AS folder, order_id\n" 'FROM __ref("stg_orders")\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_direct_logic_extraction.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_direct_logic_extraction.py index 68a66646e7..044289a65e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_direct_logic_extraction.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_direct_logic_extraction.py @@ -25,7 +25,7 @@ "sqlbuild_project.toml": ( 'name = "direct_logic"\nadapter = "duckdb"\n\n[connection]\ndatabase = "direct_logic.duckdb"\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n\n" "SELECT 1 AS order_id, 'Placed ' AS status\n" ), @@ -34,11 +34,11 @@ ' """Trim and lower-case a label."""\n' ' return f"LOWER(TRIM({expression}))"\n' ), - "functions/sql/order_label.sql": ( + "sql/functions/sql/order_label.sql": ( 'FUNCTION (\n description "Label an order status.",\n' " arguments (raw_status VARCHAR),\n returns VARCHAR,\n);\n\nUPPER(raw_status)\n" ), - "functions/sql/order_rows.sql": ( + "sql/functions/sql/order_rows.sql": ( 'FUNCTION (\n description "Orders above an id.",\n' " arguments (min_id INTEGER),\n returns table (\n order_id INTEGER\n ),\n);\n\n" "SELECT order_id FROM (VALUES (1), (2)) AS t(order_id) WHERE order_id > min_id\n" @@ -61,7 +61,7 @@ " SELECT 'PLACED' AS label /* /* __udf(\"order_label\")('x') */ */\n" ")\n" ), - "models/order_summary.sql": ( + "sql/models/order_summary.sql": ( "MODEL (description 'Order summary.', materialized table);\n\n" 'SELECT order_id, TRIM(status) AS status, order_id * 100 AS amount_cents FROM __ref("stg_orders")\n' ), @@ -143,7 +143,7 @@ 'FROM __ref("stg_orders")\n' ) _ALIASED_OPERATORS: dict[str, str] = { - "models/order_summary.sql": _OPERATOR_MODEL, + "sql/models/order_summary.sql": _OPERATOR_MODEL, _MODEL_TEST: ( "TEST ();\n\nWITH\n" "__ref__stg_orders AS (SELECT 1 AS order_id, 'placed' AS status),\n" @@ -163,7 +163,7 @@ ), } _UNALIASED_DISTINCT_FROM: dict[str, str] = { - "models/order_summary.sql": _OPERATOR_MODEL, + "sql/models/order_summary.sql": _OPERATOR_MODEL, _MODEL_TEST: ( "TEST ();\n\nWITH\n" "__ref__stg_orders AS (SELECT 1 AS order_id, 'placed' AS status),\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_fixture_declared_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_fixture_declared_types.py index c83952d766..3bcdf37a6e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_fixture_declared_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_fixture_declared_types.py @@ -17,13 +17,13 @@ 'name = "fixture_types"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "fixture_types.duckdb"\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n columns:\n" " - name: order_id\n type: INTEGER\n" " - name: ordered_on\n type: DATE\n" ), - "models/order_years.sql": ( + "sql/models/order_years.sql": ( "MODEL (description 'Test model order_years.');\n" 'SELECT o.order_id, YEAR(o.ordered_on) AS order_year FROM __source("raw_orders") AS o\n' ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_macro_mock_alias.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_macro_mock_alias.py index 9b7cb84400..538522aa8f 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_macro_mock_alias.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_macro_mock_alias.py @@ -69,9 +69,9 @@ def test_given_macro_mock_with_alias_when_testing_then_the_mock_value_is_used( project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "macros/sql/region_filter.sql": _REGION_MACRO, - "models/orders.sql": _ORDERS_MODEL, - "models/regional_orders.sql": _REGIONAL_ORDERS_MODEL, + "sql/macros/sql/region_filter.sql": _REGION_MACRO, + "sql/models/orders.sql": _ORDERS_MODEL, + "sql/models/regional_orders.sql": _REGIONAL_ORDERS_MODEL, "tests/unit/test_regional_orders.sql": _TEST.format(mock_select=test_case.mock_select), }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_output_evaluation_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_output_evaluation_errors.py index c360e4b7e7..189dc32ed0 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_output_evaluation_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_output_evaluation_errors.py @@ -63,7 +63,7 @@ '[connection]\ndatabase = "orders.duckdb"\n\n' '[defaults]\nmaterialized = "table"\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -72,7 +72,7 @@ " - name: order_id\n type: INTEGER\n" " - name: code\n type: VARCHAR\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\n" 'SELECT order_id, TRY_CAST(code AS INTEGER) AS code_number FROM __source("raw_orders")\n' ), @@ -140,7 +140,7 @@ def test_given_output_store_failure_when_testing_then_only_storage_problems_fall project_name="orders", repo_files={ **_PROJECT_FILES, - "adapters/pruning_duckdb.py": test_case.adapter_source, + "python/adapters/pruning_duckdb.py": test_case.adapter_source, **test_case.extra_files, }, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_parenthesised_join_mocks.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_parenthesised_join_mocks.py index 2eb13148af..b2abf6d298 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_parenthesised_join_mocks.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_parenthesised_join_mocks.py @@ -53,9 +53,9 @@ def test_given_parenthesised_join_when_testing_then_both_references_use_their_mo project_name="shop", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": 'MODEL (description "Orders.");\n\nSELECT 1 AS order_id\n', - "models/customers.sql": 'MODEL (description "Customers.");\n\nSELECT 1 AS order_id\n', - "models/order_customers.sql": ( + "sql/models/orders.sql": 'MODEL (description "Orders.");\n\nSELECT 1 AS order_id\n', + "sql/models/customers.sql": 'MODEL (description "Customers.");\n\nSELECT 1 AS order_id\n', + "sql/models/order_customers.sql": ( 'MODEL (description "Orders with customers.");\n\n' f"SELECT o.order_id FROM {test_case.model_from}\n" ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_python_tests.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_python_tests.py index 5885768399..9b6982e303 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_python_tests.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_python_tests.py @@ -23,10 +23,10 @@ 'name = "python_tests_project"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "python_tests_project.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\nSELECT status FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), @@ -37,15 +37,15 @@ "__expected__orders AS (SELECT 'open' AS status)\n" "SELECT 1\n" ), - "python/orders/storefront_import/node.py": ( + "python/nodes/orders/storefront_import/asset.py": ( "from sqlbuild.assets import asset\n\n\n" "@asset(description='Import storefront orders.', tags=['ingest'])\n" "def storefront_import(ctx):\n return None\n" ), - "python/orders/storefront_import/_helpers/row_mapping.py": ( + "python/nodes/orders/storefront_import/_helpers/row_mapping.py": ( "def map_row(raw):\n return {'status': str(raw['state']).lower()}\n" ), - "python/inventory/stock_sync/node.py": ( + "python/nodes/inventory/stock_sync/asset.py": ( "from sqlbuild.assets import asset\n\n\n" "@asset(description='Sync stock.')\n" "def stock_sync(ctx):\n return None\n" @@ -53,8 +53,8 @@ } PASSING_PYTHON_TEST: dict[str, str] = { - "tests/python/orders/storefront_import/_helpers/test_row_mapping.py": ( - "from python.orders.storefront_import._helpers.row_mapping import map_row\n\n\n" + "tests/python/nodes/orders/storefront_import/_helpers/test_row_mapping.py": ( + "from python.nodes.orders.storefront_import._helpers.row_mapping import map_row\n\n\n" "def test_given_paid_order_when_mapping_then_status_is_paid():\n" " assert map_row({'state': 'PAID'}) == {'status': 'paid'}\n" ), @@ -72,19 +72,19 @@ } FAILING_PYTHON_TEST: dict[str, str] = { - "tests/python/inventory/stock_sync/test_node.py": ( + "tests/python/nodes/inventory/stock_sync/test_node.py": ( "def test_given_stock_when_syncing_then_fails():\n assert False\n" ), } BROKEN_MODEL: dict[str, str] = { - "models/broken.sql": ( + "sql/models/broken.sql": ( 'MODEL (description "Test model broken.");\n\nSELECT missing_column FROM __ref("orders")\n' ), } -PASSING_FILE: str = "tests/python/orders/storefront_import/_helpers/test_row_mapping.py" -FAILING_FILE: str = "tests/python/inventory/stock_sync/test_node.py" +PASSING_FILE: str = "tests/python/nodes/orders/storefront_import/_helpers/test_row_mapping.py" +FAILING_FILE: str = "tests/python/nodes/inventory/stock_sync/test_node.py" SQL_PASSED: str = "PASS=1 FAIL=0" PYTHON_PASSED: str = "Python tests passed 1 file" @@ -199,7 +199,7 @@ def __getattr__(self, name): ), PythonTestsE2ETestCase( description="--select of a Python node's path runs its mirrored tests", - command=("--no-color", "test", "--select", "python/orders/storefront_import"), + command=("--no-color", "test", "--select", "python/nodes/orders/storefront_import"), extra_repo_files={**PASSING_PYTHON_TEST, **FAILING_PYTHON_TEST}, expected_exit_code=0, expected_output_fragments=(PYTHON_PASSED, "1 passed"), @@ -313,7 +313,7 @@ def test_given_pytest_missing_when_running_sqb_test_then_only_python_tests_need_ tmp_path: Path, ) -> None: hidden: Path = tmp_path / "hidden_pytest" - hidden.mkdir() + hidden.mkdir(parents=True) (hidden / "sitecustomize.py").write_text(HIDDEN_PYTEST_SITECUSTOMIZE, encoding="utf-8") project_dir: Path = prepare_inline_project( tmp_path=tmp_path, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_python_udf_connections.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_python_udf_connections.py index a22a256835..2e01d0f036 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_python_udf_connections.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_python_udf_connections.py @@ -57,12 +57,12 @@ def test_given_python_udf_when_testing_on_several_connections_then_every_test_ca f'[connection]\ndatabase = "{test_case.database}"\n\n' "[scopes]\nenforce_placement = false\n" ), - "functions/python/is_completed_order.py": _UDF, - "models/order_statuses.sql": ( + "sql/functions/python/is_completed_order.py": _UDF, + "sql/models/order_statuses.sql": ( "MODEL (description 'Test model order_statuses.');\n" "SELECT 'completed' AS order_status\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n" 'SELECT s.order_status, __udf("is_completed_order")(s.order_status) AS is_completed\n' 'FROM __ref("order_statuses") AS s\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_select_by_name.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_select_by_name.py index b92cf85936..43590a8347 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_select_by_name.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_select_by_name.py @@ -150,7 +150,7 @@ def test_given_test_names_when_selecting_then_exactly_those_tests_run( command=("test",), expected_exit_code=1, expected_output_fragments=( - "Project resource name 'orders' is declared as both model in models/orders.sql " + "Project resource name 'orders' is declared as both model in sql/models/orders.sql " "and unit test in tests/unit/orders.sql", "and calendar names must be globally unique", ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_set_operation_expected.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_set_operation_expected.py index 2565b90650..1fe84d7e0f 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_set_operation_expected.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_set_operation_expected.py @@ -22,10 +22,10 @@ '[connection]\ndatabase = "set_operation_expected.duckdb"\n\n' '[defaults]\nmaterialized = "table"\n' ), - "macros/python/status.py": ( + "sql/macros/python/status.py": ( 'def normalize_status(value: str) -> str:\n return f"LOWER(TRIM({value}))"\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -34,7 +34,7 @@ " - name: order_id\n type: INTEGER\n" " - name: status\n type: VARCHAR\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\n" 'SELECT order_id, @py.normalize_status("status") AS status FROM __source("raw_orders")\n' ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_since.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_since.py index 6166906e38..f843eda178 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_since.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_since.py @@ -26,8 +26,8 @@ from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import run_sqb _FILES: dict[str, str] = build_since_project_files() -_STAGING: str = "models/stg_orders.sql" -_MACRO: str = "models/_macros/python/money.py" +_STAGING: str = "sql/models/stg_orders.sql" +_MACRO: str = "sql/models/_macros/python/money.py" _EDITED_STAGING: str = _FILES[_STAGING].replace( "SELECT order_id, status", "SELECT order_id, LOWER(status) AS status" ) @@ -37,7 +37,7 @@ "-- one row per order\nselect\n order_id,\n status,\n amount_cents\n" 'from __source("raw_orders")\n' ) -_ARCHIVE: str = "models/order_archive.sql" +_ARCHIVE: str = "sql/models/order_archive.sql" _ARCHIVE_SQL: str = ( "MODEL (description 'Archived orders.');\n\nSELECT order_id FROM __ref(\"stg_orders\")\n" ) @@ -49,10 +49,10 @@ _EXPLAINED_TESTS: tuple[str, ...] = (*_TEST_COMMAND, "--explain") _EXPLAINED_SCENARIOS: tuple[str, ...] = (*_SCENARIO_COMMAND, "--explain") _SQL_MACROS: dict[str, str] = build_since_sql_macro_files() -_INNER_SQL_MACRO: str = "models/_macros/sql/round_cents.sql" -_OUTER_SQL_MACRO: str = "models/_macros/sql/net_dollars.sql" -_SLOT_MACRO: str = "models/_macros/sql/status_totals.sql" -_SLOT_MODEL: str = "models/order_status_totals.sql" +_INNER_SQL_MACRO: str = "sql/models/_macros/sql/round_cents.sql" +_OUTER_SQL_MACRO: str = "sql/models/_macros/sql/net_dollars.sql" +_SLOT_MACRO: str = "sql/models/_macros/sql/status_totals.sql" +_SLOT_MODEL: str = "sql/models/order_status_totals.sql" _SLOT_FILES: dict[str, str] = { _SLOT_MACRO: ( "MACRO (\n description 'Order totals per grain.',\n" @@ -166,7 +166,7 @@ SinceSelectionE2ETestCase( description="a pure rename through migrate_from selects nothing", edits={ - "models/order_history.sql": _ARCHIVE_SQL.replace( + "sql/models/order_history.sql": _ARCHIVE_SQL.replace( "MODEL (", "MODEL (migrate_from order_archive, " ), }, @@ -263,7 +263,7 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( ), SinceSelectionE2ETestCase( description="a helper module a macro imports changes the macro", - edits={"python/_rates.py": 'DIVISOR = "100.0"\n'}, + edits={"python/nodes/_rates.py": 'DIVISOR = "100.0"\n'}, command=_EXPLAINED_TESTS, expected_exit_code=0, expected_fragments=( @@ -277,7 +277,7 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="a function body change selects the test that calls it", edits={ - "functions/sql/is_open.sql": _INDIRECT["functions/sql/is_open.sql"].replace( + "sql/functions/sql/is_open.sql": _INDIRECT["sql/functions/sql/is_open.sql"].replace( "order_status = 'open'", "LOWER(order_status) = 'open'" ) }, @@ -292,9 +292,9 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="an audit definition change selects tests of models it is attached to", edits={ - "audits/generic/at_least.sql": _INDIRECT["audits/generic/at_least.sql"].replace( - "@column < @minimum", "@column <= @minimum" - ) + "sql/audits/generic/at_least.sql": _INDIRECT[ + "sql/audits/generic/at_least.sql" + ].replace("@column < @minimum", "@column <= @minimum") }, command=_EXPLAINED_TESTS, expected_exit_code=0, @@ -322,14 +322,14 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="a rename through migrate_from that also changes the SQL is a change", edits={ - "models/order_history.sql": _INDIRECT["models/order_archive.sql"] + "sql/models/order_history.sql": _INDIRECT["sql/models/order_archive.sql"] .replace("MODEL (", "MODEL (migrate_from order_archive, ") .replace('__ref("stg_orders")', '__ref("stg_orders") WHERE order_id > 0'), - "models/archive_counts.sql": _INDIRECT["models/archive_counts.sql"].replace( + "sql/models/archive_counts.sql": _INDIRECT["sql/models/archive_counts.sql"].replace( "order_archive", "order_history" ), }, - deletions=("models/order_archive.sql",), + deletions=("sql/models/order_archive.sql",), command=_EXPLAINED_TESTS, expected_exit_code=0, expected_fragments=( @@ -342,7 +342,7 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( ), SinceSelectionE2ETestCase( description="seed data a test mocks selects nothing", - edits={"seeds/regions.csv": "region_id,region_name\n1,south\n"}, + edits={"sql/seeds/regions.csv": "region_id,region_name\n1,south\n"}, command=_TEST_COMMAND, expected_exit_code=0, expected_fragments=( @@ -352,7 +352,7 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( ), SinceSelectionE2ETestCase( description="seed data selects the scenario that loads the seed", - edits={"seeds/regions.csv": "region_id,region_name\n1,south\n"}, + edits={"sql/seeds/regions.csv": "region_id,region_name\n1,south\n"}, command=_EXPLAINED_SCENARIOS, expected_exit_code=0, expected_fragments=( @@ -364,7 +364,7 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="a seed column type selects the scenario that loads the seed", edits={ - "seeds/regions.yml": _INDIRECT["seeds/regions.yml"].replace( + "sql/seeds/regions.yml": _INDIRECT["sql/seeds/regions.yml"].replace( "type: VARCHAR", "type: TEXT" ) }, @@ -375,9 +375,9 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="an audit definition change selects scenarios that build its model", edits={ - "audits/generic/at_least.sql": _INDIRECT["audits/generic/at_least.sql"].replace( - "@column < @minimum", "@column <= @minimum" - ) + "sql/audits/generic/at_least.sql": _INDIRECT[ + "sql/audits/generic/at_least.sql" + ].replace("@column < @minimum", "@column <= @minimum") }, command=_EXPLAINED_SCENARIOS, expected_exit_code=0, @@ -401,7 +401,7 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="a mocked source's declared column type selects the tests that mock it", edits={ - "sources/raw.yml": _FILES["sources/raw.yml"].replace( + "sql/sources/raw.yml": _FILES["sql/sources/raw.yml"].replace( "amount_cents\n type: INTEGER", "amount_cents\n type: BIGINT" ) }, @@ -445,7 +445,7 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="a macro another project-wide macro imports changes both", edits={ - "macros/python/taxes.py": _INDIRECT["macros/python/taxes.py"].replace( + "sql/macros/python/taxes.py": _INDIRECT["sql/macros/python/taxes.py"].replace( "+ 0", "+ 1 - 1" ) }, @@ -462,8 +462,8 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="a scoped macro another scoped macro imports changes both", edits={ - "models/_macros/python/currency.py": _INDIRECT[ - "models/_macros/python/currency.py" + "sql/models/_macros/python/currency.py": _INDIRECT[ + "sql/models/_macros/python/currency.py" ].replace("* 1)", "* 1.0)") }, command=_EXPLAINED_TESTS, @@ -478,8 +478,8 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="a macro a parameterized test's own fixture calls selects every case", edits={ - "macros/python/fixture_values.py": _INDIRECT[ - "macros/python/fixture_values.py" + "sql/macros/python/fixture_values.py": _INDIRECT[ + "sql/macros/python/fixture_values.py" ].replace("\"''\"", "\"'x'\"") }, command=_EXPLAINED_TESTS, @@ -547,9 +547,9 @@ def test_given_changes_since_ref_when_testing_then_runs_only_affected_tests( SinceSelectionE2ETestCase( description="a Python node change is listed", edits={ - "python/tasks/report.py": _INDIRECT["python/tasks/report.py"].replace( - "payload={}", 'payload={"orders": 1}' - ) + "python/nodes/tasks/report/asset.py": _INDIRECT[ + "python/nodes/tasks/report/asset.py" + ].replace("payload={}", 'payload={"orders": 1}') }, command=_TEST_COMMAND, expected_exit_code=0, @@ -582,12 +582,12 @@ def test_given_indirect_changes_since_ref_when_testing_then_selects_what_execute SinceBrokenBaseE2ETestCase( description="a base revision that does not compile fails and says what to do", base_files={ - "models/broken.sql": ( + "sql/models/broken.sql": ( "MODEL (description 'Reads a model that does not exist.');\n\n" 'SELECT order_id FROM __ref("missing_orders")\n' ) }, - deletions=("models/broken.sql",), + deletions=("sql/models/broken.sql",), command=_TEST_COMMAND, expected_exit_code=1, expected_fragments=( @@ -832,12 +832,12 @@ def test_given_unwritable_cache_when_testing_since_then_warns_and_succeeds( SinceSelectionE2ETestCase( description="naming the CTEs of a CTE-list sql macro call selects the caller's test", edits={ - "models/_macros/sql/live_orders.sql": ( + "sql/models/_macros/sql/live_orders.sql": ( "MACRO (\n description 'Orders still open.',\n" " arguments (src RELATION (order_id INTEGER, status VARCHAR)),\n);\n\n" "WITH live AS (SELECT * FROM @src WHERE status = 'open')\n" ), - "models/order_live.sql": ( + "sql/models/order_live.sql": ( "MODEL (description 'Live orders.');\n\n" 'WITH raw AS (SELECT * FROM __ref("stg_orders")),\n' "@sql.live_orders(raw, __cte := open_orders)\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_size.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_size.py index d880521376..7bbcedc412 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_size.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_size.py @@ -30,8 +30,8 @@ def test_given_combined_sql_over_256k_when_testing_on_duckdb_then_passes( 'name = "large_sql_test"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "orders.duckdb"\n' ), - "models/raw_orders.sql": "MODEL (description 'Test model raw_orders.');\nSELECT 'orders' AS details\n", - "models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT details FROM __ref("raw_orders")\n', + "sql/models/raw_orders.sql": "MODEL (description 'Test model raw_orders.');\nSELECT 'orders' AS details\n", + "sql/models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT details FROM __ref("raw_orders")\n', "tests/unit/test_orders.sql": ( 'TEST (name "large_orders");\nWITH __ref__raw_orders AS (\n' f"SELECT '{payload}' AS details\n), __expected__orders AS (\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_summary.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_summary.py index 3c3da37a76..f90a2d7269 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_summary.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_summary.py @@ -20,7 +20,7 @@ "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n\n[connection]\ndatabase = "orders.duckdb"\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" @@ -28,7 +28,7 @@ " - name: order_id\n type: INTEGER\n" " - name: amount\n type: INTEGER\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\n" 'SELECT order_id, amount * 2 AS doubled FROM __source("raw_orders")\n' ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_temporary_functions.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_temporary_functions.py index c2d5489e9c..cb3799b2ae 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_temporary_functions.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_temporary_functions.py @@ -20,7 +20,7 @@ run_sqb, ) -_FUNCTION_PATH: str = "functions/sql/is_completed_order.sql" +_FUNCTION_PATH: str = "sql/functions/sql/is_completed_order.sql" _FUNCTION_HEADER: str = ( "FUNCTION (description 'Whether an order status counts as completed.', " "arguments (order_status VARCHAR), returns BOOLEAN);\n" @@ -30,11 +30,11 @@ 'name = "orders_temporary_functions"\nadapter = "duckdb"\n' '[connection]\ndatabase = "orders.duckdb"\n' ), - "models/order_statuses.sql": ( + "sql/models/order_statuses.sql": ( "MODEL (description 'Test model order_statuses.', materialized table);\n" "SELECT 'completed' AS order_status\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n" 'SELECT order_status, __udf("is_completed_order")(order_status) AS is_completed ' 'FROM __ref("order_statuses")\n' @@ -47,7 +47,7 @@ ), } -_CALLEE_PATH: str = "functions/sql/status_matches.sql" +_CALLEE_PATH: str = "sql/functions/sql/status_matches.sql" _CALLEE_HEADER: str = ( "FUNCTION (description 'Whether an order status is the completed one.', " "arguments (order_status VARCHAR), returns BOOLEAN);\n" @@ -59,7 +59,7 @@ _QUOTED_CALL_FILES: dict[str, str] = { **_PROJECT_FILES, _FUNCTION_PATH: _FUNCTION_HEADER + "order_status = 'completed'", - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n" 'SELECT order_status, __udf("is_completed_order")(order_status) AS is_completed, ' "length('main.is_completed_order(order_status)') AS formula_length " @@ -83,7 +83,7 @@ "tests/unit/orders_again.sql": _PROJECT_FILES["tests/unit/orders_case.sql"].replace( "orders_case", "orders_again" ), - "adapters/duckdb_one_session.py": ( + "python/adapters/duckdb_one_session.py": ( "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n\n" "class DuckDbOneSessionAdapter(DuckDbAdapter):\n" ' adapter_name = "duckdb_one_session"\n' @@ -103,7 +103,7 @@ "sqlbuild_project.toml": _PROJECT_FILES["sqlbuild_project.toml"].replace( 'adapter = "duckdb"', 'adapter = "duckdb_no_copies"' ), - "adapters/duckdb_no_copies.py": ( + "python/adapters/duckdb_no_copies.py": ( "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n\n" "class DuckDbNoCopiesAdapter(DuckDbAdapter):\n" ' adapter_name = "duckdb_no_copies"\n\n' diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_upstream_function_fallback.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_upstream_function_fallback.py index 2d5d6e4dc9..1eba370f05 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_upstream_function_fallback.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_upstream_function_fallback.py @@ -38,18 +38,18 @@ def test_given_upstream_function_when_compiling_and_testing_then_mocked_chain_ex 'name = "orders_function_chain"\nadapter = "duckdb"\n' '[connection]\ndatabase = "orders.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n schema: main\n table: raw_orders\n" ), - "functions/sql/identity_value.sql": ( + "sql/functions/sql/identity_value.sql": ( "FUNCTION (description 'Test function identity_value.', arguments (value INTEGER), returns INTEGER);\nvalue\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n" 'SELECT __udf("identity_value")(order_id) AS order_id ' 'FROM __source("raw_orders")\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\nSELECT * FROM __ref("stg_orders")\n' ), "tests/unit/orders_case.sql": ( diff --git a/tests/e2e/src/sqlbuild/cli/commands/shared/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/shared/helpers.py index d4cf1f3b99..011925902a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/shared/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/shared/helpers.py @@ -115,8 +115,8 @@ def write_dbt_profile_orders_model(*, workspace: Path, order_id: int) -> None: def add_dbt_profile_downstream_model(*, sqlbuild_project_dir: Path) -> None: """Add a SQLBuild model downstream of the dbt profile E2E model.""" - models_dir: Path = sqlbuild_project_dir / "models" - models_dir.mkdir(exist_ok=True) + models_dir: Path = sqlbuild_project_dir / "sql" / "models" + models_dir.mkdir(parents=True, exist_ok=True) (models_dir / "downstream_orders.sql").write_text( "MODEL (description 'Test model downstream_orders.', materialized table);\n\n" 'SELECT order_id FROM __dbt_ref("analytics", "dbt_orders")\n', @@ -587,8 +587,8 @@ def build_real_warehouse_snapshot_project_files(*, project_toml: str) -> dict[st return { "sqlbuild_project.toml": project_toml, - "models/current_customers.sql": build_current_customers_model_sql(plan="basic"), - "models/current_customer_snapshot.sql": ( + "sql/models/current_customers.sql": build_current_customers_model_sql(plan="basic"), + "sql/models/current_customer_snapshot.sql": ( "MODEL (description 'Test model current_customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id, region_id],\n" @@ -606,7 +606,7 @@ def build_real_warehouse_snapshot_project_files(*, project_toml: str) -> dict[st "SELECT customer_id, region_id, plan, updated_at\n" 'FROM __ref("current_customers")\n' ), - "models/historical_customer_extracts.sql": ( + "sql/models/historical_customer_extracts.sql": ( "MODEL (description 'Test model historical_customer_extracts.', " "materialized table);\n\n" "SELECT 1 AS customer_id, 'basic' AS plan, " @@ -619,7 +619,7 @@ def build_real_warehouse_snapshot_project_files(*, project_toml: str) -> dict[st "CAST('2026-01-02 00:00:00' AS TIMESTAMP) AS updated_at, " "CAST('2026-01-04 00:00:00' AS TIMESTAMP) AS observed_at\n" ), - "models/historical_customer_snapshot.sql": ( + "sql/models/historical_customer_snapshot.sql": ( "MODEL (description 'Test model historical_customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -631,7 +631,7 @@ def build_real_warehouse_snapshot_project_files(*, project_toml: str) -> dict[st "SELECT customer_id, plan, updated_at, observed_at\n" 'FROM __ref("historical_customer_extracts")\n' ), - "models/historical_membership_daily.sql": ( + "sql/models/historical_membership_daily.sql": ( "MODEL (description 'Test model historical_membership_daily.', materialized table);\n\n" "SELECT 1 AS customer_id, 'active' AS status, " "CAST('2026-01-01 00:00:00' AS TIMESTAMP) AS observed_at\n" @@ -644,7 +644,7 @@ def build_real_warehouse_snapshot_project_files(*, project_toml: str) -> dict[st "UNION ALL SELECT 2 AS customer_id, 'active' AS status, " "CAST('2026-01-03 00:00:00' AS TIMESTAMP) AS observed_at\n" ), - "models/historical_membership_snapshot.sql": ( + "sql/models/historical_membership_snapshot.sql": ( "MODEL (description 'Test model historical_membership_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -657,7 +657,7 @@ def build_real_warehouse_snapshot_project_files(*, project_toml: str) -> dict[st "SELECT customer_id, status, observed_at\n" 'FROM __ref("historical_membership_daily")\n' ), - "audits/generic/expression_is_true.sql": ( + "sql/audits/generic/expression_is_true.sql": ( 'AUDIT ();\n\nSELECT * FROM __ref("@model") WHERE NOT (@expression)\n' ), } @@ -678,10 +678,10 @@ def build_real_warehouse_existing_snapshot_project_files(*, project_toml: str) - return { "sqlbuild_project.toml": project_toml, - "models/current_check_customers.sql": build_current_check_customers_model_sql( + "sql/models/current_check_customers.sql": build_current_check_customers_model_sql( changed=False ), - "models/current_check_snapshot.sql": ( + "sql/models/current_check_snapshot.sql": ( "MODEL (description 'Test model current_check_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -691,10 +691,10 @@ def build_real_warehouse_existing_snapshot_project_files(*, project_toml: str) - "SELECT customer_id, status\n" 'FROM __ref("current_check_customers")\n' ), - "models/current_delete_customers.sql": build_current_delete_customers_model_sql( + "sql/models/current_delete_customers.sql": build_current_delete_customers_model_sql( changed=False ), - "models/current_delete_snapshot.sql": ( + "sql/models/current_delete_snapshot.sql": ( "MODEL (description 'Test model current_delete_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -705,10 +705,10 @@ def build_real_warehouse_existing_snapshot_project_files(*, project_toml: str) - "SELECT customer_id, plan, updated_at\n" 'FROM __ref("current_delete_customers")\n' ), - "models/historical_timestamp_extracts.sql": build_historical_timestamp_extracts_model_sql( - changed=False + "sql/models/historical_timestamp_extracts.sql": ( + build_historical_timestamp_extracts_model_sql(changed=False) ), - "models/historical_timestamp_snapshot.sql": ( + "sql/models/historical_timestamp_snapshot.sql": ( "MODEL (description 'Test model historical_timestamp_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -721,8 +721,10 @@ def build_real_warehouse_existing_snapshot_project_files(*, project_toml: str) - "SELECT customer_id, plan, updated_at, observed_at\n" 'FROM __ref("historical_timestamp_extracts")\n' ), - "models/historical_check_daily.sql": build_historical_check_daily_model_sql(changed=False), - "models/historical_check_snapshot.sql": ( + "sql/models/historical_check_daily.sql": build_historical_check_daily_model_sql( + changed=False + ), + "sql/models/historical_check_snapshot.sql": ( "MODEL (description 'Test model historical_check_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" diff --git a/tests/e2e/src/sqlbuild/integrations/dagster/helpers.py b/tests/e2e/src/sqlbuild/integrations/dagster/helpers.py index 412363d24d..f09fe2d4c8 100644 --- a/tests/e2e/src/sqlbuild/integrations/dagster/helpers.py +++ b/tests/e2e/src/sqlbuild/integrations/dagster/helpers.py @@ -29,12 +29,12 @@ def prepare_python_nodes_integration_project(root: Path) -> Path: """ project_dir: Path = root / "python_nodes_project" - models_dir: Path = project_dir / "models" - tasks_dir: Path = project_dir / "python" / "tasks" - factories_dir: Path = project_dir / "python" / "factories" - assets_dir: Path = project_dir / "python" / "assets" - loaders_dir: Path = project_dir / "python" / "loaders" - checks_dir: Path = project_dir / "python" / "checks" + models_dir: Path = project_dir / "sql" / "models" + tasks_dir: Path = project_dir / "python" / "nodes" / "tasks" + factories_dir: Path = project_dir / "python" / "nodes" / "factories" + assets_dir: Path = project_dir / "python" / "nodes" / "assets" + loaders_dir: Path = project_dir / "python" / "nodes" / "loaders" + checks_dir: Path = project_dir / "python" / "nodes" / "checks" for directory in (models_dir, tasks_dir, factories_dir, assets_dir, loaders_dir, checks_dir): directory.mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( @@ -61,7 +61,8 @@ def prepare_python_nodes_integration_project(root: Path) -> Path: "MODEL (description 'Test model orders.', materialized view);\n\nSELECT 1 AS order_id\n", encoding="utf-8", ) - (factories_dir / "generated_nodes.py").write_text( + (factories_dir / "generated_nodes").mkdir() + (factories_dir / "generated_nodes" / "factory.py").write_text( "\n".join( ( "from sqlbuild.assets import asset", @@ -217,7 +218,9 @@ def _continue_stdout_poll(rendered_stdout: str, poll_wait: Event) -> None: def add_failing_daily_revenue_audits(*, project_dir: Path) -> None: """Add violation and measurement failures to the copied project.""" - audits_dir: Path = project_dir / "models" / "marts" / "_sqlbuild" / "_audits" / "generic" + audits_dir: Path = ( + project_dir / "sql" / "models" / "marts" / "_sqlbuild" / "_audits" / "generic" + ) audits_dir.mkdir(parents=True, exist_ok=True) failing_audit_sql: str = 'AUDIT ();\n\nSELECT *\nFROM __ref("@model")\nWHERE 1 = 1\n' (audits_dir / "forced_warning_failure.sql").write_text( @@ -244,7 +247,7 @@ def add_failing_daily_revenue_audits(*, project_dir: Path) -> None: """, encoding="utf-8", ) - model_path: Path = project_dir / "models" / "marts" / "daily_revenue.sql" + model_path: Path = project_dir / "sql" / "models" / "marts" / "daily_revenue.sql" contents: str = model_path.read_text(encoding="utf-8") contents = contents.replace( """ expression_is_true ( @@ -418,8 +421,8 @@ class AuditCheckOutcome: "[connection]\n" 'database = "attachment_checks.duckdb"\n' ), - "seeds/products.csv": "product_id,product_name\n1,widget\n2,gadget\n", - "seeds/products.yml": ( + "sql/seeds/products.csv": "product_id,product_name\n1,widget\n2,gadget\n", + "sql/seeds/products.yml": ( "seeds:\n" " - name: products\n" " description: Product catalogue.\n" @@ -431,7 +434,7 @@ class AuditCheckOutcome: " - name: product_name\n" " type: VARCHAR\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n" " description: Raw orders.\n" @@ -446,24 +449,24 @@ class AuditCheckOutcome: " - name: product_id\n" " type: INTEGER\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.',\n" " columns (order_id (), product_id ()),\n" " audits [not_null (column order_id)],\n" ");\n\n" 'SELECT order_id, product_id FROM __source("raw_orders")\n' ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Customers.');\n\nSELECT 1 AS customer_id, 1 AS order_id\n" ), - "audits/singular/orders_have_customers.sql": ( + "sql/audits/singular/orders_have_customers.sql": ( 'AUDIT (name "orders_have_customers", severity error);\n\n' "SELECT o.order_id\n" 'FROM __ref("orders") o\n' 'LEFT JOIN __ref("customers") c ON o.order_id = c.order_id\n' "WHERE c.order_id IS NULL AND o.order_id = 1\n" ), - "audits/singular/orders_match_raw_orders.sql": ( + "sql/audits/singular/orders_match_raw_orders.sql": ( 'AUDIT (name "orders_match_raw_orders", severity error);\n\n' "SELECT o.order_id\n" 'FROM __ref("orders") o\n' diff --git a/tests/e2e/src/sqlbuild/integrations/dagster/test_audit_attachment_checks.py b/tests/e2e/src/sqlbuild/integrations/dagster/test_audit_attachment_checks.py index 70655e79cc..7ecc08b5c4 100644 --- a/tests/e2e/src/sqlbuild/integrations/dagster/test_audit_attachment_checks.py +++ b/tests/e2e/src/sqlbuild/integrations/dagster/test_audit_attachment_checks.py @@ -32,18 +32,18 @@ 'name = "skipped_audit_checks"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "warehouse.duckdb"\n\n[defaults]\nmaterialized = "table"\n' ), - "hooks/python/skips.py": ( + "sql/hooks/python/skips.py": ( "from sqlbuild.hooks import hook\n\n\n" "@hook\ndef skip_model(ctx):\n" " '''Test hook skip_model.'''\n" " return ctx.skip(reason='paused')\n" ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Test model customers.', pre_hooks [python(\"skip_model\")]);\n" "SELECT 1 AS customer_id\n" ), - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", - "audits/singular/orders_have_customers.sql": ( + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", + "sql/audits/singular/orders_have_customers.sql": ( "AUDIT ();\n" 'SELECT o.order_id FROM __ref("orders") AS o\n' 'LEFT JOIN __ref("customers") AS c ON c.customer_id = o.order_id\n' diff --git a/tests/e2e/src/sqlbuild/integrations/dagster/test_failure_output.py b/tests/e2e/src/sqlbuild/integrations/dagster/test_failure_output.py index 51621892d8..52a0c973e0 100644 --- a/tests/e2e/src/sqlbuild/integrations/dagster/test_failure_output.py +++ b/tests/e2e/src/sqlbuild/integrations/dagster/test_failure_output.py @@ -32,10 +32,10 @@ 'name = "orders_shop"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "warehouse.duckdb"\n\n[defaults]\nmaterialized = "table"\n' ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'One row per customer.');\nSELECT 1 AS customer_id\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (\n description 'One row per order.',\n" " columns (order_id (audits [not_null])),\n);\n" 'SELECT 1 AS order_id, customer_id FROM __ref("customers")\n' diff --git a/tests/e2e/src/sqlbuild/integrations/dagster/test_sqlbuild_assets.py b/tests/e2e/src/sqlbuild/integrations/dagster/test_sqlbuild_assets.py index 818090c212..af15aa097d 100644 --- a/tests/e2e/src/sqlbuild/integrations/dagster/test_sqlbuild_assets.py +++ b/tests/e2e/src/sqlbuild/integrations/dagster/test_sqlbuild_assets.py @@ -109,7 +109,7 @@ def test_given_model_level_column_audits_when_loading_dagster_assets_then_checks "[connection]\n" 'database = "column_audit_checks.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " columns (\n" " order_id (),\n" @@ -123,7 +123,9 @@ def test_given_model_level_column_audits_when_loading_dagster_assets_then_checks ");\n\n" "SELECT 1 AS order_id, 2 AS customer_id\n" ), - "audits/generic/model_is_empty.sql": ('AUDIT ();\n\nSELECT * FROM __ref("@model")\n'), + "sql/audits/generic/model_is_empty.sql": ( + 'AUDIT ();\n\nSELECT * FROM __ref("@model")\n' + ), }, ) sqlbuild_project: SqlBuildProject = SqlBuildProject( @@ -544,20 +546,33 @@ def test_given_chained_source_loader_when_dagster_selects_source_then_reuses_int "[connection]\n" 'database = "dagster_chained_source_loader.duckdb"\n' ), - "python/loaders/raw.py": ( - "from sqlbuild.loaders import loader\n\n" + "python/nodes/loaders/raw/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" "@loader(write_strategy='table', columns=[\n" " {'name': 'event_id', 'type': 'INTEGER'},\n" "])\n" "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}]\n\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/raw/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw.fetch_events.loader import fetch_events\n" + "\n" + "\n" "@loader(depends_on=[fetch_events])\n" "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS " - "SELECT event_id FROM {events.destination}')\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS SELECT event_id FROM {events.destination}')\n" + ), + "python/nodes/loaders/raw/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" ), - "sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", + "sql/sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", }, ) setup_result: subprocess.CompletedProcess[str] = run_sqb( @@ -635,20 +650,33 @@ def test_given_chained_source_loader_when_dagster_selects_source_without_interme "[connection]\n" 'database = "dagster_missing_intermediate_source_loader.duckdb"\n' ), - "python/loaders/raw.py": ( - "from sqlbuild.loaders import loader\n\n" + "python/nodes/loaders/raw/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" "@loader(write_strategy='table', columns=[\n" " {'name': 'event_id', 'type': 'INTEGER'},\n" "])\n" "def fetch_events(ctx):\n" - " '''Test loader fetch_events.'''\n return [{'event_id': 1}]\n\n" + " '''Test loader fetch_events.'''\n" + " return [{'event_id': 1}]\n" + ), + "python/nodes/loaders/raw/raw_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw.fetch_events.loader import fetch_events\n" + "\n" + "\n" "@loader(depends_on=[fetch_events])\n" "def raw_events(ctx):\n" - " '''Test loader raw_events.'''\n events = ctx.loader(fetch_events)\n" - " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS " - "SELECT event_id FROM {events.destination}')\n" + " '''Test loader raw_events.'''\n" + " events = ctx.loader(fetch_events)\n" + " ctx.execute_sql(f'CREATE OR REPLACE TABLE {ctx.destination} AS SELECT event_id FROM {events.destination}')\n" + ), + "python/nodes/loaders/raw/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .raw_events.loader import raw_events\n" ), - "sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", + "sql/sources/raw.yml": "sources:\n - name: raw_events\n description: Test source raw_events.\n managed: true\n", }, ) command_log_path: Path = tmp_path / "sqb_command_log.txt" @@ -1040,7 +1068,7 @@ def test_given_emptied_cursor_inputs_when_executing_dagster_then_emits_declared_ monkeypatch: pytest.MonkeyPatch, ) -> None: project_dir: Path = prepare_empty_cursor_inputs_project( - tmp_path=tmp_path, models={"models/daily_revenue.sql": test_case.model_sql} + tmp_path=tmp_path, models={"sql/models/daily_revenue.sql": test_case.model_sql} ) load_empty_cursor_payments(project_dir=project_dir) build_empty_cursor_project(project_dir=project_dir) diff --git a/tests/goldens/compiler/example/hero-shop.json b/tests/goldens/compiler/example/hero-shop.json index e9235feb79..8b42b3f7b0 100644 --- a/tests/goldens/compiler/example/hero-shop.json +++ b/tests/goldens/compiler/example/hero-shop.json @@ -22,7 +22,7 @@ } ], "compiled": { - "models/finance/daily_revenue.sql": [ + "sql/models/finance/daily_revenue.sql": [ "SELECT", " CAST(paid_at AS DATE) AS revenue_date,", " SUM(amount_cents) AS total_revenue_cents", @@ -40,8 +40,8 @@ "name": "daily_revenue", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/finance/daily_revenue.sql", - "original_file_path": "models/finance/daily_revenue.sql", + "path": "sql/models/finance/daily_revenue.sql", + "original_file_path": "sql/models/finance/daily_revenue.sql", "unique_id": "model.waffle_shop.daily_revenue", "fqn": [ "waffle_shop", @@ -109,8 +109,8 @@ "name": "payments", "resource_type": "seed", "package_name": "waffle_shop", - "path": "seeds/payments.csv", - "original_file_path": "seeds/payments.csv", + "path": "sql/seeds/payments.csv", + "original_file_path": "sql/seeds/payments.csv", "unique_id": "seed.waffle_shop.payments", "fqn": [ "waffle_shop", diff --git a/tests/goldens/compiler/example/tidy-shop.json b/tests/goldens/compiler/example/tidy-shop.json index c7db14dd9c..17471b8649 100644 --- a/tests/goldens/compiler/example/tidy-shop.json +++ b/tests/goldens/compiler/example/tidy-shop.json @@ -22,7 +22,7 @@ } ], "compiled": { - "models/daily_revenue.sql": [ + "sql/models/daily_revenue.sql": [ "SELECT CAST('2026-04-01' AS DATE) AS revenue_date, 2850 AS total_revenue_cents", "" ] @@ -35,8 +35,8 @@ "name": "daily_revenue", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/daily_revenue.sql", - "original_file_path": "models/daily_revenue.sql", + "path": "sql/models/daily_revenue.sql", + "original_file_path": "sql/models/daily_revenue.sql", "unique_id": "model.waffle_shop.daily_revenue", "fqn": [ "waffle_shop", diff --git a/tests/goldens/compiler/example/waffle-shop.json b/tests/goldens/compiler/example/waffle-shop.json index 4e8e712352..90f529cca9 100644 --- a/tests/goldens/compiler/example/waffle-shop.json +++ b/tests/goldens/compiler/example/waffle-shop.json @@ -22,13 +22,13 @@ } ], "compiled": { - "audits/generic/customer_status_snapshot/not_null__customer_id.sql": [ + "sql/audits/generic/customer_status_snapshot/not_null__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"customer_status_snapshot\")", "WHERE customer_id IS NULL", "" ], - "audits/generic/customer_status_snapshot/unique__customer_id.sql": [ + "sql/audits/generic/customer_status_snapshot/unique__customer_id.sql": [ "SELECT customer_id, COUNT(*) AS duplicate_count", "FROM __ref(\"customer_status_snapshot\")", "WHERE customer_id IS NOT NULL", @@ -36,43 +36,43 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/daily_order_partitioned/not_null__order_date.sql": [ + "sql/audits/generic/daily_order_partitioned/not_null__order_date.sql": [ "SELECT order_date", "FROM __ref(\"daily_order_partitioned\")", "WHERE order_date IS NULL", "" ], - "audits/generic/daily_order_partitioned/waffles_ordered_is_positive.sql": [ + "sql/audits/generic/daily_order_partitioned/waffles_ordered_is_positive.sql": [ "SELECT *", "FROM __ref(\"daily_order_partitioned\")", "WHERE NOT (waffles_ordered > 0)", "" ], - "audits/generic/daily_order_rollup/daily_orders_placed_is_non_negative.sql": [ + "sql/audits/generic/daily_order_rollup/daily_orders_placed_is_non_negative.sql": [ "SELECT *", "FROM __ref(\"daily_order_rollup\")", "WHERE NOT (orders_placed >= 0)", "" ], - "audits/generic/daily_order_rollup/not_null__activity_day.sql": [ + "sql/audits/generic/daily_order_rollup/not_null__activity_day.sql": [ "SELECT activity_day", "FROM __ref(\"daily_order_rollup\")", "WHERE activity_day IS NULL", "" ], - "audits/generic/daily_revenue/revenue_is_non_negative.sql": [ + "sql/audits/generic/daily_revenue/revenue_is_non_negative.sql": [ "SELECT *", "FROM __ref(\"daily_revenue\")", "WHERE NOT (total_revenue_cents >= 0)", "" ], - "audits/generic/dim_customers/not_null__customer_id.sql": [ + "sql/audits/generic/dim_customers/not_null__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"dim_customers\")", "WHERE customer_id IS NULL", "" ], - "audits/generic/dim_customers/unique__customer_id.sql": [ + "sql/audits/generic/dim_customers/unique__customer_id.sql": [ "SELECT customer_id, COUNT(*) AS duplicate_count", "FROM __ref(\"dim_customers\")", "WHERE customer_id IS NOT NULL", @@ -80,43 +80,43 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/fact_orders/not_null__order_id.sql": [ + "sql/audits/generic/fact_orders/not_null__order_id.sql": [ "SELECT order_id", "FROM __ref(\"fact_orders\")", "WHERE order_id IS NULL", "" ], - "audits/generic/hourly_activity_with_daily_context/day_orders_cover_hourly_orders.sql": [ + "sql/audits/generic/hourly_activity_with_daily_context/day_orders_cover_hourly_orders.sql": [ "SELECT *", "FROM __ref(\"hourly_activity_with_daily_context\")", "WHERE NOT (day_orders_placed >= orders_placed)", "" ], - "audits/generic/hourly_activity_with_daily_context/not_null__activity_hour.sql": [ + "sql/audits/generic/hourly_activity_with_daily_context/not_null__activity_hour.sql": [ "SELECT activity_hour", "FROM __ref(\"hourly_activity_with_daily_context\")", "WHERE activity_hour IS NULL", "" ], - "audits/generic/hourly_order_activity/not_null__activity_hour.sql": [ + "sql/audits/generic/hourly_order_activity/not_null__activity_hour.sql": [ "SELECT activity_hour", "FROM __ref(\"hourly_order_activity\")", "WHERE activity_hour IS NULL", "" ], - "audits/generic/hourly_order_activity/orders_placed_is_non_negative.sql": [ + "sql/audits/generic/hourly_order_activity/orders_placed_is_non_negative.sql": [ "SELECT *", "FROM __ref(\"hourly_order_activity\")", "WHERE NOT (orders_placed >= 0)", "" ], - "audits/generic/order_status_index/not_null__order_id.sql": [ + "sql/audits/generic/order_status_index/not_null__order_id.sql": [ "SELECT order_id", "FROM __ref(\"order_status_index\")", "WHERE order_id IS NULL", "" ], - "audits/generic/order_status_index/unique__order_id.sql": [ + "sql/audits/generic/order_status_index/unique__order_id.sql": [ "SELECT order_id, COUNT(*) AS duplicate_count", "FROM __ref(\"order_status_index\")", "WHERE order_id IS NOT NULL", @@ -124,19 +124,19 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/stg_customers/not_null__customer_id.sql": [ + "sql/audits/generic/stg_customers/not_null__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"stg_customers\")", "WHERE customer_id IS NULL", "" ], - "audits/generic/stg_customers/not_null__email.sql": [ + "sql/audits/generic/stg_customers/not_null__email.sql": [ "SELECT email", "FROM __ref(\"stg_customers\")", "WHERE email IS NULL", "" ], - "audits/generic/stg_customers/unique__customer_id.sql": [ + "sql/audits/generic/stg_customers/unique__customer_id.sql": [ "SELECT customer_id, COUNT(*) AS duplicate_count", "FROM __ref(\"stg_customers\")", "WHERE customer_id IS NOT NULL", @@ -144,26 +144,26 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/stg_orders/accepted_values__status.sql": [ + "sql/audits/generic/stg_orders/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"stg_orders\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'preparing', 'ready', 'completed', 'cancelled')", "" ], - "audits/generic/stg_orders/not_null__customer_id.sql": [ + "sql/audits/generic/stg_orders/not_null__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"stg_orders\")", "WHERE customer_id IS NULL", "" ], - "audits/generic/stg_orders/not_null__order_id.sql": [ + "sql/audits/generic/stg_orders/not_null__order_id.sql": [ "SELECT order_id", "FROM __ref(\"stg_orders\")", "WHERE order_id IS NULL", "" ], - "audits/generic/stg_orders/relationships__waffle_type_id.sql": [ + "sql/audits/generic/stg_orders/relationships__waffle_type_id.sql": [ "SELECT waffle_type_id", "FROM __ref(\"stg_orders\")", "WHERE waffle_type_id IS NOT NULL", @@ -174,7 +174,7 @@ " )", "" ], - "audits/generic/stg_orders/unique__order_id.sql": [ + "sql/audits/generic/stg_orders/unique__order_id.sql": [ "SELECT order_id, COUNT(*) AS duplicate_count", "FROM __ref(\"stg_orders\")", "WHERE order_id IS NOT NULL", @@ -182,19 +182,19 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/stg_payments/not_null__order_id.sql": [ + "sql/audits/generic/stg_payments/not_null__order_id.sql": [ "SELECT order_id", "FROM __ref(\"stg_payments\")", "WHERE order_id IS NULL", "" ], - "audits/generic/stg_payments/not_null__payment_id.sql": [ + "sql/audits/generic/stg_payments/not_null__payment_id.sql": [ "SELECT payment_id", "FROM __ref(\"stg_payments\")", "WHERE payment_id IS NULL", "" ], - "audits/generic/stg_payments/relationships__order_id.sql": [ + "sql/audits/generic/stg_payments/relationships__order_id.sql": [ "SELECT order_id", "FROM __ref(\"stg_payments\")", "WHERE order_id IS NOT NULL", @@ -205,7 +205,7 @@ " )", "" ], - "audits/generic/stg_payments/unique__payment_id.sql": [ + "sql/audits/generic/stg_payments/unique__payment_id.sql": [ "SELECT payment_id, COUNT(*) AS duplicate_count", "FROM __ref(\"stg_payments\")", "WHERE payment_id IS NOT NULL", @@ -213,13 +213,13 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/waffle_types/not_null__waffle_type_id.sql": [ + "sql/audits/generic/waffle_types/not_null__waffle_type_id.sql": [ "SELECT waffle_type_id", "FROM __seed(\"waffle_types\")", "WHERE waffle_type_id IS NULL", "" ], - "audits/generic/waffle_types/unique__waffle_type_id.sql": [ + "sql/audits/generic/waffle_types/unique__waffle_type_id.sql": [ "SELECT waffle_type_id, COUNT(*) AS duplicate_count", "FROM __seed(\"waffle_types\")", "WHERE waffle_type_id IS NOT NULL", @@ -227,14 +227,14 @@ "HAVING COUNT(*) > 1", "" ], - "audits/singular/fact_orders_have_customers.sql": [ + "sql/audits/singular/fact_orders_have_customers.sql": [ "SELECT f.order_id, f.customer_id", "FROM __ref(\"fact_orders\") f", "LEFT JOIN __ref(\"dim_customers\") d ON f.customer_id = d.customer_id", "WHERE d.customer_id IS NULL", "" ], - "functions/sql/table_fn__customer_orders.sql": [ + "sql/functions/sql/table_fn__customer_orders.sql": [ "CREATE OR REPLACE MACRO dev.table_fn__customer_orders(p_customer_id) AS TABLE", "SELECT", " order_id,", @@ -247,13 +247,13 @@ "WHERE customer_id = p_customer_id", "" ], - "functions/sql/udf__is_completed_order.sql": [ + "sql/functions/sql/udf__is_completed_order.sql": [ "CREATE OR REPLACE MACRO dev.udf__is_completed_order(order_status) AS (", "order_status = 'completed'", ")", "" ], - "models/intermediate/customer_status_snapshot.sql": [ + "sql/models/intermediate/customer_status_snapshot.sql": [ "SELECT", " customer_id,", " MAX(ordered_at) AS last_ordered_at,", @@ -264,7 +264,7 @@ "GROUP BY customer_id", "" ], - "models/intermediate/order_status_index.sql": [ + "sql/models/intermediate/order_status_index.sql": [ "SELECT", " order_id,", " customer_id,", @@ -274,7 +274,7 @@ "FROM __ref(\"fact_orders\")", "" ], - "models/marts/daily_order_partitioned.sql": [ + "sql/models/marts/daily_order_partitioned.sql": [ "SELECT", " CAST(o.ordered_at AS DATE) AS order_date,", " COUNT(DISTINCT o.order_id) AS order_count,", @@ -286,7 +286,7 @@ "GROUP BY CAST(o.ordered_at AS DATE)", "" ], - "models/marts/daily_order_rollup.sql": [ + "sql/models/marts/daily_order_rollup.sql": [ "SELECT", " DATE_TRUNC('day', activity_hour) AS activity_day,", " SUM(orders_placed) AS orders_placed,", @@ -296,7 +296,7 @@ "GROUP BY DATE_TRUNC('day', activity_hour)", "" ], - "models/marts/daily_revenue.sql": [ + "sql/models/marts/daily_revenue.sql": [ "SELECT", " CAST(o.ordered_at AS DATE) AS revenue_date,", " COUNT(DISTINCT o.order_id) AS order_count,", @@ -309,7 +309,7 @@ "GROUP BY CAST(o.ordered_at AS DATE)", "" ], - "models/marts/dim_customers.sql": [ + "sql/models/marts/dim_customers.sql": [ "SELECT", " c.customer_id,", " c.first_name,", @@ -324,7 +324,7 @@ "GROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.created_at", "" ], - "models/marts/fact_orders.sql": [ + "sql/models/marts/fact_orders.sql": [ "SELECT", " o.order_id,", " o.customer_id,", @@ -344,7 +344,7 @@ "LEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id", "" ], - "models/marts/hourly_activity_with_daily_context.sql": [ + "sql/models/marts/hourly_activity_with_daily_context.sql": [ "SELECT", " h.activity_hour,", " h.orders_placed,", @@ -356,7 +356,7 @@ " ON DATE_TRUNC('day', h.activity_hour) = d.activity_day", "" ], - "models/marts/hourly_order_activity.sql": [ + "sql/models/marts/hourly_order_activity.sql": [ "SELECT", " DATE_TRUNC('hour', o.ordered_at) AS activity_hour,", " COUNT(*) AS orders_placed,", @@ -366,7 +366,7 @@ "GROUP BY DATE_TRUNC('hour', o.ordered_at)", "" ], - "models/staging/stg_customers.sql": [ + "sql/models/staging/stg_customers.sql": [ "SELECT", " id AS customer_id,", " first_name,", @@ -376,7 +376,7 @@ "FROM __source(\"raw__customers\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT", " id AS order_id,", " customer_id,", @@ -387,7 +387,7 @@ "FROM __source(\"raw__orders\")", "" ], - "models/staging/stg_payments.sql": [ + "sql/models/staging/stg_payments.sql": [ "SELECT", " id AS payment_id,", " order_id,", @@ -616,8 +616,8 @@ "name": "customer_status_snapshot", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/intermediate/customer_status_snapshot.sql", - "original_file_path": "models/intermediate/customer_status_snapshot.sql", + "path": "sql/models/intermediate/customer_status_snapshot.sql", + "original_file_path": "sql/models/intermediate/customer_status_snapshot.sql", "unique_id": "model.waffle_shop.customer_status_snapshot", "fqn": [ "waffle_shop", @@ -703,8 +703,8 @@ "name": "order_status_index", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/intermediate/order_status_index.sql", - "original_file_path": "models/intermediate/order_status_index.sql", + "path": "sql/models/intermediate/order_status_index.sql", + "original_file_path": "sql/models/intermediate/order_status_index.sql", "unique_id": "model.waffle_shop.order_status_index", "fqn": [ "waffle_shop", @@ -790,8 +790,8 @@ "name": "daily_order_partitioned", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/daily_order_partitioned.sql", - "original_file_path": "models/marts/daily_order_partitioned.sql", + "path": "sql/models/marts/daily_order_partitioned.sql", + "original_file_path": "sql/models/marts/daily_order_partitioned.sql", "unique_id": "model.waffle_shop.daily_order_partitioned", "fqn": [ "waffle_shop", @@ -873,8 +873,8 @@ "name": "daily_order_rollup", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/daily_order_rollup.sql", - "original_file_path": "models/marts/daily_order_rollup.sql", + "path": "sql/models/marts/daily_order_rollup.sql", + "original_file_path": "sql/models/marts/daily_order_rollup.sql", "unique_id": "model.waffle_shop.daily_order_rollup", "fqn": [ "waffle_shop", @@ -958,8 +958,8 @@ "name": "daily_revenue", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/daily_revenue.sql", - "original_file_path": "models/marts/daily_revenue.sql", + "path": "sql/models/marts/daily_revenue.sql", + "original_file_path": "sql/models/marts/daily_revenue.sql", "unique_id": "model.waffle_shop.daily_revenue", "fqn": [ "waffle_shop", @@ -1042,8 +1042,8 @@ "name": "dim_customers", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/dim_customers.sql", - "original_file_path": "models/marts/dim_customers.sql", + "path": "sql/models/marts/dim_customers.sql", + "original_file_path": "sql/models/marts/dim_customers.sql", "unique_id": "model.waffle_shop.dim_customers", "fqn": [ "waffle_shop", @@ -1129,8 +1129,8 @@ "name": "fact_orders", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/fact_orders.sql", - "original_file_path": "models/marts/fact_orders.sql", + "path": "sql/models/marts/fact_orders.sql", + "original_file_path": "sql/models/marts/fact_orders.sql", "unique_id": "model.waffle_shop.fact_orders", "fqn": [ "waffle_shop", @@ -1215,8 +1215,8 @@ "name": "hourly_activity_with_daily_context", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/hourly_activity_with_daily_context.sql", - "original_file_path": "models/marts/hourly_activity_with_daily_context.sql", + "path": "sql/models/marts/hourly_activity_with_daily_context.sql", + "original_file_path": "sql/models/marts/hourly_activity_with_daily_context.sql", "unique_id": "model.waffle_shop.hourly_activity_with_daily_context", "fqn": [ "waffle_shop", @@ -1301,8 +1301,8 @@ "name": "hourly_order_activity", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/hourly_order_activity.sql", - "original_file_path": "models/marts/hourly_order_activity.sql", + "path": "sql/models/marts/hourly_order_activity.sql", + "original_file_path": "sql/models/marts/hourly_order_activity.sql", "unique_id": "model.waffle_shop.hourly_order_activity", "fqn": [ "waffle_shop", @@ -1384,8 +1384,8 @@ "name": "stg_customers", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/staging/stg_customers.sql", - "original_file_path": "models/staging/stg_customers.sql", + "path": "sql/models/staging/stg_customers.sql", + "original_file_path": "sql/models/staging/stg_customers.sql", "unique_id": "model.waffle_shop.stg_customers", "fqn": [ "waffle_shop", @@ -1476,8 +1476,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.waffle_shop.stg_orders", "fqn": [ "waffle_shop", @@ -1586,8 +1586,8 @@ "name": "stg_payments", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/staging/stg_payments.sql", - "original_file_path": "models/staging/stg_payments.sql", + "path": "sql/models/staging/stg_payments.sql", + "original_file_path": "sql/models/staging/stg_payments.sql", "unique_id": "model.waffle_shop.stg_payments", "fqn": [ "waffle_shop", @@ -1678,8 +1678,8 @@ "name": "waffle_types", "resource_type": "seed", "package_name": "waffle_shop", - "path": "seeds/waffle_types.csv", - "original_file_path": "seeds/waffle_types.csv", + "path": "sql/seeds/waffle_types.csv", + "original_file_path": "sql/seeds/waffle_types.csv", "unique_id": "seed.waffle_shop.waffle_types", "fqn": [ "waffle_shop", @@ -1783,8 +1783,8 @@ "name": "raw__customers", "resource_type": "source", "package_name": "waffle_shop", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.waffle_shop.raw__customers", "fqn": [ "waffle_shop", @@ -1866,8 +1866,8 @@ "name": "raw__orders", "resource_type": "source", "package_name": "waffle_shop", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.waffle_shop.raw__orders", "fqn": [ "waffle_shop", @@ -1959,8 +1959,8 @@ "name": "raw__payments", "resource_type": "source", "package_name": "waffle_shop", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.waffle_shop.raw__payments", "fqn": [ "waffle_shop", @@ -2000,8 +2000,8 @@ "name": "line_total_cents", "resource_type": "macro", "package_name": "waffle_shop", - "path": "macros/python/currency.py", - "original_file_path": "macros/python/currency.py", + "path": "sql/macros/python/currency.py", + "original_file_path": "sql/macros/python/currency.py", "unique_id": "macro.waffle_shop.line_total_cents", "macro_sql": "\"\"\"Project-wide currency macros.\"\"\"\n\n\ndef line_total_cents(price_cents: str, quantity: str) -> str:\n \"\"\"Calculate line total cents from a unit price and quantity.\"\"\"\n return f\"{price_cents} * {quantity}\"\n", "depends_on": { @@ -2024,8 +2024,8 @@ "name": "cents_to_dollars", "resource_type": "macro", "package_name": "waffle_shop", - "path": "models/marts/_sqlbuild/_macros/python/currency.py", - "original_file_path": "models/marts/_sqlbuild/_macros/python/currency.py", + "path": "sql/models/marts/_sqlbuild/_macros/python/currency.py", + "original_file_path": "sql/models/marts/_sqlbuild/_macros/python/currency.py", "unique_id": "macro.waffle_shop.cents_to_dollars", "macro_sql": "\"\"\"Currency formatting macros.\"\"\"\n\n\ndef cents_to_dollars(column: str) -> str:\n \"\"\"Convert a cents integer column to a dollars decimal with two decimal places.\"\"\"\n return f\"ROUND(({column}) / 100.0, 2)\"\n", "depends_on": { @@ -2034,7 +2034,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/marts" + "sqlbuild_scope_path": "sql/models/marts" }, "docs": { "show": true, @@ -2048,8 +2048,8 @@ "name": "timestamp_trunc", "resource_type": "macro", "package_name": "waffle_shop", - "path": "models/marts/_sqlbuild/_macros/python/datetime.py", - "original_file_path": "models/marts/_sqlbuild/_macros/python/datetime.py", + "path": "sql/models/marts/_sqlbuild/_macros/python/datetime.py", + "original_file_path": "sql/models/marts/_sqlbuild/_macros/python/datetime.py", "unique_id": "macro.waffle_shop.timestamp_trunc", "macro_sql": "\"\"\"Datetime portability macros.\"\"\"\n\n\ndef timestamp_trunc(ctx, grain: str, expr: str) -> str:\n if ctx.adapter_name == \"bigquery\":\n return f\"TIMESTAMP_TRUNC({expr}, {grain.upper()})\"\n return f\"DATE_TRUNC('{grain}', {expr})\"\n", "depends_on": { @@ -2058,7 +2058,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/marts" + "sqlbuild_scope_path": "sql/models/marts" }, "docs": { "show": true, diff --git a/tests/goldens/compiler/failure/analysis-accepted-values-type.json b/tests/goldens/compiler/failure/analysis-accepted-values-type.json index 15c849fec9..8fafc38823 100644 --- a/tests/goldens/compiler/failure/analysis-accepted-values-type.json +++ b/tests/goldens/compiler/failure/analysis-accepted-values-type.json @@ -11,11 +11,11 @@ "message": "accepted_values: IN list contains an invalid coercible literal", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 4, "column": 5, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 4, "column": 5 }, @@ -44,20 +44,20 @@ } ], "compiled": { - "audits/generic/customer_totals/accepted_values__customer_id.sql": [ + "sql/audits/generic/customer_totals/accepted_values__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"customer_totals\")", "WHERE customer_id IS NOT NULL", " AND customer_id NOT IN ('DATE', '2026-01-01')", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -71,8 +71,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -150,8 +150,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -221,8 +221,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-aggregate-in-where.json b/tests/goldens/compiler/failure/analysis-aggregate-in-where.json index 9d81027107..2a3c07e4d7 100644 --- a/tests/goldens/compiler/failure/analysis-aggregate-in-where.json +++ b/tests/goldens/compiler/failure/analysis-aggregate-in-where.json @@ -11,11 +11,11 @@ "message": "Aggregate function is not allowed in this clause or inside another aggregate", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "end_line": 7, @@ -27,14 +27,14 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id", "FROM __ref(\"stg_orders\")", "WHERE SUM(amount) > 1", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -48,8 +48,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -117,8 +117,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -188,8 +188,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-alias-column-list-width.json b/tests/goldens/compiler/failure/analysis-alias-column-list-width.json index 119220384a..10882a7117 100644 --- a/tests/goldens/compiler/failure/analysis-alias-column-list-width.json +++ b/tests/goldens/compiler/failure/analysis-alias-column-list-width.json @@ -11,11 +11,11 @@ "message": "Derived-table column alias count exceeds its output column count", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 73, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 73, "end_line": 6, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT o.a AS first_column", "FROM (SELECT order_id, customer_id FROM __ref(\"stg_orders\")) AS o(a, b, c)", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -115,8 +115,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -186,8 +186,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-ambiguous-column.json b/tests/goldens/compiler/failure/analysis-ambiguous-column.json index 56297788ab..d1a88128c9 100644 --- a/tests/goldens/compiler/failure/analysis-ambiguous-column.json +++ b/tests/goldens/compiler/failure/analysis-ambiguous-column.json @@ -11,11 +11,11 @@ "message": "Ambiguous unqualified column 'order_id' found in 2 referenced tables", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 8, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 8, "end_line": 5, @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT order_id", "FROM __ref(\"stg_orders\") a", "JOIN __ref(\"stg_orders\") b ON a.customer_id = b.customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-arithmetic-operands.json b/tests/goldens/compiler/failure/analysis-arithmetic-operands.json index 2c63ae0638..d20a9b55bd 100644 --- a/tests/goldens/compiler/failure/analysis-arithmetic-operands.json +++ b/tests/goldens/compiler/failure/analysis-arithmetic-operands.json @@ -11,11 +11,11 @@ "message": "Arithmetic operation expects NUMERIC-compatible operands, found STRING and INTEGER", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "end_line": 5, @@ -30,12 +30,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, status + 1 AS total_amount", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -49,8 +49,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -118,8 +118,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -189,8 +189,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-cursor-type-family.json b/tests/goldens/compiler/failure/analysis-cursor-type-family.json index 4291b33669..c7a98b81cf 100644 --- a/tests/goldens/compiler/failure/analysis-cursor-type-family.json +++ b/tests/goldens/compiler/failure/analysis-cursor-type-family.json @@ -11,11 +11,11 @@ "message": "cursor_type TIMESTAMP does not match column 'customer_id' type INTEGER", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 15, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 15 }, @@ -25,13 +25,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-duplicate-cte-name.json b/tests/goldens/compiler/failure/analysis-duplicate-cte-name.json index ac30091e30..6e549b4385 100644 --- a/tests/goldens/compiler/failure/analysis-duplicate-cte-name.json +++ b/tests/goldens/compiler/failure/analysis-duplicate-cte-name.json @@ -11,11 +11,11 @@ "message": "Duplicate CTE name 'totals'", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 8, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 8, "end_line": 7, @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "WITH totals AS (SELECT customer_id FROM __ref(\"stg_orders\")),", "totals AS (SELECT customer_id FROM __ref(\"stg_orders\"))", "SELECT customer_id FROM totals", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-expression-audit-unknown-column.json b/tests/goldens/compiler/failure/analysis-expression-audit-unknown-column.json index c34e4d80c9..448c3d689d 100644 --- a/tests/goldens/compiler/failure/analysis-expression-audit-unknown-column.json +++ b/tests/goldens/compiler/failure/analysis-expression-audit-unknown-column.json @@ -11,11 +11,11 @@ "message": "Unknown column 'discount' in output", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 3, "column": 43, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 3, "column": 43 } @@ -27,11 +27,11 @@ "message": "audit 'expression_is_true' on model 'customer_totals': Unknown column 'discount' in table 'customer_totals' (context: WHERE)", "resource_type": "audit", "resource_name": "expression_is_true", - "path": "models/marts/_sqlbuild/_audits/generic/expression_is_true.sql", + "path": "sql/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql", "line": 5, "column": 21, "location": { - "path": "models/marts/_sqlbuild/_audits/generic/expression_is_true.sql", + "path": "sql/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql", "line": 5, "column": 21, "end_line": 6, @@ -42,19 +42,19 @@ } ], "compiled": { - "audits/generic/customer_totals/expression_is_true.sql": [ + "sql/audits/generic/customer_totals/expression_is_true.sql": [ "SELECT *", "FROM __ref(\"customer_totals\")", "WHERE NOT (discount >= 0)", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -68,8 +68,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -137,8 +137,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -208,8 +208,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-function-argument-count.json b/tests/goldens/compiler/failure/analysis-function-argument-count.json index f4a1354727..fd4cff4df3 100644 --- a/tests/goldens/compiler/failure/analysis-function-argument-count.json +++ b/tests/goldens/compiler/failure/analysis-function-argument-count.json @@ -11,11 +11,11 @@ "message": "Invalid arity for function 'SUBSTRING': got 1, expected 2, 3", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 31, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 31, "end_line": 5, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUBSTRING(status) AS total_amount", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -115,8 +115,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -186,8 +186,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-function-argument-type.json b/tests/goldens/compiler/failure/analysis-function-argument-type.json index e9caf69e12..fd3a6835ac 100644 --- a/tests/goldens/compiler/failure/analysis-function-argument-type.json +++ b/tests/goldens/compiler/failure/analysis-function-argument-type.json @@ -11,11 +11,11 @@ "message": "Function 'abs' argument 1 expects NUMERIC, found STRING", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 25, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 25, "end_line": 5, @@ -30,12 +30,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, ABS(status) AS total_amount", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -49,8 +49,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -118,8 +118,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -189,8 +189,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-non-boolean-predicate.json b/tests/goldens/compiler/failure/analysis-non-boolean-predicate.json index 9f30287969..f654808980 100644 --- a/tests/goldens/compiler/failure/analysis-non-boolean-predicate.json +++ b/tests/goldens/compiler/failure/analysis-non-boolean-predicate.json @@ -11,11 +11,11 @@ "message": "WHERE expects a BOOLEAN predicate, found STRING", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "end_line": 7, @@ -30,13 +30,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, amount AS total_amount", "FROM __ref(\"stg_orders\")", "WHERE status", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -50,8 +50,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -119,8 +119,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -190,8 +190,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-non-constant-limit.json b/tests/goldens/compiler/failure/analysis-non-constant-limit.json index 6d7372cef6..e02e13b507 100644 --- a/tests/goldens/compiler/failure/analysis-non-constant-limit.json +++ b/tests/goldens/compiler/failure/analysis-non-constant-limit.json @@ -11,11 +11,11 @@ "message": "LIMIT/OFFSET must be a non-negative constant NUMERIC expression", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "end_line": 7, @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id", "FROM __ref(\"stg_orders\")", "LIMIT customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-rejected-opt-out-hides-findings.json b/tests/goldens/compiler/failure/analysis-rejected-opt-out-hides-findings.json index 4f7a31b683..fc76ca0b6d 100644 --- a/tests/goldens/compiler/failure/analysis-rejected-opt-out-hides-findings.json +++ b/tests/goldens/compiler/failure/analysis-rejected-opt-out-hides-findings.json @@ -11,11 +11,11 @@ "message": "`sql_analysis false` is not needed for model 'customer_totals'", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 3, "column": 3, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 3, "column": 3 }, @@ -28,13 +28,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(refund) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -48,8 +48,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -117,8 +117,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -188,8 +188,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-relationships-unknown-field.json b/tests/goldens/compiler/failure/analysis-relationships-unknown-field.json index eea8403898..597840acdd 100644 --- a/tests/goldens/compiler/failure/analysis-relationships-unknown-field.json +++ b/tests/goldens/compiler/failure/analysis-relationships-unknown-field.json @@ -11,11 +11,11 @@ "message": "relationships target has no column 'customer_key'", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 4, "column": 71, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 4, "column": 71 }, @@ -61,7 +61,7 @@ } ], "compiled": { - "audits/generic/customer_totals/relationships__customer_id.sql": [ + "sql/audits/generic/customer_totals/relationships__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"customer_totals\")", "WHERE customer_id IS NOT NULL", @@ -72,13 +72,13 @@ " )", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -92,8 +92,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -171,8 +171,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -242,8 +242,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-session-cte-chain-unknown-column.json b/tests/goldens/compiler/failure/analysis-session-cte-chain-unknown-column.json index a06ea313c2..76ed10360a 100644 --- a/tests/goldens/compiler/failure/analysis-session-cte-chain-unknown-column.json +++ b/tests/goldens/compiler/failure/analysis-session-cte-chain-unknown-column.json @@ -11,11 +11,11 @@ "message": "Unknown column 'order_count' in totals", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 35, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 35, "end_line": 7, @@ -26,13 +26,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "WITH base AS (SELECT * FROM __ref(\"stg_orders\")),", "totals AS (SELECT customer_id, SUM(amount) AS total_amount FROM base GROUP BY 1)", "SELECT customer_id, total_amount, order_count FROM totals", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -115,8 +115,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -186,8 +186,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-session-cte-fact-nullability.json b/tests/goldens/compiler/failure/analysis-session-cte-fact-nullability.json index 501ce3c08c..c1248959c3 100644 --- a/tests/goldens/compiler/failure/analysis-session-cte-fact-nullability.json +++ b/tests/goldens/compiler/failure/analysis-session-cte-fact-nullability.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "customer_totals", "column_name": "note", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 5, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 5, "end_line": 6, @@ -26,7 +26,7 @@ { "label": "output", "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 14, "column": 40, "end_line": 14, @@ -41,7 +41,7 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "WITH base AS (", " SELECT customer_id, CAST(NULL AS VARCHAR) AS note", " FROM __ref(\"stg_orders\")", @@ -49,7 +49,7 @@ "SELECT customer_id + 0 AS customer_id, note FROM base", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -63,8 +63,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -151,8 +151,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -222,8 +222,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-session-cte-fact-type-mismatch.json b/tests/goldens/compiler/failure/analysis-session-cte-fact-type-mismatch.json index 3e09c1bcdc..1bc0942cda 100644 --- a/tests/goldens/compiler/failure/analysis-session-cte-fact-type-mismatch.json +++ b/tests/goldens/compiler/failure/analysis-session-cte-fact-type-mismatch.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "customer_totals", "column_name": "total_amount", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 5, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 5, "end_line": 6, @@ -26,7 +26,7 @@ { "label": "output", "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 14, "column": 40, "end_line": 14, @@ -41,7 +41,7 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "WITH totals AS (", " SELECT customer_id, CAST(amount AS DOUBLE) AS total_amount", " FROM __ref(\"stg_orders\")", @@ -49,7 +49,7 @@ "SELECT customer_id + 0 AS customer_id, total_amount FROM totals", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -63,8 +63,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -151,8 +151,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -222,8 +222,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-session-enriched-subquery-type-mismatch.json b/tests/goldens/compiler/failure/analysis-session-enriched-subquery-type-mismatch.json index 346bfa9476..3987000e5a 100644 --- a/tests/goldens/compiler/failure/analysis-session-enriched-subquery-type-mismatch.json +++ b/tests/goldens/compiler/failure/analysis-session-enriched-subquery-type-mismatch.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "customer_totals", "column_name": "amount", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 5, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 5, "end_line": 6, @@ -26,7 +26,7 @@ { "label": "output", "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 10, "column": 21, "end_line": 10, @@ -41,12 +41,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, amount", "FROM (SELECT * FROM __ref(\"stg_orders\")) staged", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -60,8 +60,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -148,8 +148,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -219,8 +219,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-session-pivot-family-column-mismatch.json b/tests/goldens/compiler/failure/analysis-session-pivot-family-column-mismatch.json index c4e0b17259..6a62562684 100644 --- a/tests/goldens/compiler/failure/analysis-session-pivot-family-column-mismatch.json +++ b/tests/goldens/compiler/failure/analysis-session-pivot-family-column-mismatch.json @@ -11,27 +11,27 @@ "message": "model 'status_amounts' dynamic column contract is not proven: dynamic family 'status_amounts' declares pivot_column 'region' but the output pivot uses 'status'", "resource_type": "model", "resource_name": "status_amounts", - "path": "models/marts/status_amounts.sql", + "path": "sql/models/marts/status_amounts.sql", "help": "project one supported runtime-dynamic pivot through a wildcard output boundary and declare every generated family" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/marts/status_amounts.sql": [ + "sql/models/marts/status_amounts.sql": [ "PIVOT __source(\"raw_orders\")", "ON status", "USING MAX(amount)", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "status_amounts", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/status_amounts.sql", - "original_file_path": "models/marts/status_amounts.sql", + "path": "sql/models/marts/status_amounts.sql", + "original_file_path": "sql/models/marts/status_amounts.sql", "unique_id": "model.failure_corpus.status_amounts", "fqn": [ "failure_corpus", @@ -206,8 +206,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -277,8 +277,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-session-pivot-values-on-clause.json b/tests/goldens/compiler/failure/analysis-session-pivot-values-on-clause.json index 830a05d90f..13d81f93b5 100644 --- a/tests/goldens/compiler/failure/analysis-session-pivot-values-on-clause.json +++ b/tests/goldens/compiler/failure/analysis-session-pivot-values-on-clause.json @@ -11,27 +11,27 @@ "message": "model 'status_amounts' dynamic column contract is not proven: dynamic column contracts currently require exactly one pivot column", "resource_type": "model", "resource_name": "status_amounts", - "path": "models/marts/status_amounts.sql", + "path": "sql/models/marts/status_amounts.sql", "help": "project one supported runtime-dynamic pivot through a wildcard output boundary and declare every generated family" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/marts/status_amounts.sql": [ + "sql/models/marts/status_amounts.sql": [ "PIVOT __source(\"raw_orders\")", "ON status IN ('placed')", "USING MAX(amount)", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "status_amounts", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/status_amounts.sql", - "original_file_path": "models/marts/status_amounts.sql", + "path": "sql/models/marts/status_amounts.sql", + "original_file_path": "sql/models/marts/status_amounts.sql", "unique_id": "model.failure_corpus.status_amounts", "fqn": [ "failure_corpus", @@ -206,8 +206,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -277,8 +277,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-session-set-operation-unknown-column.json b/tests/goldens/compiler/failure/analysis-session-set-operation-unknown-column.json index 3ad0352ce1..75db308250 100644 --- a/tests/goldens/compiler/failure/analysis-session-set-operation-unknown-column.json +++ b/tests/goldens/compiler/failure/analysis-session-set-operation-unknown-column.json @@ -11,11 +11,11 @@ "message": "Unknown column 'refund_amount' in stg_orders", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 21, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 21, "end_line": 7, @@ -29,13 +29,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, amount AS total_amount FROM __ref(\"stg_orders\")", "UNION ALL", "SELECT customer_id, refund_amount FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -49,8 +49,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -118,8 +118,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -189,8 +189,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-session-star-published-unknown-column.json b/tests/goldens/compiler/failure/analysis-session-star-published-unknown-column.json index 496a2c776b..58f7b9d1d5 100644 --- a/tests/goldens/compiler/failure/analysis-session-star-published-unknown-column.json +++ b/tests/goldens/compiler/failure/analysis-session-star-published-unknown-column.json @@ -11,11 +11,11 @@ "message": "Unknown column 'missing_amount' in order_layers", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 25, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 25, "end_line": 5, @@ -29,18 +29,18 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(missing_amount) AS total_amount", "FROM __ref(\"order_layers\")", "GROUP BY customer_id", "" ], - "models/marts/order_layers.sql": [ + "sql/models/marts/order_layers.sql": [ "SELECT s.*, s.amount * 2 AS doubled_amount", "FROM __ref(\"stg_orders\") s", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT *", "FROM __source(\"raw_orders\")", "" @@ -54,8 +54,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -123,8 +123,8 @@ "name": "order_layers", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/order_layers.sql", - "original_file_path": "models/marts/order_layers.sql", + "path": "sql/models/marts/order_layers.sql", + "original_file_path": "sql/models/marts/order_layers.sql", "unique_id": "model.failure_corpus.order_layers", "fqn": [ "failure_corpus", @@ -192,8 +192,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -263,8 +263,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-set-operation-branch-types.json b/tests/goldens/compiler/failure/analysis-set-operation-branch-types.json index a4037c2270..6038246ab9 100644 --- a/tests/goldens/compiler/failure/analysis-set-operation-branch-types.json +++ b/tests/goldens/compiler/failure/analysis-set-operation-branch-types.json @@ -11,11 +11,11 @@ "message": "UNION column 2 has incompatible types: NUMERIC vs DATE", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 1, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 1 }, @@ -25,13 +25,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, amount FROM __ref(\"stg_orders\")", "UNION ALL", "SELECT customer_id, DATE '2026-01-01' FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -185,8 +185,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-sqlite-temporal-cast.json b/tests/goldens/compiler/failure/analysis-sqlite-temporal-cast.json index 3de33d2fe5..1a25fc34f6 100644 --- a/tests/goldens/compiler/failure/analysis-sqlite-temporal-cast.json +++ b/tests/goldens/compiler/failure/analysis-sqlite-temporal-cast.json @@ -11,11 +11,11 @@ "message": "Unknown column 'missing' in stg_orders", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 64, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 64, "end_line": 5, @@ -32,11 +32,11 @@ "message": "SQLite casts to TIMESTAMP with NUMERIC affinity and keeps only the leading number, so '2026-01-01 10:00:00' becomes 2026", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "end_line": 5, @@ -48,12 +48,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, CAST(amount AS TIMESTAMP) AS total_amount, missing", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -67,8 +67,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -136,8 +136,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -207,8 +207,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-test-fixture-unknown-column.json b/tests/goldens/compiler/failure/analysis-test-fixture-unknown-column.json index a984fd998d..bb1e9f598a 100644 --- a/tests/goldens/compiler/failure/analysis-test-fixture-unknown-column.json +++ b/tests/goldens/compiler/failure/analysis-test-fixture-unknown-column.json @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -56,8 +56,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -125,8 +125,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -196,8 +196,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-udf-argument-count.json b/tests/goldens/compiler/failure/analysis-udf-argument-count.json index 58323fe460..c86d42ffe4 100644 --- a/tests/goldens/compiler/failure/analysis-udf-argument-count.json +++ b/tests/goldens/compiler/failure/analysis-udf-argument-count.json @@ -11,11 +11,11 @@ "message": "Function 'scaled_amount' expects 2 arguments but received 1", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 28, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 28 }, @@ -25,18 +25,18 @@ } ], "compiled": { - "functions/sql/scaled_amount.sql": [ + "sql/functions/sql/scaled_amount.sql": [ "CREATE OR REPLACE MACRO main.scaled_amount(p_amount, p_factor) AS (", "p_amount * p_factor", ")", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, __udf(\"scaled_amount\")(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -50,8 +50,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -120,8 +120,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -191,8 +191,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-udf-argument-family.json b/tests/goldens/compiler/failure/analysis-udf-argument-family.json index 945bc8950d..0d69c1971c 100644 --- a/tests/goldens/compiler/failure/analysis-udf-argument-family.json +++ b/tests/goldens/compiler/failure/analysis-udf-argument-family.json @@ -11,11 +11,11 @@ "message": "Function 'scaled_amount' argument 'p_amount' expects DOUBLE, received VARCHAR; convert the argument explicitly", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 28, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 28 }, @@ -25,18 +25,18 @@ } ], "compiled": { - "functions/sql/scaled_amount.sql": [ + "sql/functions/sql/scaled_amount.sql": [ "CREATE OR REPLACE MACRO main.scaled_amount(p_amount, p_factor) AS (", "p_amount * p_factor", ")", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, __udf(\"scaled_amount\")(status, 2) AS total_amount", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -50,8 +50,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -120,8 +120,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -191,8 +191,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-unique-key-unknown-column.json b/tests/goldens/compiler/failure/analysis-unique-key-unknown-column.json index ca04c7c838..caa37c75cf 100644 --- a/tests/goldens/compiler/failure/analysis-unique-key-unknown-column.json +++ b/tests/goldens/compiler/failure/analysis-unique-key-unknown-column.json @@ -11,11 +11,11 @@ "message": "unique_key references unknown column 'order_key'", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 4, "column": 15, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 4, "column": 15 }, @@ -25,13 +25,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-unknown-function.json b/tests/goldens/compiler/failure/analysis-unknown-function.json index f421777a0b..1ab5f9622d 100644 --- a/tests/goldens/compiler/failure/analysis-unknown-function.json +++ b/tests/goldens/compiler/failure/analysis-unknown-function.json @@ -11,11 +11,11 @@ "message": "Unknown function 'not_a_function' for dialect DuckDB", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "end_line": 5, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, not_a_function(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -115,8 +115,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -186,8 +186,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-unknown-qualifier.json b/tests/goldens/compiler/failure/analysis-unknown-qualifier.json index a9ba57f63f..208dcd5e35 100644 --- a/tests/goldens/compiler/failure/analysis-unknown-qualifier.json +++ b/tests/goldens/compiler/failure/analysis-unknown-qualifier.json @@ -11,11 +11,11 @@ "message": "Unknown table or alias 'x' referenced by column 'order_id'", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 8, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 8, "end_line": 5, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT x.order_id", "FROM __ref(\"stg_orders\") o", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -115,8 +115,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -186,8 +186,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-unsupported-cast.json b/tests/goldens/compiler/failure/analysis-unsupported-cast.json index 413dbe4691..84a8e316b6 100644 --- a/tests/goldens/compiler/failure/analysis-unsupported-cast.json +++ b/tests/goldens/compiler/failure/analysis-unsupported-cast.json @@ -11,11 +11,11 @@ "message": "Invalid temporal literal", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "end_line": 5, @@ -30,12 +30,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, DATE '2026-13-45' AS placed_on", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -49,8 +49,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -118,8 +118,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -189,8 +189,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-unsupported-truth-test.json b/tests/goldens/compiler/failure/analysis-unsupported-truth-test.json index f9ac66d232..0c382f6d13 100644 --- a/tests/goldens/compiler/failure/analysis-unsupported-truth-test.json +++ b/tests/goldens/compiler/failure/analysis-unsupported-truth-test.json @@ -11,11 +11,11 @@ "message": "'IS NOT TRUE' is not supported for dialect Snowflake; write NOT COALESCE(, FALSE) or IS DISTINCT FROM TRUE", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 20, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 20, "end_line": 7, @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, amount AS total_amount", "FROM __ref(\"stg_orders\")", "WHERE (amount > 1) IS NOT TRUE", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/analysis-window-without-over.json b/tests/goldens/compiler/failure/analysis-window-without-over.json index c4ea9ab5f9..1a86031888 100644 --- a/tests/goldens/compiler/failure/analysis-window-without-over.json +++ b/tests/goldens/compiler/failure/analysis-window-without-over.json @@ -11,11 +11,11 @@ "message": "Window function requires an OVER clause", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "end_line": 5, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, ROW_NUMBER() AS position", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -115,8 +115,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -186,8 +186,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/attached-audit-reads-dependant.json b/tests/goldens/compiler/failure/attached-audit-reads-dependant.json index e49035df7a..155bd41313 100644 --- a/tests/goldens/compiler/failure/attached-audit-reads-dependant.json +++ b/tests/goldens/compiler/failure/attached-audit-reads-dependant.json @@ -11,26 +11,26 @@ "message": "Audit 'matches_totals' on model 'stg_orders' reads model 'customer_totals', which depends on 'stg_orders'; an attached audit gates its target, so it cannot wait for a resource built from that target", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/_sqlbuild/_audits/generic/matches_totals.sql", + "path": "sql/models/staging/_sqlbuild/_audits/generic/matches_totals.sql", "help": "write a singular audit under audits/singular/ that references both 'stg_orders' and 'customer_totals'; it runs once both are built" } ] } ], "compiled": { - "audits/generic/stg_orders/matches_totals.sql": [ + "sql/audits/generic/stg_orders/matches_totals.sql": [ "SELECT *", "FROM __ref(\"stg_orders\") o", "WHERE o.customer_id NOT IN (SELECT customer_id FROM __ref(\"customer_totals\"))", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -44,8 +44,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -113,8 +113,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -184,8 +184,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/audit-parse.json b/tests/goldens/compiler/failure/audit-parse.json index 2804df5d96..5adb0884c0 100644 --- a/tests/goldens/compiler/failure/audit-parse.json +++ b/tests/goldens/compiler/failure/audit-parse.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D004", - "message": "AUDIT(...) in '/models/marts/_sqlbuild/audits/singular/broken.sql' contains invalid SQLBuild header syntax: unexpected token 'name' without a value; quote values with spaces" + "message": "AUDIT(...) in '/sql/models/marts/_sqlbuild/audits/singular/broken.sql' contains invalid SQLBuild header syntax: unexpected token 'name' without a value; quote values with spaces" } ] } diff --git a/tests/goldens/compiler/failure/audit-role-unsupported-entry.json b/tests/goldens/compiler/failure/audit-role-unsupported-entry.json index 9d174e5294..2ca0a957e9 100644 --- a/tests/goldens/compiler/failure/audit-role-unsupported-entry.json +++ b/tests/goldens/compiler/failure/audit-role-unsupported-entry.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "Unsupported entries in audits/: audits/at_least.sql; audit files must live in audits/generic/ or audits/singular/" + "message": "Unsupported entries in sql/audits/: sql/audits/at_least.sql; audit files must live in sql/audits/generic/ or sql/audits/singular/" } ] } diff --git a/tests/goldens/compiler/failure/audit-unknown-project-variable.json b/tests/goldens/compiler/failure/audit-unknown-project-variable.json index 3525ad0f6b..74148ea079 100644 --- a/tests/goldens/compiler/failure/audit-unknown-project-variable.json +++ b/tests/goldens/compiler/failure/audit-unknown-project-variable.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "unknown project variable '@@floor_amount' in '/models/staging/_sqlbuild/_audits/generic/floor.sql'. Available vars: region" + "message": "unknown project variable '@@floor_amount' in '/sql/models/staging/_sqlbuild/_audits/generic/floor.sql'. Available vars: region" } ] } diff --git a/tests/goldens/compiler/failure/audit-variable-in-doubled-backticks.json b/tests/goldens/compiler/failure/audit-variable-in-doubled-backticks.json index 3525ad0f6b..74148ea079 100644 --- a/tests/goldens/compiler/failure/audit-variable-in-doubled-backticks.json +++ b/tests/goldens/compiler/failure/audit-variable-in-doubled-backticks.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "unknown project variable '@@floor_amount' in '/models/staging/_sqlbuild/_audits/generic/floor.sql'. Available vars: region" + "message": "unknown project variable '@@floor_amount' in '/sql/models/staging/_sqlbuild/_audits/generic/floor.sql'. Available vars: region" } ] } diff --git a/tests/goldens/compiler/failure/built-in-audit-shadow.json b/tests/goldens/compiler/failure/built-in-audit-shadow.json index eda200b8ff..203b9c9a35 100644 --- a/tests/goldens/compiler/failure/built-in-audit-shadow.json +++ b/tests/goldens/compiler/failure/built-in-audit-shadow.json @@ -9,21 +9,21 @@ "severity": "warning", "code": "P003", "message": "project audit 'not_null' overrides built-in audit 'not_null'", - "path": "models/staging/_sqlbuild/_audits/generic/not_null.sql", + "path": "sql/models/staging/_sqlbuild/_audits/generic/not_null.sql", "help": "rename the project audit if this override is unintended" }, { "phase": "compile", "severity": "error", "code": "S010", - "message": "Unused local declaration 'audit:not_null' at models/staging/_sqlbuild/_audits/generic/not_null.sql; remove it or add a genuine runtime use", + "message": "Unused local declaration 'audit:not_null' at sql/models/staging/_sqlbuild/_audits/generic/not_null.sql; remove it or add a genuine runtime use", "resource_type": "audit", "resource_name": "not_null", - "path": "models/staging/_sqlbuild/_audits/generic/not_null.sql", + "path": "sql/models/staging/_sqlbuild/_audits/generic/not_null.sql", "line": 1, "column": 1, "location": { - "path": "models/staging/_sqlbuild/_audits/generic/not_null.sql", + "path": "sql/models/staging/_sqlbuild/_audits/generic/not_null.sql", "line": 1, "column": 1 } @@ -32,13 +32,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -52,8 +52,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -121,8 +121,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -192,8 +192,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/column-nullable-not-null.json b/tests/goldens/compiler/failure/column-nullable-not-null.json index 967e247e56..cce759d32f 100644 --- a/tests/goldens/compiler/failure/column-nullable-not-null.json +++ b/tests/goldens/compiler/failure/column-nullable-not-null.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P002", - "message": "models/staging/stg_orders.sql column 'order_id' cannot set nullable = true and audit not_null", + "message": "sql/models/staging/stg_orders.sql column 'order_id' cannot set nullable = true and audit not_null", "help": "remove the not_null audit or set nullable = false" } ] diff --git a/tests/goldens/compiler/failure/command-output-sink-unknown-provider.json b/tests/goldens/compiler/failure/command-output-sink-unknown-provider.json index 9fb21e36bd..05c7cead59 100644 --- a/tests/goldens/compiler/failure/command-output-sink-unknown-provider.json +++ b/tests/goldens/compiler/failure/command-output-sink-unknown-provider.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D015", - "message": "Command-output sink 'publish_output' in sinks/output.py requires unknown provider 'destination_client'" + "message": "Command-output sink 'publish_output' in python/event_sinks/output.py requires unknown provider 'destination_client'" } ] } diff --git a/tests/goldens/compiler/failure/commented-ref-argument.json b/tests/goldens/compiler/failure/commented-ref-argument.json index c4d7ff89d0..9caad3e626 100644 --- a/tests/goldens/compiler/failure/commented-ref-argument.json +++ b/tests/goldens/compiler/failure/commented-ref-argument.json @@ -11,11 +11,11 @@ "message": "__ref( /* upstream */ 'stg_orders') is not a valid __ref() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref( /* upstream */ 'stg_orders')", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -185,8 +185,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/comparison-type.json b/tests/goldens/compiler/failure/comparison-type.json index 51fbf222ca..bf73527e0d 100644 --- a/tests/goldens/compiler/failure/comparison-type.json +++ b/tests/goldens/compiler/failure/comparison-type.json @@ -11,11 +11,11 @@ "message": "Incompatible comparison between NUMERIC and DATE", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "end_line": 7, @@ -30,14 +30,14 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "WHERE amount = DATE '2026-01-01'", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -51,8 +51,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -120,8 +120,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -191,8 +191,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/config-unknown-adapter.json b/tests/goldens/compiler/failure/config-unknown-adapter.json index 8ebcdfe9d3..61d83caba6 100644 --- a/tests/goldens/compiler/failure/config-unknown-adapter.json +++ b/tests/goldens/compiler/failure/config-unknown-adapter.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "C601", - "message": "unknown adapter 'warehouse9000'. Available built-in adapters: bigquery, clickhouse, databricks, duckdb, motherduck, postgres, snowflake, sqlite, sqlserver. Project-local adapters are discovered from adapters/**/*.py." + "message": "unknown adapter 'warehouse9000'. Available built-in adapters: bigquery, clickhouse, databricks, duckdb, motherduck, postgres, snowflake, sqlite, sqlserver. Project-local adapters are discovered from python/adapters/**/*.py." } ] } diff --git a/tests/goldens/compiler/failure/config-unknown-model-reference.json b/tests/goldens/compiler/failure/config-unknown-model-reference.json index e30c3b4ce0..4d209dfc39 100644 --- a/tests/goldens/compiler/failure/config-unknown-model-reference.json +++ b/tests/goldens/compiler/failure/config-unknown-model-reference.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Model file models/marts/customer_totals.sql references unknown model 'stg_refunds'" + "message": "Model file sql/models/marts/customer_totals.sql references unknown model 'stg_refunds'" } ] } diff --git a/tests/goldens/compiler/failure/constant-header-nested-too-deep.json b/tests/goldens/compiler/failure/constant-header-nested-too-deep.json index 766c4e1b73..1184ebeba3 100644 --- a/tests/goldens/compiler/failure/constant-header-nested-too-deep.json +++ b/tests/goldens/compiler/failure/constant-header-nested-too-deep.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "CONSTANT(...) in '/models/staging/_sqlbuild/_constants/statuses.sql:1' contains invalid SQLBuild header syntax: values nest deeper than 256 levels", + "message": "CONSTANT(...) in '/sql/models/staging/_sqlbuild/_constants/statuses.sql:1' contains invalid SQLBuild header syntax: values nest deeper than 256 levels", "help": "flatten the value so it nests at most 256 levels deep" } ] diff --git a/tests/goldens/compiler/failure/context-variable-in-model-sql.json b/tests/goldens/compiler/failure/context-variable-in-model-sql.json index 7f1b08f4cf..f94bd9b60d 100644 --- a/tests/goldens/compiler/failure/context-variable-in-model-sql.json +++ b/tests/goldens/compiler/failure/context-variable-in-model-sql.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL text in '/models/staging/stg_orders.sql' does not allow @@CTX templates" + "message": "SQL text in '/sql/models/staging/stg_orders.sql' does not allow @@CTX templates" } ] } diff --git a/tests/goldens/compiler/failure/contract-dynamic-columns-unproven.json b/tests/goldens/compiler/failure/contract-dynamic-columns-unproven.json index fc9632ced7..36ad53081d 100644 --- a/tests/goldens/compiler/failure/contract-dynamic-columns-unproven.json +++ b/tests/goldens/compiler/failure/contract-dynamic-columns-unproven.json @@ -11,21 +11,21 @@ "message": "model 'customer_totals' dynamic column contract is not proven: dynamic pivot input does not have an authoritative, explicit schema", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "help": "project one supported runtime-dynamic pivot through a wildcard output boundary and declare every generated family" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "PIVOT __ref(\"stg_orders\")", "ON status", "USING MAX(amount)", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -39,8 +39,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -131,8 +131,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -202,8 +202,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-dynamic-columns-unsupported-dialect.json b/tests/goldens/compiler/failure/contract-dynamic-columns-unsupported-dialect.json index 2d8a604087..b0b110729b 100644 --- a/tests/goldens/compiler/failure/contract-dynamic-columns-unsupported-dialect.json +++ b/tests/goldens/compiler/failure/contract-dynamic-columns-unsupported-dialect.json @@ -11,20 +11,20 @@ "message": "model 'customer_totals' dynamic column contract is not proven: adapter dialect 'postgresql' does not support compiler-proven dynamic pivots", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "help": "project one supported runtime-dynamic pivot through a wildcard output boundary and declare every generated family" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, MAX(amount) AS placed", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -38,8 +38,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -130,8 +130,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -201,8 +201,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-dynamic-family-type-mismatch.json b/tests/goldens/compiler/failure/contract-dynamic-family-type-mismatch.json index fda60c4471..50a4ebc9ed 100644 --- a/tests/goldens/compiler/failure/contract-dynamic-family-type-mismatch.json +++ b/tests/goldens/compiler/failure/contract-dynamic-family-type-mismatch.json @@ -11,21 +11,21 @@ "message": "dynamic column family 'status_amounts' inferred as DOUBLE but declared type is VARCHAR", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "help": "correct the family type or the pivot aggregate input type" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "PIVOT __ref(\"stg_orders\")", "ON status", "USING MAX(amount)", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT CAST(order_id AS INTEGER) AS order_id,", " CAST(customer_id AS INTEGER) AS customer_id,", " CAST(amount AS DOUBLE) AS amount, CAST(status AS VARCHAR) AS status", @@ -41,8 +41,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -133,8 +133,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -241,8 +241,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-enum-literal.json b/tests/goldens/compiler/failure/contract-enum-literal.json index d535e52379..94df58370a 100644 --- a/tests/goldens/compiler/failure/contract-enum-literal.json +++ b/tests/goldens/compiler/failure/contract-enum-literal.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "status", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 39, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 39, "end_line": 12, @@ -28,20 +28,20 @@ } ], "compiled": { - "audits/generic/stg_orders/accepted_values__status.sql": [ + "sql/audits/generic/stg_orders/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"stg_orders\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'shipped')", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, 'held' AS status", "FROM __source(\"raw_orders\")", "" @@ -55,8 +55,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -124,8 +124,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -232,8 +232,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-errors-across-models.json b/tests/goldens/compiler/failure/contract-errors-across-models.json index 76a591bf7f..0652d3064b 100644 --- a/tests/goldens/compiler/failure/contract-errors-across-models.json +++ b/tests/goldens/compiler/failure/contract-errors-across-models.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "typed_totals", "column_name": "total_amount", - "path": "models/marts/typed_totals.sql", + "path": "sql/models/marts/typed_totals.sql", "line": 3, "column": 12, "location": { - "path": "models/marts/typed_totals.sql", + "path": "sql/models/marts/typed_totals.sql", "line": 3, "column": 12, "end_line": 3, @@ -26,7 +26,7 @@ { "label": "output", "location": { - "path": "models/marts/typed_totals.sql", + "path": "sql/models/marts/typed_totals.sql", "line": 6, "column": 8, "end_line": 6, @@ -44,24 +44,24 @@ "message": "model 'stg_orders' has contract enforced but declares no columns", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "help": "add MODEL(columns (...)), declare a proven MODEL(dynamic_columns (...)) family, or set contract none for this model" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, CAST(SUM(amount) AS VARCHAR) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/marts/typed_totals.sql": [ + "sql/models/marts/typed_totals.sql": [ "SELECT CAST(1.5 AS DOUBLE) AS total_amount", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -75,8 +75,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -144,8 +144,8 @@ "name": "typed_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/typed_totals.sql", - "original_file_path": "models/marts/typed_totals.sql", + "path": "sql/models/marts/typed_totals.sql", + "original_file_path": "sql/models/marts/typed_totals.sql", "unique_id": "model.failure_corpus.typed_totals", "fqn": [ "failure_corpus", @@ -221,8 +221,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -292,8 +292,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-extra-column.json b/tests/goldens/compiler/failure/contract-extra-column.json index b67d98b5f4..01d94906b1 100644 --- a/tests/goldens/compiler/failure/contract-extra-column.json +++ b/tests/goldens/compiler/failure/contract-extra-column.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "status", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 11, "column": 39, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 11, "column": 39, "end_line": 11, @@ -28,13 +28,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -48,8 +48,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -117,8 +117,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -216,8 +216,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-immediate-promotion-several-models.json b/tests/goldens/compiler/failure/contract-immediate-promotion-several-models.json index c6fab88b86..adeed15ee8 100644 --- a/tests/goldens/compiler/failure/contract-immediate-promotion-several-models.json +++ b/tests/goldens/compiler/failure/contract-immediate-promotion-several-models.json @@ -11,20 +11,20 @@ "message": "model 'customer_totals': contract enforced requires staged table promotion; immediate table promotion cannot validate runtime output before target mutation", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "help": "sqlbuild_project.toml sets [settings] table_promotion_mode = \"immediate\"; enforced contracts are validated in a staging table before promotion\n = help: remove that line to use the default staged promotion, or set this in sqlbuild_project.toml:\n [settings]\n table_promotion_mode = \"staged\"\n = help: or remove the model's enforced contract: `contract enforced` in its MODEL header, or `contract = \"enforced\"` in the [defaults] or [path_defaults] entry that applies to it" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -38,8 +38,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -126,8 +126,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -234,8 +234,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-immediate-promotion.json b/tests/goldens/compiler/failure/contract-immediate-promotion.json index e6761a433d..c4fb4f8ad4 100644 --- a/tests/goldens/compiler/failure/contract-immediate-promotion.json +++ b/tests/goldens/compiler/failure/contract-immediate-promotion.json @@ -11,20 +11,20 @@ "message": "model 'stg_orders': contract enforced requires staged table promotion; immediate table promotion cannot validate runtime output before target mutation", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "help": "sqlbuild_project.toml sets [settings] table_promotion_mode = \"immediate\"; enforced contracts are validated in a staging table before promotion\n = help: remove that line to use the default staged promotion, or set this in sqlbuild_project.toml:\n [settings]\n table_promotion_mode = \"staged\"\n = help: or remove the model's enforced contract: `contract enforced` in its MODEL header, or `contract = \"enforced\"` in the [defaults] or [path_defaults] entry that applies to it" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -38,8 +38,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -107,8 +107,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -215,8 +215,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-implicit-missing-column.json b/tests/goldens/compiler/failure/contract-implicit-missing-column.json index 5e7e902f31..aed430ab14 100644 --- a/tests/goldens/compiler/failure/contract-implicit-missing-column.json +++ b/tests/goldens/compiler/failure/contract-implicit-missing-column.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "customer_totals", "column_name": "order_count", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 5, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 5, "end_line": 6, @@ -28,13 +28,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -48,8 +48,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -145,8 +145,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -216,8 +216,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-local-immediate-promotion.json b/tests/goldens/compiler/failure/contract-local-immediate-promotion.json index ffbc3c59c3..ee7bacf957 100644 --- a/tests/goldens/compiler/failure/contract-local-immediate-promotion.json +++ b/tests/goldens/compiler/failure/contract-local-immediate-promotion.json @@ -11,20 +11,20 @@ "message": "model 'stg_orders': contract enforced requires staged table promotion; immediate table promotion cannot validate runtime output before target mutation", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "help": "sqlbuild_local.toml sets [settings] table_promotion_mode = \"immediate\"; enforced contracts are validated in a staging table before promotion\n = help: remove that line to use the default staged promotion, or set this in sqlbuild_local.toml:\n [settings]\n table_promotion_mode = \"staged\"\n = help: or remove the model's enforced contract: `contract enforced` in its MODEL header, or `contract = \"enforced\"` in the [defaults] or [path_defaults] entry that applies to it" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -38,8 +38,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -107,8 +107,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -215,8 +215,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-missing-column.json b/tests/goldens/compiler/failure/contract-missing-column.json index 4569eb6cb6..4b2fc0ca20 100644 --- a/tests/goldens/compiler/failure/contract-missing-column.json +++ b/tests/goldens/compiler/failure/contract-missing-column.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "discount", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 9, "column": 5, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 9, "column": 5, "end_line": 9, @@ -28,13 +28,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -48,8 +48,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -117,8 +117,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -234,8 +234,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-named-schema-columns.json b/tests/goldens/compiler/failure/contract-named-schema-columns.json index 6c70207613..79d4a43541 100644 --- a/tests/goldens/compiler/failure/contract-named-schema-columns.json +++ b/tests/goldens/compiler/failure/contract-named-schema-columns.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "status", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 7, "column": 39, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 7, "column": 39, "end_line": 7, @@ -32,11 +32,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "shipped_at", - "path": "models/staging/_sqlbuild/_schemas/staged_order.sql", + "path": "sql/models/staging/_sqlbuild/_schemas/staged_order.sql", "line": 8, "column": 5, "location": { - "path": "models/staging/_sqlbuild/_schemas/staged_order.sql", + "path": "sql/models/staging/_sqlbuild/_schemas/staged_order.sql", "line": 8, "column": 5, "end_line": 8, @@ -48,13 +48,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -68,8 +68,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -137,8 +137,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -245,8 +245,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-nullability.json b/tests/goldens/compiler/failure/contract-nullability.json index b76fd7bb4e..a992c81565 100644 --- a/tests/goldens/compiler/failure/contract-nullability.json +++ b/tests/goldens/compiler/failure/contract-nullability.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "customer_id", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 5, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 5, "end_line": 6, @@ -26,7 +26,7 @@ { "label": "output", "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 18, "end_line": 12, @@ -41,13 +41,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, CAST(NULL AS INTEGER) AS customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -61,8 +61,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -130,8 +130,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -238,8 +238,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-order-every-column-family.json b/tests/goldens/compiler/failure/contract-order-every-column-family.json index 8726fb269d..b2f6591a0f 100644 --- a/tests/goldens/compiler/failure/contract-order-every-column-family.json +++ b/tests/goldens/compiler/failure/contract-order-every-column-family.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "status", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 64, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 64, "end_line": 12, @@ -32,11 +32,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "order_id", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 5, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 5, "end_line": 5, @@ -46,7 +46,7 @@ { "label": "output", "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 8, "end_line": 12, @@ -65,11 +65,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "customer_id", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 5, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 5, "end_line": 6, @@ -79,7 +79,7 @@ { "label": "output", "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 18, "end_line": 12, @@ -98,11 +98,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "shipped_at", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 7, "column": 5, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 7, "column": 5, "end_line": 7, @@ -114,13 +114,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, CAST(NULL AS INTEGER) AS customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -134,8 +134,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -203,8 +203,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -311,8 +311,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-type-mismatch.json b/tests/goldens/compiler/failure/contract-type-mismatch.json index b02987306e..5c45392d89 100644 --- a/tests/goldens/compiler/failure/contract-type-mismatch.json +++ b/tests/goldens/compiler/failure/contract-type-mismatch.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "order_id", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 5, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 5, "end_line": 5, @@ -26,7 +26,7 @@ { "label": "output", "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 8, "end_line": 12, @@ -41,13 +41,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -61,8 +61,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -130,8 +130,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -238,8 +238,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-unknown-type.json b/tests/goldens/compiler/failure/contract-unknown-type.json index c0d4f7a6f1..cb38f4c533 100644 --- a/tests/goldens/compiler/failure/contract-unknown-type.json +++ b/tests/goldens/compiler/failure/contract-unknown-type.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "order_id", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 4, "column": 5, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 4, "column": 5, "end_line": 4, @@ -26,7 +26,7 @@ { "label": "output", "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 8, "column": 8, "end_line": 8, @@ -41,13 +41,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -61,8 +61,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -130,8 +130,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -211,8 +211,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/contract-without-columns.json b/tests/goldens/compiler/failure/contract-without-columns.json index 480749a518..227c164afb 100644 --- a/tests/goldens/compiler/failure/contract-without-columns.json +++ b/tests/goldens/compiler/failure/contract-without-columns.json @@ -11,20 +11,20 @@ "message": "model 'stg_orders' has contract enforced but declares no columns", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "help": "add MODEL(columns (...)), declare a proven MODEL(dynamic_columns (...)) family, or set contract none for this model" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -38,8 +38,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -107,8 +107,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -178,8 +178,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/cursor-model-without-inputs.json b/tests/goldens/compiler/failure/cursor-model-without-inputs.json index 8fed1f1c08..c09deb7ce2 100644 --- a/tests/goldens/compiler/failure/cursor-model-without-inputs.json +++ b/tests/goldens/compiler/failure/cursor-model-without-inputs.json @@ -11,11 +11,11 @@ "message": "incremental model 'customer_totals' reads no inputs, so builds after the first cannot work out their cursor window", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 3, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 3, "end_line": 5, @@ -27,11 +27,11 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT TIMESTAMP '2026-01-01 00:00:00' AS placed_at, 1 AS customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -112,8 +112,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -183,8 +183,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/cursor-unknown-column.json b/tests/goldens/compiler/failure/cursor-unknown-column.json index f614aa5ce4..3821664ed6 100644 --- a/tests/goldens/compiler/failure/cursor-unknown-column.json +++ b/tests/goldens/compiler/failure/cursor-unknown-column.json @@ -11,11 +11,11 @@ "message": "cursor references unknown column 'placed_at'", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 10, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 10 }, @@ -25,13 +25,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -185,8 +185,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/dbt-reference-without-manifest.json b/tests/goldens/compiler/failure/dbt-reference-without-manifest.json index 6f3b715373..dbfe5dbf29 100644 --- a/tests/goldens/compiler/failure/dbt-reference-without-manifest.json +++ b/tests/goldens/compiler/failure/dbt-reference-without-manifest.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "C214", - "message": "Model file models/marts/customer_totals.sql uses __dbt_ref(\"upstream_orders\") but no dbt manifest was found", + "message": "Model file sql/models/marts/customer_totals.sql uses __dbt_ref(\"upstream_orders\") but no dbt manifest was found", "help": "Run dbt compile or configure dbt target_path so SQLBuild can read manifest.json." } ] diff --git a/tests/goldens/compiler/failure/declaration-first-of-two-reference-errors.json b/tests/goldens/compiler/failure/declaration-first-of-two-reference-errors.json index a2c4b904e1..a974bf9abe 100644 --- a/tests/goldens/compiler/failure/declaration-first-of-two-reference-errors.json +++ b/tests/goldens/compiler/failure/declaration-first-of-two-reference-errors.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Unknown member 'HELD' for enum 'staged_status' in '/models/staging/stg_orders.sql'. Available members: PLACED" + "message": "Unknown member 'HELD' for enum 'staged_status' in '/sql/models/staging/stg_orders.sql'. Available members: PLACED" } ] } diff --git a/tests/goldens/compiler/failure/declaration-group-below-root.json b/tests/goldens/compiler/failure/declaration-group-below-root.json index ebbb8b534f..38b3bdec26 100644 --- a/tests/goldens/compiler/failure/declaration-group-below-root.json +++ b/tests/goldens/compiler/failure/declaration-group-below-root.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "Grouped declaration root models/_sqlbuild/ must be below a concrete owner directory; use the project-wide macros/, enums/, constants/, audits/, schemas/, or hooks/ root instead" + "message": "Grouped declaration root sql/models/_sqlbuild/ must be below a concrete owner directory; use the project-wide sql/macros/, sql/enums/, sql/constants/, sql/audits/, sql/schemas/, or sql/hooks/ root instead" } ] } diff --git a/tests/goldens/compiler/failure/declaration-group-unsupported-entry.json b/tests/goldens/compiler/failure/declaration-group-unsupported-entry.json index 71f4684d71..2e92d68df8 100644 --- a/tests/goldens/compiler/failure/declaration-group-unsupported-entry.json +++ b/tests/goldens/compiler/failure/declaration-group-unsupported-entry.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "Declaration group models/marts/_sqlbuild/ contains unsupported entries: models/marts/_sqlbuild/notes.txt" + "message": "Declaration group sql/models/marts/_sqlbuild/ contains unsupported entries: sql/models/marts/_sqlbuild/notes.txt" } ] } diff --git a/tests/goldens/compiler/failure/declaration-inaccessible-local-constant.json b/tests/goldens/compiler/failure/declaration-inaccessible-local-constant.json index 32d7405555..6a96f5e57d 100644 --- a/tests/goldens/compiler/failure/declaration-inaccessible-local-constant.json +++ b/tests/goldens/compiler/failure/declaration-inaccessible-local-constant.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Constant 'order_cap' is known but inaccessible in '/models/staging/stg_orders.sql'. It is defined at models/marts/_constants/limits.sql:1:1 with local scope owned by 'models/marts'; consumer path: '/models/staging/stg_orders.sql'" + "message": "Constant 'order_cap' is known but inaccessible in '/sql/models/staging/stg_orders.sql'. It is defined at sql/models/marts/_constants/limits.sql:1:1 with local scope owned by 'sql/models/marts'; consumer path: '/sql/models/staging/stg_orders.sql'" } ] } diff --git a/tests/goldens/compiler/failure/declaration-invalid-constant-reference.json b/tests/goldens/compiler/failure/declaration-invalid-constant-reference.json index 407aef0a1a..6d3f04a78f 100644 --- a/tests/goldens/compiler/failure/declaration-invalid-constant-reference.json +++ b/tests/goldens/compiler/failure/declaration-invalid-constant-reference.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Invalid constant reference in '/models/staging/stg_orders.sql'" + "message": "Invalid constant reference in '/sql/models/staging/stg_orders.sql'" } ] } diff --git a/tests/goldens/compiler/failure/declaration-root-nested.json b/tests/goldens/compiler/failure/declaration-root-nested.json index 1a803d6726..0ae5770f09 100644 --- a/tests/goldens/compiler/failure/declaration-root-nested.json +++ b/tests/goldens/compiler/failure/declaration-root-nested.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "Declaration root models/marts/_enums/_constants/ is nested inside another declaration tree" + "message": "Declaration root sql/models/marts/_enums/_constants/ is nested inside another declaration tree" } ] } diff --git a/tests/goldens/compiler/failure/declaration-unknown-enum-after-macro.json b/tests/goldens/compiler/failure/declaration-unknown-enum-after-macro.json index 3e9904a035..a5281e0f95 100644 --- a/tests/goldens/compiler/failure/declaration-unknown-enum-after-macro.json +++ b/tests/goldens/compiler/failure/declaration-unknown-enum-after-macro.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Unknown enum 'missing_status' in '/models/staging/stg_orders.sql'. Visible enums: none" + "message": "Unknown enum 'missing_status' in '/sql/models/staging/stg_orders.sql'. Visible enums: none" } ] } diff --git a/tests/goldens/compiler/failure/duplicate-declaration.json b/tests/goldens/compiler/failure/duplicate-declaration.json index bbf984bf10..91fa1f3bfb 100644 --- a/tests/goldens/compiler/failure/duplicate-declaration.json +++ b/tests/goldens/compiler/failure/duplicate-declaration.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Invalid declaration scope index:\n[S003] Duplicate declaration 'constant:minimum_amount' at models/staging/_sqlbuild/_constants/limits.sql:1:1, models/staging/_sqlbuild/_constants/limits.sql:1:1\n[S003] Duplicate declaration 'constant:minimum_amount' at models/staging/_sqlbuild/_constants/limits.sql:1:1, models/staging/_sqlbuild/_constants/limits.sql:1:1" + "message": "Invalid declaration scope index:\n[S003] Duplicate declaration 'constant:minimum_amount' at sql/models/staging/_sqlbuild/_constants/limits.sql:1:1, sql/models/staging/_sqlbuild/_constants/limits.sql:1:1\n[S003] Duplicate declaration 'constant:minimum_amount' at sql/models/staging/_sqlbuild/_constants/limits.sql:1:1, sql/models/staging/_sqlbuild/_constants/limits.sql:1:1" } ] } diff --git a/tests/goldens/compiler/failure/duplicate-hook.json b/tests/goldens/compiler/failure/duplicate-hook.json index 2a11772cb4..5877335ee4 100644 --- a/tests/goldens/compiler/failure/duplicate-hook.json +++ b/tests/goldens/compiler/failure/duplicate-hook.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D011", - "message": "Duplicate hook name 'note_refresh' found in hooks/python/first.py and hooks/python/second.py" + "message": "Duplicate hook name 'note_refresh' found in sql/hooks/python/first.py and sql/hooks/python/second.py" } ] } diff --git a/tests/goldens/compiler/failure/duplicate-model.json b/tests/goldens/compiler/failure/duplicate-model.json index b9b49b0472..25bd10fbc7 100644 --- a/tests/goldens/compiler/failure/duplicate-model.json +++ b/tests/goldens/compiler/failure/duplicate-model.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D007", - "message": "Duplicate model file name found for 'stg_orders' in models/marts/stg_orders.sql and models/staging/stg_orders.sql" + "message": "Duplicate model file name found for 'stg_orders' in sql/models/marts/stg_orders.sql and sql/models/staging/stg_orders.sql" } ] } diff --git a/tests/goldens/compiler/failure/duplicate-provider.json b/tests/goldens/compiler/failure/duplicate-provider.json index 2c25af46db..6d765589c2 100644 --- a/tests/goldens/compiler/failure/duplicate-provider.json +++ b/tests/goldens/compiler/failure/duplicate-provider.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D012", - "message": "Duplicate provider name 'export_settings' found in providers/first.py and providers/second.py" + "message": "Duplicate provider name 'export_settings' found in python/providers/first.py and python/providers/second.py" } ] } diff --git a/tests/goldens/compiler/failure/duplicate-python-node.json b/tests/goldens/compiler/failure/duplicate-python-node.json index d8090a36ba..bf0089b17e 100644 --- a/tests/goldens/compiler/failure/duplicate-python-node.json +++ b/tests/goldens/compiler/failure/duplicate-python-node.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D007", - "message": "Duplicate Python node found for 'export_orders' in python/tasks/first.py and python/tasks/second.py; loader, asset, and check names must be globally unique" + "message": "Duplicate Python node found for 'export_orders' in python/nodes/tasks/first/asset.py and python/nodes/tasks/second/asset.py; loader, asset, and check names must be globally unique" } ] } diff --git a/tests/goldens/compiler/failure/duplicate-source.json b/tests/goldens/compiler/failure/duplicate-source.json index 1b824c951e..64820ffc91 100644 --- a/tests/goldens/compiler/failure/duplicate-source.json +++ b/tests/goldens/compiler/failure/duplicate-source.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D007", - "message": "Duplicate source declaration found for 'raw_orders' in sources/more.yml and sources/raw.yml" + "message": "Duplicate source declaration found for 'raw_orders' in sql/sources/more.yml and sql/sources/raw.yml" } ] } diff --git a/tests/goldens/compiler/failure/engine-error-case-folded-duplicate-column.json b/tests/goldens/compiler/failure/engine-error-case-folded-duplicate-column.json index 8595e5f723..f4aa234934 100644 --- a/tests/goldens/compiler/failure/engine-error-case-folded-duplicate-column.json +++ b/tests/goldens/compiler/failure/engine-error-case-folded-duplicate-column.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/marts/customer_totals.sql model has duplicate column 'größe' (column names are case-insensitive)" + "message": "sql/models/marts/customer_totals.sql model has duplicate column 'größe' (column names are case-insensitive)" } ] } diff --git a/tests/goldens/compiler/failure/engine-error-description-escaped-quote.json b/tests/goldens/compiler/failure/engine-error-description-escaped-quote.json index 7c14153f95..18f21afc22 100644 --- a/tests/goldens/compiler/failure/engine-error-description-escaped-quote.json +++ b/tests/goldens/compiler/failure/engine-error-description-escaped-quote.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "MODEL(...) in '/models/marts/customer_totals.sql:2:34' contains invalid SQLBuild header syntax: a double quote ends this \"...\" string early; use \"\"\"…\"\"\" for text containing double quotes", + "message": "MODEL(...) in '/sql/models/marts/customer_totals.sql:2:34' contains invalid SQLBuild header syntax: a double quote ends this \"...\" string early; use \"\"\"…\"\"\" for text containing double quotes", "help": "write the text between triple quotes, where quotes need no escaping: description \"\"\"Matches \"Miss\".\"\"\"; sqb format --fix rewrites a description that escapes its quotes as \\\" or doubles them as \"\"" } ] diff --git a/tests/goldens/compiler/failure/engine-error-macro-argument-bytes.json b/tests/goldens/compiler/failure/engine-error-macro-argument-bytes.json index 4c763c6a6b..b74949e3e1 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-argument-bytes.json +++ b/tests/goldens/compiler/failure/engine-error-macro-argument-bytes.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/marts/customer_totals.sql' use a bytes literal at line 5, column 31", - "path": "models/marts/customer_totals.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/marts/customer_totals.sql' use a bytes literal at line 5, column 31", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 31, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 31 }, diff --git a/tests/goldens/compiler/failure/engine-error-macro-argument-complex.json b/tests/goldens/compiler/failure/engine-error-macro-argument-complex.json index 0fa58ebd2a..ce1ce3a716 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-argument-complex.json +++ b/tests/goldens/compiler/failure/engine-error-macro-argument-complex.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/marts/customer_totals.sql' use a complex number literal at line 5, column 31", - "path": "models/marts/customer_totals.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/marts/customer_totals.sql' use a complex number literal at line 5, column 31", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 31, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 31 }, diff --git a/tests/goldens/compiler/failure/engine-error-macro-argument-ellipsis.json b/tests/goldens/compiler/failure/engine-error-macro-argument-ellipsis.json index 5eb84db4eb..9897b47e71 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-argument-ellipsis.json +++ b/tests/goldens/compiler/failure/engine-error-macro-argument-ellipsis.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/marts/customer_totals.sql' use '...' (Ellipsis) at line 5, column 31", - "path": "models/marts/customer_totals.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/marts/customer_totals.sql' use '...' (Ellipsis) at line 5, column 31", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 31, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 31 }, diff --git a/tests/goldens/compiler/failure/engine-error-macro-argument-named-sequence.json b/tests/goldens/compiler/failure/engine-error-macro-argument-named-sequence.json index 45329debf1..13a36d8033 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-argument-named-sequence.json +++ b/tests/goldens/compiler/failure/engine-error-macro-argument-named-sequence.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/marts/customer_totals.sql' could not be parsed: \\N{LATIN CAPITAL LETTER A WITH MACRON AND GRAVE} names a sequence of 2 characters, and \\N escapes name one character at line 5, column 32", - "path": "models/marts/customer_totals.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/marts/customer_totals.sql' could not be parsed: \\N{LATIN CAPITAL LETTER A WITH MACRON AND GRAVE} names a sequence of 2 characters, and \\N escapes name one character at line 5, column 32", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 32, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 32 }, diff --git a/tests/goldens/compiler/failure/engine-error-macro-argument-nested-call-sign.json b/tests/goldens/compiler/failure/engine-error-macro-argument-nested-call-sign.json index 1a4cb97cd0..15b3f1d47f 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-argument-nested-call-sign.json +++ b/tests/goldens/compiler/failure/engine-error-macro-argument-nested-call-sign.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/marts/customer_totals.sql' apply unary - to the value of a nested macro call, which is a str and not a number at line 5, column 32", - "path": "models/marts/customer_totals.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/marts/customer_totals.sql' apply unary - to the value of a nested macro call, which is a str and not a number at line 5, column 32", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 32, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 32 }, diff --git a/tests/goldens/compiler/failure/engine-error-macro-argument-second-call.json b/tests/goldens/compiler/failure/engine-error-macro-argument-second-call.json index af53adddb9..ab776888a5 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-argument-second-call.json +++ b/tests/goldens/compiler/failure/engine-error-macro-argument-second-call.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/marts/customer_totals.sql' could not be parsed: a comma is missing between arguments at line 6, column 22", - "path": "models/marts/customer_totals.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/marts/customer_totals.sql' could not be parsed: a comma is missing between arguments at line 6, column 22", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 22, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 22 }, diff --git a/tests/goldens/compiler/failure/engine-error-macro-argument-surrogate-pair.json b/tests/goldens/compiler/failure/engine-error-macro-argument-surrogate-pair.json index 9bd47b1eb2..e19ce56380 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-argument-surrogate-pair.json +++ b/tests/goldens/compiler/failure/engine-error-macro-argument-surrogate-pair.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/marts/customer_totals.sql' contain the lone surrogate escape '\\ud83d' at line 5, column 32", - "path": "models/marts/customer_totals.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/marts/customer_totals.sql' contain the lone surrogate escape '\\ud83d' at line 5, column 32", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 32, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 32 }, diff --git a/tests/goldens/compiler/failure/engine-error-macro-argument-syntax.json b/tests/goldens/compiler/failure/engine-error-macro-argument-syntax.json index 0cb2d5f903..29463916e9 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-argument-syntax.json +++ b/tests/goldens/compiler/failure/engine-error-macro-argument-syntax.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/marts/customer_totals.sql' could not be parsed: a value is missing here at line 5, column 40", - "path": "models/marts/customer_totals.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/marts/customer_totals.sql' could not be parsed: a value is missing here at line 5, column 40", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 40, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 40 }, diff --git a/tests/goldens/compiler/failure/engine-error-macro-argument-unhashable-key.json b/tests/goldens/compiler/failure/engine-error-macro-argument-unhashable-key.json index 68b233d213..fde5b9f86a 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-argument-unhashable-key.json +++ b/tests/goldens/compiler/failure/engine-error-macro-argument-unhashable-key.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/marts/customer_totals.sql' use a list or dict as a dict key at line 5, column 32", - "path": "models/marts/customer_totals.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/marts/customer_totals.sql' use a list or dict as a dict key at line 5, column 32", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 32, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 32 }, diff --git a/tests/goldens/compiler/failure/engine-error-macro-description-escaped-quote.json b/tests/goldens/compiler/failure/engine-error-macro-description-escaped-quote.json index 732dd9a47f..d66caf00c4 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-description-escaped-quote.json +++ b/tests/goldens/compiler/failure/engine-error-macro-description-escaped-quote.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P015", - "message": "a double quote ends this \"...\" string early; use \"\"\"…\"\"\" for text containing double quotes\n --> macros/sql/customer_label.sql:3:10", + "message": "a double quote ends this \"...\" string early; use \"\"\"…\"\"\" for text containing double quotes\n --> sql/macros/sql/customer_label.sql:3:10", "help": "write the text between triple quotes, where quotes need no escaping: description \"\"\"Matches \"Miss\".\"\"\"; sqb format --fix rewrites a description that escapes its quotes as \\\" or doubles them as \"\"" } ] diff --git a/tests/goldens/compiler/failure/engine-error-macro-output-lone-surrogate.json b/tests/goldens/compiler/failure/engine-error-macro-output-lone-surrogate.json index 6da3f30bfd..63a7d831ae 100644 --- a/tests/goldens/compiler/failure/engine-error-macro-output-lone-surrogate.json +++ b/tests/goldens/compiler/failure/engine-error-macro-output-lone-surrogate.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.cents' in '/models/marts/customer_totals.sql' returned text with the lone surrogate '\\udcff', which is not valid Unicode", + "message": "Macro '@py.cents' in '/sql/models/marts/customer_totals.sql' returned text with the lone surrogate '\\udcff', which is not valid Unicode", "help": "Return valid Unicode text from the macro; lone surrogates usually come from bytes decoded with errors='surrogateescape'" } ] diff --git a/tests/goldens/compiler/failure/engine-error-non-ascii-digit-bare-number.json b/tests/goldens/compiler/failure/engine-error-non-ascii-digit-bare-number.json index 9b393a86a3..5591025ba6 100644 --- a/tests/goldens/compiler/failure/engine-error-non-ascii-digit-bare-number.json +++ b/tests/goldens/compiler/failure/engine-error-non-ascii-digit-bare-number.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "/enums/order_priority.sql has the bare number '٣', written with non-ASCII digits", + "message": "/sql/enums/order_priority.sql has the bare number '٣', written with non-ASCII digits", "help": "Quote it to keep it as text (\"٣\"), or write the number with ASCII digits 0-9" } ] diff --git a/tests/goldens/compiler/failure/engine-error-non-ascii-digit-constant-value.json b/tests/goldens/compiler/failure/engine-error-non-ascii-digit-constant-value.json index 21436b9879..60fa52135d 100644 --- a/tests/goldens/compiler/failure/engine-error-non-ascii-digit-constant-value.json +++ b/tests/goldens/compiler/failure/engine-error-non-ascii-digit-constant-value.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "/constants/limits.sql has the bare number '٣', written with non-ASCII digits", + "message": "/sql/constants/limits.sql has the bare number '٣', written with non-ASCII digits", "help": "Quote it to keep it as text (\"٣\"), or write the number with ASCII digits 0-9" } ] diff --git a/tests/goldens/compiler/failure/engine-error-non-ascii-digit-model-constant.json b/tests/goldens/compiler/failure/engine-error-non-ascii-digit-model-constant.json index 0b39f21d60..ed8b609667 100644 --- a/tests/goldens/compiler/failure/engine-error-non-ascii-digit-model-constant.json +++ b/tests/goldens/compiler/failure/engine-error-non-ascii-digit-model-constant.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "/models/marts/customer_totals.sql has the bare number '٣', written with non-ASCII digits", + "message": "/sql/models/marts/customer_totals.sql has the bare number '٣', written with non-ASCII digits", "help": "Quote it to keep it as text (\"٣\"), or write the number with ASCII digits 0-9" } ] diff --git a/tests/goldens/compiler/failure/engine-error-unset-environment-variable.json b/tests/goldens/compiler/failure/engine-error-unset-environment-variable.json index d34e094776..d33420ef85 100644 --- a/tests/goldens/compiler/failure/engine-error-unset-environment-variable.json +++ b/tests/goldens/compiler/failure/engine-error-unset-environment-variable.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "unknown environment variable '@@ENV:SQB_ENGINE_ERROR_UNSET_REGION' in '/models/marts/customer_totals.sql'" + "message": "unknown environment variable '@@ENV:SQB_ENGINE_ERROR_UNSET_REGION' in '/sql/models/marts/customer_totals.sql'" } ] } diff --git a/tests/goldens/compiler/failure/enum-duplicate-member.json b/tests/goldens/compiler/failure/enum-duplicate-member.json index aea3a7ecad..ab8ab57c0b 100644 --- a/tests/goldens/compiler/failure/enum-duplicate-member.json +++ b/tests/goldens/compiler/failure/enum-duplicate-member.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "/models/staging/_sqlbuild/_enums/order_status.sql enum 'order_status' has duplicate member 'PLACED'" + "message": "/sql/models/staging/_sqlbuild/_enums/order_status.sql enum 'order_status' has duplicate member 'PLACED'" } ] } diff --git a/tests/goldens/compiler/failure/enum-parse.json b/tests/goldens/compiler/failure/enum-parse.json index 57406a204d..e27c76f607 100644 --- a/tests/goldens/compiler/failure/enum-parse.json +++ b/tests/goldens/compiler/failure/enum-parse.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "ENUM(...) in '/enums/order_status.sql' contains invalid SQLBuild header syntax: expected value at position 35" + "message": "ENUM(...) in '/sql/enums/order_status.sql' contains invalid SQLBuild header syntax: expected value at position 35" } ] } diff --git a/tests/goldens/compiler/failure/failing-macro.json b/tests/goldens/compiler/failure/failing-macro.json index 0f854efd9a..80efbdb82a 100644 --- a/tests/goldens/compiler/failure/failing-macro.json +++ b/tests/goldens/compiler/failure/failing-macro.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.cents' in '/models/staging/stg_orders.sql' failed: cannot convert amount" + "message": "Macro '@py.cents' in '/sql/models/staging/stg_orders.sql' failed: cannot convert amount" } ] } diff --git a/tests/goldens/compiler/failure/generic-audit-header.json b/tests/goldens/compiler/failure/generic-audit-header.json index 3bbb5d34fa..2ba5f8e271 100644 --- a/tests/goldens/compiler/failure/generic-audit-header.json +++ b/tests/goldens/compiler/failure/generic-audit-header.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D004", - "message": "AUDIT() in '/models/marts/_sqlbuild/_audits/generic/at_least.sql:1' has unsupported keys: unknown_option", + "message": "AUDIT() in '/sql/models/marts/_sqlbuild/_audits/generic/at_least.sql:1' has unsupported keys: unknown_option", "help": "supported keys: always_run, evaluation, minimum_samples, name, run_scope, sample_count, sample_unit, severity, sql_analysis, thresholds, value" } ] diff --git a/tests/goldens/compiler/failure/generic-audit-missing-argument.json b/tests/goldens/compiler/failure/generic-audit-missing-argument.json index 5e02dc2c5e..23fe17d909 100644 --- a/tests/goldens/compiler/failure/generic-audit-missing-argument.json +++ b/tests/goldens/compiler/failure/generic-audit-missing-argument.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql is missing argument 'minimum' for generic audit 'floor'" + "message": "sql/models/staging/stg_orders.sql is missing argument 'minimum' for generic audit 'floor'" } ] } diff --git a/tests/goldens/compiler/failure/generic-audit-overrides-implicit-model.json b/tests/goldens/compiler/failure/generic-audit-overrides-implicit-model.json index 31faebe172..e9055ff902 100644 --- a/tests/goldens/compiler/failure/generic-audit-overrides-implicit-model.json +++ b/tests/goldens/compiler/failure/generic-audit-overrides-implicit-model.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql audit 'floor' must not override implicit model from attached context" + "message": "sql/models/staging/stg_orders.sql audit 'floor' must not override implicit model from attached context" } ] } diff --git a/tests/goldens/compiler/failure/generic-audit-unused-argument.json b/tests/goldens/compiler/failure/generic-audit-unused-argument.json index 187cc93f97..efc91ba020 100644 --- a/tests/goldens/compiler/failure/generic-audit-unused-argument.json +++ b/tests/goldens/compiler/failure/generic-audit-unused-argument.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql audit 'floor' passes argument 'where_condition', which the audit's SQL in models/staging/_sqlbuild/_audits/generic/floor.sql never uses; remove 'where_condition' from the attachment" + "message": "sql/models/staging/stg_orders.sql audit 'floor' passes argument 'where_condition', which the audit's SQL in sql/models/staging/_sqlbuild/_audits/generic/floor.sql never uses; remove 'where_condition' from the attachment" } ] } diff --git a/tests/goldens/compiler/failure/hard-coded-relation-in-python.json b/tests/goldens/compiler/failure/hard-coded-relation-in-python.json index b4155ad796..e3f2bd9bfe 100644 --- a/tests/goldens/compiler/failure/hard-coded-relation-in-python.json +++ b/tests/goldens/compiler/failure/hard-coded-relation-in-python.json @@ -9,11 +9,11 @@ "severity": "error", "code": "P008", "message": "asset:export_orders names model:stg_orders as 'stg_orders' in SQL passed to ctx.query()", - "path": "python/tasks/exports.py", + "path": "python/nodes/tasks/exports/asset.py", "line": 7, "column": 1, "location": { - "path": "python/tasks/exports.py", + "path": "python/nodes/tasks/exports/asset.py", "line": 7, "column": 1 }, @@ -23,13 +23,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -43,8 +43,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -112,8 +112,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -183,8 +183,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/header-audit-identity.json b/tests/goldens/compiler/failure/header-audit-identity.json index 90bd441865..3997fbe89f 100644 --- a/tests/goldens/compiler/failure/header-audit-identity.json +++ b/tests/goldens/compiler/failure/header-audit-identity.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D016", - "message": "Invalid model audit definition identity 'NotNull' in models/staging/stg_orders.sql; use snake_case 'not_null'", + "message": "Invalid model audit definition identity 'NotNull' in sql/models/staging/stg_orders.sql; use snake_case 'not_null'", "help": "Rename the authored identity and update its references, selectors, and integration keys. SQLBuild does not silently normalize resource identities. Double underscores remain valid." } ] diff --git a/tests/goldens/compiler/failure/header-audit-minimum-samples-beyond-64-bits.json b/tests/goldens/compiler/failure/header-audit-minimum-samples-beyond-64-bits.json index 303aac38a0..cd2719dbe1 100644 --- a/tests/goldens/compiler/failure/header-audit-minimum-samples-beyond-64-bits.json +++ b/tests/goldens/compiler/failure/header-audit-minimum-samples-beyond-64-bits.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model audit 'not_null' 'minimum_samples' 18446744073709551616 is larger than a 64-bit integer", + "message": "sql/models/staging/stg_orders.sql model audit 'not_null' 'minimum_samples' 18446744073709551616 is larger than a 64-bit integer", "help": "set minimum_samples to a value that fits in 64 bits, add this to the MODEL header:\n MODEL (\n audits [not_null (name \"order_ids_present\", minimum_samples 9223372036854775807, severity \"warn\", meta (tiers [\"gold\"]))],\n ...\n );" } ] diff --git a/tests/goldens/compiler/failure/header-audit-severity.json b/tests/goldens/compiler/failure/header-audit-severity.json index c4c39c8630..05191dcbc4 100644 --- a/tests/goldens/compiler/failure/header-audit-severity.json +++ b/tests/goldens/compiler/failure/header-audit-severity.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model audit 'unique_combination' 'severity' must be one of: warn, error" + "message": "sql/models/staging/stg_orders.sql model audit 'unique_combination' 'severity' must be one of: warn, error" } ] } diff --git a/tests/goldens/compiler/failure/header-column-audit-evidence-limit-beyond-64-bits.json b/tests/goldens/compiler/failure/header-column-audit-evidence-limit-beyond-64-bits.json index a66b21e7ad..b9d7a6d0a9 100644 --- a/tests/goldens/compiler/failure/header-column-audit-evidence-limit-beyond-64-bits.json +++ b/tests/goldens/compiler/failure/header-column-audit-evidence-limit-beyond-64-bits.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model column 'order_id' audit 'not_null' 'evidence_limit' 18446744073709551616 is larger than a 64-bit integer", + "message": "sql/models/staging/stg_orders.sql model column 'order_id' audit 'not_null' 'evidence_limit' 18446744073709551616 is larger than a 64-bit integer", "help": "set evidence_limit to a value that fits in 64 bits, add this to the MODEL header:\n MODEL (\n columns (order_id (audits [not_null (evidence_limit 9223372036854775807)])),\n ...\n );" } ] diff --git a/tests/goldens/compiler/failure/header-column-audits-not-a-list.json b/tests/goldens/compiler/failure/header-column-audits-not-a-list.json index 411e67da84..5d1c85393e 100644 --- a/tests/goldens/compiler/failure/header-column-audits-not-a-list.json +++ b/tests/goldens/compiler/failure/header-column-audits-not-a-list.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model column 'order_id' audits must be a list" + "message": "sql/models/staging/stg_orders.sql model column 'order_id' audits must be a list" } ] } diff --git a/tests/goldens/compiler/failure/header-column-type-not-text.json b/tests/goldens/compiler/failure/header-column-type-not-text.json index f3b20117b1..5af16a2db2 100644 --- a/tests/goldens/compiler/failure/header-column-type-not-text.json +++ b/tests/goldens/compiler/failure/header-column-type-not-text.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model column 'order_id' 'type' must be a non-empty string" + "message": "sql/models/staging/stg_orders.sql model column 'order_id' 'type' must be a non-empty string" } ] } diff --git a/tests/goldens/compiler/failure/header-column-unknown-metadata-key.json b/tests/goldens/compiler/failure/header-column-unknown-metadata-key.json index 26fd68c93b..32e5cee7dd 100644 --- a/tests/goldens/compiler/failure/header-column-unknown-metadata-key.json +++ b/tests/goldens/compiler/failure/header-column-unknown-metadata-key.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model column 'order_id' has unknown metadata keys: format" + "message": "sql/models/staging/stg_orders.sql model column 'order_id' has unknown metadata keys: format" } ] } diff --git a/tests/goldens/compiler/failure/header-duplicate-column.json b/tests/goldens/compiler/failure/header-duplicate-column.json index 33959188fb..7af4ca33ce 100644 --- a/tests/goldens/compiler/failure/header-duplicate-column.json +++ b/tests/goldens/compiler/failure/header-duplicate-column.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model has duplicate column 'ORDER_ID' (column names are case-insensitive)" + "message": "sql/models/staging/stg_orders.sql model has duplicate column 'ORDER_ID' (column names are case-insensitive)" } ] } diff --git a/tests/goldens/compiler/failure/hook-reads-dependant.json b/tests/goldens/compiler/failure/hook-reads-dependant.json index 58c2f1bc67..7d8123a7f7 100644 --- a/tests/goldens/compiler/failure/hook-reads-dependant.json +++ b/tests/goldens/compiler/failure/hook-reads-dependant.json @@ -11,20 +11,20 @@ "message": "Python hook 'note_refresh' on model 'stg_orders' reads model 'customer_totals', which depends on 'stg_orders'; a hook runs as part of its model, so it cannot wait for a resource built from that model", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/_sqlbuild/_hooks/python/notes.py", + "path": "sql/models/staging/_sqlbuild/_hooks/python/notes.py", "help": "attach the hook to a model built after 'customer_totals', or drop the read and use ctx.destination for 'stg_orders' itself" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -38,8 +38,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -107,8 +107,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -159,7 +159,7 @@ "type": "python", "name": "note_refresh", "kwargs": {}, - "relative_path": "models/staging/_sqlbuild/_hooks/python/notes.py", + "relative_path": "sql/models/staging/_sqlbuild/_hooks/python/notes.py", "definition_hash": "5d9bbe39d4017828edf4fac4743dc8253cd0f9b3d65779e5f9cff6100bee89dd", "version_hash": "38cb2db363acaa4f13ad2ac96e920b672895acf529c55e86c75d1ab2c73137a9" } @@ -193,8 +193,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/hook-role-unsupported-entry.json b/tests/goldens/compiler/failure/hook-role-unsupported-entry.json index c9109a0c9a..1de95db3b1 100644 --- a/tests/goldens/compiler/failure/hook-role-unsupported-entry.json +++ b/tests/goldens/compiler/failure/hook-role-unsupported-entry.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "Unsupported entries in models/marts/_sqlbuild/hooks/: models/marts/_sqlbuild/hooks/notes.sql; hooks/ accepts only python/, sql/" + "message": "Unsupported entries in sql/models/marts/_sqlbuild/hooks/: sql/models/marts/_sqlbuild/hooks/notes.sql; hooks/ accepts only python/, sql/" } ] } diff --git a/tests/goldens/compiler/failure/hook-unknown-argument.json b/tests/goldens/compiler/failure/hook-unknown-argument.json index accbb62629..bb898c80bb 100644 --- a/tests/goldens/compiler/failure/hook-unknown-argument.json +++ b/tests/goldens/compiler/failure/hook-unknown-argument.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "/models/marts/customer_totals.sql post_hooks[0] sql(\"record_refresh\") passes unknown argument(s) to SQL hook 'record_refresh' in hooks/sql/record_refresh.sql: tag" + "message": "/sql/models/marts/customer_totals.sql post_hooks[0] sql(\"record_refresh\") passes unknown argument(s) to SQL hook 'record_refresh' in sql/hooks/sql/record_refresh.sql: tag" } ] } diff --git a/tests/goldens/compiler/failure/hook-without-header.json b/tests/goldens/compiler/failure/hook-without-header.json index 0ab3158d7b..a610f6e8d6 100644 --- a/tests/goldens/compiler/failure/hook-without-header.json +++ b/tests/goldens/compiler/failure/hook-without-header.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D014", - "message": "SQL hook '/hooks/sql/record_refresh.sql' must start with a HOOK() header as the first non-whitespace content" + "message": "SQL hook '/sql/hooks/sql/record_refresh.sql' must start with a HOOK() header as the first non-whitespace content" } ] } diff --git a/tests/goldens/compiler/failure/inaccessible-declaration.json b/tests/goldens/compiler/failure/inaccessible-declaration.json index 905dddc45a..fd5bde80e8 100644 --- a/tests/goldens/compiler/failure/inaccessible-declaration.json +++ b/tests/goldens/compiler/failure/inaccessible-declaration.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Constant 'minimum_amount' is known but inaccessible in '/models/staging/stg_orders.sql'. It is defined at models/marts/_sqlbuild/_constants/limits.sql:1:1 with local scope owned by 'models/marts'; consumer path: '/models/staging/stg_orders.sql'" + "message": "Constant 'minimum_amount' is known but inaccessible in '/sql/models/staging/stg_orders.sql'. It is defined at sql/models/marts/_sqlbuild/_constants/limits.sql:1:1 with local scope owned by 'sql/models/marts'; consumer path: '/sql/models/staging/stg_orders.sql'" } ] } diff --git a/tests/goldens/compiler/failure/inherited-declaration-used-in-one-folder.json b/tests/goldens/compiler/failure/inherited-declaration-used-in-one-folder.json index 45086430ab..5852de08f2 100644 --- a/tests/goldens/compiler/failure/inherited-declaration-used-in-one-folder.json +++ b/tests/goldens/compiler/failure/inherited-declaration-used-in-one-folder.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "S008", - "message": "Declaration 'constant:minimum_amount' is currently descendant-public at 'models/staging' (models/staging/_sqlbuild/constants/limits.sql); required exact-owner-private at 'models/staging'. Consumers: model:stg_orders. Move it to 'models/staging/_sqlbuild/_constants/'", - "path": "models/staging/_sqlbuild/constants/limits.sql", + "message": "Declaration 'constant:minimum_amount' is currently descendant-public at 'sql/models/staging' (sql/models/staging/_sqlbuild/constants/limits.sql); required exact-owner-private at 'sql/models/staging'. Consumers: model:stg_orders. Move it to 'sql/models/staging/_sqlbuild/_constants/'", + "path": "sql/models/staging/_sqlbuild/constants/limits.sql", "line": 1, "column": 1, "location": { - "path": "models/staging/_sqlbuild/constants/limits.sql", + "path": "sql/models/staging/_sqlbuild/constants/limits.sql", "line": 1, "column": 1 } @@ -22,13 +22,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "WHERE amount > 1", @@ -43,8 +43,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -112,8 +112,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -183,8 +183,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/invalid-decimal-constant.json b/tests/goldens/compiler/failure/invalid-decimal-constant.json index a1488abd9f..b1ece0c0f0 100644 --- a/tests/goldens/compiler/failure/invalid-decimal-constant.json +++ b/tests/goldens/compiler/failure/invalid-decimal-constant.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "/models/staging/_sqlbuild/_constants/limits.sql constant 'minimum_amount' has invalid decimal value 'ten'" + "message": "/sql/models/staging/_sqlbuild/_constants/limits.sql constant 'minimum_amount' has invalid decimal value 'ten'" } ] } diff --git a/tests/goldens/compiler/failure/invalid-declaration-name.json b/tests/goldens/compiler/failure/invalid-declaration-name.json index 74a1835434..4e05031cdf 100644 --- a/tests/goldens/compiler/failure/invalid-declaration-name.json +++ b/tests/goldens/compiler/failure/invalid-declaration-name.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D016", - "message": "Invalid public constant identity 'MinimumAmount' in /models/staging/_sqlbuild/_constants/limits.sql; use snake_case 'minimum_amount'", + "message": "Invalid public constant identity 'MinimumAmount' in /sql/models/staging/_sqlbuild/_constants/limits.sql; use snake_case 'minimum_amount'", "help": "Rename the authored identity and update its references, selectors, and integration keys. SQLBuild does not silently normalize resource identities. Double underscores remain valid." } ] diff --git a/tests/goldens/compiler/failure/invalid-reference-calls-in-two-files.json b/tests/goldens/compiler/failure/invalid-reference-calls-in-two-files.json index 021ff54895..424be011a6 100644 --- a/tests/goldens/compiler/failure/invalid-reference-calls-in-two-files.json +++ b/tests/goldens/compiler/failure/invalid-reference-calls-in-two-files.json @@ -11,11 +11,11 @@ "message": "__ref(stg_orders) is not a valid __ref() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -30,11 +30,11 @@ "message": "__source('raw_orders') is not a valid __source() call", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 6, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 6, "end_line": 6, @@ -46,13 +46,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(stg_orders)", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source('raw_orders')", "" @@ -66,8 +66,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -133,8 +133,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -202,8 +202,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/invalid-resource-name.json b/tests/goldens/compiler/failure/invalid-resource-name.json index 33c6c184a5..000742245a 100644 --- a/tests/goldens/compiler/failure/invalid-resource-name.json +++ b/tests/goldens/compiler/failure/invalid-resource-name.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D016", - "message": "Invalid model identity 'order-totals' in models/marts/order-totals.sql; use snake_case 'order_totals'", + "message": "Invalid model identity 'order-totals' in sql/models/marts/order-totals.sql; use snake_case 'order_totals'", "help": "Rename the authored identity and update its references, selectors, and integration keys. SQLBuild does not silently normalize resource identities. Double underscores remain valid." } ] diff --git a/tests/goldens/compiler/failure/legacy-event-exporters-directory.json b/tests/goldens/compiler/failure/legacy-event-exporters-directory.json deleted file mode 100644 index 2c0a87d690..0000000000 --- a/tests/goldens/compiler/failure/legacy-event-exporters-directory.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "commands": [ - { - "label": "compile", - "exit_code": 1, - "diagnostics": [ - { - "phase": "compile", - "severity": "error", - "code": "D015", - "message": "event_exporters/ was replaced by sinks/ and @lifecycle_event_sink" - } - ] - } - ], - "compiled": {}, - "manifest": null -} diff --git a/tests/goldens/compiler/failure/lifecycle-sink-default-parameter.json b/tests/goldens/compiler/failure/lifecycle-sink-default-parameter.json index 04787f8f41..0d4c8ca4b2 100644 --- a/tests/goldens/compiler/failure/lifecycle-sink-default-parameter.json +++ b/tests/goldens/compiler/failure/lifecycle-sink-default-parameter.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D015", - "message": "Event exporter 'ignore_events' in sinks/lifecycle.py parameters must not have defaults" + "message": "Event exporter 'ignore_events' in python/event_sinks/lifecycle.py parameters must not have defaults" } ] } diff --git a/tests/goldens/compiler/failure/lifecycle-sink-unknown-provider.json b/tests/goldens/compiler/failure/lifecycle-sink-unknown-provider.json index e1b706e978..4031ae0479 100644 --- a/tests/goldens/compiler/failure/lifecycle-sink-unknown-provider.json +++ b/tests/goldens/compiler/failure/lifecycle-sink-unknown-provider.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D015", - "message": "Event exporter 'publish_events' in sinks/lifecycle.py requires unknown provider 'destination_client'" + "message": "Event exporter 'publish_events' in python/event_sinks/lifecycle.py requires unknown provider 'destination_client'" } ] } diff --git a/tests/goldens/compiler/failure/lineage-opted-out-except-and-ctes.json b/tests/goldens/compiler/failure/lineage-opted-out-except-and-ctes.json index 0e07d34bb1..0e1ed5f03a 100644 --- a/tests/goldens/compiler/failure/lineage-opted-out-except-and-ctes.json +++ b/tests/goldens/compiler/failure/lineage-opted-out-except-and-ctes.json @@ -11,11 +11,11 @@ "message": "Unknown table or alias 'x' referenced by column 'order_id'", "resource_type": "model", "resource_name": "broken_orders", - "path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", "line": 5, "column": 8, "location": { - "path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", "line": 5, "column": 8, "end_line": 5, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/broken_orders.sql": [ + "sql/models/marts/broken_orders.sql": [ "SELECT x.order_id", "FROM __ref(\"stg_orders\") o", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "WITH kept AS (SELECT customer_id FROM __ref(\"stg_orders\")),", "again AS (SELECT * FROM kept)", "SELECT customer_id, COUNT(*) AS total_amount FROM again GROUP BY 1", @@ -40,7 +40,7 @@ "SELECT customer_id, amount FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -54,8 +54,8 @@ "name": "broken_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/broken_orders.sql", - "original_file_path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", + "original_file_path": "sql/models/marts/broken_orders.sql", "unique_id": "model.failure_corpus.broken_orders", "fqn": [ "failure_corpus", @@ -123,8 +123,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -192,8 +192,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -263,8 +263,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/lineage-opted-out-quoted-columns.json b/tests/goldens/compiler/failure/lineage-opted-out-quoted-columns.json index 708c091054..7671001452 100644 --- a/tests/goldens/compiler/failure/lineage-opted-out-quoted-columns.json +++ b/tests/goldens/compiler/failure/lineage-opted-out-quoted-columns.json @@ -11,11 +11,11 @@ "message": "Unknown table or alias 'x' referenced by column 'order_id'", "resource_type": "model", "resource_name": "broken_orders", - "path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", "line": 5, "column": 8, "location": { - "path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", "line": 5, "column": 8, "end_line": 5, @@ -27,19 +27,19 @@ } ], "compiled": { - "models/marts/broken_orders.sql": [ + "sql/models/marts/broken_orders.sql": [ "SELECT x.order_id", "FROM __ref(\"stg_orders\") o", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT \"Customer_ID\", SUM(O.Amount) AS \"Total_Amount\",", " CAST(MAX(o.status) AS VARCHAR) AS last_status, 'fixed' AS label", "FROM __ref(\"stg_orders\") AS O", "GROUP BY 1", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -53,8 +53,8 @@ "name": "broken_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/broken_orders.sql", - "original_file_path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", + "original_file_path": "sql/models/marts/broken_orders.sql", "unique_id": "model.failure_corpus.broken_orders", "fqn": [ "failure_corpus", @@ -122,8 +122,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -191,8 +191,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -262,8 +262,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/lineage-opted-out-star.json b/tests/goldens/compiler/failure/lineage-opted-out-star.json index 0d8db9c495..76c6f7ebfe 100644 --- a/tests/goldens/compiler/failure/lineage-opted-out-star.json +++ b/tests/goldens/compiler/failure/lineage-opted-out-star.json @@ -11,11 +11,11 @@ "message": "Unknown table or alias 'x' referenced by column 'order_id'", "resource_type": "model", "resource_name": "broken_orders", - "path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", "line": 5, "column": 8, "location": { - "path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", "line": 5, "column": 8, "end_line": 5, @@ -27,17 +27,17 @@ } ], "compiled": { - "models/marts/broken_orders.sql": [ + "sql/models/marts/broken_orders.sql": [ "SELECT x.order_id", "FROM __ref(\"stg_orders\") o", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT o.order_id AS first_order, o.*", "FROM __ref(\"stg_orders\") o", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -51,8 +51,8 @@ "name": "broken_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/broken_orders.sql", - "original_file_path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", + "original_file_path": "sql/models/marts/broken_orders.sql", "unique_id": "model.failure_corpus.broken_orders", "fqn": [ "failure_corpus", @@ -120,8 +120,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -189,8 +189,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -260,8 +260,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/lineage-opted-out-union-of-stars.json b/tests/goldens/compiler/failure/lineage-opted-out-union-of-stars.json index 854fbc877f..814dd13571 100644 --- a/tests/goldens/compiler/failure/lineage-opted-out-union-of-stars.json +++ b/tests/goldens/compiler/failure/lineage-opted-out-union-of-stars.json @@ -11,11 +11,11 @@ "message": "Unknown table or alias 'x' referenced by column 'order_id'", "resource_type": "model", "resource_name": "broken_orders", - "path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", "line": 5, "column": 8, "location": { - "path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", "line": 5, "column": 8, "end_line": 5, @@ -27,19 +27,19 @@ } ], "compiled": { - "models/marts/broken_orders.sql": [ + "sql/models/marts/broken_orders.sql": [ "SELECT x.order_id", "FROM __ref(\"stg_orders\") o", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT *, 1 AS copy_number", "FROM __ref(\"stg_orders\")", "UNION ALL", "SELECT \"R\".*, 2 FROM __source(\"raw_orders\") AS \"R\" JOIN __ref(\"stg_orders\") s ON TRUE", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -53,8 +53,8 @@ "name": "broken_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/broken_orders.sql", - "original_file_path": "models/marts/broken_orders.sql", + "path": "sql/models/marts/broken_orders.sql", + "original_file_path": "sql/models/marts/broken_orders.sql", "unique_id": "model.failure_corpus.broken_orders", "fqn": [ "failure_corpus", @@ -122,8 +122,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -192,8 +192,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -263,8 +263,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/list-constant-mixed-types.json b/tests/goldens/compiler/failure/list-constant-mixed-types.json index e1ef440e76..b4f9765858 100644 --- a/tests/goldens/compiler/failure/list-constant-mixed-types.json +++ b/tests/goldens/compiler/failure/list-constant-mixed-types.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "/models/staging/_sqlbuild/_constants/statuses.sql constant 'kept_statuses'[1] has type integer; expected string" + "message": "/sql/models/staging/_sqlbuild/_constants/statuses.sql constant 'kept_statuses'[1] has type integer; expected string" } ] } diff --git a/tests/goldens/compiler/failure/local-macro-needed-below-owner.json b/tests/goldens/compiler/failure/local-macro-needed-below-owner.json index 7cf361c390..2e3e176fde 100644 --- a/tests/goldens/compiler/failure/local-macro-needed-below-owner.json +++ b/tests/goldens/compiler/failure/local-macro-needed-below-owner.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "S007", - "message": "Declaration 'macro:cents' is currently exact-owner-private at 'models/staging' (models/staging/_sqlbuild/_macros/python/orders.py); required exact-owner-private at 'models/staging/regional'. Consumers: macro:wrapped. Move it to 'models/staging/regional/_sqlbuild/_macros/python/'", - "path": "models/staging/_sqlbuild/_macros/python/orders.py", + "message": "Declaration 'macro:cents' is currently exact-owner-private at 'sql/models/staging' (sql/models/staging/_sqlbuild/_macros/python/orders.py); required exact-owner-private at 'sql/models/staging/regional'. Consumers: macro:wrapped. Move it to 'sql/models/staging/regional/_sqlbuild/_macros/python/'", + "path": "sql/models/staging/_sqlbuild/_macros/python/orders.py", "line": 1, "column": 1, "location": { - "path": "models/staging/_sqlbuild/_macros/python/orders.py", + "path": "sql/models/staging/_sqlbuild/_macros/python/orders.py", "line": 1, "column": 1 } @@ -22,12 +22,12 @@ "phase": "compile", "severity": "error", "code": "S008", - "message": "Declaration 'macro:wrapped' is currently descendant-public at 'models/staging' (models/staging/_sqlbuild/macros/python/wrapping.py); required exact-owner-private at 'models/staging/regional'. Consumers: model:stg_regional_orders. Move it to 'models/staging/regional/_sqlbuild/_macros/python/'", - "path": "models/staging/_sqlbuild/macros/python/wrapping.py", + "message": "Declaration 'macro:wrapped' is currently descendant-public at 'sql/models/staging' (sql/models/staging/_sqlbuild/macros/python/wrapping.py); required exact-owner-private at 'sql/models/staging/regional'. Consumers: model:stg_regional_orders. Move it to 'sql/models/staging/regional/_sqlbuild/_macros/python/'", + "path": "sql/models/staging/_sqlbuild/macros/python/wrapping.py", "line": 4, "column": 1, "location": { - "path": "models/staging/_sqlbuild/macros/python/wrapping.py", + "path": "sql/models/staging/_sqlbuild/macros/python/wrapping.py", "line": 4, "column": 1 } @@ -36,18 +36,18 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/regional/stg_regional_orders.sql": [ + "sql/models/staging/regional/stg_regional_orders.sql": [ "SELECT order_id, (amount * 100) AS amount_cents", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -61,8 +61,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -130,8 +130,8 @@ "name": "stg_regional_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/regional/stg_regional_orders.sql", - "original_file_path": "models/staging/regional/stg_regional_orders.sql", + "path": "sql/models/staging/regional/stg_regional_orders.sql", + "original_file_path": "sql/models/staging/regional/stg_regional_orders.sql", "unique_id": "model.failure_corpus.stg_regional_orders", "fqn": [ "failure_corpus", @@ -200,8 +200,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -271,8 +271,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", @@ -339,8 +339,8 @@ "name": "cents", "resource_type": "macro", "package_name": "failure_corpus", - "path": "models/staging/_sqlbuild/_macros/python/orders.py", - "original_file_path": "models/staging/_sqlbuild/_macros/python/orders.py", + "path": "sql/models/staging/_sqlbuild/_macros/python/orders.py", + "original_file_path": "sql/models/staging/_sqlbuild/_macros/python/orders.py", "unique_id": "macro.failure_corpus.cents", "macro_sql": "def cents(expression: str) -> str:\n \"\"\"Convert to cents.\"\"\"\n return f\"({expression} * 100)\"\n", "depends_on": { @@ -349,7 +349,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/staging" + "sqlbuild_scope_path": "sql/models/staging" }, "docs": { "show": true, @@ -363,10 +363,10 @@ "name": "wrapped", "resource_type": "macro", "package_name": "failure_corpus", - "path": "models/staging/_sqlbuild/macros/python/wrapping.py", - "original_file_path": "models/staging/_sqlbuild/macros/python/wrapping.py", + "path": "sql/models/staging/_sqlbuild/macros/python/wrapping.py", + "original_file_path": "sql/models/staging/_sqlbuild/macros/python/wrapping.py", "unique_id": "macro.failure_corpus.wrapped", - "macro_sql": "from models.staging._sqlbuild._macros.python.orders import cents\n\n\ndef wrapped(expression: str) -> str:\n \"\"\"Wrap cents.\"\"\"\n return cents(expression)\n", + "macro_sql": "from sql.models.staging._sqlbuild._macros.python.orders import cents\n\n\ndef wrapped(expression: str) -> str:\n \"\"\"Wrap cents.\"\"\"\n return cents(expression)\n", "depends_on": { "macros": [ "macro.failure_corpus.cents" @@ -375,7 +375,7 @@ "description": "", "meta": { "sqlbuild_visibility": "inherited", - "sqlbuild_scope_path": "models/staging" + "sqlbuild_scope_path": "sql/models/staging" }, "docs": { "show": true, diff --git a/tests/goldens/compiler/failure/local-singular-audit.json b/tests/goldens/compiler/failure/local-singular-audit.json index 5e954f12ed..bf88f4003a 100644 --- a/tests/goldens/compiler/failure/local-singular-audit.json +++ b/tests/goldens/compiler/failure/local-singular-audit.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "models/marts/_sqlbuild/_audits/singular/ is invalid: singular audits are never used by name, so folder-only visibility has no meaning; use _sqlbuild/audits/singular/" + "message": "sql/models/marts/_sqlbuild/_audits/singular/ is invalid: singular audits are never used by name, so folder-only visibility has no meaning; use _sqlbuild/audits/singular/" } ] } diff --git a/tests/goldens/compiler/failure/macro-arguments-do-not-parse.json b/tests/goldens/compiler/failure/macro-arguments-do-not-parse.json index 3b8b903c9b..1d773818c5 100644 --- a/tests/goldens/compiler/failure/macro-arguments-do-not-parse.json +++ b/tests/goldens/compiler/failure/macro-arguments-do-not-parse.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/staging/stg_orders.sql' could not be parsed: a value is missing here at line 5, column 66", - "path": "models/staging/stg_orders.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/staging/stg_orders.sql' could not be parsed: a value is missing here at line 5, column 66", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 66, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 66 }, diff --git a/tests/goldens/compiler/failure/macro-first-of-two-failing-models.json b/tests/goldens/compiler/failure/macro-first-of-two-failing-models.json index ec53349e2d..aff1f2ecbe 100644 --- a/tests/goldens/compiler/failure/macro-first-of-two-failing-models.json +++ b/tests/goldens/compiler/failure/macro-first-of-two-failing-models.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.blow_up' in '/models/marts/customer_totals.sql' failed: cannot render total" + "message": "Macro '@py.blow_up' in '/sql/models/marts/customer_totals.sql' failed: cannot render total" } ] } diff --git a/tests/goldens/compiler/failure/macro-generated-reference.json b/tests/goldens/compiler/failure/macro-generated-reference.json index c20b745ee3..a32e4177d6 100644 --- a/tests/goldens/compiler/failure/macro-generated-reference.json +++ b/tests/goldens/compiler/failure/macro-generated-reference.json @@ -11,20 +11,20 @@ "message": "model:customer_totals depends on model:stg_orders through macro staged_orders()", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/_sqlbuild/_macros/python/orders.py", + "path": "sql/models/marts/_sqlbuild/_macros/python/orders.py", "help": "write the reference in the model, or pass it in: @py.staged_orders(__ref(\"stg_orders\"))\n = help: the current value is [references] enforce_explicit = true (from sqlbuild_project.toml or its default); while migrating a project, to allow macro-generated references, set this in sqlbuild_project.toml:\n [references]\n enforce_explicit = false" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -38,8 +38,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -107,8 +107,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -178,8 +178,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", @@ -246,8 +246,8 @@ "name": "staged_orders", "resource_type": "macro", "package_name": "failure_corpus", - "path": "models/marts/_sqlbuild/_macros/python/orders.py", - "original_file_path": "models/marts/_sqlbuild/_macros/python/orders.py", + "path": "sql/models/marts/_sqlbuild/_macros/python/orders.py", + "original_file_path": "sql/models/marts/_sqlbuild/_macros/python/orders.py", "unique_id": "macro.failure_corpus.staged_orders", "macro_sql": "def staged_orders() -> str:\n \"\"\"Return the staged orders relation.\"\"\"\n return '__ref(\"stg_orders\")'\n", "depends_on": { @@ -256,7 +256,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/marts" + "sqlbuild_scope_path": "sql/models/marts" }, "docs": { "show": true, diff --git a/tests/goldens/compiler/failure/macro-import-cycle.json b/tests/goldens/compiler/failure/macro-import-cycle.json index 8988073fb6..bcb79a05b3 100644 --- a/tests/goldens/compiler/failure/macro-import-cycle.json +++ b/tests/goldens/compiler/failure/macro-import-cycle.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro import cycle in 'macros/python/first.py': macros.python.first -> macros.python.second -> macros.python.first" + "message": "Macro import cycle in 'sql/macros/python/first.py': sql.macros.python.first -> sql.macros.python.second -> sql.macros.python.first" } ] } diff --git a/tests/goldens/compiler/failure/macro-in-sibling-scope.json b/tests/goldens/compiler/failure/macro-in-sibling-scope.json index f0bbc2cdff..fe902a3062 100644 --- a/tests/goldens/compiler/failure/macro-in-sibling-scope.json +++ b/tests/goldens/compiler/failure/macro-in-sibling-scope.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.cents' in '/models/staging/stg_orders.sql' is inaccessible. Defined at 'models/marts/_sqlbuild/_macros/python/orders.py:1:1' with scope owner 'models/marts'; consumer/definition path is '/models/staging/stg_orders.sql'. Visible macros: none" + "message": "Macro '@py.cents' in '/sql/models/staging/stg_orders.sql' is inaccessible. Defined at 'sql/models/marts/_sqlbuild/_macros/python/orders.py:1:1' with scope owner 'sql/models/marts'; consumer/definition path is '/sql/models/staging/stg_orders.sql'. Visible macros: none" } ] } diff --git a/tests/goldens/compiler/failure/macro-non-literal-argument.json b/tests/goldens/compiler/failure/macro-non-literal-argument.json index 1fc4d3c11b..075e27424a 100644 --- a/tests/goldens/compiler/failure/macro-non-literal-argument.json +++ b/tests/goldens/compiler/failure/macro-non-literal-argument.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro arguments of '@py.cents' in '/models/staging/stg_orders.sql' must use only Python literals, nested macro calls, and __ref(), __source(), or __seed() references at line 5, column 57", - "path": "models/staging/stg_orders.sql", + "message": "Macro arguments of '@py.cents' in '/sql/models/staging/stg_orders.sql' must use only Python literals, nested macro calls, and __ref(), __source(), or __seed() references at line 5, column 57", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 57, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 57 }, diff --git a/tests/goldens/compiler/failure/macro-output-calls-macro.json b/tests/goldens/compiler/failure/macro-output-calls-macro.json index 5902f91dd9..a2d67e4b25 100644 --- a/tests/goldens/compiler/failure/macro-output-calls-macro.json +++ b/tests/goldens/compiler/failure/macro-output-calls-macro.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.wrapped' in '/models/staging/stg_orders.sql' returned SQLBuild call(s) @py.cents(). Macro output must be final SQL. Compose macros with ordinary Python imports and function calls instead; nested @py.macro() calls are supported only when explicitly authored in SQL" + "message": "Macro '@py.wrapped' in '/sql/models/staging/stg_orders.sql' returned SQLBuild call(s) @py.cents(). Macro output must be final SQL. Compose macros with ordinary Python imports and function calls instead; nested @py.macro() calls are supported only when explicitly authored in SQL" } ] } diff --git a/tests/goldens/compiler/failure/macro-private-helper.json b/tests/goldens/compiler/failure/macro-private-helper.json index 72446a365f..1b3ba82b13 100644 --- a/tests/goldens/compiler/failure/macro-private-helper.json +++ b/tests/goldens/compiler/failure/macro-private-helper.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Unknown macro '@py._scaled' in '/models/staging/stg_orders.sql'. Available macros: cents" + "message": "Unknown macro '@py._scaled' in '/sql/models/staging/stg_orders.sql'. Available macros: cents" } ] } diff --git a/tests/goldens/compiler/failure/macro-raises-after-a-call.json b/tests/goldens/compiler/failure/macro-raises-after-a-call.json index de4a51338b..69c2a6b564 100644 --- a/tests/goldens/compiler/failure/macro-raises-after-a-call.json +++ b/tests/goldens/compiler/failure/macro-raises-after-a-call.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.explode' in '/models/staging/stg_orders.sql' failed: cannot render status" + "message": "Macro '@py.explode' in '/sql/models/staging/stg_orders.sql' failed: cannot render status" } ] } diff --git a/tests/goldens/compiler/failure/macro-returned-invalid-reference-call.json b/tests/goldens/compiler/failure/macro-returned-invalid-reference-call.json index de02acfcd6..6c3d4f9d0c 100644 --- a/tests/goldens/compiler/failure/macro-returned-invalid-reference-call.json +++ b/tests/goldens/compiler/failure/macro-returned-invalid-reference-call.json @@ -11,11 +11,11 @@ "message": "__ref(stg_orders) is not a valid __ref() call, returned by macro staged_orders()", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/_sqlbuild/_macros/python/orders.py", + "path": "sql/models/marts/_sqlbuild/_macros/python/orders.py", "line": 3, "column": 13, "location": { - "path": "models/marts/_sqlbuild/_macros/python/orders.py", + "path": "sql/models/marts/_sqlbuild/_macros/python/orders.py", "line": 3, "column": 13, "end_line": 3, @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(stg_orders)", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -185,8 +185,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", @@ -253,8 +253,8 @@ "name": "staged_orders", "resource_type": "macro", "package_name": "failure_corpus", - "path": "models/marts/_sqlbuild/_macros/python/orders.py", - "original_file_path": "models/marts/_sqlbuild/_macros/python/orders.py", + "path": "sql/models/marts/_sqlbuild/_macros/python/orders.py", + "original_file_path": "sql/models/marts/_sqlbuild/_macros/python/orders.py", "unique_id": "macro.failure_corpus.staged_orders", "macro_sql": "def staged_orders() -> str:\n \"\"\"Return the staged orders relation.\"\"\"\n return '__ref(stg_orders)'\n", "depends_on": { @@ -263,7 +263,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/marts" + "sqlbuild_scope_path": "sql/models/marts" }, "docs": { "show": true, diff --git a/tests/goldens/compiler/failure/macro-returns-non-string.json b/tests/goldens/compiler/failure/macro-returns-non-string.json index 56adcc3eb0..f9b9b98d44 100644 --- a/tests/goldens/compiler/failure/macro-returns-non-string.json +++ b/tests/goldens/compiler/failure/macro-returns-non-string.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.answer' in '/models/staging/stg_orders.sql' must return a SQL string when used directly in SQL" + "message": "Macro '@py.answer' in '/sql/models/staging/stg_orders.sql' must return a SQL string when used directly in SQL" } ] } diff --git a/tests/goldens/compiler/failure/macro-test-helper-malformed-reference.json b/tests/goldens/compiler/failure/macro-test-helper-malformed-reference.json index ce488d1480..8e62b7fbf2 100644 --- a/tests/goldens/compiler/failure/macro-test-helper-malformed-reference.json +++ b/tests/goldens/compiler/failure/macro-test-helper-malformed-reference.json @@ -25,13 +25,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -53,8 +53,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -122,8 +122,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -193,8 +193,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/managed-source-without-loader.json b/tests/goldens/compiler/failure/managed-source-without-loader.json index 470980d011..0b27a99955 100644 --- a/tests/goldens/compiler/failure/managed-source-without-loader.json +++ b/tests/goldens/compiler/failure/managed-source-without-loader.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D007", - "message": "Managed source 'loaded_products' in sources/raw.yml requires loader 'loaded_products'" + "message": "Managed source 'loaded_products' in sql/sources/raw.yml requires loader 'loaded_products'" } ] } diff --git a/tests/goldens/compiler/failure/materialization-import-error.json b/tests/goldens/compiler/failure/materialization-import-error.json index c135e75ea8..f2ad1ad7fe 100644 --- a/tests/goldens/compiler/failure/materialization-import-error.json +++ b/tests/goldens/compiler/failure/materialization-import-error.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D011", - "message": "Failed to import materialization file materializations/copy_table.py: No module named 'missing_warehouse_client'" + "message": "Failed to import materialization file python/materializations/copy_table.py: No module named 'missing_warehouse_client'" } ] } diff --git a/tests/goldens/compiler/failure/missing-description.json b/tests/goldens/compiler/failure/missing-description.json index 996e78aa3c..1abc7466a7 100644 --- a/tests/goldens/compiler/failure/missing-description.json +++ b/tests/goldens/compiler/failure/missing-description.json @@ -11,27 +11,27 @@ "message": "model 'stg_orders' has no description", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 1, "column": 1, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 1, "column": 1 }, - "help": "to describe model 'stg_orders', add this to the MODEL header in models/staging/stg_orders.sql:\n MODEL (\n description \"What one row of stg_orders represents\",\n ...\n );" + "help": "to describe model 'stg_orders', add this to the MODEL header in sql/models/staging/stg_orders.sql:\n MODEL (\n description \"What one row of stg_orders represents\",\n ...\n );" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -185,8 +185,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/model-blank-column-type.json b/tests/goldens/compiler/failure/model-blank-column-type.json index bfb4d464a3..3930fb5b13 100644 --- a/tests/goldens/compiler/failure/model-blank-column-type.json +++ b/tests/goldens/compiler/failure/model-blank-column-type.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model column 'amount' 'type' must be a non-empty string" + "message": "sql/models/staging/stg_orders.sql model column 'amount' 'type' must be a non-empty string" } ] } diff --git a/tests/goldens/compiler/failure/model-bom.json b/tests/goldens/compiler/failure/model-bom.json index 46c3a414d8..5cb26bb170 100644 --- a/tests/goldens/compiler/failure/model-bom.json +++ b/tests/goldens/compiler/failure/model-bom.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "SQL model '/models/staging/stg_orders.sql' must start with a MODEL(...) header as the first non-whitespace content" + "message": "SQL model '/sql/models/staging/stg_orders.sql' must start with a MODEL(...) header as the first non-whitespace content" } ] } diff --git a/tests/goldens/compiler/failure/model-column-audit-unknown-severity.json b/tests/goldens/compiler/failure/model-column-audit-unknown-severity.json index 12389687b5..8ed0482518 100644 --- a/tests/goldens/compiler/failure/model-column-audit-unknown-severity.json +++ b/tests/goldens/compiler/failure/model-column-audit-unknown-severity.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model column 'amount' audit 'not_null' 'severity' must be one of: warn, error" + "message": "sql/models/staging/stg_orders.sql model column 'amount' audit 'not_null' 'severity' must be one of: warn, error" } ] } diff --git a/tests/goldens/compiler/failure/model-duplicate-column.json b/tests/goldens/compiler/failure/model-duplicate-column.json index db3b188fff..d2ee63f3d6 100644 --- a/tests/goldens/compiler/failure/model-duplicate-column.json +++ b/tests/goldens/compiler/failure/model-duplicate-column.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/staging/stg_orders.sql model has duplicate column 'AMOUNT' (column names are case-insensitive)" + "message": "sql/models/staging/stg_orders.sql model has duplicate column 'AMOUNT' (column names are case-insensitive)" } ] } diff --git a/tests/goldens/compiler/failure/model-header-nested-too-deep.json b/tests/goldens/compiler/failure/model-header-nested-too-deep.json index f0eb3e117e..a0dfd27dd7 100644 --- a/tests/goldens/compiler/failure/model-header-nested-too-deep.json +++ b/tests/goldens/compiler/failure/model-header-nested-too-deep.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "MODEL(...) in '/models/staging/stg_orders.sql:3' contains invalid SQLBuild header syntax: values nest deeper than 256 levels", + "message": "MODEL(...) in '/sql/models/staging/stg_orders.sql:3' contains invalid SQLBuild header syntax: values nest deeper than 256 levels", "help": "flatten the value so it nests at most 256 levels deep" } ] diff --git a/tests/goldens/compiler/failure/model-header-syntax.json b/tests/goldens/compiler/failure/model-header-syntax.json index 5d3b1f5aca..122f815af8 100644 --- a/tests/goldens/compiler/failure/model-header-syntax.json +++ b/tests/goldens/compiler/failure/model-header-syntax.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "MODEL(...) in '/models/staging/stg_orders.sql' contains invalid SQLBuild header syntax: expected key at position 50" + "message": "MODEL(...) in '/sql/models/staging/stg_orders.sql' contains invalid SQLBuild header syntax: expected key at position 50" } ] } diff --git a/tests/goldens/compiler/failure/model-missing-header.json b/tests/goldens/compiler/failure/model-missing-header.json index 46c3a414d8..5cb26bb170 100644 --- a/tests/goldens/compiler/failure/model-missing-header.json +++ b/tests/goldens/compiler/failure/model-missing-header.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "SQL model '/models/staging/stg_orders.sql' must start with a MODEL(...) header as the first non-whitespace content" + "message": "SQL model '/sql/models/staging/stg_orders.sql' must start with a MODEL(...) header as the first non-whitespace content" } ] } diff --git a/tests/goldens/compiler/failure/model-nullable-column-with-not-null.json b/tests/goldens/compiler/failure/model-nullable-column-with-not-null.json index 0c8e55f2d1..1b26560d69 100644 --- a/tests/goldens/compiler/failure/model-nullable-column-with-not-null.json +++ b/tests/goldens/compiler/failure/model-nullable-column-with-not-null.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P002", - "message": "models/staging/stg_orders.sql column 'amount' cannot set nullable = true and audit not_null", + "message": "sql/models/staging/stg_orders.sql column 'amount' cannot set nullable = true and audit not_null", "help": "remove the not_null audit or set nullable = false" } ] diff --git a/tests/goldens/compiler/failure/model-path-not-utf8.json b/tests/goldens/compiler/failure/model-path-not-utf8.json index a04a655ed8..e7711105e1 100644 --- a/tests/goldens/compiler/failure/model-path-not-utf8.json +++ b/tests/goldens/compiler/failure/model-path-not-utf8.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D016", - "message": "Project path /models/staging/caf\\xe9.sql is not valid UTF-8; rename it so SQLBuild can read it" + "message": "Project path /sql/models/staging/caf\\xe9.sql is not valid UTF-8; rename it so SQLBuild can read it" } ] } diff --git a/tests/goldens/compiler/failure/model-private-enum-misuse.json b/tests/goldens/compiler/failure/model-private-enum-misuse.json index e1cf0a0865..8d9fc981cc 100644 --- a/tests/goldens/compiler/failure/model-private-enum-misuse.json +++ b/tests/goldens/compiler/failure/model-private-enum-misuse.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Unknown member 'PENDING' for enum '_state' in '/models/staging/stg_orders.sql'. Available members: OPEN, CLOSED" + "message": "Unknown member 'PENDING' for enum '_state' in '/sql/models/staging/stg_orders.sql'. Available members: OPEN, CLOSED" } ] } diff --git a/tests/goldens/compiler/failure/model-reserved-name.json b/tests/goldens/compiler/failure/model-reserved-name.json index d6fc87b3d8..f668db5a84 100644 --- a/tests/goldens/compiler/failure/model-reserved-name.json +++ b/tests/goldens/compiler/failure/model-reserved-name.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D016", - "message": "Invalid model identity '_chain_' in models/marts/_chain_.sql; use snake_case 'chain'", + "message": "Invalid model identity '_chain_' in sql/models/marts/_chain_.sql; use snake_case 'chain'", "help": "Rename the authored identity and update its references, selectors, and integration keys. SQLBuild does not silently normalize resource identities. Double underscores remain valid." } ] diff --git a/tests/goldens/compiler/failure/model-schema-extends-unknown.json b/tests/goldens/compiler/failure/model-schema-extends-unknown.json index 4721971d57..4233d1150f 100644 --- a/tests/goldens/compiler/failure/model-schema-extends-unknown.json +++ b/tests/goldens/compiler/failure/model-schema-extends-unknown.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Schema 'order_row' in schemas/orders.sql extends unknown schema 'base_row'" + "message": "Schema 'order_row' in sql/schemas/orders.sql extends unknown schema 'base_row'" } ] } diff --git a/tests/goldens/compiler/failure/model-schema-redeclared-column.json b/tests/goldens/compiler/failure/model-schema-redeclared-column.json index f4d8e65977..5ce5604c0d 100644 --- a/tests/goldens/compiler/failure/model-schema-redeclared-column.json +++ b/tests/goldens/compiler/failure/model-schema-redeclared-column.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Schema 'order_row' in schemas/orders.sql redeclares inherited column 'ID' from schemas/orders.sql:1; column overrides are not supported" + "message": "Schema 'order_row' in sql/schemas/orders.sql redeclares inherited column 'ID' from sql/schemas/orders.sql:1; column overrides are not supported" } ] } diff --git a/tests/goldens/compiler/failure/model-sql-syntax.json b/tests/goldens/compiler/failure/model-sql-syntax.json index afdd3eaddc..b13aef5dad 100644 --- a/tests/goldens/compiler/failure/model-sql-syntax.json +++ b/tests/goldens/compiler/failure/model-sql-syntax.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL syntax error in model 'stg_orders' (/models/staging/stg_orders.sql): the duckdb parser cannot read Syntax error at or near ',' at line 5, column 17", + "message": "SQL syntax error in model 'stg_orders' (/sql/models/staging/stg_orders.sql): the duckdb parser cannot read Syntax error at or near ',' at line 5, column 17", "help": "if this SQL is valid for your warehouse, skip SQL analysis for this model, add this to the MODEL header:\n MODEL (\n sql_analysis false,\n ...\n );\n and please report the SQL so the parser can support it\n = help: SQL analysis is on for this project; to turn it off for every model, set this in sqlbuild_project.toml:\n [settings]\n sql_analysis = false\n = help: to skip SQL analysis for one run, use `--no-sql-analysis`" } ] diff --git a/tests/goldens/compiler/failure/model-unknown-header-key.json b/tests/goldens/compiler/failure/model-unknown-header-key.json index a7f7d46ce2..85a32bb35b 100644 --- a/tests/goldens/compiler/failure/model-unknown-header-key.json +++ b/tests/goldens/compiler/failure/model-unknown-header-key.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "MODEL() in '/models/staging/stg_orders.sql:3' has unsupported keys: materialised", + "message": "MODEL() in '/sql/models/staging/stg_orders.sql:3' has unsupported keys: materialised", "help": "did you mean 'materialized'?" } ] diff --git a/tests/goldens/compiler/failure/multiple-errors-order.json b/tests/goldens/compiler/failure/multiple-errors-order.json index a2e8ee113f..b7826a5191 100644 --- a/tests/goldens/compiler/failure/multiple-errors-order.json +++ b/tests/goldens/compiler/failure/multiple-errors-order.json @@ -11,15 +11,15 @@ "message": "model 'customer_totals' has no description", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 1, "column": 1, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 1, "column": 1 }, - "help": "to describe model 'customer_totals', add this to the MODEL header in models/marts/customer_totals.sql:\n MODEL (\n description \"What one row of customer_totals represents\",\n ...\n );" + "help": "to describe model 'customer_totals', add this to the MODEL header in sql/models/marts/customer_totals.sql:\n MODEL (\n description \"What one row of customer_totals represents\",\n ...\n );" }, { "phase": "compile", @@ -28,15 +28,15 @@ "message": "model 'order_counts' has no description", "resource_type": "model", "resource_name": "order_counts", - "path": "models/marts/order_counts.sql", + "path": "sql/models/marts/order_counts.sql", "line": 1, "column": 1, "location": { - "path": "models/marts/order_counts.sql", + "path": "sql/models/marts/order_counts.sql", "line": 1, "column": 1 }, - "help": "to describe model 'order_counts', add this to the MODEL header in models/marts/order_counts.sql:\n MODEL (\n description \"What one row of order_counts represents\",\n ...\n );" + "help": "to describe model 'order_counts', add this to the MODEL header in sql/models/marts/order_counts.sql:\n MODEL (\n description \"What one row of order_counts represents\",\n ...\n );" }, { "phase": "compile", @@ -45,33 +45,33 @@ "message": "model 'stg_orders' has no description", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 1, "column": 1, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 1, "column": 1 }, - "help": "to describe model 'stg_orders', add this to the MODEL header in models/staging/stg_orders.sql:\n MODEL (\n description \"What one row of stg_orders represents\",\n ...\n );" + "help": "to describe model 'stg_orders', add this to the MODEL header in sql/models/staging/stg_orders.sql:\n MODEL (\n description \"What one row of stg_orders represents\",\n ...\n );" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/marts/order_counts.sql": [ + "sql/models/marts/order_counts.sql": [ "SELECT customer_id, COUNT(*) AS order_count", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -85,8 +85,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -154,8 +154,8 @@ "name": "order_counts", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/order_counts.sql", - "original_file_path": "models/marts/order_counts.sql", + "path": "sql/models/marts/order_counts.sql", + "original_file_path": "sql/models/marts/order_counts.sql", "unique_id": "model.failure_corpus.order_counts", "fqn": [ "failure_corpus", @@ -223,8 +223,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -294,8 +294,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/named-hook-missing-argument.json b/tests/goldens/compiler/failure/named-hook-missing-argument.json index 8d741b20ca..6bbb47649b 100644 --- a/tests/goldens/compiler/failure/named-hook-missing-argument.json +++ b/tests/goldens/compiler/failure/named-hook-missing-argument.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "/models/marts/customer_totals.sql post_hooks[0] sql(\"record_refresh\") is missing argument 'label' for SQL hook 'record_refresh' in hooks/sql/record_refresh.sql" + "message": "/sql/models/marts/customer_totals.sql post_hooks[0] sql(\"record_refresh\") is missing argument 'label' for SQL hook 'record_refresh' in sql/hooks/sql/record_refresh.sql" } ] } diff --git a/tests/goldens/compiler/failure/named-role-nested-declaration.json b/tests/goldens/compiler/failure/named-role-nested-declaration.json index 6f8b5789cc..0d7f679753 100644 --- a/tests/goldens/compiler/failure/named-role-nested-declaration.json +++ b/tests/goldens/compiler/failure/named-role-nested-declaration.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "Declaration directory schemas/enums/ is not allowed inside the project-wide schemas/ role; scoped declarations belong under /_sqlbuild/ below a resource tree" + "message": "Declaration directory sql/schemas/enums/ is not allowed inside the project-wide sql/schemas/ role; scoped declarations belong under /_sqlbuild/ below a resource tree" } ] } diff --git a/tests/goldens/compiler/failure/order-binding-metadata-contract.json b/tests/goldens/compiler/failure/order-binding-metadata-contract.json index c515f0891b..50717d3c98 100644 --- a/tests/goldens/compiler/failure/order-binding-metadata-contract.json +++ b/tests/goldens/compiler/failure/order-binding-metadata-contract.json @@ -11,11 +11,11 @@ "message": "Unknown column 'refund' in stg_orders", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 25, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 25, "end_line": 7, @@ -32,11 +32,11 @@ "message": "unique_key references unknown column 'order_key'", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 4, "column": 15, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 4, "column": 15 }, @@ -50,11 +50,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "discount", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 9, "column": 5, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 9, "column": 5, "end_line": 9, @@ -66,13 +66,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(refund) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -86,8 +86,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -157,8 +157,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -274,8 +274,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/order-closest-column-help.json b/tests/goldens/compiler/failure/order-closest-column-help.json index e50e568592..077785f0cb 100644 --- a/tests/goldens/compiler/failure/order-closest-column-help.json +++ b/tests/goldens/compiler/failure/order-closest-column-help.json @@ -11,11 +11,11 @@ "message": "Unknown column 'amonut' in stg_orders", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 25, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 25, "end_line": 5, @@ -30,13 +30,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amonut) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -50,8 +50,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -119,8 +119,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -190,8 +190,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/order-contract-error-then-warning.json b/tests/goldens/compiler/failure/order-contract-error-then-warning.json index 742801ce10..3810d6d918 100644 --- a/tests/goldens/compiler/failure/order-contract-error-then-warning.json +++ b/tests/goldens/compiler/failure/order-contract-error-then-warning.json @@ -12,11 +12,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "status", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 53, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 53, "end_line": 12, @@ -32,11 +32,11 @@ "resource_type": "model", "resource_name": "stg_orders", "column_name": "note", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 5, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 5, "end_line": 6, @@ -46,7 +46,7 @@ { "label": "output", "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 12, "column": 18, "end_line": 12, @@ -61,13 +61,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, NULL AS note, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -81,8 +81,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -150,8 +150,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -258,8 +258,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/order-poisoned-downstream-uses.json b/tests/goldens/compiler/failure/order-poisoned-downstream-uses.json index 631ed47dc9..e9b6330006 100644 --- a/tests/goldens/compiler/failure/order-poisoned-downstream-uses.json +++ b/tests/goldens/compiler/failure/order-poisoned-downstream-uses.json @@ -11,11 +11,11 @@ "message": "Unknown column 'refund' in raw_orders", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 39, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 39, "end_line": 5, @@ -30,13 +30,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(refund) AS total_refund", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, refund, status", "FROM __source(\"raw_orders\")", "" @@ -50,8 +50,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -119,8 +119,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -190,8 +190,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/order-two-failing-models.json b/tests/goldens/compiler/failure/order-two-failing-models.json index c3bfef6368..158ffd017d 100644 --- a/tests/goldens/compiler/failure/order-two-failing-models.json +++ b/tests/goldens/compiler/failure/order-two-failing-models.json @@ -11,11 +11,11 @@ "message": "Unknown column 'missing_column' in stg_orders", "resource_type": "model", "resource_name": "order_counts", - "path": "models/marts/order_counts.sql", + "path": "sql/models/marts/order_counts.sql", "line": 5, "column": 27, "location": { - "path": "models/marts/order_counts.sql", + "path": "sql/models/marts/order_counts.sql", "line": 5, "column": 27, "end_line": 5, @@ -32,11 +32,11 @@ "message": "Unknown column 'discount' in raw_orders", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 39, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 39, "end_line": 5, @@ -50,19 +50,19 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/marts/order_counts.sql": [ + "sql/models/marts/order_counts.sql": [ "SELECT customer_id, COUNT(missing_column) AS order_count", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, discount, status", "FROM __source(\"raw_orders\")", "" @@ -76,8 +76,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -145,8 +145,8 @@ "name": "order_counts", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/order_counts.sql", - "original_file_path": "models/marts/order_counts.sql", + "path": "sql/models/marts/order_counts.sql", + "original_file_path": "sql/models/marts/order_counts.sql", "unique_id": "model.failure_corpus.order_counts", "fqn": [ "failure_corpus", @@ -214,8 +214,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -285,8 +285,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/orphan-audit-factory.json b/tests/goldens/compiler/failure/orphan-audit-factory.json index 99894f52bb..8a58424697 100644 --- a/tests/goldens/compiler/failure/orphan-audit-factory.json +++ b/tests/goldens/compiler/failure/orphan-audit-factory.json @@ -11,11 +11,11 @@ "message": "Audit factory 'order_quality' is not referenced by any model and will not produce audits", "resource_type": "audit", "resource_name": "order_quality", - "path": "python/audits/quality.py", + "path": "python/nodes/audits/quality.py", "line": 4, "column": 1, "location": { - "path": "python/audits/quality.py", + "path": "python/nodes/audits/quality.py", "line": 4, "column": 1 } @@ -24,12 +24,12 @@ "phase": "compile", "severity": "error", "code": "S024", - "message": "Declaration 'constant:minimum_amount' is currently project at 'constants' (constants/limits.sql); required exact-owner-private at 'models/staging'. Consumers: model:stg_orders. Move it to 'models/staging/_sqlbuild/_constants/'", - "path": "constants/limits.sql", + "message": "Declaration 'constant:minimum_amount' is currently project at 'sql/constants' (sql/constants/limits.sql); required exact-owner-private at 'sql/models/staging'. Consumers: model:stg_orders. Move it to 'sql/models/staging/_sqlbuild/_constants/'", + "path": "sql/constants/limits.sql", "line": 1, "column": 1, "location": { - "path": "constants/limits.sql", + "path": "sql/constants/limits.sql", "line": 1, "column": 1 } @@ -38,13 +38,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "WHERE amount > 1", @@ -59,8 +59,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -128,8 +128,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -199,8 +199,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/over-broad-global.json b/tests/goldens/compiler/failure/over-broad-global.json index 4489bdef1f..2dee68e5b7 100644 --- a/tests/goldens/compiler/failure/over-broad-global.json +++ b/tests/goldens/compiler/failure/over-broad-global.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "S024", - "message": "Declaration 'constant:minimum_amount' is currently project at 'constants' (constants/limits.sql); required exact-owner-private at 'models/staging'. Consumers: model:stg_orders. Move it to 'models/staging/_sqlbuild/_constants/'", - "path": "constants/limits.sql", + "message": "Declaration 'constant:minimum_amount' is currently project at 'sql/constants' (sql/constants/limits.sql); required exact-owner-private at 'sql/models/staging'. Consumers: model:stg_orders. Move it to 'sql/models/staging/_sqlbuild/_constants/'", + "path": "sql/constants/limits.sql", "line": 1, "column": 1, "location": { - "path": "constants/limits.sql", + "path": "sql/constants/limits.sql", "line": 1, "column": 1 } @@ -22,13 +22,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "WHERE amount > 1", @@ -43,8 +43,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -112,8 +112,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -183,8 +183,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/project-layout-scoped-root-at-project-root.json b/tests/goldens/compiler/failure/project-layout-scoped-root-at-project-root.json new file mode 100644 index 0000000000..141906c800 --- /dev/null +++ b/tests/goldens/compiler/failure/project-layout-scoped-root-at-project-root.json @@ -0,0 +1,19 @@ +{ + "commands": [ + { + "label": "compile", + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "D018", + "message": "'_enums/' is not part of a SQLBuild project", + "help": "move it under one of: sql/, python/, orchestration/, rules/, tests/,\n or list it in extra_paths in sqlbuild_project.toml if it belongs here on purpose" + } + ] + } + ], + "compiled": {}, + "manifest": null +} diff --git a/tests/goldens/compiler/failure/project-layout-unknown-python-module.json b/tests/goldens/compiler/failure/project-layout-unknown-python-module.json new file mode 100644 index 0000000000..8b52ff0c81 --- /dev/null +++ b/tests/goldens/compiler/failure/project-layout-unknown-python-module.json @@ -0,0 +1,19 @@ +{ + "commands": [ + { + "label": "compile", + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "D018", + "message": "'python/helpers.py' is not part of a SQLBuild project", + "help": "move it under one of: python/nodes/, python/providers/, python/event_sinks/, python/materializations/, python/adapters/,\n or list it in extra_paths in sqlbuild_project.toml if it belongs here on purpose" + } + ] + } + ], + "compiled": {}, + "manifest": null +} diff --git a/tests/goldens/compiler/failure/project-layout-unknown-sql-folder.json b/tests/goldens/compiler/failure/project-layout-unknown-sql-folder.json new file mode 100644 index 0000000000..c35474da07 --- /dev/null +++ b/tests/goldens/compiler/failure/project-layout-unknown-sql-folder.json @@ -0,0 +1,19 @@ +{ + "commands": [ + { + "label": "compile", + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "D018", + "message": "'sql/notes/' is not part of a SQLBuild project", + "help": "move it under one of: sql/models/, sql/seeds/, sql/sources/, sql/macros/, sql/functions/, sql/enums/, sql/constants/, sql/audits/, sql/hooks/, sql/schemas/,\n or list it in extra_paths in sqlbuild_project.toml if it belongs here on purpose" + } + ] + } + ], + "compiled": {}, + "manifest": null +} diff --git a/tests/goldens/compiler/failure/project-layout-unknown-top-level-folder.json b/tests/goldens/compiler/failure/project-layout-unknown-top-level-folder.json new file mode 100644 index 0000000000..7690fe1683 --- /dev/null +++ b/tests/goldens/compiler/failure/project-layout-unknown-top-level-folder.json @@ -0,0 +1,19 @@ +{ + "commands": [ + { + "label": "compile", + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "D018", + "message": "'event_exporters/' is not part of a SQLBuild project", + "help": "move it under one of: sql/, python/, orchestration/, rules/, tests/,\n or list it in extra_paths in sqlbuild_project.toml if it belongs here on purpose" + } + ] + } + ], + "compiled": {}, + "manifest": null +} diff --git a/tests/goldens/compiler/failure/provider-invalid-settings.json b/tests/goldens/compiler/failure/provider-invalid-settings.json index e067a82f9d..531f5bfc46 100644 --- a/tests/goldens/compiler/failure/provider-invalid-settings.json +++ b/tests/goldens/compiler/failure/provider-invalid-settings.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D012", - "message": "provider 'export_settings' (providers/export_settings.py) is missing secret API_TOKEN", + "message": "provider 'export_settings' (python/providers/export_settings.py) is missing secret API_TOKEN", "help": "set API_TOKEN in this shell, or pass --allow-missing-secrets where secrets aren't available" } ] diff --git a/tests/goldens/compiler/failure/python-function-missing-runtime-version.json b/tests/goldens/compiler/failure/python-function-missing-runtime-version.json index e89e186cb7..84b247256d 100644 --- a/tests/goldens/compiler/failure/python-function-missing-runtime-version.json +++ b/tests/goldens/compiler/failure/python-function-missing-runtime-version.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Python function file functions/python/order_flag.py must declare runtime_version" + "message": "Python function file sql/functions/python/order_flag.py must declare runtime_version" } ] } diff --git a/tests/goldens/compiler/failure/python-function-packages-not-a-list.json b/tests/goldens/compiler/failure/python-function-packages-not-a-list.json index 26af96568e..6241e9eead 100644 --- a/tests/goldens/compiler/failure/python-function-packages-not-a-list.json +++ b/tests/goldens/compiler/failure/python-function-packages-not-a-list.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Python function file functions/python/order_flag.py packages must be a list" + "message": "Python function file sql/functions/python/order_flag.py packages must be a list" } ] } diff --git a/tests/goldens/compiler/failure/python-node-description-too-long.json b/tests/goldens/compiler/failure/python-node-description-too-long.json index 2ae93a0356..b4aac789ee 100644 --- a/tests/goldens/compiler/failure/python-node-description-too-long.json +++ b/tests/goldens/compiler/failure/python-node-description-too-long.json @@ -10,11 +10,11 @@ "code": "P027", "message": "asset 'export_orders' description exceeds 10 lines", "resource_name": "export_orders", - "path": "python/tasks/exports.py", + "path": "python/nodes/tasks/exports/asset.py", "line": 4, "column": 1, "location": { - "path": "python/tasks/exports.py", + "path": "python/nodes/tasks/exports/asset.py", "line": 4, "column": 1 }, @@ -24,13 +24,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -44,8 +44,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -113,8 +113,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -184,8 +184,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/python-node-import-error.json b/tests/goldens/compiler/failure/python-node-import-error.json index 1e4fa38507..2b18e82a25 100644 --- a/tests/goldens/compiler/failure/python-node-import-error.json +++ b/tests/goldens/compiler/failure/python-node-import-error.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D011", - "message": "Failed to import Python node file python/tasks/exports.py: No module named 'missing_orders_client'" + "message": "Failed to import Python node file python/nodes/tasks/exports/asset.py: No module named 'missing_orders_client'" } ] } diff --git a/tests/goldens/compiler/failure/python-node-missing-description.json b/tests/goldens/compiler/failure/python-node-missing-description.json index eef733411c..14d989a0e5 100644 --- a/tests/goldens/compiler/failure/python-node-missing-description.json +++ b/tests/goldens/compiler/failure/python-node-missing-description.json @@ -10,27 +10,27 @@ "code": "P010", "message": "asset 'export_orders' has no description", "resource_name": "export_orders", - "path": "python/tasks/exports.py", + "path": "python/nodes/tasks/exports/asset.py", "line": 4, "column": 1, "location": { - "path": "python/tasks/exports.py", + "path": "python/nodes/tasks/exports/asset.py", "line": 4, "column": 1 }, - "help": "to describe asset 'export_orders', give its function in python/tasks/exports.py a docstring or pass a description to @asset:\n @asset(description=\"What export_orders does\", ...)" + "help": "to describe asset 'export_orders', give its function in python/nodes/tasks/exports/asset.py a docstring or pass a description to @asset:\n @asset(description=\"What export_orders does\", ...)" } ] } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -44,8 +44,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -113,8 +113,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -184,8 +184,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/python-node-syntax.json b/tests/goldens/compiler/failure/python-node-syntax.json index 961ba2eae4..8b55601341 100644 --- a/tests/goldens/compiler/failure/python-node-syntax.json +++ b/tests/goldens/compiler/failure/python-node-syntax.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D011", - "message": "Failed to import Python node file python/tasks/exports.py: invalid syntax (exports.py, line 1)" + "message": "Failed to import Python node file python/nodes/tasks/exports/asset.py: invalid syntax (asset.py, line 1)" } ] } diff --git a/tests/goldens/compiler/failure/python-outside-extension-root.json b/tests/goldens/compiler/failure/python-outside-extension-root.json index 30a354b381..83dfcad7fb 100644 --- a/tests/goldens/compiler/failure/python-outside-extension-root.json +++ b/tests/goldens/compiler/failure/python-outside-extension-root.json @@ -8,8 +8,8 @@ "phase": "compile", "severity": "error", "code": "D016", - "message": "Unsupported project Python path(s): helpers/formatting.py", - "help": "Move pipeline Python nodes and the helper modules they import under python/, or move SQLBuild extensions under their documented extension path." + "message": "Unsupported project Python path(s): sql/models/formatting.py", + "help": "Move pipeline Python nodes and the helper modules they import under python/nodes/, or move SQLBuild extensions under their documented extension path." } ] } diff --git a/tests/goldens/compiler/failure/refactor-mv-model.json b/tests/goldens/compiler/failure/refactor-mv-model.json index 5e1d48b577..7b82708fd8 100644 --- a/tests/goldens/compiler/failure/refactor-mv-model.json +++ b/tests/goldens/compiler/failure/refactor-mv-model.json @@ -8,14 +8,14 @@ "operation": "move_model", "target": "model:customer_totals", "new_name": "customer_totals", - "destination": "models/finance/customer_totals.sql", + "destination": "sql/models/finance/customer_totals.sql", "cascade": false, "status": "applied", "files_changed": 1, "files": [ { - "path": "models/finance/customer_totals.sql", - "from_path": "models/marts/customer_totals.sql", + "path": "sql/models/finance/customer_totals.sql", + "from_path": "sql/models/marts/customer_totals.sql", "edits": [] } ], @@ -42,13 +42,13 @@ } ], "compiled": { - "models/finance/customer_totals.sql": [ + "sql/models/finance/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -62,8 +62,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/finance/customer_totals.sql", - "original_file_path": "models/finance/customer_totals.sql", + "path": "sql/models/finance/customer_totals.sql", + "original_file_path": "sql/models/finance/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -131,8 +131,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -202,8 +202,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/refactor-rename-column-cascade.json b/tests/goldens/compiler/failure/refactor-rename-column-cascade.json index d166fda85f..ce6141a529 100644 --- a/tests/goldens/compiler/failure/refactor-rename-column-cascade.json +++ b/tests/goldens/compiler/failure/refactor-rename-column-cascade.json @@ -14,7 +14,7 @@ "files_changed": 1, "files": [ { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "from_path": null, "edits": [ { @@ -61,12 +61,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT *", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount AS order_amount, status", "FROM __source(\"raw_orders\")", "" @@ -80,8 +80,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -149,8 +149,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -220,8 +220,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/refactor-rename-column-star-refused.json b/tests/goldens/compiler/failure/refactor-rename-column-star-refused.json index 985ffd5ca8..b203756718 100644 --- a/tests/goldens/compiler/failure/refactor-rename-column-star-refused.json +++ b/tests/goldens/compiler/failure/refactor-rename-column-star-refused.json @@ -14,7 +14,7 @@ "files_changed": 0, "files": [ { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "from_path": null, "edits": [ { @@ -37,7 +37,7 @@ ], "manual": [ { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 1, "reason": "SELECT * passes amount through, so this model's output column would be renamed too; rerun with --cascade or list the columns" @@ -63,12 +63,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT *", "FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -82,8 +82,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -151,8 +151,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -222,8 +222,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/refactor-rename-column.json b/tests/goldens/compiler/failure/refactor-rename-column.json index 1972938bdb..0088d2f0bb 100644 --- a/tests/goldens/compiler/failure/refactor-rename-column.json +++ b/tests/goldens/compiler/failure/refactor-rename-column.json @@ -14,7 +14,7 @@ "files_changed": 2, "files": [ { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "from_path": null, "edits": [ { @@ -27,7 +27,7 @@ ] }, { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "from_path": null, "edits": [ { @@ -69,13 +69,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(order_amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount AS order_amount, status", "FROM __source(\"raw_orders\")", "" @@ -89,8 +89,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -158,8 +158,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -229,8 +229,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/refactor-rename-model-collision-refused.json b/tests/goldens/compiler/failure/refactor-rename-model-collision-refused.json index 217eb87ba6..40bdbf0016 100644 --- a/tests/goldens/compiler/failure/refactor-rename-model-collision-refused.json +++ b/tests/goldens/compiler/failure/refactor-rename-model-collision-refused.json @@ -8,13 +8,13 @@ "operation": "rename_model", "target": "model:stg_orders", "new_name": "customer_totals", - "destination": "models/staging/customer_totals.sql", + "destination": "sql/models/staging/customer_totals.sql", "cascade": false, "status": "refused", "files_changed": 0, "files": [ { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "from_path": null, "edits": [ { @@ -27,8 +27,8 @@ ] }, { - "path": "models/staging/customer_totals.sql", - "from_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/customer_totals.sql", + "from_path": "sql/models/staging/stg_orders.sql", "edits": [] } ], @@ -37,7 +37,7 @@ "manual": [], "blocking": [ { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": null, "column": null, "reason": "model:customer_totals already exists" @@ -62,13 +62,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -82,8 +82,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -151,8 +151,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -222,8 +222,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/refactor-rename-model-dry-run.json b/tests/goldens/compiler/failure/refactor-rename-model-dry-run.json index cb5d073d1d..aee98c5de3 100644 --- a/tests/goldens/compiler/failure/refactor-rename-model-dry-run.json +++ b/tests/goldens/compiler/failure/refactor-rename-model-dry-run.json @@ -8,13 +8,13 @@ "operation": "rename_model", "target": "model:stg_orders", "new_name": "stg_order_lines", - "destination": "models/staging/stg_order_lines.sql", + "destination": "sql/models/staging/stg_order_lines.sql", "cascade": false, "status": "dry_run", "files_changed": 0, "files": [ { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "from_path": null, "edits": [ { @@ -27,8 +27,8 @@ ] }, { - "path": "models/staging/stg_order_lines.sql", - "from_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_order_lines.sql", + "from_path": "sql/models/staging/stg_orders.sql", "edits": [] } ], @@ -55,13 +55,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -75,8 +75,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -144,8 +144,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -215,8 +215,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/refactor-rename-model-yaml-anchors.json b/tests/goldens/compiler/failure/refactor-rename-model-yaml-anchors.json index 0ee7341015..000c05ad46 100644 --- a/tests/goldens/compiler/failure/refactor-rename-model-yaml-anchors.json +++ b/tests/goldens/compiler/failure/refactor-rename-model-yaml-anchors.json @@ -8,13 +8,13 @@ "operation": "rename_model", "target": "model:stg_orders", "new_name": "stg_order_lines", - "destination": "models/staging/stg_order_lines.sql", + "destination": "sql/models/staging/stg_order_lines.sql", "cascade": false, "status": "applied", "files_changed": 3, "files": [ { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "from_path": null, "edits": [ { @@ -27,12 +27,12 @@ ] }, { - "path": "models/staging/stg_order_lines.sql", - "from_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_order_lines.sql", + "from_path": "sql/models/staging/stg_orders.sql", "edits": [] }, { - "path": "sources/raw.yml", + "path": "sql/sources/raw.yml", "from_path": null, "edits": [ { @@ -75,13 +75,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_order_lines\")", "GROUP BY customer_id", "" ], - "models/staging/stg_order_lines.sql": [ + "sql/models/staging/stg_order_lines.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -95,8 +95,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -164,8 +164,8 @@ "name": "stg_order_lines", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_order_lines.sql", - "original_file_path": "models/staging/stg_order_lines.sql", + "path": "sql/models/staging/stg_order_lines.sql", + "original_file_path": "sql/models/staging/stg_order_lines.sql", "unique_id": "model.failure_corpus.stg_order_lines", "fqn": [ "failure_corpus", @@ -235,8 +235,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", @@ -303,8 +303,8 @@ "name": "raw_orders_copy", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders_copy", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/refactor-rename-model.json b/tests/goldens/compiler/failure/refactor-rename-model.json index c585797596..f2044037e0 100644 --- a/tests/goldens/compiler/failure/refactor-rename-model.json +++ b/tests/goldens/compiler/failure/refactor-rename-model.json @@ -8,13 +8,13 @@ "operation": "rename_model", "target": "model:stg_orders", "new_name": "stg_order_lines", - "destination": "models/staging/stg_order_lines.sql", + "destination": "sql/models/staging/stg_order_lines.sql", "cascade": false, "status": "applied", "files_changed": 2, "files": [ { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "from_path": null, "edits": [ { @@ -34,8 +34,8 @@ ] }, { - "path": "models/staging/stg_order_lines.sql", - "from_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_order_lines.sql", + "from_path": "sql/models/staging/stg_orders.sql", "edits": [ { "line": 1, @@ -76,13 +76,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_order_lines\")", "GROUP BY customer_id", "" ], - "models/staging/stg_order_lines.sql": [ + "sql/models/staging/stg_order_lines.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -96,8 +96,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -165,8 +165,8 @@ "name": "stg_order_lines", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_order_lines.sql", - "original_file_path": "models/staging/stg_order_lines.sql", + "path": "sql/models/staging/stg_order_lines.sql", + "original_file_path": "sql/models/staging/stg_order_lines.sql", "unique_id": "model.failure_corpus.stg_order_lines", "fqn": [ "failure_corpus", @@ -236,8 +236,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/reference-dbt-three-arguments.json b/tests/goldens/compiler/failure/reference-dbt-three-arguments.json index b21a746e88..90e69aee07 100644 --- a/tests/goldens/compiler/failure/reference-dbt-three-arguments.json +++ b/tests/goldens/compiler/failure/reference-dbt-three-arguments.json @@ -11,11 +11,11 @@ "message": "__dbt_ref(\"shop\", \"orders\", \"extra\") is not a valid __dbt_ref() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT order_id AS customer_id, 1 AS total_amount", "FROM __dbt_ref(\"shop\", \"orders\", \"extra\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -113,8 +113,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -184,8 +184,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/reference-empty-argument.json b/tests/goldens/compiler/failure/reference-empty-argument.json index 3021f71bd6..346fefd61a 100644 --- a/tests/goldens/compiler/failure/reference-empty-argument.json +++ b/tests/goldens/compiler/failure/reference-empty-argument.json @@ -11,11 +11,11 @@ "message": "__ref(\"stg_orders\", ) is not a valid __ref() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT order_id AS customer_id, 1 AS total_amount", "FROM __ref(\"stg_orders\", )", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -113,8 +113,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -184,8 +184,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/reference-error-after-rejected-calls.json b/tests/goldens/compiler/failure/reference-error-after-rejected-calls.json index cd15879862..a107fa6779 100644 --- a/tests/goldens/compiler/failure/reference-error-after-rejected-calls.json +++ b/tests/goldens/compiler/failure/reference-error-after-rejected-calls.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/marts/customer_totals.sql:7:39: SQL reference contains an unclosed quoted string" + "message": "sql/models/marts/customer_totals.sql:7:39: SQL reference contains an unclosed quoted string" } ] } diff --git a/tests/goldens/compiler/failure/reference-expression-name.json b/tests/goldens/compiler/failure/reference-expression-name.json index de4eaf4ffc..d38285028a 100644 --- a/tests/goldens/compiler/failure/reference-expression-name.json +++ b/tests/goldens/compiler/failure/reference-expression-name.json @@ -11,11 +11,11 @@ "message": "__ref(concat('stg_', 'orders')) is not a valid __ref() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT order_id AS customer_id, 1 AS total_amount", "FROM __ref(concat('stg_', 'orders'))", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -113,8 +113,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -184,8 +184,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/reference-rejected-calls-across-files.json b/tests/goldens/compiler/failure/reference-rejected-calls-across-files.json index bc8c93801e..2ed05c24cc 100644 --- a/tests/goldens/compiler/failure/reference-rejected-calls-across-files.json +++ b/tests/goldens/compiler/failure/reference-rejected-calls-across-files.json @@ -11,11 +11,11 @@ "message": "__dbt_ref(shop, orders, extra) is not a valid __dbt_ref() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -30,11 +30,11 @@ "message": "__table_fn must be followed by an argument list", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 6, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 6, "end_line": 6, @@ -46,12 +46,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT order_id AS customer_id, 1 AS total_amount", "FROM __dbt_ref(shop, orders, extra)", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __table_fn(\"table_fn__orders_for\") -- no call", "" @@ -65,8 +65,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -132,8 +132,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -201,8 +201,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/reference-several-rejected-calls-in-one-file.json b/tests/goldens/compiler/failure/reference-several-rejected-calls-in-one-file.json index 13f1d3968b..d262755828 100644 --- a/tests/goldens/compiler/failure/reference-several-rejected-calls-in-one-file.json +++ b/tests/goldens/compiler/failure/reference-several-rejected-calls-in-one-file.json @@ -11,11 +11,11 @@ "message": "__ref(stg_orders) is not a valid __ref() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 8, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 8, "column": 6, "end_line": 8, @@ -30,11 +30,11 @@ "message": "__source( 'raw_orders' ) is not a valid __source() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 9, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 9, "column": 6, "end_line": 9, @@ -49,11 +49,11 @@ "message": "__seed(\"a\", \"b\") is not a valid __seed() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 10, "column": 47, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 10, "column": 47, "end_line": 10, @@ -65,7 +65,7 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "-- __ref(hidden)", "SELECT order_id AS customer_id, 'é __ref(hidden)' AS note, $$__ref(hidden)$$ AS body,", " 1 AS total_amount /* __ref(hidden) */", @@ -74,7 +74,7 @@ "WHERE customer_id IN (SELECT customer_id FROM __seed(\"a\", \"b\"))", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -88,8 +88,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -155,8 +155,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -226,8 +226,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/reference-two-name-arguments.json b/tests/goldens/compiler/failure/reference-two-name-arguments.json index a419ba1b44..b657fc0aa3 100644 --- a/tests/goldens/compiler/failure/reference-two-name-arguments.json +++ b/tests/goldens/compiler/failure/reference-two-name-arguments.json @@ -11,11 +11,11 @@ "message": "__ref(\"stg_orders\", \"orders\") is not a valid __ref() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT order_id AS customer_id, 1 AS total_amount", "FROM __ref(\"stg_orders\", \"orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -113,8 +113,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -184,8 +184,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/reference-unclosed-call.json b/tests/goldens/compiler/failure/reference-unclosed-call.json index ff28d64647..e1e5583b43 100644 --- a/tests/goldens/compiler/failure/reference-unclosed-call.json +++ b/tests/goldens/compiler/failure/reference-unclosed-call.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/marts/customer_totals.sql:6:6: SQL reference contains an unclosed parenthesis" + "message": "sql/models/marts/customer_totals.sql:6:6: SQL reference contains an unclosed parenthesis" } ] } diff --git a/tests/goldens/compiler/failure/resource-name-collision.json b/tests/goldens/compiler/failure/resource-name-collision.json index 65d112fa88..4d41ad57ed 100644 --- a/tests/goldens/compiler/failure/resource-name-collision.json +++ b/tests/goldens/compiler/failure/resource-name-collision.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D007", - "message": "Logical relation name 'stg_orders' is declared as both model in models/staging/stg_orders.sql and seed in seeds/stg_orders.yml" + "message": "Logical relation name 'stg_orders' is declared as both model in sql/models/staging/stg_orders.sql and seed in sql/seeds/stg_orders.yml" } ] } diff --git a/tests/goldens/compiler/failure/rule-custom-finding.json b/tests/goldens/compiler/failure/rule-custom-finding.json index b79f012d73..692a97ced6 100644 --- a/tests/goldens/compiler/failure/rule-custom-finding.json +++ b/tests/goldens/compiler/failure/rule-custom-finding.json @@ -9,11 +9,11 @@ "severity": "error", "code": "XSQBRDIFF001", "message": "Models avoid the stg_ prefix", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 1, "column": 1, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 1, "column": 1 }, @@ -24,15 +24,15 @@ ], "compiled": {}, "compiled_failed": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "-- sqb: compile failed for this model; not buildable", - "-- XSQBRDIFF001 at models/staging/stg_orders.sql:1:1: Models avoid the stg_ prefix", + "-- XSQBRDIFF001 at sql/models/staging/stg_orders.sql:1:1: Models avoid the stg_ prefix", "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" diff --git a/tests/goldens/compiler/failure/rule-unused-cte-after-variable-and-macro.json b/tests/goldens/compiler/failure/rule-unused-cte-after-variable-and-macro.json index 5b2ab41638..17219ecb0d 100644 --- a/tests/goldens/compiler/failure/rule-unused-cte-after-variable-and-macro.json +++ b/tests/goldens/compiler/failure/rule-unused-cte-after-variable-and-macro.json @@ -9,11 +9,11 @@ "severity": "error", "code": "SQLCLEAN005", "message": "CTE is unreachable from the final query", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 117, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 117 }, @@ -27,16 +27,16 @@ ], "compiled": {}, "compiled_failed": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "-- sqb: compile failed for this model; not buildable", - "-- SQLCLEAN005 at models/marts/customer_totals.sql:5:117: CTE is unreachable from the final query", + "-- SQLCLEAN005 at sql/models/marts/customer_totals.sql:5:117: CTE is unreachable from the final query", "WITH totals AS (SELECT customer_id, (amount * 100) AS cents, 2 AS floor_cents FROM __ref(\"stg_orders\")), spare AS (SELECT 1 AS one)", "SELECT customer_id, SUM(cents) AS total_amount", "FROM totals WHERE cents > floor_cents", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" diff --git a/tests/goldens/compiler/failure/rule-unused-cte.json b/tests/goldens/compiler/failure/rule-unused-cte.json index b9c998fdd2..f50c03476e 100644 --- a/tests/goldens/compiler/failure/rule-unused-cte.json +++ b/tests/goldens/compiler/failure/rule-unused-cte.json @@ -9,11 +9,11 @@ "severity": "error", "code": "SQLCLEAN005", "message": "CTE is unreachable from the final query", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 6 }, @@ -27,16 +27,16 @@ ], "compiled": {}, "compiled_failed": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "-- sqb: compile failed for this model; not buildable", - "-- SQLCLEAN005 at models/marts/customer_totals.sql:5:6: CTE is unreachable from the final query", + "-- SQLCLEAN005 at sql/models/marts/customer_totals.sql:5:6: CTE is unreachable from the final query", "WITH spare AS (SELECT 1 AS one)", "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" diff --git a/tests/goldens/compiler/failure/schema-from-sibling-folder.json b/tests/goldens/compiler/failure/schema-from-sibling-folder.json index fb5dc4d694..22a45f561b 100644 --- a/tests/goldens/compiler/failure/schema-from-sibling-folder.json +++ b/tests/goldens/compiler/failure/schema-from-sibling-folder.json @@ -8,22 +8,22 @@ "phase": "compile", "severity": "error", "code": "S006", - "message": "Schema 'order_shape' is not visible from 'models/staging/stg_orders.sql'. It is defined at models/marts/_sqlbuild/_schemas/order_shape.sql with local scope owned by 'models/marts'", + "message": "Schema 'order_shape' is not visible from 'sql/models/staging/stg_orders.sql'. It is defined at sql/models/marts/_sqlbuild/_schemas/order_shape.sql with local scope owned by 'sql/models/marts'", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", - "help": "move 'models/marts/_sqlbuild/_schemas/order_shape.sql' to a schemas/ role owned by 'models/staging' or one of its parent folders, or to the project-wide schemas/ when consumers span resource trees" + "path": "sql/models/staging/stg_orders.sql", + "help": "move 'sql/models/marts/_sqlbuild/_schemas/order_shape.sql' to a schemas/ role owned by 'sql/models/staging' or one of its parent folders, or to the project-wide sql/schemas/ when consumers span resource trees" }, { "phase": "compile", "severity": "error", "code": "S007", - "message": "Declaration 'schema:order_shape' is currently exact-owner-private at 'models/marts' (models/marts/_sqlbuild/_schemas/order_shape.sql); required exact-owner-private at 'models/staging'. Consumers: model:stg_orders. Move it to 'models/staging/_sqlbuild/_schemas/'", - "path": "models/marts/_sqlbuild/_schemas/order_shape.sql", + "message": "Declaration 'schema:order_shape' is currently exact-owner-private at 'sql/models/marts' (sql/models/marts/_sqlbuild/_schemas/order_shape.sql); required exact-owner-private at 'sql/models/staging'. Consumers: model:stg_orders. Move it to 'sql/models/staging/_sqlbuild/_schemas/'", + "path": "sql/models/marts/_sqlbuild/_schemas/order_shape.sql", "line": 1, "column": 1, "location": { - "path": "models/marts/_sqlbuild/_schemas/order_shape.sql", + "path": "sql/models/marts/_sqlbuild/_schemas/order_shape.sql", "line": 1, "column": 1 } @@ -32,13 +32,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -52,8 +52,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -121,8 +121,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -202,8 +202,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/schema-unterminated-declaration.json b/tests/goldens/compiler/failure/schema-unterminated-declaration.json index 82860340ab..719029afbf 100644 --- a/tests/goldens/compiler/failure/schema-unterminated-declaration.json +++ b/tests/goldens/compiler/failure/schema-unterminated-declaration.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D013", - "message": "/models/staging/_sqlbuild/_schemas/orders.sql has an unterminated declaration header" + "message": "/sql/models/staging/_sqlbuild/_schemas/orders.sql has an unterminated declaration header" } ] } diff --git a/tests/goldens/compiler/failure/schema-yml-invalid-yaml.json b/tests/goldens/compiler/failure/schema-yml-invalid-yaml.json index ae3dc287c4..410f23d4b7 100644 --- a/tests/goldens/compiler/failure/schema-yml-invalid-yaml.json +++ b/tests/goldens/compiler/failure/schema-yml-invalid-yaml.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D005", - "message": "/models/marts/schema.yml contains invalid YAML at line 2, column 1: while parsing a node, did not find expected node content" + "message": "/sql/models/marts/schema.yml contains invalid YAML at line 2, column 1: while parsing a node, did not find expected node content" } ] } diff --git a/tests/goldens/compiler/failure/schema-yml-model-metadata.json b/tests/goldens/compiler/failure/schema-yml-model-metadata.json index 0d428b077f..4dac68a507 100644 --- a/tests/goldens/compiler/failure/schema-yml-model-metadata.json +++ b/tests/goldens/compiler/failure/schema-yml-model-metadata.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D005", - "message": "/models/marts/schema.yml declares model metadata in 'models', but model metadata must live in the model file MODEL(...). Move description, columns, and audits into the model header." + "message": "/sql/models/marts/schema.yml declares model metadata in 'models', but model metadata must live in the model file MODEL(...). Move description, columns, and audits into the model header." } ] } diff --git a/tests/goldens/compiler/failure/scope-duplicate-scoped-enum.json b/tests/goldens/compiler/failure/scope-duplicate-scoped-enum.json index f0290603a8..35859b4d12 100644 --- a/tests/goldens/compiler/failure/scope-duplicate-scoped-enum.json +++ b/tests/goldens/compiler/failure/scope-duplicate-scoped-enum.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Invalid declaration scope index:\n[S003] Duplicate declaration 'enum:staged_status' at enums/status.sql:1:1, models/staging/_enums/status.sql:1:1\n[S003] Duplicate declaration 'enum:staged_status' at enums/status.sql:1:1, models/staging/_enums/status.sql:1:1" + "message": "Invalid declaration scope index:\n[S003] Duplicate declaration 'enum:staged_status' at sql/enums/status.sql:1:1, sql/models/staging/_enums/status.sql:1:1\n[S003] Duplicate declaration 'enum:staged_status' at sql/enums/status.sql:1:1, sql/models/staging/_enums/status.sql:1:1" } ] } diff --git a/tests/goldens/compiler/failure/scope-first-of-two-visibility-errors.json b/tests/goldens/compiler/failure/scope-first-of-two-visibility-errors.json index e2a6fe7353..edd13d6414 100644 --- a/tests/goldens/compiler/failure/scope-first-of-two-visibility-errors.json +++ b/tests/goldens/compiler/failure/scope-first-of-two-visibility-errors.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Enum 'staged_status' is known but inaccessible in '/models/marts/customer_totals.sql'. It is defined at models/staging/_enums/status.sql:1:1 with local scope owned by 'models/staging'; consumer path: '/models/marts/customer_totals.sql'" + "message": "Enum 'staged_status' is known but inaccessible in '/sql/models/marts/customer_totals.sql'. It is defined at sql/models/staging/_enums/status.sql:1:1 with local scope owned by 'sql/models/staging'; consumer path: '/sql/models/marts/customer_totals.sql'" } ] } diff --git a/tests/goldens/compiler/failure/scope-inaccessible-local-macro.json b/tests/goldens/compiler/failure/scope-inaccessible-local-macro.json index 87c131c94e..fba516bbfa 100644 --- a/tests/goldens/compiler/failure/scope-inaccessible-local-macro.json +++ b/tests/goldens/compiler/failure/scope-inaccessible-local-macro.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.staged_amount' in '/models/marts/customer_totals.sql' is inaccessible. Defined at 'models/staging/_macros/python/amounts.py:1:1' with scope owner 'models/staging'; consumer/definition path is '/models/marts/customer_totals.sql'. Visible macros: none" + "message": "Macro '@py.staged_amount' in '/sql/models/marts/customer_totals.sql' is inaccessible. Defined at 'sql/models/staging/_macros/python/amounts.py:1:1' with scope owner 'sql/models/staging'; consumer/definition path is '/sql/models/marts/customer_totals.sql'. Visible macros: none" } ] } diff --git a/tests/goldens/compiler/failure/scope-test-outside-relationship-grant.json b/tests/goldens/compiler/failure/scope-test-outside-relationship-grant.json index c0fdc3f0d4..ed00fd0daf 100644 --- a/tests/goldens/compiler/failure/scope-test-outside-relationship-grant.json +++ b/tests/goldens/compiler/failure/scope-test-outside-relationship-grant.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Enum 'staged_status' is known but inaccessible in '/tests/unit/test_customer_totals.sql'. It is defined at models/staging/_enums/status.sql:1:1 with local scope owned by 'models/staging'; consumer path: '/tests/unit/test_customer_totals.sql'" + "message": "Enum 'staged_status' is known but inaccessible in '/tests/unit/test_customer_totals.sql'. It is defined at sql/models/staging/_enums/status.sql:1:1 with local scope owned by 'sql/models/staging'; consumer path: '/tests/unit/test_customer_totals.sql'" } ] } diff --git a/tests/goldens/compiler/failure/scoped-root-at-project-root.json b/tests/goldens/compiler/failure/scoped-root-at-project-root.json deleted file mode 100644 index a2b71957ba..0000000000 --- a/tests/goldens/compiler/failure/scoped-root-at-project-root.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "commands": [ - { - "label": "compile", - "exit_code": 1, - "diagnostics": [ - { - "phase": "compile", - "severity": "error", - "code": "D013", - "message": "Scoped declaration root _enums/ must be below a canonical authored root" - } - ] - } - ], - "compiled": {}, - "manifest": null -} diff --git a/tests/goldens/compiler/failure/seed-declaration-without-csv.json b/tests/goldens/compiler/failure/seed-declaration-without-csv.json index 8eb1c9b5d2..79afae1df0 100644 --- a/tests/goldens/compiler/failure/seed-declaration-without-csv.json +++ b/tests/goldens/compiler/failure/seed-declaration-without-csv.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D008", - "message": "Seed declaration 'order_channels' in seeds/order_channels.yml has no matching CSV file under seeds/" + "message": "Seed declaration 'order_channels' in sql/seeds/order_channels.yml has no matching CSV file under sql/seeds/" } ] } diff --git a/tests/goldens/compiler/failure/seed-header-mismatch.json b/tests/goldens/compiler/failure/seed-header-mismatch.json index d333066a74..3c3dd4f82d 100644 --- a/tests/goldens/compiler/failure/seed-header-mismatch.json +++ b/tests/goldens/compiler/failure/seed-header-mismatch.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D008", - "message": "seeds/order_channels.csv header ('id', 'name') does not match declared seed columns ('id', 'label') for 'order_channels'" + "message": "sql/seeds/order_channels.csv header ('id', 'name') does not match declared seed columns ('id', 'label') for 'order_channels'" } ] } diff --git a/tests/goldens/compiler/failure/seed-without-header.json b/tests/goldens/compiler/failure/seed-without-header.json index 323aeb2ead..fcfa58aca0 100644 --- a/tests/goldens/compiler/failure/seed-without-header.json +++ b/tests/goldens/compiler/failure/seed-without-header.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D008", - "message": "Seed CSV seeds/lookups.csv has no matching declaration for seed 'lookups' under seeds/**/*.yml" + "message": "Seed CSV sql/seeds/lookups.csv has no matching declaration for seed 'lookups' under sql/seeds/**/*.yml" } ] } diff --git a/tests/goldens/compiler/failure/seed-yaml-extension.json b/tests/goldens/compiler/failure/seed-yaml-extension.json index 57cedec1d4..af91ea8f23 100644 --- a/tests/goldens/compiler/failure/seed-yaml-extension.json +++ b/tests/goldens/compiler/failure/seed-yaml-extension.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D005", - "message": "Seed declaration file seeds/order_channels.yaml must use .yml; .yaml is not supported" + "message": "Seed declaration file sql/seeds/order_channels.yaml must use .yml; .yaml is not supported" } ] } diff --git a/tests/goldens/compiler/failure/semantic-cursor-inputs-unknown-column.json b/tests/goldens/compiler/failure/semantic-cursor-inputs-unknown-column.json index ea2df9429b..c1793ad3a2 100644 --- a/tests/goldens/compiler/failure/semantic-cursor-inputs-unknown-column.json +++ b/tests/goldens/compiler/failure/semantic-cursor-inputs-unknown-column.json @@ -11,11 +11,11 @@ "message": "cursor_inputs stg_orders references unknown column 'placed_at'", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 9, "column": 16, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 9, "column": 16 }, @@ -25,13 +25,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/semantic-qualified-alias-unknown-column.json b/tests/goldens/compiler/failure/semantic-qualified-alias-unknown-column.json index 662ed8627a..f78dd08dc7 100644 --- a/tests/goldens/compiler/failure/semantic-qualified-alias-unknown-column.json +++ b/tests/goldens/compiler/failure/semantic-qualified-alias-unknown-column.json @@ -11,11 +11,11 @@ "message": "Unknown column 'amonut' in stg_orders (as o)", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 29, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 29, "end_line": 5, @@ -30,13 +30,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT o.customer_id, SUM(o.amonut) AS total_amount", "FROM __ref(\"stg_orders\") AS o", "GROUP BY o.customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -50,8 +50,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -119,8 +119,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -190,8 +190,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/semantic-recovered-downstream-uses.json b/tests/goldens/compiler/failure/semantic-recovered-downstream-uses.json index 6a894d3e8f..0756536f38 100644 --- a/tests/goldens/compiler/failure/semantic-recovered-downstream-uses.json +++ b/tests/goldens/compiler/failure/semantic-recovered-downstream-uses.json @@ -11,11 +11,11 @@ "message": "Unknown column 'amonut' in raw_orders", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 31, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 31, "end_line": 5, @@ -31,13 +31,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amonut, status", "FROM __source(\"raw_orders\")", "" @@ -51,8 +51,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -120,8 +120,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -191,8 +191,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/semantic-recovered-uses-through-intermediate.json b/tests/goldens/compiler/failure/semantic-recovered-uses-through-intermediate.json index ed37acb33b..7c2290e1e7 100644 --- a/tests/goldens/compiler/failure/semantic-recovered-uses-through-intermediate.json +++ b/tests/goldens/compiler/failure/semantic-recovered-uses-through-intermediate.json @@ -11,11 +11,11 @@ "message": "Unknown column 'amonut' in raw_orders", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 31, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 31, "end_line": 5, @@ -31,18 +31,18 @@ } ], "compiled": { - "models/intermediate/int_orders.sql": [ + "sql/models/intermediate/int_orders.sql": [ "SELECT customer_id, amount * 2 AS doubled_amount", "FROM __ref(\"stg_orders\")", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(doubled_amount) AS total_amount", "FROM __ref(\"int_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amonut, status", "FROM __source(\"raw_orders\")", "" @@ -56,8 +56,8 @@ "name": "int_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/intermediate/int_orders.sql", - "original_file_path": "models/intermediate/int_orders.sql", + "path": "sql/models/intermediate/int_orders.sql", + "original_file_path": "sql/models/intermediate/int_orders.sql", "unique_id": "model.failure_corpus.int_orders", "fqn": [ "failure_corpus", @@ -125,8 +125,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -194,8 +194,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -265,8 +265,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/semantic-rejected-opt-out-counts-findings.json b/tests/goldens/compiler/failure/semantic-rejected-opt-out-counts-findings.json index 588ae44763..d7ec81c919 100644 --- a/tests/goldens/compiler/failure/semantic-rejected-opt-out-counts-findings.json +++ b/tests/goldens/compiler/failure/semantic-rejected-opt-out-counts-findings.json @@ -11,11 +11,11 @@ "message": "`sql_analysis false` is not needed for model 'customer_totals'", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 3, "column": 3, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 3, "column": 3 }, @@ -28,14 +28,14 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(refund) AS total_amount, MAX(amonut) AS top_amount", "FROM __ref(\"stg_orders\")", "WHERE status > 5", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -49,8 +49,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -118,8 +118,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -189,8 +189,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/semantic-source-cursor-unknown-column.json b/tests/goldens/compiler/failure/semantic-source-cursor-unknown-column.json index 112420a01c..29523c8b06 100644 --- a/tests/goldens/compiler/failure/semantic-source-cursor-unknown-column.json +++ b/tests/goldens/compiler/failure/semantic-source-cursor-unknown-column.json @@ -11,11 +11,11 @@ "message": "cursor_column references unknown column 'loaded_at'", "resource_type": "source", "resource_name": "raw_events", - "path": "sources/raw.yml", + "path": "sql/sources/raw.yml", "line": 21, "column": 20, "location": { - "path": "sources/raw.yml", + "path": "sql/sources/raw.yml", "line": 21, "column": 20 }, @@ -25,13 +25,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -185,8 +185,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", @@ -253,8 +253,8 @@ "name": "raw_events", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_events", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/semantic-temporal-comparison-help.json b/tests/goldens/compiler/failure/semantic-temporal-comparison-help.json index 877af0724a..930543ca31 100644 --- a/tests/goldens/compiler/failure/semantic-temporal-comparison-help.json +++ b/tests/goldens/compiler/failure/semantic-temporal-comparison-help.json @@ -11,11 +11,11 @@ "message": "Incompatible comparison between TIMESTAMP and INTEGER", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 7, "column": 7, "end_line": 7, @@ -30,14 +30,14 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT o.customer_id, SUM(o.amount) AS total_amount", "FROM __ref(\"stg_orders\") AS o", "WHERE o.ordered_at > 5", "GROUP BY o.customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status, CAST('2026-01-01' AS TIMESTAMP) AS ordered_at", "FROM __source(\"raw_orders\")", "" @@ -51,8 +51,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -120,8 +120,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -191,8 +191,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/semantic-type-error-unchecked-uses.json b/tests/goldens/compiler/failure/semantic-type-error-unchecked-uses.json index 6b3daf288b..540dcdb818 100644 --- a/tests/goldens/compiler/failure/semantic-type-error-unchecked-uses.json +++ b/tests/goldens/compiler/failure/semantic-type-error-unchecked-uses.json @@ -11,11 +11,11 @@ "message": "Arithmetic operation expects NUMERIC-compatible operands, found STRING and INTEGER", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 31, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 5, "column": 31, "end_line": 5, @@ -31,13 +31,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, status + 1 AS amount, status", "FROM __source(\"raw_orders\")", "" @@ -51,8 +51,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -120,8 +120,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -191,8 +191,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/semantic-udf-qualified-cast-argument-family.json b/tests/goldens/compiler/failure/semantic-udf-qualified-cast-argument-family.json index 591093f15e..09bad64724 100644 --- a/tests/goldens/compiler/failure/semantic-udf-qualified-cast-argument-family.json +++ b/tests/goldens/compiler/failure/semantic-udf-qualified-cast-argument-family.json @@ -11,11 +11,11 @@ "message": "Function 'scaled_amount' argument 'p_factor' expects INTEGER, received TEXT; convert the argument explicitly", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 10, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 10 }, @@ -25,19 +25,19 @@ } ], "compiled": { - "functions/sql/scaled_amount.sql": [ + "sql/functions/sql/scaled_amount.sql": [ "CREATE OR REPLACE MACRO main.scaled_amount(p_amount, p_factor) AS (", "p_amount * p_factor", ")", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT o.customer_id,", " __udf(\"scaled_amount\")(o.amount, CAST(o.status AS VARCHAR)) AS total_amount", "FROM __ref(\"stg_orders\") AS o", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -51,8 +51,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -121,8 +121,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -192,8 +192,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/set-operation-width.json b/tests/goldens/compiler/failure/set-operation-width.json index 216edb4671..f06f7bacab 100644 --- a/tests/goldens/compiler/failure/set-operation-width.json +++ b/tests/goldens/compiler/failure/set-operation-width.json @@ -11,11 +11,11 @@ "message": "UNION operands return different column counts: left 2, right 1", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 1, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 1 }, @@ -25,13 +25,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, amount FROM __ref(\"stg_orders\")", "UNION ALL", "SELECT customer_id FROM __ref(\"stg_orders\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -45,8 +45,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -185,8 +185,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/single-quoted-source-name.json b/tests/goldens/compiler/failure/single-quoted-source-name.json index 85819900ef..4151b6a8c9 100644 --- a/tests/goldens/compiler/failure/single-quoted-source-name.json +++ b/tests/goldens/compiler/failure/single-quoted-source-name.json @@ -11,11 +11,11 @@ "message": "__source('raw_orders') is not a valid __source() call", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 6, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 6, "column": 6, "end_line": 6, @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source('raw_orders')", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -185,8 +185,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/singular-audit-across-trees.json b/tests/goldens/compiler/failure/singular-audit-across-trees.json index 0609e7b219..7ab44ccc0f 100644 --- a/tests/goldens/compiler/failure/singular-audit-across-trees.json +++ b/tests/goldens/compiler/failure/singular-audit-across-trees.json @@ -8,14 +8,14 @@ "phase": "compile", "severity": "error", "code": "S009", - "message": "Declaration 'singular_audit:totals_have_orders' is currently descendant-public at 'models/marts' (models/marts/_sqlbuild/audits/singular/totals_have_orders.sql); required project at 'top-level root'. References: model:customer_totals, source:raw_orders. Move it to 'top-level audits/singular/'", + "message": "Declaration 'singular_audit:totals_have_orders' is currently descendant-public at 'sql/models/marts' (sql/models/marts/_sqlbuild/audits/singular/totals_have_orders.sql); required project at 'top-level root'. References: model:customer_totals, source:raw_orders. Move it to 'top-level sql/audits/singular/'", "resource_type": "audit", "resource_name": "totals_have_orders", - "path": "models/marts/_sqlbuild/audits/singular/totals_have_orders.sql", + "path": "sql/models/marts/_sqlbuild/audits/singular/totals_have_orders.sql", "line": 1, "column": 1, "location": { - "path": "models/marts/_sqlbuild/audits/singular/totals_have_orders.sql", + "path": "sql/models/marts/_sqlbuild/audits/singular/totals_have_orders.sql", "line": 1, "column": 1 } @@ -24,20 +24,20 @@ } ], "compiled": { - "audits/singular/totals_have_orders.sql": [ + "sql/audits/singular/totals_have_orders.sql": [ "SELECT t.customer_id", "FROM __ref(\"customer_totals\") t", "LEFT JOIN __source(\"raw_orders\") o ON t.customer_id = o.customer_id", "WHERE o.customer_id IS NULL", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -51,8 +51,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -120,8 +120,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -191,8 +191,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/singular-audit-one-resource.json b/tests/goldens/compiler/failure/singular-audit-one-resource.json index 0985d3bfad..9ff9b853c8 100644 --- a/tests/goldens/compiler/failure/singular-audit-one-resource.json +++ b/tests/goldens/compiler/failure/singular-audit-one-resource.json @@ -8,27 +8,27 @@ "phase": "compile", "severity": "error", "code": "P004", - "message": "Singular audit 'positive_totals' in models/marts/_sqlbuild/audits/singular/positive_totals.sql checks only model 'customer_totals'; singular audits must be cross-resource", + "message": "Singular audit 'positive_totals' in sql/models/marts/_sqlbuild/audits/singular/positive_totals.sql checks only model 'customer_totals'; singular audits must be cross-resource", "resource_type": "audit", "resource_name": "positive_totals", - "path": "models/marts/_sqlbuild/audits/singular/positive_totals.sql", + "path": "sql/models/marts/_sqlbuild/audits/singular/positive_totals.sql", "help": "attach a generic audit to 'customer_totals' instead: write it in an audits/generic/ role and select FROM @relation, joining @relation to itself for self-join checks" } ] } ], "compiled": { - "audits/singular/positive_totals.sql": [ + "sql/audits/singular/positive_totals.sql": [ "SELECT customer_id FROM __ref(\"customer_totals\") WHERE total_amount < 0", "" ], - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -42,8 +42,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -111,8 +111,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -182,8 +182,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/source-parse.json b/tests/goldens/compiler/failure/source-parse.json index 905f62d103..4ce944c21a 100644 --- a/tests/goldens/compiler/failure/source-parse.json +++ b/tests/goldens/compiler/failure/source-parse.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D006", - "message": "/sources/raw.yml contains invalid YAML at line 4, column 1: while parsing a node, did not find expected node content" + "message": "/sql/sources/raw.yml contains invalid YAML at line 4, column 1: while parsing a node, did not find expected node content" } ] } diff --git a/tests/goldens/compiler/failure/source-removed-ingestr-block.json b/tests/goldens/compiler/failure/source-removed-ingestr-block.json index 2261883f87..be50a8253a 100644 --- a/tests/goldens/compiler/failure/source-removed-ingestr-block.json +++ b/tests/goldens/compiler/failure/source-removed-ingestr-block.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D006", - "message": "/sources/raw.yml source 'raw_orders' declares an ingestr integration, which SQLBuild no longer supports; declare the source with `managed: true` and load it with a Python `@loader` named after the source instead" + "message": "/sql/sources/raw.yml source 'raw_orders' declares an ingestr integration, which SQLBuild no longer supports; declare the source with `managed: true` and load it with a Python `@loader` named after the source instead" } ] } diff --git a/tests/goldens/compiler/failure/source-unknown-key.json b/tests/goldens/compiler/failure/source-unknown-key.json index cb5e919763..a772946733 100644 --- a/tests/goldens/compiler/failure/source-unknown-key.json +++ b/tests/goldens/compiler/failure/source-unknown-key.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D006", - "message": "/sources/raw.yml source has unknown keys: freshnes; allowed keys: audits, columns, contract, cursor_column, database, description, expression, final, freshness, load_batch_size, managed, meta, name, schema, table, type_enforcement, unique_key, write_strategy", + "message": "/sql/sources/raw.yml source has unknown keys: freshnes; allowed keys: audits, columns, contract, cursor_column, database, description, expression, final, freshness, load_batch_size, managed, meta, name, schema, table, type_enforcement, unique_key, write_strategy", "help": "did you mean 'freshness'?" } ] diff --git a/tests/goldens/compiler/failure/source-unsupported-yaml.json b/tests/goldens/compiler/failure/source-unsupported-yaml.json index 76820a2e86..61187494e9 100644 --- a/tests/goldens/compiler/failure/source-unsupported-yaml.json +++ b/tests/goldens/compiler/failure/source-unsupported-yaml.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D006", - "message": "/sources/raw.yml uses YAML that SQLBuild does not support at line 17, column 22: values tagged !!binary", + "message": "/sql/sources/raw.yml uses YAML that SQLBuild does not support at line 17, column 22: values tagged !!binary", "help": "SQLBuild reads plain YAML: block and flow mappings and sequences, plain and quoted scalars, literal and folded block scalars, anchors, aliases and merge keys. Rewrite this part in one of those forms." } ] diff --git a/tests/goldens/compiler/failure/sources-removed-dlt-sources.json b/tests/goldens/compiler/failure/sources-removed-dlt-sources.json index 61f3d75708..4f2314e0b3 100644 --- a/tests/goldens/compiler/failure/sources-removed-dlt-sources.json +++ b/tests/goldens/compiler/failure/sources-removed-dlt-sources.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D006", - "message": "/sources/loaded.yml declares dlt_sources, a dlt integration, which SQLBuild no longer supports; declare each source under `sources:` with `managed: true` and load it with a Python `@loader` named after the source instead" + "message": "/sql/sources/loaded.yml declares dlt_sources, a dlt integration, which SQLBuild no longer supports; declare each source under `sources:` with `managed: true` and load it with a Python `@loader` named after the source instead" } ] } diff --git a/tests/goldens/compiler/failure/sql-function-arguments-not-a-map.json b/tests/goldens/compiler/failure/sql-function-arguments-not-a-map.json index 99c8c340fb..7ef5177917 100644 --- a/tests/goldens/compiler/failure/sql-function-arguments-not-a-map.json +++ b/tests/goldens/compiler/failure/sql-function-arguments-not-a-map.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL function file functions/sql/order_label.sql arguments must be a map" + "message": "SQL function file sql/functions/sql/order_label.sql arguments must be a map" } ] } diff --git a/tests/goldens/compiler/failure/sql-function-blank-tag.json b/tests/goldens/compiler/failure/sql-function-blank-tag.json index c2a5f5563b..8e2d60657d 100644 --- a/tests/goldens/compiler/failure/sql-function-blank-tag.json +++ b/tests/goldens/compiler/failure/sql-function-blank-tag.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL function file functions/sql/order_label.sql tags entries must be non-empty strings" + "message": "SQL function file sql/functions/sql/order_label.sql tags entries must be non-empty strings" } ] } diff --git a/tests/goldens/compiler/failure/sql-function-header.json b/tests/goldens/compiler/failure/sql-function-header.json index 4b0cd22780..099b3f9a23 100644 --- a/tests/goldens/compiler/failure/sql-function-header.json +++ b/tests/goldens/compiler/failure/sql-function-header.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "FUNCTION(...) in '/functions/sql/is_placed.sql' contains invalid SQLBuild header syntax: expected value at position 42" + "message": "FUNCTION(...) in '/sql/functions/sql/is_placed.sql' contains invalid SQLBuild header syntax: expected value at position 42" } ] } diff --git a/tests/goldens/compiler/failure/sql-function-invalid-return-type.json b/tests/goldens/compiler/failure/sql-function-invalid-return-type.json index fe046ea9ec..b2cab9f49c 100644 --- a/tests/goldens/compiler/failure/sql-function-invalid-return-type.json +++ b/tests/goldens/compiler/failure/sql-function-invalid-return-type.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL function functions/sql/order_label.sql return type type 'DECIMAL(10,' is not valid for adapter 'duckdb' SQL analysis dialect 'duckdb': Parse error at line 1, column 12: Expected number" + "message": "SQL function sql/functions/sql/order_label.sql return type type 'DECIMAL(10,' is not valid for adapter 'duckdb' SQL analysis dialect 'duckdb': Parse error at line 1, column 12: Expected number" } ] } diff --git a/tests/goldens/compiler/failure/sql-function-missing-returns.json b/tests/goldens/compiler/failure/sql-function-missing-returns.json index 56078e96cd..476ef1cbf0 100644 --- a/tests/goldens/compiler/failure/sql-function-missing-returns.json +++ b/tests/goldens/compiler/failure/sql-function-missing-returns.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL function file functions/sql/order_label.sql must declare returns" + "message": "SQL function file sql/functions/sql/order_label.sql must declare returns" } ] } diff --git a/tests/goldens/compiler/failure/sql-function-returns-list.json b/tests/goldens/compiler/failure/sql-function-returns-list.json index 9402bbc9b4..e1fd7e4dad 100644 --- a/tests/goldens/compiler/failure/sql-function-returns-list.json +++ b/tests/goldens/compiler/failure/sql-function-returns-list.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL function file functions/sql/order_label.sql returns must be a type string or table column declaration" + "message": "SQL function file sql/functions/sql/order_label.sql returns must be a type string or table column declaration" } ] } diff --git a/tests/goldens/compiler/failure/sql-function-template-namespace.json b/tests/goldens/compiler/failure/sql-function-template-namespace.json index a245f00d16..129b9ddba9 100644 --- a/tests/goldens/compiler/failure/sql-function-template-namespace.json +++ b/tests/goldens/compiler/failure/sql-function-template-namespace.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL function functions/sql/order_label.sql returns references unsupported template namespace 'VAR'" + "message": "SQL function sql/functions/sql/order_label.sql returns references unsupported template namespace 'VAR'" } ] } diff --git a/tests/goldens/compiler/failure/sql-hook-unknown-key.json b/tests/goldens/compiler/failure/sql-hook-unknown-key.json index 2911434d9e..c94f29f943 100644 --- a/tests/goldens/compiler/failure/sql-hook-unknown-key.json +++ b/tests/goldens/compiler/failure/sql-hook-unknown-key.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D014", - "message": "HOOK() in '/hooks/sql/record_refresh.sql:3' has unsupported keys: phase", + "message": "HOOK() in '/sql/hooks/sql/record_refresh.sql:3' has unsupported keys: phase", "help": "supported keys: description" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-argument-mismatch.json b/tests/goldens/compiler/failure/sql-macro-argument-mismatch.json index fe91c81220..1d3dbd738c 100644 --- a/tests/goldens/compiler/failure/sql-macro-argument-mismatch.json +++ b/tests/goldens/compiler/failure/sql-macro-argument-mismatch.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P017", - "message": "call to macro cents() is missing argument amount DOUBLE\n model: stg_orders\n --> models/staging/stg_orders.sql:5:31\n --> models/staging/_sqlbuild/_macros/sql/cents.sql:7:1" + "message": "call to macro cents() is missing argument amount DOUBLE\n model: stg_orders\n --> sql/models/staging/stg_orders.sql:5:31\n --> sql/models/staging/_sqlbuild/_macros/sql/cents.sql:7:1" } ] } diff --git a/tests/goldens/compiler/failure/sql-macro-bare-call.json b/tests/goldens/compiler/failure/sql-macro-bare-call.json index 8460cad670..2d04df6ea8 100644 --- a/tests/goldens/compiler/failure/sql-macro-bare-call.json +++ b/tests/goldens/compiler/failure/sql-macro-bare-call.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P014", - "message": "macro call @cents() does not say which kind of macro it calls\n model: stg_orders\n --> models/staging/stg_orders.sql:5:31", + "message": "macro call @cents() does not say which kind of macro it calls\n model: stg_orders\n --> sql/models/staging/stg_orders.sql:5:31", "help": "write @sql.cents(...) to call a SQL macro or @py.cents(...) to call a Python macro" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-body-declaration-not-visible.json b/tests/goldens/compiler/failure/sql-macro-body-declaration-not-visible.json index ef701b1c3a..b924ac2736 100644 --- a/tests/goldens/compiler/failure/sql-macro-body-declaration-not-visible.json +++ b/tests/goldens/compiler/failure/sql-macro-body-declaration-not-visible.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "S026", - "message": "constant price_places is not visible from macros/sql/x.sql\n model: stg_orders\n --> models/staging/stg_orders.sql:5:31\n --> macros/sql/x.sql:3:11", + "message": "constant price_places is not visible from sql/macros/sql/x.sql\n model: stg_orders\n --> sql/models/staging/stg_orders.sql:5:31\n --> sql/macros/sql/x.sql:3:11", "help": "a SQL macro body resolves constants from its own folder, not its caller's; make it a parameter, e.g. value CONST, and pass @const(\"price_places\") from the model" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-body-misuses-an-any-family.json b/tests/goldens/compiler/failure/sql-macro-body-misuses-an-any-family.json index 716f276699..905836e713 100644 --- a/tests/goldens/compiler/failure/sql-macro-body-misuses-an-any-family.json +++ b/tests/goldens/compiler/failure/sql-macro-body-misuses-an-any-family.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P025", - "message": "body of macro x() does not accept every value of v ANY NUMERIC: Function 'upper' argument 1 expects String, found numeric\n model: stg_orders\n --> models/staging/_sqlbuild/_macros/sql/x.sql:3:1\n --> models/staging/stg_orders.sql:5:31", + "message": "body of macro x() does not accept every value of v ANY NUMERIC: Function 'upper' argument 1 expects String, found numeric\n model: stg_orders\n --> sql/models/staging/_sqlbuild/_macros/sql/x.sql:3:1\n --> sql/models/staging/stg_orders.sql:5:31", "help": "an ANY family argument may be any type of its family; the body is checked with the family's widest type, so CAST the argument or narrow its declared type" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-cte-name-clash.json b/tests/goldens/compiler/failure/sql-macro-cte-name-clash.json index 360c1a6978..bdb51eddfa 100644 --- a/tests/goldens/compiler/failure/sql-macro-cte-name-clash.json +++ b/tests/goldens/compiler/failure/sql-macro-cte-name-clash.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P018", - "message": "CTE \"live\" from macro live_orders() clashes with a CTE already defined in model:stg_orders\n model: stg_orders\n --> models/staging/stg_orders.sql:7:1\n --> models/staging/_sqlbuild/_macros/sql/live_orders.sql:6:6", + "message": "CTE \"live\" from macro live_orders() clashes with a CTE already defined in model:stg_orders\n model: stg_orders\n --> sql/models/staging/stg_orders.sql:7:1\n --> sql/models/staging/_sqlbuild/_macros/sql/live_orders.sql:6:6", "help": "pass __cte := to give the CTEs one call inserts their own names, as in @sql.live_orders(..., __cte := first_orders), or rename one of the CTEs" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-cycle.json b/tests/goldens/compiler/failure/sql-macro-cycle.json index 91db4be82e..000e657049 100644 --- a/tests/goldens/compiler/failure/sql-macro-cycle.json +++ b/tests/goldens/compiler/failure/sql-macro-cycle.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P019", - "message": "SQL macros call each other in a cycle: x() -> y() -> x()\n --> models/staging/_sqlbuild/_macros/sql/y.sql:3:1", + "message": "SQL macros call each other in a cycle: x() -> y() -> x()\n --> sql/models/staging/_sqlbuild/_macros/sql/y.sql:3:1", "help": "SQL macros may call other SQL macros, but not back into themselves" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-invalid-definition.json b/tests/goldens/compiler/failure/sql-macro-invalid-definition.json index a85b291acf..0648ea1510 100644 --- a/tests/goldens/compiler/failure/sql-macro-invalid-definition.json +++ b/tests/goldens/compiler/failure/sql-macro-invalid-definition.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P015", - "message": "returns TYPE OF w names no argument of macro x()\n --> models/staging/_sqlbuild/_macros/sql/x.sql:1:63", + "message": "returns TYPE OF w names no argument of macro x()\n --> sql/models/staging/_sqlbuild/_macros/sql/x.sql:1:63", "help": "name one of its arguments: v" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-misplaced-call.json b/tests/goldens/compiler/failure/sql-macro-misplaced-call.json index 9d15934b0d..2f5c6c47f8 100644 --- a/tests/goldens/compiler/failure/sql-macro-misplaced-call.json +++ b/tests/goldens/compiler/failure/sql-macro-misplaced-call.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P021", - "message": "CTE-list macro live_orders() must be called inside a WITH list\n model: stg_orders\n --> models/staging/stg_orders.sql:5:47", + "message": "CTE-list macro live_orders() must be called inside a WITH list\n model: stg_orders\n --> sql/models/staging/stg_orders.sql:5:47", "help": "call it between CTEs, such as WITH a AS (...), @sql.live_orders(a) b AS (...) SELECT ..." } ] diff --git a/tests/goldens/compiler/failure/sql-macro-reference-in-body.json b/tests/goldens/compiler/failure/sql-macro-reference-in-body.json index 7617b67704..d5dd7ced05 100644 --- a/tests/goldens/compiler/failure/sql-macro-reference-in-body.json +++ b/tests/goldens/compiler/failure/sql-macro-reference-in-body.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P016", - "message": "macro x() reads source:raw_orders through __source() in its body\n --> models/staging/_sqlbuild/_macros/sql/x.sql:3:31", + "message": "macro x() reads source:raw_orders through __source() in its body\n --> sql/models/staging/_sqlbuild/_macros/sql/x.sql:3:31", "help": "pass the relation in as a RELATION argument and write __source(\"raw_orders\") in the model" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-returns-disagrees-with-body.json b/tests/goldens/compiler/failure/sql-macro-returns-disagrees-with-body.json index e9042051be..041ff88d9c 100644 --- a/tests/goldens/compiler/failure/sql-macro-returns-disagrees-with-body.json +++ b/tests/goldens/compiler/failure/sql-macro-returns-disagrees-with-body.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P024", - "message": "macro x() declares returns DOUBLE, but its body is VARCHAR\n model: stg_orders\n --> models/staging/_sqlbuild/_macros/sql/x.sql:3:1\n --> models/staging/stg_orders.sql:5:31", + "message": "macro x() declares returns DOUBLE, but its body is VARCHAR\n model: stg_orders\n --> sql/models/staging/_sqlbuild/_macros/sql/x.sql:3:1\n --> sql/models/staging/stg_orders.sql:5:31", "help": "declare returns VARCHAR, CAST the body to DOUBLE, or remove returns to use the inferred type" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-runtime-parameter-as-literal.json b/tests/goldens/compiler/failure/sql-macro-runtime-parameter-as-literal.json index 45181b022f..d4c048f5ef 100644 --- a/tests/goldens/compiler/failure/sql-macro-runtime-parameter-as-literal.json +++ b/tests/goldens/compiler/failure/sql-macro-runtime-parameter-as-literal.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P023", - "message": "n is used where a literal is required; declare it n INTEGER CONST\n --> models/staging/_sqlbuild/_macros/sql/x.sql:3:49", + "message": "n is used where a literal is required; declare it n INTEGER CONST\n --> sql/models/staging/_sqlbuild/_macros/sql/x.sql:3:49", "help": "macro x() uses @n as LIMIT, which SQL accepts only as a literal; a CONST argument takes only values known at compile time" } ] diff --git a/tests/goldens/compiler/failure/sql-macro-undeclared-parameter.json b/tests/goldens/compiler/failure/sql-macro-undeclared-parameter.json index beefa100fa..99e7a5dcfc 100644 --- a/tests/goldens/compiler/failure/sql-macro-undeclared-parameter.json +++ b/tests/goldens/compiler/failure/sql-macro-undeclared-parameter.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P022", - "message": "@w in the body of macro x() names no parameter of the macro\n --> models/staging/_sqlbuild/_macros/sql/x.sql:3:6", + "message": "@w in the body of macro x() names no parameter of the macro\n --> sql/models/staging/_sqlbuild/_macros/sql/x.sql:3:6", "help": "its parameters are @v; declare it in arguments (...) or fix the name" } ] diff --git a/tests/goldens/compiler/failure/sql-test-glue-inverted-window.json b/tests/goldens/compiler/failure/sql-test-glue-inverted-window.json index f4752ebca8..de4ffe3d33 100644 --- a/tests/goldens/compiler/failure/sql-test-glue-inverted-window.json +++ b/tests/goldens/compiler/failure/sql-test-glue-inverted-window.json @@ -14,19 +14,19 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/marts/windowed_orders.sql": [ + "sql/models/marts/windowed_orders.sql": [ "SELECT order_id, amount", "FROM __source(\"raw_orders\")", "WHERE order_id >= __cursor_start() AND order_id < __cursor_end()", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" diff --git a/tests/goldens/compiler/failure/sql-test-glue-missing-mock.json b/tests/goldens/compiler/failure/sql-test-glue-missing-mock.json index b271f44a27..b75dc87bca 100644 --- a/tests/goldens/compiler/failure/sql-test-glue-missing-mock.json +++ b/tests/goldens/compiler/failure/sql-test-glue-missing-mock.json @@ -17,13 +17,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -53,8 +53,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -122,8 +122,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -193,8 +193,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/sql-test-glue-mock-reads-referencing-helper.json b/tests/goldens/compiler/failure/sql-test-glue-mock-reads-referencing-helper.json index 66df657efc..740bb385f7 100644 --- a/tests/goldens/compiler/failure/sql-test-glue-mock-reads-referencing-helper.json +++ b/tests/goldens/compiler/failure/sql-test-glue-mock-reads-referencing-helper.json @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -57,8 +57,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -126,8 +126,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -197,8 +197,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/sql-test-glue-window-without-cursor-model.json b/tests/goldens/compiler/failure/sql-test-glue-window-without-cursor-model.json index 2b0c5b3c1f..9804815490 100644 --- a/tests/goldens/compiler/failure/sql-test-glue-window-without-cursor-model.json +++ b/tests/goldens/compiler/failure/sql-test-glue-window-without-cursor-model.json @@ -14,13 +14,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" diff --git a/tests/goldens/compiler/failure/syntax-function.json b/tests/goldens/compiler/failure/syntax-function.json index b6ddf7cd24..fa41756e1c 100644 --- a/tests/goldens/compiler/failure/syntax-function.json +++ b/tests/goldens/compiler/failure/syntax-function.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL syntax error in function 'scaled_amount' (/functions/sql/scaled_amount.sql): Parse error at line 1, column 21: Expected RParen, got end of input ('') near [* (p_factor]", + "message": "SQL syntax error in function 'scaled_amount' (/sql/functions/sql/scaled_amount.sql): Parse error at line 1, column 21: Expected RParen, got end of input ('') near [* (p_factor]", "help": "if this SQL is valid for your warehouse, please report it so the parser can support it\n = help: SQL analysis is on for this project; to turn it off for every model, set this in sqlbuild_project.toml:\n [settings]\n sql_analysis = false\n = help: to skip SQL analysis for one run, use `--no-sql-analysis`" } ] diff --git a/tests/goldens/compiler/failure/syntax-hook.json b/tests/goldens/compiler/failure/syntax-hook.json index c1e7f2bcee..5d98fc7140 100644 --- a/tests/goldens/compiler/failure/syntax-hook.json +++ b/tests/goldens/compiler/failure/syntax-hook.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL syntax error in model 'customer_totals' post_hooks[0] sql(\"record_refresh\") (hooks/sql/record_refresh.sql): the duckdb parser cannot read Syntax error at or near 'WHERE' at line 1, column 13 of its SQL", + "message": "SQL syntax error in model 'customer_totals' post_hooks[0] sql(\"record_refresh\") (sql/hooks/sql/record_refresh.sql): the duckdb parser cannot read Syntax error at or near 'WHERE' at line 1, column 13 of its SQL", "help": "if this SQL is valid for your warehouse, skip SQL analysis for this model, add this to the MODEL header:\n MODEL (\n sql_analysis false,\n ...\n );\n and please report the SQL so the parser can support it\n = help: SQL analysis is on for this project; to turn it off for every model, set this in sqlbuild_project.toml:\n [settings]\n sql_analysis = false\n = help: to skip SQL analysis for one run, use `--no-sql-analysis`" } ] diff --git a/tests/goldens/compiler/failure/syntax-inline-hook.json b/tests/goldens/compiler/failure/syntax-inline-hook.json index 40c797daf7..c312de7247 100644 --- a/tests/goldens/compiler/failure/syntax-inline-hook.json +++ b/tests/goldens/compiler/failure/syntax-inline-hook.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL syntax error in model 'customer_totals' post_hooks[0] inline_sql(\"...\") (/models/marts/customer_totals.sql): the duckdb parser cannot read Syntax error at or near 'WHERE' at line 1, column 13 of its SQL", + "message": "SQL syntax error in model 'customer_totals' post_hooks[0] inline_sql(\"...\") (/sql/models/marts/customer_totals.sql): the duckdb parser cannot read Syntax error at or near 'WHERE' at line 1, column 13 of its SQL", "help": "if this SQL is valid for your warehouse, skip SQL analysis for this model, add this to the MODEL header:\n MODEL (\n sql_analysis false,\n ...\n );\n and please report the SQL so the parser can support it\n = help: SQL analysis is on for this project; to turn it off for every model, set this in sqlbuild_project.toml:\n [settings]\n sql_analysis = false\n = help: to skip SQL analysis for one run, use `--no-sql-analysis`" } ] diff --git a/tests/goldens/compiler/failure/syntax-source-expression.json b/tests/goldens/compiler/failure/syntax-source-expression.json index e336422be3..4624ada6e0 100644 --- a/tests/goldens/compiler/failure/syntax-source-expression.json +++ b/tests/goldens/compiler/failure/syntax-source-expression.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "SQL syntax error in source expression 'raw_orders' (/sources/raw.yml): Parse error at line 1, column 38: Unexpected token: Comma", + "message": "SQL syntax error in source expression 'raw_orders' (/sql/sources/raw.yml): Parse error at line 1, column 38: Unexpected token: Comma", "help": "if this SQL is valid for your warehouse, please report it so the parser can support it\n = help: SQL analysis is on for this project; to turn it off for every model, set this in sqlbuild_project.toml:\n [settings]\n sql_analysis = false\n = help: to skip SQL analysis for one run, use `--no-sql-analysis`" } ] diff --git a/tests/goldens/compiler/failure/table-function-arity.json b/tests/goldens/compiler/failure/table-function-arity.json index 22621bb4fa..47c7d41259 100644 --- a/tests/goldens/compiler/failure/table-function-arity.json +++ b/tests/goldens/compiler/failure/table-function-arity.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Model file models/marts/customer_totals.sql table function 'table_fn__orders_for' expects 1 argument but received 2" + "message": "Model file sql/models/marts/customer_totals.sql table function 'table_fn__orders_for' expects 1 argument but received 2" } ] } diff --git a/tests/goldens/compiler/failure/table-function-empty-call-argument.json b/tests/goldens/compiler/failure/table-function-empty-call-argument.json index 946df88075..ab510b9742 100644 --- a/tests/goldens/compiler/failure/table-function-empty-call-argument.json +++ b/tests/goldens/compiler/failure/table-function-empty-call-argument.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/marts/customer_totals.sql:6:6: SQL reference contains an empty argument" + "message": "sql/models/marts/customer_totals.sql:6:6: SQL reference contains an empty argument" } ] } diff --git a/tests/goldens/compiler/failure/table-function-single-quoted-name.json b/tests/goldens/compiler/failure/table-function-single-quoted-name.json index 9b0b2aaa4e..a2870df2e4 100644 --- a/tests/goldens/compiler/failure/table-function-single-quoted-name.json +++ b/tests/goldens/compiler/failure/table-function-single-quoted-name.json @@ -11,11 +11,11 @@ "message": "__table_fn('table_fn__orders_for') is not a valid __table_fn() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT order_id AS customer_id, 1 AS total_amount", "FROM __table_fn('table_fn__orders_for')(1)", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -113,8 +113,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -184,8 +184,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/table-function-unclosed-call.json b/tests/goldens/compiler/failure/table-function-unclosed-call.json index 233c2dadd1..f4a6a01579 100644 --- a/tests/goldens/compiler/failure/table-function-unclosed-call.json +++ b/tests/goldens/compiler/failure/table-function-unclosed-call.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "models/marts/customer_totals.sql:6:6: SQL table function call contains an unclosed parenthesis" + "message": "sql/models/marts/customer_totals.sql:6:6: SQL table function call contains an unclosed parenthesis" } ] } diff --git a/tests/goldens/compiler/failure/table-function-without-arguments.json b/tests/goldens/compiler/failure/table-function-without-arguments.json index 8ce7a7e6a3..9b0969eac9 100644 --- a/tests/goldens/compiler/failure/table-function-without-arguments.json +++ b/tests/goldens/compiler/failure/table-function-without-arguments.json @@ -11,11 +11,11 @@ "message": "__table_fn must be followed by an argument list", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -27,12 +27,12 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT order_id AS customer_id, 1 AS total_amount", "FROM __table_fn(\"table_fn__orders_for\") /* no call */", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -46,8 +46,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -113,8 +113,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -184,8 +184,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/test-assertion-reads-unmocked-source.json b/tests/goldens/compiler/failure/test-assertion-reads-unmocked-source.json index 0d989d6ad8..2d5ca7a882 100644 --- a/tests/goldens/compiler/failure/test-assertion-reads-unmocked-source.json +++ b/tests/goldens/compiler/failure/test-assertion-reads-unmocked-source.json @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/test-expected-reads-unknown-model.json b/tests/goldens/compiler/failure/test-expected-reads-unknown-model.json index fabb28be9c..947e39e9e6 100644 --- a/tests/goldens/compiler/failure/test-expected-reads-unknown-model.json +++ b/tests/goldens/compiler/failure/test-expected-reads-unknown-model.json @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/test-expected-unknown-column.json b/tests/goldens/compiler/failure/test-expected-unknown-column.json index c1e0924657..d4789a4277 100644 --- a/tests/goldens/compiler/failure/test-expected-unknown-column.json +++ b/tests/goldens/compiler/failure/test-expected-unknown-column.json @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -56,8 +56,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -125,8 +125,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -196,8 +196,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/test-helper-reads-unknown-model.json b/tests/goldens/compiler/failure/test-helper-reads-unknown-model.json index be0c3d62df..6a77512bd5 100644 --- a/tests/goldens/compiler/failure/test-helper-reads-unknown-model.json +++ b/tests/goldens/compiler/failure/test-helper-reads-unknown-model.json @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/test-reads-only-mocks.json b/tests/goldens/compiler/failure/test-reads-only-mocks.json index d91fc257f0..f267ebc058 100644 --- a/tests/goldens/compiler/failure/test-reads-only-mocks.json +++ b/tests/goldens/compiler/failure/test-reads-only-mocks.json @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/ungrouped-column.json b/tests/goldens/compiler/failure/ungrouped-column.json index 7c623a89c5..eb8ec35a26 100644 --- a/tests/goldens/compiler/failure/ungrouped-column.json +++ b/tests/goldens/compiler/failure/ungrouped-column.json @@ -11,11 +11,11 @@ "message": "Column must be grouped or used in an aggregate function", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 21, "end_line": 5, @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, status, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -116,8 +116,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -187,8 +187,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/unknown-column.json b/tests/goldens/compiler/failure/unknown-column.json index 3a592e9c09..15eb46f2f7 100644 --- a/tests/goldens/compiler/failure/unknown-column.json +++ b/tests/goldens/compiler/failure/unknown-column.json @@ -11,11 +11,11 @@ "message": "Unknown column 'discount' in stg_orders", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 25, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 5, "column": 25, "end_line": 5, @@ -29,13 +29,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(discount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -49,8 +49,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -118,8 +118,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -189,8 +189,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/unknown-constant.json b/tests/goldens/compiler/failure/unknown-constant.json index 5c030968f4..dd0cc6bf17 100644 --- a/tests/goldens/compiler/failure/unknown-constant.json +++ b/tests/goldens/compiler/failure/unknown-constant.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Unknown constant 'minimum_amount' in '/models/staging/stg_orders.sql'. Visible constants: none" + "message": "Unknown constant 'minimum_amount' in '/sql/models/staging/stg_orders.sql'. Visible constants: none" } ] } diff --git a/tests/goldens/compiler/failure/unknown-enum-member.json b/tests/goldens/compiler/failure/unknown-enum-member.json index 893223e5ee..2e707384a6 100644 --- a/tests/goldens/compiler/failure/unknown-enum-member.json +++ b/tests/goldens/compiler/failure/unknown-enum-member.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Unknown member 'RETURNED' for enum 'order_status' in '/models/staging/stg_orders.sql'. Available members: PLACED, SHIPPED" + "message": "Unknown member 'RETURNED' for enum 'order_status' in '/sql/models/staging/stg_orders.sql'. Available members: PLACED, SHIPPED" } ] } diff --git a/tests/goldens/compiler/failure/unknown-macro.json b/tests/goldens/compiler/failure/unknown-macro.json index d6438350d1..a530b06c5f 100644 --- a/tests/goldens/compiler/failure/unknown-macro.json +++ b/tests/goldens/compiler/failure/unknown-macro.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Unknown macro '@py.cents' in '/models/staging/stg_orders.sql'. Available macros: none" + "message": "Unknown macro '@py.cents' in '/sql/models/staging/stg_orders.sql'. Available macros: none" } ] } diff --git a/tests/goldens/compiler/failure/unknown-ref.json b/tests/goldens/compiler/failure/unknown-ref.json index 7ae331d589..b4cd69d03d 100644 --- a/tests/goldens/compiler/failure/unknown-ref.json +++ b/tests/goldens/compiler/failure/unknown-ref.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Model file models/marts/customer_totals.sql references unknown model 'stg_payments'" + "message": "Model file sql/models/marts/customer_totals.sql references unknown model 'stg_payments'" } ] } diff --git a/tests/goldens/compiler/failure/unknown-scalar-function.json b/tests/goldens/compiler/failure/unknown-scalar-function.json index 1a6bb7ca94..7be1d4fcf2 100644 --- a/tests/goldens/compiler/failure/unknown-scalar-function.json +++ b/tests/goldens/compiler/failure/unknown-scalar-function.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Model file models/staging/stg_orders.sql references unknown SQL function 'is_large'" + "message": "Model file sql/models/staging/stg_orders.sql references unknown SQL function 'is_large'" } ] } diff --git a/tests/goldens/compiler/failure/unknown-source.json b/tests/goldens/compiler/failure/unknown-source.json index b62cf8f45d..54fa8a5564 100644 --- a/tests/goldens/compiler/failure/unknown-source.json +++ b/tests/goldens/compiler/failure/unknown-source.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Model file models/staging/stg_orders.sql references unknown source 'raw_payments'" + "message": "Model file sql/models/staging/stg_orders.sql references unknown source 'raw_payments'" } ] } diff --git a/tests/goldens/compiler/failure/unknown-table-function.json b/tests/goldens/compiler/failure/unknown-table-function.json index 73f39c7925..0c4aaba43e 100644 --- a/tests/goldens/compiler/failure/unknown-table-function.json +++ b/tests/goldens/compiler/failure/unknown-table-function.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Model file models/marts/customer_totals.sql references unknown table function 'table_fn__missing'" + "message": "Model file sql/models/marts/customer_totals.sql references unknown table function 'table_fn__missing'" } ] } diff --git a/tests/goldens/compiler/failure/unneeded-sql-analysis-opt-out.json b/tests/goldens/compiler/failure/unneeded-sql-analysis-opt-out.json index 623f4193a5..ce6f05d61b 100644 --- a/tests/goldens/compiler/failure/unneeded-sql-analysis-opt-out.json +++ b/tests/goldens/compiler/failure/unneeded-sql-analysis-opt-out.json @@ -11,11 +11,11 @@ "message": "`sql_analysis false` is not needed for model 'stg_orders'", "resource_type": "model", "resource_name": "stg_orders", - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 3, "column": 3, "location": { - "path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", "line": 3, "column": 3 }, @@ -28,13 +28,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -48,8 +48,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -117,8 +117,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -188,8 +188,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/unquoted-ref-name.json b/tests/goldens/compiler/failure/unquoted-ref-name.json index 11c1f3b0c7..6ac75d4ad1 100644 --- a/tests/goldens/compiler/failure/unquoted-ref-name.json +++ b/tests/goldens/compiler/failure/unquoted-ref-name.json @@ -11,11 +11,11 @@ "message": "__ref(stg_orders) is not a valid __ref() call", "resource_type": "model", "resource_name": "customer_totals", - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "location": { - "path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", "line": 6, "column": 6, "end_line": 6, @@ -27,13 +27,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(stg_orders)", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -47,8 +47,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -114,8 +114,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -185,8 +185,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/unset-environment-variable.json b/tests/goldens/compiler/failure/unset-environment-variable.json index 330dd64b66..e364659e2a 100644 --- a/tests/goldens/compiler/failure/unset-environment-variable.json +++ b/tests/goldens/compiler/failure/unset-environment-variable.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "unknown environment variable '@@ENV:SQB_DIFFERENTIAL_UNSET' in '/models/staging/stg_orders.sql'" + "message": "unknown environment variable '@@ENV:SQB_DIFFERENTIAL_UNSET' in '/sql/models/staging/stg_orders.sql'" } ] } diff --git a/tests/goldens/compiler/failure/unused-declaration.json b/tests/goldens/compiler/failure/unused-declaration.json index 8daa69c5ed..fde497b08f 100644 --- a/tests/goldens/compiler/failure/unused-declaration.json +++ b/tests/goldens/compiler/failure/unused-declaration.json @@ -8,12 +8,12 @@ "phase": "compile", "severity": "error", "code": "S010", - "message": "Unused local declaration 'constant:spare' at models/staging/_sqlbuild/_constants/limits.sql; remove it or add a genuine runtime use", - "path": "models/staging/_sqlbuild/_constants/limits.sql", + "message": "Unused local declaration 'constant:spare' at sql/models/staging/_sqlbuild/_constants/limits.sql; remove it or add a genuine runtime use", + "path": "sql/models/staging/_sqlbuild/_constants/limits.sql", "line": 1, "column": 1, "location": { - "path": "models/staging/_sqlbuild/_constants/limits.sql", + "path": "sql/models/staging/_sqlbuild/_constants/limits.sql", "line": 1, "column": 1 } @@ -22,13 +22,13 @@ } ], "compiled": { - "models/marts/customer_totals.sql": [ + "sql/models/marts/customer_totals.sql": [ "SELECT customer_id, SUM(amount) AS total_amount", "FROM __ref(\"stg_orders\")", "GROUP BY customer_id", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT order_id, customer_id, amount, status", "FROM __source(\"raw_orders\")", "" @@ -42,8 +42,8 @@ "name": "customer_totals", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/marts/customer_totals.sql", - "original_file_path": "models/marts/customer_totals.sql", + "path": "sql/models/marts/customer_totals.sql", + "original_file_path": "sql/models/marts/customer_totals.sql", "unique_id": "model.failure_corpus.customer_totals", "fqn": [ "failure_corpus", @@ -111,8 +111,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "failure_corpus", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.failure_corpus.stg_orders", "fqn": [ "failure_corpus", @@ -182,8 +182,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "failure_corpus", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.failure_corpus.raw_orders", "fqn": [ "failure_corpus", diff --git a/tests/goldens/compiler/failure/variable-not-defined.json b/tests/goldens/compiler/failure/variable-not-defined.json index 4054304f5e..e9c5b4c470 100644 --- a/tests/goldens/compiler/failure/variable-not-defined.json +++ b/tests/goldens/compiler/failure/variable-not-defined.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "unknown project variable '@@region' in '/models/staging/stg_orders.sql'. Available vars: none" + "message": "unknown project variable '@@region' in '/sql/models/staging/stg_orders.sql'. Available vars: none" } ] } diff --git a/tests/goldens/compiler/fixture/dbt_interop.json b/tests/goldens/compiler/fixture/dbt_interop.json index 0bd687b95e..5c8706362b 100644 --- a/tests/goldens/compiler/fixture/dbt_interop.json +++ b/tests/goldens/compiler/fixture/dbt_interop.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "C214", - "message": "Model file models/marts/downstream_orders.sql uses __dbt_ref(\"fact_orders\") but no dbt manifest was found", + "message": "Model file sql/models/marts/downstream_orders.sql uses __dbt_ref(\"fact_orders\") but no dbt manifest was found", "help": "Run dbt compile or configure dbt target_path so SQLBuild can read manifest.json." } ] @@ -21,7 +21,7 @@ "phase": "compile", "severity": "error", "code": "C214", - "message": "Model file models/marts/downstream_orders.sql uses __dbt_ref(\"fact_orders\") but no dbt manifest was found", + "message": "Model file sql/models/marts/downstream_orders.sql uses __dbt_ref(\"fact_orders\") but no dbt manifest was found", "help": "Run dbt compile or configure dbt target_path so SQLBuild can read manifest.json." } ] @@ -34,7 +34,7 @@ "phase": "compile", "severity": "error", "code": "C214", - "message": "Model file models/marts/downstream_orders.sql uses __dbt_ref(\"fact_orders\") but no dbt manifest was found", + "message": "Model file sql/models/marts/downstream_orders.sql uses __dbt_ref(\"fact_orders\") but no dbt manifest was found", "help": "Run dbt compile or configure dbt target_path so SQLBuild can read manifest.json." } ] @@ -54,7 +54,7 @@ "External manifest discovery START", "External manifest discovery OK ()", "Compiling project...", - "error[C214]: Model file models/marts/downstream_orders.sql uses __dbt_ref(\"fact_orders\") but no dbt manifest was found", + "error[C214]: Model file sql/models/marts/downstream_orders.sql uses __dbt_ref(\"fact_orders\") but no dbt manifest was found", " = help: Run dbt compile or configure dbt target_path so SQLBuild can read manifest.json.", "", "" diff --git a/tests/goldens/compiler/fixture/source_loader_strategies.json b/tests/goldens/compiler/fixture/source_loader_strategies.json index 122ad0c76d..ccd21eaed2 100644 --- a/tests/goldens/compiler/fixture/source_loader_strategies.json +++ b/tests/goldens/compiler/fixture/source_loader_strategies.json @@ -31,8 +31,8 @@ "name": "raw_countries", "resource_type": "source", "package_name": "source_loader_strategies", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.source_loader_strategies.raw_countries", "fqn": [ "source_loader_strategies", @@ -96,8 +96,8 @@ "name": "raw_webhook_events", "resource_type": "source", "package_name": "source_loader_strategies", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.source_loader_strategies.raw_webhook_events", "fqn": [ "source_loader_strategies", @@ -152,8 +152,8 @@ "name": "raw_order_events", "resource_type": "source", "package_name": "source_loader_strategies", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.source_loader_strategies.raw_order_events", "fqn": [ "source_loader_strategies", @@ -218,8 +218,8 @@ "name": "raw_customers", "resource_type": "source", "package_name": "source_loader_strategies", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.source_loader_strategies.raw_customers", "fqn": [ "source_loader_strategies", @@ -287,8 +287,8 @@ "name": "raw_loader_status", "resource_type": "source", "package_name": "source_loader_strategies", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.source_loader_strategies.raw_loader_status", "fqn": [ "source_loader_strategies", diff --git a/tests/goldens/compiler/fixture/waffle_shop.json b/tests/goldens/compiler/fixture/waffle_shop.json index 6226b98588..3aa23cf0de 100644 --- a/tests/goldens/compiler/fixture/waffle_shop.json +++ b/tests/goldens/compiler/fixture/waffle_shop.json @@ -22,13 +22,13 @@ } ], "compiled": { - "audits/generic/customer_status_snapshot/not_null__customer_id.sql": [ + "sql/audits/generic/customer_status_snapshot/not_null__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"customer_status_snapshot\")", "WHERE customer_id IS NULL", "" ], - "audits/generic/customer_status_snapshot/unique__customer_id.sql": [ + "sql/audits/generic/customer_status_snapshot/unique__customer_id.sql": [ "SELECT customer_id, COUNT(*) AS duplicate_count", "FROM __ref(\"customer_status_snapshot\")", "WHERE customer_id IS NOT NULL", @@ -36,43 +36,43 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/daily_activity_rollup/daily_orders_placed_is_non_negative.sql": [ + "sql/audits/generic/daily_activity_rollup/daily_orders_placed_is_non_negative.sql": [ "SELECT *", "FROM __ref(\"daily_activity_rollup\")", "WHERE NOT (orders_placed >= 0)", "" ], - "audits/generic/daily_activity_rollup/not_null__activity_day.sql": [ + "sql/audits/generic/daily_activity_rollup/not_null__activity_day.sql": [ "SELECT activity_day", "FROM __ref(\"daily_activity_rollup\")", "WHERE activity_day IS NULL", "" ], - "audits/generic/daily_order_partitioned/not_null__order_date.sql": [ + "sql/audits/generic/daily_order_partitioned/not_null__order_date.sql": [ "SELECT order_date", "FROM __ref(\"daily_order_partitioned\")", "WHERE order_date IS NULL", "" ], - "audits/generic/daily_order_partitioned/waffles_ordered_is_positive.sql": [ + "sql/audits/generic/daily_order_partitioned/waffles_ordered_is_positive.sql": [ "SELECT *", "FROM __ref(\"daily_order_partitioned\")", "WHERE NOT (waffles_ordered > 0)", "" ], - "audits/generic/daily_revenue/revenue_is_non_negative.sql": [ + "sql/audits/generic/daily_revenue/revenue_is_non_negative.sql": [ "SELECT *", "FROM __ref(\"daily_revenue\")", "WHERE NOT (total_revenue_cents >= 0)", "" ], - "audits/generic/dim_customers/not_null__customer_id.sql": [ + "sql/audits/generic/dim_customers/not_null__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"dim_customers\")", "WHERE customer_id IS NULL", "" ], - "audits/generic/dim_customers/unique__customer_id.sql": [ + "sql/audits/generic/dim_customers/unique__customer_id.sql": [ "SELECT customer_id, COUNT(*) AS duplicate_count", "FROM __ref(\"dim_customers\")", "WHERE customer_id IS NOT NULL", @@ -80,43 +80,43 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/fact_orders/not_null__order_id.sql": [ + "sql/audits/generic/fact_orders/not_null__order_id.sql": [ "SELECT order_id", "FROM __ref(\"fact_orders\")", "WHERE order_id IS NULL", "" ], - "audits/generic/hourly_activity_with_daily_context/day_orders_cover_hourly_orders.sql": [ + "sql/audits/generic/hourly_activity_with_daily_context/day_orders_cover_hourly_orders.sql": [ "SELECT *", "FROM __ref(\"hourly_activity_with_daily_context\")", "WHERE NOT (day_orders_placed >= orders_placed)", "" ], - "audits/generic/hourly_activity_with_daily_context/not_null__activity_hour.sql": [ + "sql/audits/generic/hourly_activity_with_daily_context/not_null__activity_hour.sql": [ "SELECT activity_hour", "FROM __ref(\"hourly_activity_with_daily_context\")", "WHERE activity_hour IS NULL", "" ], - "audits/generic/hourly_order_activity/not_null__activity_hour.sql": [ + "sql/audits/generic/hourly_order_activity/not_null__activity_hour.sql": [ "SELECT activity_hour", "FROM __ref(\"hourly_order_activity\")", "WHERE activity_hour IS NULL", "" ], - "audits/generic/hourly_order_activity/orders_placed_is_non_negative.sql": [ + "sql/audits/generic/hourly_order_activity/orders_placed_is_non_negative.sql": [ "SELECT *", "FROM __ref(\"hourly_order_activity\")", "WHERE NOT (orders_placed >= 0)", "" ], - "audits/generic/order_status_index/not_null__order_id.sql": [ + "sql/audits/generic/order_status_index/not_null__order_id.sql": [ "SELECT order_id", "FROM __ref(\"order_status_index\")", "WHERE order_id IS NULL", "" ], - "audits/generic/order_status_index/unique__order_id.sql": [ + "sql/audits/generic/order_status_index/unique__order_id.sql": [ "SELECT order_id, COUNT(*) AS duplicate_count", "FROM __ref(\"order_status_index\")", "WHERE order_id IS NOT NULL", @@ -124,19 +124,19 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/stg_customers/not_null__customer_id.sql": [ + "sql/audits/generic/stg_customers/not_null__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"stg_customers\")", "WHERE customer_id IS NULL", "" ], - "audits/generic/stg_customers/not_null__email.sql": [ + "sql/audits/generic/stg_customers/not_null__email.sql": [ "SELECT email", "FROM __ref(\"stg_customers\")", "WHERE email IS NULL", "" ], - "audits/generic/stg_customers/unique__customer_id.sql": [ + "sql/audits/generic/stg_customers/unique__customer_id.sql": [ "SELECT customer_id, COUNT(*) AS duplicate_count", "FROM __ref(\"stg_customers\")", "WHERE customer_id IS NOT NULL", @@ -144,26 +144,26 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/stg_orders/accepted_values__status.sql": [ + "sql/audits/generic/stg_orders/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"stg_orders\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'preparing', 'ready', 'completed', 'cancelled')", "" ], - "audits/generic/stg_orders/not_null__customer_id.sql": [ + "sql/audits/generic/stg_orders/not_null__customer_id.sql": [ "SELECT customer_id", "FROM __ref(\"stg_orders\")", "WHERE customer_id IS NULL", "" ], - "audits/generic/stg_orders/not_null__order_id.sql": [ + "sql/audits/generic/stg_orders/not_null__order_id.sql": [ "SELECT order_id", "FROM __ref(\"stg_orders\")", "WHERE order_id IS NULL", "" ], - "audits/generic/stg_orders/relationships__waffle_type_id.sql": [ + "sql/audits/generic/stg_orders/relationships__waffle_type_id.sql": [ "SELECT waffle_type_id", "FROM __ref(\"stg_orders\")", "WHERE waffle_type_id IS NOT NULL", @@ -174,7 +174,7 @@ " )", "" ], - "audits/generic/stg_orders/unique__order_id.sql": [ + "sql/audits/generic/stg_orders/unique__order_id.sql": [ "SELECT order_id, COUNT(*) AS duplicate_count", "FROM __ref(\"stg_orders\")", "WHERE order_id IS NOT NULL", @@ -182,19 +182,19 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/stg_payments/not_null__order_id.sql": [ + "sql/audits/generic/stg_payments/not_null__order_id.sql": [ "SELECT order_id", "FROM __ref(\"stg_payments\")", "WHERE order_id IS NULL", "" ], - "audits/generic/stg_payments/not_null__payment_id.sql": [ + "sql/audits/generic/stg_payments/not_null__payment_id.sql": [ "SELECT payment_id", "FROM __ref(\"stg_payments\")", "WHERE payment_id IS NULL", "" ], - "audits/generic/stg_payments/relationships__order_id.sql": [ + "sql/audits/generic/stg_payments/relationships__order_id.sql": [ "SELECT order_id", "FROM __ref(\"stg_payments\")", "WHERE order_id IS NOT NULL", @@ -205,7 +205,7 @@ " )", "" ], - "audits/generic/stg_payments/unique__payment_id.sql": [ + "sql/audits/generic/stg_payments/unique__payment_id.sql": [ "SELECT payment_id, COUNT(*) AS duplicate_count", "FROM __ref(\"stg_payments\")", "WHERE payment_id IS NOT NULL", @@ -213,11 +213,11 @@ "HAVING COUNT(*) > 1", "" ], - "functions/python/is_completed_order_py.sql": [ + "sql/functions/python/is_completed_order_py.sql": [ "REGISTER PYTHON FUNCTION is_completed_order_py(STRING) RETURNS BOOLEAN", "" ], - "functions/sql/customer_orders.sql": [ + "sql/functions/sql/customer_orders.sql": [ "CREATE OR REPLACE MACRO main.customer_orders(p_customer_id) AS TABLE", "SELECT", " order_id,", @@ -230,13 +230,13 @@ "WHERE customer_id = p_customer_id", "" ], - "functions/sql/is_completed_order.sql": [ + "sql/functions/sql/is_completed_order.sql": [ "CREATE OR REPLACE MACRO main.is_completed_order(order_status) AS (", "order_status = 'completed'", ")", "" ], - "models/intermediate/customer_status_snapshot.sql": [ + "sql/models/intermediate/customer_status_snapshot.sql": [ "SELECT", " customer_id,", " MAX(ordered_at) AS last_ordered_at,", @@ -247,7 +247,7 @@ "GROUP BY customer_id", "" ], - "models/intermediate/order_status_index.sql": [ + "sql/models/intermediate/order_status_index.sql": [ "SELECT", " order_id,", " customer_id,", @@ -257,7 +257,7 @@ "FROM __ref(\"fact_orders\")", "" ], - "models/marts/daily_activity_rollup.sql": [ + "sql/models/marts/daily_activity_rollup.sql": [ "SELECT", " DATE_TRUNC('day', activity_hour) AS activity_day,", " SUM(orders_placed) AS orders_placed,", @@ -267,7 +267,7 @@ "GROUP BY DATE_TRUNC('day', activity_hour)", "" ], - "models/marts/daily_order_partitioned.sql": [ + "sql/models/marts/daily_order_partitioned.sql": [ "SELECT", " CAST(o.ordered_at AS DATE) AS order_date,", " COUNT(DISTINCT o.order_id) AS order_count,", @@ -279,7 +279,7 @@ "GROUP BY CAST(o.ordered_at AS DATE)", "" ], - "models/marts/daily_revenue.sql": [ + "sql/models/marts/daily_revenue.sql": [ "SELECT", " CAST(o.ordered_at AS DATE) AS revenue_date,", " COUNT(DISTINCT o.order_id) AS order_count,", @@ -291,7 +291,7 @@ "GROUP BY CAST(o.ordered_at AS DATE)", "" ], - "models/marts/dim_customers.sql": [ + "sql/models/marts/dim_customers.sql": [ "SELECT", " c.customer_id,", " c.first_name,", @@ -306,7 +306,7 @@ "GROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.created_at", "" ], - "models/marts/fact_orders.sql": [ + "sql/models/marts/fact_orders.sql": [ "SELECT", " o.order_id,", " o.customer_id,", @@ -327,7 +327,7 @@ "LEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id", "" ], - "models/marts/hourly_activity_with_daily_context.sql": [ + "sql/models/marts/hourly_activity_with_daily_context.sql": [ "SELECT", " h.activity_hour,", " h.orders_placed,", @@ -339,7 +339,7 @@ " ON DATE_TRUNC('day', h.activity_hour) = d.activity_day", "" ], - "models/marts/hourly_order_activity.sql": [ + "sql/models/marts/hourly_order_activity.sql": [ "SELECT", " DATE_TRUNC('hour', o.ordered_at) AS activity_hour,", " COUNT(*) AS orders_placed,", @@ -349,7 +349,7 @@ "GROUP BY DATE_TRUNC('hour', o.ordered_at)", "" ], - "models/marts/scenario_order_prices.sql": [ + "sql/models/marts/scenario_order_prices.sql": [ "SELECT", " o.order_id,", " o.quantity,", @@ -362,7 +362,7 @@ "LEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id", "" ], - "models/staging/stg_customers.sql": [ + "sql/models/staging/stg_customers.sql": [ "SELECT", " id AS customer_id,", " first_name,", @@ -372,7 +372,7 @@ "FROM __source(\"raw_customers\")", "" ], - "models/staging/stg_orders.sql": [ + "sql/models/staging/stg_orders.sql": [ "SELECT", " id AS order_id,", " customer_id,", @@ -383,7 +383,7 @@ "FROM __source(\"raw_orders\")", "" ], - "models/staging/stg_payments.sql": [ + "sql/models/staging/stg_payments.sql": [ "SELECT", " id AS payment_id,", " order_id,", @@ -533,8 +533,8 @@ "name": "customer_status_snapshot", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/intermediate/customer_status_snapshot.sql", - "original_file_path": "models/intermediate/customer_status_snapshot.sql", + "path": "sql/models/intermediate/customer_status_snapshot.sql", + "original_file_path": "sql/models/intermediate/customer_status_snapshot.sql", "unique_id": "model.waffle_shop.customer_status_snapshot", "fqn": [ "waffle_shop", @@ -620,8 +620,8 @@ "name": "order_status_index", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/intermediate/order_status_index.sql", - "original_file_path": "models/intermediate/order_status_index.sql", + "path": "sql/models/intermediate/order_status_index.sql", + "original_file_path": "sql/models/intermediate/order_status_index.sql", "unique_id": "model.waffle_shop.order_status_index", "fqn": [ "waffle_shop", @@ -705,8 +705,8 @@ "name": "daily_activity_rollup", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/daily_activity_rollup.sql", - "original_file_path": "models/marts/daily_activity_rollup.sql", + "path": "sql/models/marts/daily_activity_rollup.sql", + "original_file_path": "sql/models/marts/daily_activity_rollup.sql", "unique_id": "model.waffle_shop.daily_activity_rollup", "fqn": [ "waffle_shop", @@ -790,8 +790,8 @@ "name": "daily_order_partitioned", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/daily_order_partitioned.sql", - "original_file_path": "models/marts/daily_order_partitioned.sql", + "path": "sql/models/marts/daily_order_partitioned.sql", + "original_file_path": "sql/models/marts/daily_order_partitioned.sql", "unique_id": "model.waffle_shop.daily_order_partitioned", "fqn": [ "waffle_shop", @@ -873,8 +873,8 @@ "name": "daily_revenue", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/daily_revenue.sql", - "original_file_path": "models/marts/daily_revenue.sql", + "path": "sql/models/marts/daily_revenue.sql", + "original_file_path": "sql/models/marts/daily_revenue.sql", "unique_id": "model.waffle_shop.daily_revenue", "fqn": [ "waffle_shop", @@ -957,8 +957,8 @@ "name": "dim_customers", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/dim_customers.sql", - "original_file_path": "models/marts/dim_customers.sql", + "path": "sql/models/marts/dim_customers.sql", + "original_file_path": "sql/models/marts/dim_customers.sql", "unique_id": "model.waffle_shop.dim_customers", "fqn": [ "waffle_shop", @@ -1042,8 +1042,8 @@ "name": "fact_orders", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/fact_orders.sql", - "original_file_path": "models/marts/fact_orders.sql", + "path": "sql/models/marts/fact_orders.sql", + "original_file_path": "sql/models/marts/fact_orders.sql", "unique_id": "model.waffle_shop.fact_orders", "fqn": [ "waffle_shop", @@ -1129,8 +1129,8 @@ "name": "hourly_activity_with_daily_context", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/hourly_activity_with_daily_context.sql", - "original_file_path": "models/marts/hourly_activity_with_daily_context.sql", + "path": "sql/models/marts/hourly_activity_with_daily_context.sql", + "original_file_path": "sql/models/marts/hourly_activity_with_daily_context.sql", "unique_id": "model.waffle_shop.hourly_activity_with_daily_context", "fqn": [ "waffle_shop", @@ -1215,8 +1215,8 @@ "name": "hourly_order_activity", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/hourly_order_activity.sql", - "original_file_path": "models/marts/hourly_order_activity.sql", + "path": "sql/models/marts/hourly_order_activity.sql", + "original_file_path": "sql/models/marts/hourly_order_activity.sql", "unique_id": "model.waffle_shop.hourly_order_activity", "fqn": [ "waffle_shop", @@ -1298,8 +1298,8 @@ "name": "scenario_order_prices", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/marts/scenario_order_prices.sql", - "original_file_path": "models/marts/scenario_order_prices.sql", + "path": "sql/models/marts/scenario_order_prices.sql", + "original_file_path": "sql/models/marts/scenario_order_prices.sql", "unique_id": "model.waffle_shop.scenario_order_prices", "fqn": [ "waffle_shop", @@ -1375,8 +1375,8 @@ "name": "stg_customers", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/staging/stg_customers.sql", - "original_file_path": "models/staging/stg_customers.sql", + "path": "sql/models/staging/stg_customers.sql", + "original_file_path": "sql/models/staging/stg_customers.sql", "unique_id": "model.waffle_shop.stg_customers", "fqn": [ "waffle_shop", @@ -1467,8 +1467,8 @@ "name": "stg_orders", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/staging/stg_orders.sql", - "original_file_path": "models/staging/stg_orders.sql", + "path": "sql/models/staging/stg_orders.sql", + "original_file_path": "sql/models/staging/stg_orders.sql", "unique_id": "model.waffle_shop.stg_orders", "fqn": [ "waffle_shop", @@ -1577,8 +1577,8 @@ "name": "stg_payments", "resource_type": "model", "package_name": "waffle_shop", - "path": "models/staging/stg_payments.sql", - "original_file_path": "models/staging/stg_payments.sql", + "path": "sql/models/staging/stg_payments.sql", + "original_file_path": "sql/models/staging/stg_payments.sql", "unique_id": "model.waffle_shop.stg_payments", "fqn": [ "waffle_shop", @@ -1669,8 +1669,8 @@ "name": "waffle_types", "resource_type": "seed", "package_name": "waffle_shop", - "path": "seeds/waffle_types.csv", - "original_file_path": "seeds/waffle_types.csv", + "path": "sql/seeds/waffle_types.csv", + "original_file_path": "sql/seeds/waffle_types.csv", "unique_id": "seed.waffle_shop.waffle_types", "fqn": [ "waffle_shop", @@ -1774,8 +1774,8 @@ "name": "raw_customers", "resource_type": "source", "package_name": "waffle_shop", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.waffle_shop.raw_customers", "fqn": [ "waffle_shop", @@ -1857,8 +1857,8 @@ "name": "raw_orders", "resource_type": "source", "package_name": "waffle_shop", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.waffle_shop.raw_orders", "fqn": [ "waffle_shop", @@ -1950,8 +1950,8 @@ "name": "raw_payments", "resource_type": "source", "package_name": "waffle_shop", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.waffle_shop.raw_payments", "fqn": [ "waffle_shop", @@ -1991,8 +1991,8 @@ "name": "line_total_cents", "resource_type": "macro", "package_name": "waffle_shop", - "path": "macros/python/currency.py", - "original_file_path": "macros/python/currency.py", + "path": "sql/macros/python/currency.py", + "original_file_path": "sql/macros/python/currency.py", "unique_id": "macro.waffle_shop.line_total_cents", "macro_sql": "\"\"\"Currency formatting macros.\"\"\"\n\n\ndef line_total_cents(price_cents: str, quantity: str) -> str:\n \"\"\"Calculate line total cents from a unit price and quantity.\"\"\"\n return f\"{price_cents} * {quantity}\"\n", "depends_on": { @@ -2015,8 +2015,8 @@ "name": "timestamp_trunc", "resource_type": "macro", "package_name": "waffle_shop", - "path": "models/marts/_macros/python/time.py", - "original_file_path": "models/marts/_macros/python/time.py", + "path": "sql/models/marts/_macros/python/time.py", + "original_file_path": "sql/models/marts/_macros/python/time.py", "unique_id": "macro.waffle_shop.timestamp_trunc", "macro_sql": "\"\"\"Time expression macros.\"\"\"\n\nfrom sqlbuild.compiler.compile.models import MacroContext\n\n\ndef timestamp_trunc(ctx: MacroContext, grain: str, expression: str) -> str:\n \"\"\"Render timestamp truncation for the active adapter.\"\"\"\n\n if ctx.adapter_name == \"bigquery\":\n return f\"TIMESTAMP_TRUNC({expression}, {grain.upper()})\"\n return f\"DATE_TRUNC('{grain}', {expression})\"\n", "depends_on": { @@ -2025,7 +2025,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/marts" + "sqlbuild_scope_path": "sql/models/marts" }, "docs": { "show": true, diff --git a/tests/goldens/compiler/seed/0-postgres.json b/tests/goldens/compiler/seed/0-postgres.json index 021cb0bea7..61c053f9fb 100644 --- a/tests/goldens/compiler/seed/0-postgres.json +++ b/tests/goldens/compiler/seed/0-postgres.json @@ -12,20 +12,20 @@ } ], "compiled": { - "audits/generic/checked_stg_fulfillment_1/accepted_values__status.sql": [ + "sql/audits/generic/checked_stg_fulfillment_1/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"checked_stg_fulfillment_1\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/checked_stg_fulfillment_1/expression_is_true.sql": [ + "sql/audits/generic/checked_stg_fulfillment_1/expression_is_true.sql": [ "SELECT *", "FROM __ref(\"checked_stg_fulfillment_1\")", "WHERE NOT (amount >= -1000)", "" ], - "audits/generic/checked_stg_fulfillment_1/relationships__id.sql": [ + "sql/audits/generic/checked_stg_fulfillment_1/relationships__id.sql": [ "SELECT id", "FROM __ref(\"checked_stg_fulfillment_1\")", "WHERE id IS NOT NULL", @@ -36,43 +36,43 @@ " )", "" ], - "audits/generic/fulfillment_summary_1/not_null__id.sql": [ + "sql/audits/generic/fulfillment_summary_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"fulfillment_summary_1\")", "WHERE id IS NULL", "" ], - "audits/generic/sales_summary_0/not_null__id.sql": [ + "sql/audits/generic/sales_summary_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"sales_summary_0\")", "WHERE id IS NULL", "" ], - "audits/generic/sales_summary_2/not_null__id.sql": [ + "sql/audits/generic/sales_summary_2/not_null__id.sql": [ "SELECT id", "FROM __ref(\"sales_summary_2\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_fulfillment_0/not_null__id.sql": [ + "sql/audits/generic/stg_fulfillment_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_fulfillment_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_sales_0/not_null__id.sql": [ + "sql/audits/generic/stg_sales_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_sales_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_sales_1/not_null__id.sql": [ + "sql/audits/generic/stg_sales_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_sales_1\")", "WHERE id IS NULL", "" ], - "functions/sql/scaled_amount.sql": [ + "sql/functions/sql/scaled_amount.sql": [ "CREATE OR REPLACE FUNCTION analytics.scaled_amount(p_amount DOUBLE, p_factor INTEGER)", "RETURNS DOUBLE", "LANGUAGE SQL AS $$", @@ -80,7 +80,7 @@ "$$", "" ], - "functions/sql/table_fn__amount_bands.sql": [ + "sql/functions/sql/table_fn__amount_bands.sql": [ "CREATE OR REPLACE FUNCTION analytics.table_fn__amount_bands(p_floor DOUBLE)", "RETURNS TABLE (id INTEGER, band VARCHAR)", "LANGUAGE SQL AS $$", @@ -90,32 +90,32 @@ "$$", "" ], - "models/analysis/banded_amounts.sql": [ + "sql/models/analysis/banded_amounts.sql": [ "SELECT bands.id, bands.band", "FROM __table_fn(\"table_fn__amount_bands\")(2.5) AS bands", "" ], - "models/analysis/chain_1_stg_sales_0.sql": [ + "sql/models/analysis/chain_1_stg_sales_0.sql": [ "SELECT id, label, amount", "FROM __ref(\"contracted_stg_sales_0\")", "" ], - "models/analysis/chain_2_stg_sales_0.sql": [ + "sql/models/analysis/chain_2_stg_sales_0.sql": [ "SELECT id, UPPER(label) AS label, amount", "FROM __ref(\"chain_1_stg_sales_0\")", "" ], - "models/analysis/chain_3_stg_sales_0.sql": [ + "sql/models/analysis/chain_3_stg_sales_0.sql": [ "SELECT id, label, amount", "FROM __ref(\"chain_2_stg_sales_0\")", "" ], - "models/analysis/checked_stg_fulfillment_1.sql": [ + "sql/models/analysis/checked_stg_fulfillment_1.sql": [ "SELECT id, amount, status", "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/analysis/combined_stg_fulfillment_0.sql": [ + "sql/models/analysis/combined_stg_fulfillment_0.sql": [ "WITH recent AS (", " SELECT id, created_at FROM __ref(\"stg_fulfillment_0\") WHERE amount > 0", "),", @@ -127,28 +127,28 @@ "SELECT id, created_at FROM older", "" ], - "models/analysis/contracted_stg_sales_0.sql": [ + "sql/models/analysis/contracted_stg_sales_0.sql": [ "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR(19)) AS label,", " amount", "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/every_open_event.sql": [ + "sql/models/analysis/every_open_event.sql": [ "SELECT *", "FROM __source(\"open_events\")", "" ], - "models/analysis/every_raw_events_0.sql": [ + "sql/models/analysis/every_raw_events_0.sql": [ "SELECT *", "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/every_stg_fulfillment_0.sql": [ + "sql/models/analysis/every_stg_fulfillment_0.sql": [ "SELECT *", "FROM __ref(\"stg_fulfillment_0\")", "" ], - "models/analysis/passed_stg_fulfillment_0.sql": [ + "sql/models/analysis/passed_stg_fulfillment_0.sql": [ "WITH passthrough AS (", " SELECT id, created_at FROM __ref(\"stg_fulfillment_0\")", ")", @@ -156,29 +156,29 @@ "FROM passthrough", "" ], - "models/analysis/regional_stg_fulfillment_1.sql": [ + "sql/models/analysis/regional_stg_fulfillment_1.sql": [ "SELECT id, amount, 'east' AS region", "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/analysis/scaled_stg_fulfillment_0.sql": [ + "sql/models/analysis/scaled_stg_fulfillment_0.sql": [ "SELECT id, __udf(\"scaled_amount\")(amount, 2) AS scaled_amount", "FROM __ref(\"stg_fulfillment_0\")", "" ], - "models/analysis/typed_stg_fulfillment_0.sql": [ + "sql/models/analysis/typed_stg_fulfillment_0.sql": [ "SELECT id, amount * 2 AS doubled_amount, CAST(status AS VARCHAR) AS status_text,", " created_at, NULL AS missing_note", "FROM __ref(\"stg_fulfillment_0\")", "" ], - "models/analysis/unanalysed_stg_fulfillment_0.sql": [ + "sql/models/analysis/unanalysed_stg_fulfillment_0.sql": [ "SELECT a.id, a.amount", "FROM __ref(\"stg_fulfillment_0\") AS a", "JOIN __ref(\"stg_fulfillment_0\") AS b NEAREST 1 BY DISTANCE abs(a.amount - b.amount)", "" ], - "models/fulfillment/marts/fulfillment_summary_0.sql": [ + "sql/models/fulfillment/marts/fulfillment_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -191,7 +191,7 @@ "LEFT JOIN __seed(\"lookup_1\") j2 ON t.id = j2.id", "" ], - "models/fulfillment/marts/fulfillment_summary_1.sql": [ + "sql/models/fulfillment/marts/fulfillment_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -200,7 +200,7 @@ "FROM __ref(\"stg_fulfillment_0\") t", "" ], - "models/fulfillment/marts/fulfillment_summary_2.sql": [ + "sql/models/fulfillment/marts/fulfillment_summary_2.sql": [ "SELECT", " t.id,", " t.amount,", @@ -213,7 +213,7 @@ "LEFT JOIN __seed(\"lookup_0\") j1 ON t.id = j1.id", "" ], - "models/fulfillment/staging/stg_fulfillment_0.sql": [ + "sql/models/fulfillment/staging/stg_fulfillment_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -224,7 +224,7 @@ "FROM __source(\"raw_events_1\") t", "" ], - "models/fulfillment/staging/stg_fulfillment_1.sql": [ + "sql/models/fulfillment/staging/stg_fulfillment_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -236,7 +236,7 @@ "WHERE t.status <> 'expédié'", "" ], - "models/sales/marts/sales_summary_0.sql": [ + "sql/models/sales/marts/sales_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -248,7 +248,7 @@ "LEFT JOIN __seed(\"lookup_1\") j1 ON t.id = j1.id", "" ], - "models/sales/marts/sales_summary_1.sql": [ + "sql/models/sales/marts/sales_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -261,7 +261,7 @@ "WHERE t.status <> '取消'", "" ], - "models/sales/marts/sales_summary_2.sql": [ + "sql/models/sales/marts/sales_summary_2.sql": [ "SELECT", " t.id,", " t.amount,", @@ -275,7 +275,7 @@ "LEFT JOIN __seed(\"lookup_1\") j2 ON t.id = j2.id", "" ], - "models/sales/staging/stg_sales_0.sql": [ + "sql/models/sales/staging/stg_sales_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -286,7 +286,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/sales/staging/stg_sales_1.sql": [ + "sql/models/sales/staging/stg_sales_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -331,8 +331,8 @@ "name": "banded_amounts", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/banded_amounts.sql", - "original_file_path": "models/analysis/banded_amounts.sql", + "path": "sql/models/analysis/banded_amounts.sql", + "original_file_path": "sql/models/analysis/banded_amounts.sql", "unique_id": "model.generated_0.banded_amounts", "fqn": [ "generated_0", @@ -400,8 +400,8 @@ "name": "chain_1_stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/chain_1_stg_sales_0.sql", - "original_file_path": "models/analysis/chain_1_stg_sales_0.sql", + "path": "sql/models/analysis/chain_1_stg_sales_0.sql", + "original_file_path": "sql/models/analysis/chain_1_stg_sales_0.sql", "unique_id": "model.generated_0.chain_1_stg_sales_0", "fqn": [ "generated_0", @@ -469,8 +469,8 @@ "name": "chain_2_stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/chain_2_stg_sales_0.sql", - "original_file_path": "models/analysis/chain_2_stg_sales_0.sql", + "path": "sql/models/analysis/chain_2_stg_sales_0.sql", + "original_file_path": "sql/models/analysis/chain_2_stg_sales_0.sql", "unique_id": "model.generated_0.chain_2_stg_sales_0", "fqn": [ "generated_0", @@ -538,8 +538,8 @@ "name": "chain_3_stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/chain_3_stg_sales_0.sql", - "original_file_path": "models/analysis/chain_3_stg_sales_0.sql", + "path": "sql/models/analysis/chain_3_stg_sales_0.sql", + "original_file_path": "sql/models/analysis/chain_3_stg_sales_0.sql", "unique_id": "model.generated_0.chain_3_stg_sales_0", "fqn": [ "generated_0", @@ -607,8 +607,8 @@ "name": "checked_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/checked_stg_fulfillment_1.sql", - "original_file_path": "models/analysis/checked_stg_fulfillment_1.sql", + "path": "sql/models/analysis/checked_stg_fulfillment_1.sql", + "original_file_path": "sql/models/analysis/checked_stg_fulfillment_1.sql", "unique_id": "model.generated_0.checked_stg_fulfillment_1", "fqn": [ "generated_0", @@ -697,8 +697,8 @@ "name": "combined_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/combined_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/combined_stg_fulfillment_0.sql", + "path": "sql/models/analysis/combined_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/combined_stg_fulfillment_0.sql", "unique_id": "model.generated_0.combined_stg_fulfillment_0", "fqn": [ "generated_0", @@ -767,8 +767,8 @@ "name": "contracted_stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/contracted_stg_sales_0.sql", - "original_file_path": "models/analysis/contracted_stg_sales_0.sql", + "path": "sql/models/analysis/contracted_stg_sales_0.sql", + "original_file_path": "sql/models/analysis/contracted_stg_sales_0.sql", "unique_id": "model.generated_0.contracted_stg_sales_0", "fqn": [ "generated_0", @@ -864,8 +864,8 @@ "name": "every_open_event", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/every_open_event.sql", - "original_file_path": "models/analysis/every_open_event.sql", + "path": "sql/models/analysis/every_open_event.sql", + "original_file_path": "sql/models/analysis/every_open_event.sql", "unique_id": "model.generated_0.every_open_event", "fqn": [ "generated_0", @@ -933,8 +933,8 @@ "name": "every_raw_events_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/every_raw_events_0.sql", - "original_file_path": "models/analysis/every_raw_events_0.sql", + "path": "sql/models/analysis/every_raw_events_0.sql", + "original_file_path": "sql/models/analysis/every_raw_events_0.sql", "unique_id": "model.generated_0.every_raw_events_0", "fqn": [ "generated_0", @@ -1002,8 +1002,8 @@ "name": "every_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/every_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/every_stg_fulfillment_0.sql", + "path": "sql/models/analysis/every_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/every_stg_fulfillment_0.sql", "unique_id": "model.generated_0.every_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1071,8 +1071,8 @@ "name": "passed_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/passed_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/passed_stg_fulfillment_0.sql", + "path": "sql/models/analysis/passed_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/passed_stg_fulfillment_0.sql", "unique_id": "model.generated_0.passed_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1140,8 +1140,8 @@ "name": "regional_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/regional_stg_fulfillment_1.sql", - "original_file_path": "models/analysis/regional_stg_fulfillment_1.sql", + "path": "sql/models/analysis/regional_stg_fulfillment_1.sql", + "original_file_path": "sql/models/analysis/regional_stg_fulfillment_1.sql", "unique_id": "model.generated_0.regional_stg_fulfillment_1", "fqn": [ "generated_0", @@ -1209,8 +1209,8 @@ "name": "scaled_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/scaled_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/scaled_stg_fulfillment_0.sql", + "path": "sql/models/analysis/scaled_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/scaled_stg_fulfillment_0.sql", "unique_id": "model.generated_0.scaled_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1279,8 +1279,8 @@ "name": "typed_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/typed_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/typed_stg_fulfillment_0.sql", + "path": "sql/models/analysis/typed_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/typed_stg_fulfillment_0.sql", "unique_id": "model.generated_0.typed_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1348,8 +1348,8 @@ "name": "unanalysed_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/unanalysed_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/unanalysed_stg_fulfillment_0.sql", + "path": "sql/models/analysis/unanalysed_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/unanalysed_stg_fulfillment_0.sql", "unique_id": "model.generated_0.unanalysed_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1417,8 +1417,8 @@ "name": "fulfillment_summary_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/marts/fulfillment_summary_0.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_0.sql", + "path": "sql/models/fulfillment/marts/fulfillment_summary_0.sql", + "original_file_path": "sql/models/fulfillment/marts/fulfillment_summary_0.sql", "unique_id": "model.generated_0.fulfillment_summary_0", "fqn": [ "generated_0", @@ -1489,8 +1489,8 @@ "name": "fulfillment_summary_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/marts/fulfillment_summary_1.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_1.sql", + "path": "sql/models/fulfillment/marts/fulfillment_summary_1.sql", + "original_file_path": "sql/models/fulfillment/marts/fulfillment_summary_1.sql", "unique_id": "model.generated_0.fulfillment_summary_1", "fqn": [ "generated_0", @@ -1563,7 +1563,7 @@ "type": "sql", "statement": "SELECT 'analytics.fulfillment_summary_1' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -1603,8 +1603,8 @@ "name": "fulfillment_summary_2", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/marts/fulfillment_summary_2.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_2.sql", + "path": "sql/models/fulfillment/marts/fulfillment_summary_2.sql", + "original_file_path": "sql/models/fulfillment/marts/fulfillment_summary_2.sql", "unique_id": "model.generated_0.fulfillment_summary_2", "fqn": [ "generated_0", @@ -1667,7 +1667,7 @@ "type": "sql", "statement": "SELECT 'analytics.fulfillment_summary_2' AS refreshed_relation, 'café ☕ counter' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -1708,8 +1708,8 @@ "name": "stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/staging/stg_fulfillment_0.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_0.sql", + "path": "sql/models/fulfillment/staging/stg_fulfillment_0.sql", + "original_file_path": "sql/models/fulfillment/staging/stg_fulfillment_0.sql", "unique_id": "model.generated_0.stg_fulfillment_0", "fqn": [ "generated_0", @@ -1792,8 +1792,8 @@ "name": "stg_fulfillment_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/staging/stg_fulfillment_1.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_1.sql", + "path": "sql/models/fulfillment/staging/stg_fulfillment_1.sql", + "original_file_path": "sql/models/fulfillment/staging/stg_fulfillment_1.sql", "unique_id": "model.generated_0.stg_fulfillment_1", "fqn": [ "generated_0", @@ -1866,8 +1866,8 @@ "name": "sales_summary_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/marts/sales_summary_0.sql", - "original_file_path": "models/sales/marts/sales_summary_0.sql", + "path": "sql/models/sales/marts/sales_summary_0.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_0.sql", "unique_id": "model.generated_0.sales_summary_0", "fqn": [ "generated_0", @@ -1953,8 +1953,8 @@ "name": "sales_summary_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/marts/sales_summary_1.sql", - "original_file_path": "models/sales/marts/sales_summary_1.sql", + "path": "sql/models/sales/marts/sales_summary_1.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_1.sql", "unique_id": "model.generated_0.sales_summary_1", "fqn": [ "generated_0", @@ -2023,7 +2023,7 @@ "type": "sql", "statement": "SELECT 'analytics.sales_summary_1' AS refreshed_relation, '東京 warehouse' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2064,8 +2064,8 @@ "name": "sales_summary_2", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/marts/sales_summary_2.sql", - "original_file_path": "models/sales/marts/sales_summary_2.sql", + "path": "sql/models/sales/marts/sales_summary_2.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_2.sql", "unique_id": "model.generated_0.sales_summary_2", "fqn": [ "generated_0", @@ -2152,8 +2152,8 @@ "name": "stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/staging/stg_sales_0.sql", - "original_file_path": "models/sales/staging/stg_sales_0.sql", + "path": "sql/models/sales/staging/stg_sales_0.sql", + "original_file_path": "sql/models/sales/staging/stg_sales_0.sql", "unique_id": "model.generated_0.stg_sales_0", "fqn": [ "generated_0", @@ -2236,8 +2236,8 @@ "name": "stg_sales_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/staging/stg_sales_1.sql", - "original_file_path": "models/sales/staging/stg_sales_1.sql", + "path": "sql/models/sales/staging/stg_sales_1.sql", + "original_file_path": "sql/models/sales/staging/stg_sales_1.sql", "unique_id": "model.generated_0.stg_sales_1", "fqn": [ "generated_0", @@ -2320,8 +2320,8 @@ "name": "lookup_0", "resource_type": "seed", "package_name": "generated_0", - "path": "seeds/lookup_0.csv", - "original_file_path": "seeds/lookup_0.csv", + "path": "sql/seeds/lookup_0.csv", + "original_file_path": "sql/seeds/lookup_0.csv", "unique_id": "seed.generated_0.lookup_0", "fqn": [ "generated_0", @@ -2405,8 +2405,8 @@ "name": "lookup_1", "resource_type": "seed", "package_name": "generated_0", - "path": "seeds/lookup_1.csv", - "original_file_path": "seeds/lookup_1.csv", + "path": "sql/seeds/lookup_1.csv", + "original_file_path": "sql/seeds/lookup_1.csv", "unique_id": "seed.generated_0.lookup_1", "fqn": [ "generated_0", @@ -2492,8 +2492,8 @@ "name": "open_events", "resource_type": "source", "package_name": "generated_0", - "path": "sources/open.yml", - "original_file_path": "sources/open.yml", + "path": "sql/sources/open.yml", + "original_file_path": "sql/sources/open.yml", "unique_id": "source.generated_0.open_events", "fqn": [ "generated_0", @@ -2523,8 +2523,8 @@ "name": "raw_events_0", "resource_type": "source", "package_name": "generated_0", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_0.raw_events_0", "fqn": [ "generated_0", @@ -2591,8 +2591,8 @@ "name": "raw_events_1", "resource_type": "source", "package_name": "generated_0", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_0.raw_events_1", "fqn": [ "generated_0", @@ -2659,8 +2659,8 @@ "name": "adjust_0", "resource_type": "macro", "package_name": "generated_0", - "path": "macros/python/adjust_0.py", - "original_file_path": "macros/python/adjust_0.py", + "path": "sql/macros/python/adjust_0.py", + "original_file_path": "sql/macros/python/adjust_0.py", "unique_id": "macro.generated_0.adjust_0", "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2685,8 +2685,8 @@ "name": "adjust_0_round", "resource_type": "macro", "package_name": "generated_0", - "path": "macros/python/adjust_0.py", - "original_file_path": "macros/python/adjust_0.py", + "path": "sql/macros/python/adjust_0.py", + "original_file_path": "sql/macros/python/adjust_0.py", "unique_id": "macro.generated_0.adjust_0_round", "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2709,8 +2709,8 @@ "name": "adjust_2", "resource_type": "macro", "package_name": "generated_0", - "path": "macros/python/adjust_2.py", - "original_file_path": "macros/python/adjust_2.py", + "path": "sql/macros/python/adjust_2.py", + "original_file_path": "sql/macros/python/adjust_2.py", "unique_id": "macro.generated_0.adjust_2", "macro_sql": "def adjust_2(ctx, expression: str) -> str:\n \"\"\"Scale an amount by the configured discount.\"\"\"\n rate = ctx.vars[\"discount_rate\"]\n return f\"({expression} * (1 - {rate}))\"\n", "depends_on": { @@ -2733,8 +2733,8 @@ "name": "analysis_region", "resource_type": "macro", "package_name": "generated_0", - "path": "models/analysis/_sqlbuild/_macros/python/regions.py", - "original_file_path": "models/analysis/_sqlbuild/_macros/python/regions.py", + "path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", + "original_file_path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", "unique_id": "macro.generated_0.analysis_region", "macro_sql": "def analysis_region() -> str:\n \"\"\"Return the region rows are assigned to.\"\"\"\n return \"'east'\"\n", "depends_on": { @@ -2743,7 +2743,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/analysis" + "sqlbuild_scope_path": "sql/models/analysis" }, "docs": { "show": true, @@ -2757,8 +2757,8 @@ "name": "adjust_1", "resource_type": "macro", "package_name": "generated_0", - "path": "models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", - "original_file_path": "models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", + "path": "sql/models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", + "original_file_path": "sql/models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", "unique_id": "macro.generated_0.adjust_1", "macro_sql": "import os\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Tag an amount with the deployment region.\"\"\"\n region = os.environ.get(\"SQB_DIFFERENTIAL_REGION\", \"east\")\n return f\"({expression} + LENGTH('{region}'))\"\n", "depends_on": { @@ -2767,7 +2767,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/fulfillment/staging" + "sqlbuild_scope_path": "sql/models/fulfillment/staging" }, "docs": { "show": true, @@ -2781,8 +2781,8 @@ "name": "record_refresh", "resource_type": "macro", "package_name": "generated_0__sqlbuild_hooks", - "path": "hooks/sql/record_refresh.sql", - "original_file_path": "hooks/sql/record_refresh.sql", + "path": "sql/hooks/sql/record_refresh.sql", + "original_file_path": "sql/hooks/sql/record_refresh.sql", "unique_id": "macro.generated_0__sqlbuild_hooks.record_refresh", "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "depends_on": { diff --git a/tests/goldens/compiler/seed/0-snowflake.json b/tests/goldens/compiler/seed/0-snowflake.json index 155ae3efc0..f9dfc254c0 100644 --- a/tests/goldens/compiler/seed/0-snowflake.json +++ b/tests/goldens/compiler/seed/0-snowflake.json @@ -12,20 +12,20 @@ } ], "compiled": { - "audits/generic/checked_stg_fulfillment_1/accepted_values__status.sql": [ + "sql/audits/generic/checked_stg_fulfillment_1/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"checked_stg_fulfillment_1\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/checked_stg_fulfillment_1/expression_is_true.sql": [ + "sql/audits/generic/checked_stg_fulfillment_1/expression_is_true.sql": [ "SELECT *", "FROM __ref(\"checked_stg_fulfillment_1\")", "WHERE NOT (amount >= -1000)", "" ], - "audits/generic/checked_stg_fulfillment_1/relationships__id.sql": [ + "sql/audits/generic/checked_stg_fulfillment_1/relationships__id.sql": [ "SELECT id", "FROM __ref(\"checked_stg_fulfillment_1\")", "WHERE id IS NOT NULL", @@ -36,43 +36,43 @@ " )", "" ], - "audits/generic/fulfillment_summary_1/not_null__id.sql": [ + "sql/audits/generic/fulfillment_summary_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"fulfillment_summary_1\")", "WHERE id IS NULL", "" ], - "audits/generic/sales_summary_0/not_null__id.sql": [ + "sql/audits/generic/sales_summary_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"sales_summary_0\")", "WHERE id IS NULL", "" ], - "audits/generic/sales_summary_2/not_null__id.sql": [ + "sql/audits/generic/sales_summary_2/not_null__id.sql": [ "SELECT id", "FROM __ref(\"sales_summary_2\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_fulfillment_0/not_null__id.sql": [ + "sql/audits/generic/stg_fulfillment_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_fulfillment_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_sales_0/not_null__id.sql": [ + "sql/audits/generic/stg_sales_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_sales_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_sales_1/not_null__id.sql": [ + "sql/audits/generic/stg_sales_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_sales_1\")", "WHERE id IS NULL", "" ], - "functions/sql/scaled_amount.sql": [ + "sql/functions/sql/scaled_amount.sql": [ "CREATE OR REPLACE FUNCTION GENERATED.analytics.scaled_amount(p_amount DOUBLE, p_factor INTEGER)", "RETURNS DOUBLE", "LANGUAGE SQL", @@ -81,7 +81,7 @@ "$$", "" ], - "functions/sql/table_fn__amount_bands.sql": [ + "sql/functions/sql/table_fn__amount_bands.sql": [ "CREATE OR REPLACE FUNCTION GENERATED.analytics.table_fn__amount_bands(p_floor DOUBLE)", "RETURNS TABLE (id INTEGER, band VARCHAR)", "AS $$", @@ -91,32 +91,32 @@ "$$", "" ], - "models/analysis/banded_amounts.sql": [ + "sql/models/analysis/banded_amounts.sql": [ "SELECT bands.id, bands.band", "FROM __table_fn(\"table_fn__amount_bands\")(2.5) AS bands", "" ], - "models/analysis/chain_1_stg_sales_0.sql": [ + "sql/models/analysis/chain_1_stg_sales_0.sql": [ "SELECT id, label, amount", "FROM __ref(\"contracted_stg_sales_0\")", "" ], - "models/analysis/chain_2_stg_sales_0.sql": [ + "sql/models/analysis/chain_2_stg_sales_0.sql": [ "SELECT id, UPPER(label) AS label, amount", "FROM __ref(\"chain_1_stg_sales_0\")", "" ], - "models/analysis/chain_3_stg_sales_0.sql": [ + "sql/models/analysis/chain_3_stg_sales_0.sql": [ "SELECT id, label, amount", "FROM __ref(\"chain_2_stg_sales_0\")", "" ], - "models/analysis/checked_stg_fulfillment_1.sql": [ + "sql/models/analysis/checked_stg_fulfillment_1.sql": [ "SELECT id, amount, status", "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/analysis/combined_stg_fulfillment_0.sql": [ + "sql/models/analysis/combined_stg_fulfillment_0.sql": [ "WITH recent AS (", " SELECT id, created_at FROM __ref(\"stg_fulfillment_0\") WHERE amount > 0", "),", @@ -128,28 +128,28 @@ "SELECT id, created_at FROM older", "" ], - "models/analysis/contracted_stg_sales_0.sql": [ + "sql/models/analysis/contracted_stg_sales_0.sql": [ "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR(19)) AS label,", " amount", "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/every_open_event.sql": [ + "sql/models/analysis/every_open_event.sql": [ "SELECT *", "FROM __source(\"open_events\")", "" ], - "models/analysis/every_raw_events_0.sql": [ + "sql/models/analysis/every_raw_events_0.sql": [ "SELECT *", "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/every_stg_fulfillment_0.sql": [ + "sql/models/analysis/every_stg_fulfillment_0.sql": [ "SELECT *", "FROM __ref(\"stg_fulfillment_0\")", "" ], - "models/analysis/passed_stg_fulfillment_0.sql": [ + "sql/models/analysis/passed_stg_fulfillment_0.sql": [ "WITH passthrough AS (", " SELECT id, created_at FROM __ref(\"stg_fulfillment_0\")", ")", @@ -157,29 +157,29 @@ "FROM passthrough", "" ], - "models/analysis/regional_stg_fulfillment_1.sql": [ + "sql/models/analysis/regional_stg_fulfillment_1.sql": [ "SELECT id, amount, 'east' AS region", "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/analysis/scaled_stg_fulfillment_0.sql": [ + "sql/models/analysis/scaled_stg_fulfillment_0.sql": [ "SELECT id, __udf(\"scaled_amount\")(amount, 2) AS scaled_amount", "FROM __ref(\"stg_fulfillment_0\")", "" ], - "models/analysis/typed_stg_fulfillment_0.sql": [ + "sql/models/analysis/typed_stg_fulfillment_0.sql": [ "SELECT id, amount * 2 AS doubled_amount, CAST(status AS VARCHAR) AS status_text,", " created_at, NULL AS missing_note", "FROM __ref(\"stg_fulfillment_0\")", "" ], - "models/analysis/unanalysed_stg_fulfillment_0.sql": [ + "sql/models/analysis/unanalysed_stg_fulfillment_0.sql": [ "SELECT a.id, a.amount", "FROM __ref(\"stg_fulfillment_0\") AS a", "JOIN __ref(\"stg_fulfillment_0\") AS b NEAREST 1 BY DISTANCE abs(a.amount - b.amount)", "" ], - "models/fulfillment/marts/fulfillment_summary_0.sql": [ + "sql/models/fulfillment/marts/fulfillment_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -192,7 +192,7 @@ "LEFT JOIN __seed(\"lookup_1\") j2 ON t.id = j2.id", "" ], - "models/fulfillment/marts/fulfillment_summary_1.sql": [ + "sql/models/fulfillment/marts/fulfillment_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -201,7 +201,7 @@ "FROM __ref(\"stg_fulfillment_0\") t", "" ], - "models/fulfillment/marts/fulfillment_summary_2.sql": [ + "sql/models/fulfillment/marts/fulfillment_summary_2.sql": [ "SELECT", " t.id,", " t.amount,", @@ -214,7 +214,7 @@ "LEFT JOIN __seed(\"lookup_0\") j1 ON t.id = j1.id", "" ], - "models/fulfillment/staging/stg_fulfillment_0.sql": [ + "sql/models/fulfillment/staging/stg_fulfillment_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -225,7 +225,7 @@ "FROM __source(\"raw_events_1\") t", "" ], - "models/fulfillment/staging/stg_fulfillment_1.sql": [ + "sql/models/fulfillment/staging/stg_fulfillment_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -237,7 +237,7 @@ "WHERE t.status <> 'expédié'", "" ], - "models/sales/marts/sales_summary_0.sql": [ + "sql/models/sales/marts/sales_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -249,7 +249,7 @@ "LEFT JOIN __seed(\"lookup_1\") j1 ON t.id = j1.id", "" ], - "models/sales/marts/sales_summary_1.sql": [ + "sql/models/sales/marts/sales_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -262,7 +262,7 @@ "WHERE t.status <> '取消'", "" ], - "models/sales/marts/sales_summary_2.sql": [ + "sql/models/sales/marts/sales_summary_2.sql": [ "SELECT", " t.id,", " t.amount,", @@ -276,7 +276,7 @@ "LEFT JOIN __seed(\"lookup_1\") j2 ON t.id = j2.id", "" ], - "models/sales/staging/stg_sales_0.sql": [ + "sql/models/sales/staging/stg_sales_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -287,7 +287,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/sales/staging/stg_sales_1.sql": [ + "sql/models/sales/staging/stg_sales_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -332,8 +332,8 @@ "name": "banded_amounts", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/banded_amounts.sql", - "original_file_path": "models/analysis/banded_amounts.sql", + "path": "sql/models/analysis/banded_amounts.sql", + "original_file_path": "sql/models/analysis/banded_amounts.sql", "unique_id": "model.generated_0.banded_amounts", "fqn": [ "generated_0", @@ -401,8 +401,8 @@ "name": "chain_1_stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/chain_1_stg_sales_0.sql", - "original_file_path": "models/analysis/chain_1_stg_sales_0.sql", + "path": "sql/models/analysis/chain_1_stg_sales_0.sql", + "original_file_path": "sql/models/analysis/chain_1_stg_sales_0.sql", "unique_id": "model.generated_0.chain_1_stg_sales_0", "fqn": [ "generated_0", @@ -470,8 +470,8 @@ "name": "chain_2_stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/chain_2_stg_sales_0.sql", - "original_file_path": "models/analysis/chain_2_stg_sales_0.sql", + "path": "sql/models/analysis/chain_2_stg_sales_0.sql", + "original_file_path": "sql/models/analysis/chain_2_stg_sales_0.sql", "unique_id": "model.generated_0.chain_2_stg_sales_0", "fqn": [ "generated_0", @@ -539,8 +539,8 @@ "name": "chain_3_stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/chain_3_stg_sales_0.sql", - "original_file_path": "models/analysis/chain_3_stg_sales_0.sql", + "path": "sql/models/analysis/chain_3_stg_sales_0.sql", + "original_file_path": "sql/models/analysis/chain_3_stg_sales_0.sql", "unique_id": "model.generated_0.chain_3_stg_sales_0", "fqn": [ "generated_0", @@ -608,8 +608,8 @@ "name": "checked_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/checked_stg_fulfillment_1.sql", - "original_file_path": "models/analysis/checked_stg_fulfillment_1.sql", + "path": "sql/models/analysis/checked_stg_fulfillment_1.sql", + "original_file_path": "sql/models/analysis/checked_stg_fulfillment_1.sql", "unique_id": "model.generated_0.checked_stg_fulfillment_1", "fqn": [ "generated_0", @@ -698,8 +698,8 @@ "name": "combined_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/combined_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/combined_stg_fulfillment_0.sql", + "path": "sql/models/analysis/combined_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/combined_stg_fulfillment_0.sql", "unique_id": "model.generated_0.combined_stg_fulfillment_0", "fqn": [ "generated_0", @@ -768,8 +768,8 @@ "name": "contracted_stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/contracted_stg_sales_0.sql", - "original_file_path": "models/analysis/contracted_stg_sales_0.sql", + "path": "sql/models/analysis/contracted_stg_sales_0.sql", + "original_file_path": "sql/models/analysis/contracted_stg_sales_0.sql", "unique_id": "model.generated_0.contracted_stg_sales_0", "fqn": [ "generated_0", @@ -865,8 +865,8 @@ "name": "every_open_event", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/every_open_event.sql", - "original_file_path": "models/analysis/every_open_event.sql", + "path": "sql/models/analysis/every_open_event.sql", + "original_file_path": "sql/models/analysis/every_open_event.sql", "unique_id": "model.generated_0.every_open_event", "fqn": [ "generated_0", @@ -934,8 +934,8 @@ "name": "every_raw_events_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/every_raw_events_0.sql", - "original_file_path": "models/analysis/every_raw_events_0.sql", + "path": "sql/models/analysis/every_raw_events_0.sql", + "original_file_path": "sql/models/analysis/every_raw_events_0.sql", "unique_id": "model.generated_0.every_raw_events_0", "fqn": [ "generated_0", @@ -1003,8 +1003,8 @@ "name": "every_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/every_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/every_stg_fulfillment_0.sql", + "path": "sql/models/analysis/every_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/every_stg_fulfillment_0.sql", "unique_id": "model.generated_0.every_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1072,8 +1072,8 @@ "name": "passed_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/passed_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/passed_stg_fulfillment_0.sql", + "path": "sql/models/analysis/passed_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/passed_stg_fulfillment_0.sql", "unique_id": "model.generated_0.passed_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1141,8 +1141,8 @@ "name": "regional_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/regional_stg_fulfillment_1.sql", - "original_file_path": "models/analysis/regional_stg_fulfillment_1.sql", + "path": "sql/models/analysis/regional_stg_fulfillment_1.sql", + "original_file_path": "sql/models/analysis/regional_stg_fulfillment_1.sql", "unique_id": "model.generated_0.regional_stg_fulfillment_1", "fqn": [ "generated_0", @@ -1210,8 +1210,8 @@ "name": "scaled_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/scaled_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/scaled_stg_fulfillment_0.sql", + "path": "sql/models/analysis/scaled_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/scaled_stg_fulfillment_0.sql", "unique_id": "model.generated_0.scaled_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1280,8 +1280,8 @@ "name": "typed_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/typed_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/typed_stg_fulfillment_0.sql", + "path": "sql/models/analysis/typed_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/typed_stg_fulfillment_0.sql", "unique_id": "model.generated_0.typed_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1349,8 +1349,8 @@ "name": "unanalysed_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/analysis/unanalysed_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/unanalysed_stg_fulfillment_0.sql", + "path": "sql/models/analysis/unanalysed_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/unanalysed_stg_fulfillment_0.sql", "unique_id": "model.generated_0.unanalysed_stg_fulfillment_0", "fqn": [ "generated_0", @@ -1418,8 +1418,8 @@ "name": "fulfillment_summary_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/marts/fulfillment_summary_0.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_0.sql", + "path": "sql/models/fulfillment/marts/fulfillment_summary_0.sql", + "original_file_path": "sql/models/fulfillment/marts/fulfillment_summary_0.sql", "unique_id": "model.generated_0.fulfillment_summary_0", "fqn": [ "generated_0", @@ -1490,8 +1490,8 @@ "name": "fulfillment_summary_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/marts/fulfillment_summary_1.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_1.sql", + "path": "sql/models/fulfillment/marts/fulfillment_summary_1.sql", + "original_file_path": "sql/models/fulfillment/marts/fulfillment_summary_1.sql", "unique_id": "model.generated_0.fulfillment_summary_1", "fqn": [ "generated_0", @@ -1564,7 +1564,7 @@ "type": "sql", "statement": "SELECT 'GENERATED.analytics.fulfillment_summary_1' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -1604,8 +1604,8 @@ "name": "fulfillment_summary_2", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/marts/fulfillment_summary_2.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_2.sql", + "path": "sql/models/fulfillment/marts/fulfillment_summary_2.sql", + "original_file_path": "sql/models/fulfillment/marts/fulfillment_summary_2.sql", "unique_id": "model.generated_0.fulfillment_summary_2", "fqn": [ "generated_0", @@ -1668,7 +1668,7 @@ "type": "sql", "statement": "SELECT 'GENERATED.analytics.fulfillment_summary_2' AS refreshed_relation, 'café ☕ counter' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -1709,8 +1709,8 @@ "name": "stg_fulfillment_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/staging/stg_fulfillment_0.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_0.sql", + "path": "sql/models/fulfillment/staging/stg_fulfillment_0.sql", + "original_file_path": "sql/models/fulfillment/staging/stg_fulfillment_0.sql", "unique_id": "model.generated_0.stg_fulfillment_0", "fqn": [ "generated_0", @@ -1793,8 +1793,8 @@ "name": "stg_fulfillment_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/fulfillment/staging/stg_fulfillment_1.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_1.sql", + "path": "sql/models/fulfillment/staging/stg_fulfillment_1.sql", + "original_file_path": "sql/models/fulfillment/staging/stg_fulfillment_1.sql", "unique_id": "model.generated_0.stg_fulfillment_1", "fqn": [ "generated_0", @@ -1867,8 +1867,8 @@ "name": "sales_summary_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/marts/sales_summary_0.sql", - "original_file_path": "models/sales/marts/sales_summary_0.sql", + "path": "sql/models/sales/marts/sales_summary_0.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_0.sql", "unique_id": "model.generated_0.sales_summary_0", "fqn": [ "generated_0", @@ -1954,8 +1954,8 @@ "name": "sales_summary_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/marts/sales_summary_1.sql", - "original_file_path": "models/sales/marts/sales_summary_1.sql", + "path": "sql/models/sales/marts/sales_summary_1.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_1.sql", "unique_id": "model.generated_0.sales_summary_1", "fqn": [ "generated_0", @@ -2024,7 +2024,7 @@ "type": "sql", "statement": "SELECT 'GENERATED.analytics.sales_summary_1' AS refreshed_relation, '東京 warehouse' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2065,8 +2065,8 @@ "name": "sales_summary_2", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/marts/sales_summary_2.sql", - "original_file_path": "models/sales/marts/sales_summary_2.sql", + "path": "sql/models/sales/marts/sales_summary_2.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_2.sql", "unique_id": "model.generated_0.sales_summary_2", "fqn": [ "generated_0", @@ -2153,8 +2153,8 @@ "name": "stg_sales_0", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/staging/stg_sales_0.sql", - "original_file_path": "models/sales/staging/stg_sales_0.sql", + "path": "sql/models/sales/staging/stg_sales_0.sql", + "original_file_path": "sql/models/sales/staging/stg_sales_0.sql", "unique_id": "model.generated_0.stg_sales_0", "fqn": [ "generated_0", @@ -2237,8 +2237,8 @@ "name": "stg_sales_1", "resource_type": "model", "package_name": "generated_0", - "path": "models/sales/staging/stg_sales_1.sql", - "original_file_path": "models/sales/staging/stg_sales_1.sql", + "path": "sql/models/sales/staging/stg_sales_1.sql", + "original_file_path": "sql/models/sales/staging/stg_sales_1.sql", "unique_id": "model.generated_0.stg_sales_1", "fqn": [ "generated_0", @@ -2321,8 +2321,8 @@ "name": "lookup_0", "resource_type": "seed", "package_name": "generated_0", - "path": "seeds/lookup_0.csv", - "original_file_path": "seeds/lookup_0.csv", + "path": "sql/seeds/lookup_0.csv", + "original_file_path": "sql/seeds/lookup_0.csv", "unique_id": "seed.generated_0.lookup_0", "fqn": [ "generated_0", @@ -2406,8 +2406,8 @@ "name": "lookup_1", "resource_type": "seed", "package_name": "generated_0", - "path": "seeds/lookup_1.csv", - "original_file_path": "seeds/lookup_1.csv", + "path": "sql/seeds/lookup_1.csv", + "original_file_path": "sql/seeds/lookup_1.csv", "unique_id": "seed.generated_0.lookup_1", "fqn": [ "generated_0", @@ -2493,8 +2493,8 @@ "name": "open_events", "resource_type": "source", "package_name": "generated_0", - "path": "sources/open.yml", - "original_file_path": "sources/open.yml", + "path": "sql/sources/open.yml", + "original_file_path": "sql/sources/open.yml", "unique_id": "source.generated_0.open_events", "fqn": [ "generated_0", @@ -2524,8 +2524,8 @@ "name": "raw_events_0", "resource_type": "source", "package_name": "generated_0", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_0.raw_events_0", "fqn": [ "generated_0", @@ -2592,8 +2592,8 @@ "name": "raw_events_1", "resource_type": "source", "package_name": "generated_0", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_0.raw_events_1", "fqn": [ "generated_0", @@ -2660,8 +2660,8 @@ "name": "adjust_0", "resource_type": "macro", "package_name": "generated_0", - "path": "macros/python/adjust_0.py", - "original_file_path": "macros/python/adjust_0.py", + "path": "sql/macros/python/adjust_0.py", + "original_file_path": "sql/macros/python/adjust_0.py", "unique_id": "macro.generated_0.adjust_0", "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2686,8 +2686,8 @@ "name": "adjust_0_round", "resource_type": "macro", "package_name": "generated_0", - "path": "macros/python/adjust_0.py", - "original_file_path": "macros/python/adjust_0.py", + "path": "sql/macros/python/adjust_0.py", + "original_file_path": "sql/macros/python/adjust_0.py", "unique_id": "macro.generated_0.adjust_0_round", "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2710,8 +2710,8 @@ "name": "adjust_2", "resource_type": "macro", "package_name": "generated_0", - "path": "macros/python/adjust_2.py", - "original_file_path": "macros/python/adjust_2.py", + "path": "sql/macros/python/adjust_2.py", + "original_file_path": "sql/macros/python/adjust_2.py", "unique_id": "macro.generated_0.adjust_2", "macro_sql": "def adjust_2(ctx, expression: str) -> str:\n \"\"\"Scale an amount by the configured discount.\"\"\"\n rate = ctx.vars[\"discount_rate\"]\n return f\"({expression} * (1 - {rate}))\"\n", "depends_on": { @@ -2734,8 +2734,8 @@ "name": "analysis_region", "resource_type": "macro", "package_name": "generated_0", - "path": "models/analysis/_sqlbuild/_macros/python/regions.py", - "original_file_path": "models/analysis/_sqlbuild/_macros/python/regions.py", + "path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", + "original_file_path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", "unique_id": "macro.generated_0.analysis_region", "macro_sql": "def analysis_region() -> str:\n \"\"\"Return the region rows are assigned to.\"\"\"\n return \"'east'\"\n", "depends_on": { @@ -2744,7 +2744,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/analysis" + "sqlbuild_scope_path": "sql/models/analysis" }, "docs": { "show": true, @@ -2758,8 +2758,8 @@ "name": "adjust_1", "resource_type": "macro", "package_name": "generated_0", - "path": "models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", - "original_file_path": "models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", + "path": "sql/models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", + "original_file_path": "sql/models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", "unique_id": "macro.generated_0.adjust_1", "macro_sql": "import os\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Tag an amount with the deployment region.\"\"\"\n region = os.environ.get(\"SQB_DIFFERENTIAL_REGION\", \"east\")\n return f\"({expression} + LENGTH('{region}'))\"\n", "depends_on": { @@ -2768,7 +2768,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/fulfillment/staging" + "sqlbuild_scope_path": "sql/models/fulfillment/staging" }, "docs": { "show": true, @@ -2782,8 +2782,8 @@ "name": "record_refresh", "resource_type": "macro", "package_name": "generated_0__sqlbuild_hooks", - "path": "hooks/sql/record_refresh.sql", - "original_file_path": "hooks/sql/record_refresh.sql", + "path": "sql/hooks/sql/record_refresh.sql", + "original_file_path": "sql/hooks/sql/record_refresh.sql", "unique_id": "macro.generated_0__sqlbuild_hooks.record_refresh", "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "depends_on": { diff --git a/tests/goldens/compiler/seed/0.json b/tests/goldens/compiler/seed/0.json index 97606b604d..235df0080d 100644 --- a/tests/goldens/compiler/seed/0.json +++ b/tests/goldens/compiler/seed/0.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + "message": "Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" } ] }, @@ -20,7 +20,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + "message": "Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" } ] }, @@ -37,7 +37,7 @@ "Project assembly OK ()", "Project discovery OK ()", "Compiling project...", - "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "error[P001]: Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", "", "" ] @@ -50,7 +50,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + "message": "Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" } ] }, @@ -62,7 +62,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + "message": "Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" } ] }, @@ -74,7 +74,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + "message": "Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" } ] }, @@ -90,7 +90,7 @@ "Python discovery OK ()", "Project assembly OK ()", "Project discovery OK ()", - "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "error[P001]: Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", "", "" ], @@ -110,7 +110,7 @@ "Python discovery OK ()", "Project assembly OK ()", "Project discovery OK ()", - "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "error[P001]: Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", "", "" ], @@ -130,7 +130,7 @@ "Python discovery OK ()", "Project assembly OK ()", "Project discovery OK ()", - "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "error[P001]: Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", "", "" ], @@ -150,7 +150,7 @@ "Python discovery OK ()", "Project assembly OK ()", "Project discovery OK ()", - "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "error[P001]: Macro '@py.explode' in '/sql/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", "", "" ], diff --git a/tests/goldens/compiler/seed/1.json b/tests/goldens/compiler/seed/1.json index 49b3078359..da93f902e9 100644 --- a/tests/goldens/compiler/seed/1.json +++ b/tests/goldens/compiler/seed/1.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "C214", - "message": "Model file models/features/dbt_order_counts.sql uses __dbt_ref(\"upstream_orders\") but no dbt manifest was found", + "message": "Model file sql/models/features/dbt_order_counts.sql uses __dbt_ref(\"upstream_orders\") but no dbt manifest was found", "help": "Run dbt compile or configure dbt target_path so SQLBuild can read manifest.json." } ] @@ -21,7 +21,7 @@ "phase": "compile", "severity": "error", "code": "C214", - "message": "Model file models/features/dbt_order_counts.sql uses __dbt_ref(\"upstream_orders\") but no dbt manifest was found", + "message": "Model file sql/models/features/dbt_order_counts.sql uses __dbt_ref(\"upstream_orders\") but no dbt manifest was found", "help": "Run dbt compile or configure dbt target_path so SQLBuild can read manifest.json." } ] diff --git a/tests/goldens/compiler/seed/10.json b/tests/goldens/compiler/seed/10.json index a6a3bdf907..df95960402 100644 --- a/tests/goldens/compiler/seed/10.json +++ b/tests/goldens/compiler/seed/10.json @@ -257,49 +257,49 @@ "id": "model:cte_facts_stg_inventory_1", "name": "cte_facts_stg_inventory_1", "resource_type": "model", - "relative_path": "models/analysis/cte_facts_stg_inventory_1.sql", + "relative_path": "sql/models/analysis/cte_facts_stg_inventory_1.sql", "qualified_name": "analytics.cte_facts_stg_inventory_1" }, { "id": "model:guarded_stg_inventory_1", "name": "guarded_stg_inventory_1", "resource_type": "model", - "relative_path": "models/features/guarded_stg_inventory_1.sql", + "relative_path": "sql/models/features/guarded_stg_inventory_1.sql", "qualified_name": "analytics.guarded_stg_inventory_1" }, { "id": "model:inventory_summary_0", "name": "inventory_summary_0", "resource_type": "model", - "relative_path": "models/inventory/marts/inventory_summary_0.sql", + "relative_path": "sql/models/inventory/marts/inventory_summary_0.sql", "qualified_name": "analytics.inventory_summary_0" }, { "id": "model:inventory_summary_1", "name": "inventory_summary_1", "resource_type": "model", - "relative_path": "models/inventory/marts/inventory_summary_1.sql", + "relative_path": "sql/models/inventory/marts/inventory_summary_1.sql", "qualified_name": "analytics.inventory_summary_1" }, { "id": "model:stg_inventory_1", "name": "stg_inventory_1", "resource_type": "model", - "relative_path": "models/inventory/staging/stg_inventory_1.sql", + "relative_path": "sql/models/inventory/staging/stg_inventory_1.sql", "qualified_name": "analytics.stg_inventory_1" }, { "id": "model:taxed_stg_inventory_1", "name": "taxed_stg_inventory_1", "resource_type": "model", - "relative_path": "models/features/taxed_stg_inventory_1.sql", + "relative_path": "sql/models/features/taxed_stg_inventory_1.sql", "qualified_name": "analytics.taxed_stg_inventory_1" }, { "id": "source:raw_events_0", "name": "raw_events_0", "resource_type": "source", - "relative_path": "sources/raw.yml" + "relative_path": "sql/sources/raw.yml" } ], "edges": [ @@ -336,26 +336,26 @@ } ], "compiled": { - "audits/generic/audited_stg_sales_0/id_present__id.sql": [ + "sql/audits/generic/audited_stg_sales_0/id_present__id.sql": [ "SELECT id", "FROM __ref(\"audited_stg_sales_0\")", "WHERE id IS NULL", "" ], - "audits/generic/checked_stg_sales_0/accepted_values__status.sql": [ + "sql/audits/generic/checked_stg_sales_0/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"checked_stg_sales_0\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/checked_stg_sales_0/expression_is_true.sql": [ + "sql/audits/generic/checked_stg_sales_0/expression_is_true.sql": [ "SELECT *", "FROM __ref(\"checked_stg_sales_0\")", "WHERE NOT (amount >= -1000)", "" ], - "audits/generic/checked_stg_sales_0/relationships__id.sql": [ + "sql/audits/generic/checked_stg_sales_0/relationships__id.sql": [ "SELECT id", "FROM __ref(\"checked_stg_sales_0\")", "WHERE id IS NOT NULL", @@ -366,106 +366,106 @@ " )", "" ], - "audits/generic/guarded_stg_inventory_1/amount_at_least__amount.sql": [ + "sql/audits/generic/guarded_stg_inventory_1/amount_at_least__amount.sql": [ "SELECT *", "FROM __ref(\"guarded_stg_inventory_1\")", "WHERE amount < 0", "" ], - "audits/generic/inventory_summary_0/not_null__id.sql": [ + "sql/audits/generic/inventory_summary_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"inventory_summary_0\")", "WHERE id IS NULL", "" ], - "audits/generic/sales_summary_0/not_null__id.sql": [ + "sql/audits/generic/sales_summary_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"sales_summary_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stated_stg_sales_0/accepted_values__status.sql": [ + "sql/audits/generic/stated_stg_sales_0/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"stated_stg_sales_0\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/stg_fulfillment_0/not_null__id.sql": [ + "sql/audits/generic/stg_fulfillment_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_fulfillment_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_fulfillment_1/not_null__id.sql": [ + "sql/audits/generic/stg_fulfillment_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_fulfillment_1\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_inventory_0/not_null__id.sql": [ + "sql/audits/generic/stg_inventory_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_inventory_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_inventory_1/not_null__id.sql": [ + "sql/audits/generic/stg_inventory_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_inventory_1\")", "WHERE id IS NULL", "" ], - "audits/singular/inventory_summary_0_matches.sql": [ + "sql/audits/singular/inventory_summary_0_matches.sql": [ "SELECT a.id", "FROM __ref(\"inventory_summary_0\") a", "LEFT JOIN __ref(\"inventory_summary_1\") b ON a.id = b.id", "WHERE b.id IS NULL", "" ], - "functions/python/is_large.sql": [ + "sql/functions/python/is_large.sql": [ "REGISTER PYTHON FUNCTION is_large(DOUBLE) RETURNS BOOLEAN", "" ], - "functions/sql/is_placed.sql": [ + "sql/functions/sql/is_placed.sql": [ "CREATE OR REPLACE MACRO analytics.is_placed(event_status) AS (", "event_status = 'placed'", ")", "" ], - "functions/sql/table_fn__events_above.sql": [ + "sql/functions/sql/table_fn__events_above.sql": [ "CREATE OR REPLACE MACRO analytics.table_fn__events_above(p_minimum) AS TABLE", "SELECT id, amount", "FROM __ref(\"stg_fulfillment_1\")", "WHERE amount > p_minimum", "" ], - "models/analysis/chain_1_stg_inventory_0.sql": [ + "sql/models/analysis/chain_1_stg_inventory_0.sql": [ "SELECT id, label, amount", "FROM __ref(\"contracted_stg_inventory_0\")", "" ], - "models/analysis/chain_2_stg_inventory_0.sql": [ + "sql/models/analysis/chain_2_stg_inventory_0.sql": [ "SELECT id, UPPER(label) AS label, amount", "FROM __ref(\"chain_1_stg_inventory_0\")", "" ], - "models/analysis/chain_3_stg_inventory_0.sql": [ + "sql/models/analysis/chain_3_stg_inventory_0.sql": [ "SELECT id, label, amount", "FROM __ref(\"chain_2_stg_inventory_0\")", "" ], - "models/analysis/checked_stg_sales_0.sql": [ + "sql/models/analysis/checked_stg_sales_0.sql": [ "SELECT id, amount, status", "FROM __ref(\"stg_sales_0\")", "" ], - "models/analysis/contracted_stg_inventory_0.sql": [ + "sql/models/analysis/contracted_stg_inventory_0.sql": [ "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR(22)) AS label,", " amount", "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/cte_facts_stg_inventory_1.sql": [ + "sql/models/analysis/cte_facts_stg_inventory_1.sql": [ "WITH base AS (", " SELECT id, CAST(amount AS DECIMAL(12, 2)) AS amount, 'event' AS kind,", " COALESCE(status, 'unknown') AS status", @@ -476,48 +476,48 @@ "FROM base", "" ], - "models/analysis/regional_stg_fulfillment_1.sql": [ + "sql/models/analysis/regional_stg_fulfillment_1.sql": [ "SELECT id, amount, 'south' AS region", "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/features/audited_stg_sales_0.sql": [ + "sql/models/features/audited_stg_sales_0.sql": [ "SELECT id, amount", "FROM __ref(\"stg_sales_0\")", "" ], - "models/features/check_history_stg_inventory_0.sql": [ + "sql/models/features/check_history_stg_inventory_0.sql": [ "SELECT id, status, amount", "FROM __ref(\"stg_inventory_0\")", "" ], - "models/features/copied_stg_sales_0.sql": [ + "sql/models/features/copied_stg_sales_0.sql": [ "SELECT id, status", "FROM __ref(\"stg_sales_0\")", "" ], - "models/features/flagged_stg_sales_0.sql": [ + "sql/models/features/flagged_stg_sales_0.sql": [ "SELECT id, __udf(\"is_placed\")(status) AS is_placed,", " __udf(\"is_large\")(amount) AS is_large", "FROM __ref(\"stg_sales_0\")", "" ], - "models/features/guarded_stg_inventory_1.sql": [ + "sql/models/features/guarded_stg_inventory_1.sql": [ "SELECT id, amount", "FROM __ref(\"stg_inventory_1\")", "" ], - "models/features/merge_stg_fulfillment_1.sql": [ + "sql/models/features/merge_stg_fulfillment_1.sql": [ "SELECT id, amount, status, created_at", "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/features/product_labels.sql": [ + "sql/models/features/product_labels.sql": [ "SELECT id, label", "FROM __source(\"loaded_products\")", "" ], - "models/features/spaced_stg_fulfillment_1.sql": [ + "sql/models/features/spaced_stg_fulfillment_1.sql": [ "-- Généré pour naïve résumé", "SELECT", "\tid,", @@ -526,12 +526,12 @@ "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/features/taxed_stg_inventory_1.sql": [ + "sql/models/features/taxed_stg_inventory_1.sql": [ "SELECT id, ROUND(amount * 1.2, 2) AS taxed, ROUND(amount, 1) AS rounded", "FROM __ref(\"stg_inventory_1\")", "" ], - "models/fulfillment/marts/fulfillment_summary_0.sql": [ + "sql/models/fulfillment/marts/fulfillment_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -542,7 +542,7 @@ "FROM __ref(\"stg_fulfillment_1\") t", "" ], - "models/fulfillment/marts/fulfillment_summary_1.sql": [ + "sql/models/fulfillment/marts/fulfillment_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -551,7 +551,7 @@ "FROM __ref(\"stg_fulfillment_0\") t", "" ], - "models/fulfillment/staging/stg_fulfillment_0.sql": [ + "sql/models/fulfillment/staging/stg_fulfillment_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -563,7 +563,7 @@ "FROM __source(\"raw_events_2\") t", "" ], - "models/fulfillment/staging/stg_fulfillment_1.sql": [ + "sql/models/fulfillment/staging/stg_fulfillment_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -575,7 +575,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/inventory/marts/inventory_summary_0.sql": [ + "sql/models/inventory/marts/inventory_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -586,7 +586,7 @@ "FROM __ref(\"stg_inventory_1\") t", "" ], - "models/inventory/marts/inventory_summary_1.sql": [ + "sql/models/inventory/marts/inventory_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -596,7 +596,7 @@ "FROM __ref(\"stg_inventory_1\") t", "" ], - "models/inventory/staging/stg_inventory_0.sql": [ + "sql/models/inventory/staging/stg_inventory_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -607,7 +607,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/inventory/staging/stg_inventory_1.sql": [ + "sql/models/inventory/staging/stg_inventory_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -616,29 +616,29 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/rendering/large_events.sql": [ + "sql/models/rendering/large_events.sql": [ "SELECT id, amount", "FROM __table_fn(\"table_fn__events_above\")(1.5)", "" ], - "models/rendering/latest_raw_events_0.sql": [ + "sql/models/rendering/latest_raw_events_0.sql": [ "SELECT id, amount", "FROM (SELECT id, amount FROM __source(\"raw_events_0\") ORDER BY id DESC LIMIT 2) AS latest", "" ], - "models/rendering/stated_stg_sales_0.sql": [ + "sql/models/rendering/stated_stg_sales_0.sql": [ "SELECT CAST(id AS INTEGER) AS id, status,", " CASE WHEN amount >= 4 THEN 'HIGH'", " ELSE 'LOW' END AS tier", "FROM __ref(\"stg_sales_0\")", "" ], - "models/rendering/unioned_event_ids.sql": [ + "sql/models/rendering/unioned_event_ids.sql": [ "SELECT id", "FROM (SELECT id FROM __ref(\"stg_fulfillment_1\") UNION ALL SELECT id FROM __ref(\"stg_inventory_0\")) AS unioned", "" ], - "models/sales/marts/sales_summary_0.sql": [ + "sql/models/sales/marts/sales_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -649,7 +649,7 @@ "WHERE t.status <> 'returned ✓'", "" ], - "models/sales/staging/stg_sales_0.sql": [ + "sql/models/sales/staging/stg_sales_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -708,8 +708,8 @@ "name": "chain_1_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/chain_1_stg_inventory_0.sql", - "original_file_path": "models/analysis/chain_1_stg_inventory_0.sql", + "path": "sql/models/analysis/chain_1_stg_inventory_0.sql", + "original_file_path": "sql/models/analysis/chain_1_stg_inventory_0.sql", "unique_id": "model.generated_10.chain_1_stg_inventory_0", "fqn": [ "generated_10", @@ -777,8 +777,8 @@ "name": "chain_2_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/chain_2_stg_inventory_0.sql", - "original_file_path": "models/analysis/chain_2_stg_inventory_0.sql", + "path": "sql/models/analysis/chain_2_stg_inventory_0.sql", + "original_file_path": "sql/models/analysis/chain_2_stg_inventory_0.sql", "unique_id": "model.generated_10.chain_2_stg_inventory_0", "fqn": [ "generated_10", @@ -846,8 +846,8 @@ "name": "chain_3_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/chain_3_stg_inventory_0.sql", - "original_file_path": "models/analysis/chain_3_stg_inventory_0.sql", + "path": "sql/models/analysis/chain_3_stg_inventory_0.sql", + "original_file_path": "sql/models/analysis/chain_3_stg_inventory_0.sql", "unique_id": "model.generated_10.chain_3_stg_inventory_0", "fqn": [ "generated_10", @@ -915,8 +915,8 @@ "name": "checked_stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/checked_stg_sales_0.sql", - "original_file_path": "models/analysis/checked_stg_sales_0.sql", + "path": "sql/models/analysis/checked_stg_sales_0.sql", + "original_file_path": "sql/models/analysis/checked_stg_sales_0.sql", "unique_id": "model.generated_10.checked_stg_sales_0", "fqn": [ "generated_10", @@ -1005,8 +1005,8 @@ "name": "contracted_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/contracted_stg_inventory_0.sql", - "original_file_path": "models/analysis/contracted_stg_inventory_0.sql", + "path": "sql/models/analysis/contracted_stg_inventory_0.sql", + "original_file_path": "sql/models/analysis/contracted_stg_inventory_0.sql", "unique_id": "model.generated_10.contracted_stg_inventory_0", "fqn": [ "generated_10", @@ -1102,8 +1102,8 @@ "name": "cte_facts_stg_inventory_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/cte_facts_stg_inventory_1.sql", - "original_file_path": "models/analysis/cte_facts_stg_inventory_1.sql", + "path": "sql/models/analysis/cte_facts_stg_inventory_1.sql", + "original_file_path": "sql/models/analysis/cte_facts_stg_inventory_1.sql", "unique_id": "model.generated_10.cte_facts_stg_inventory_1", "fqn": [ "generated_10", @@ -1208,8 +1208,8 @@ "name": "regional_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/regional_stg_fulfillment_1.sql", - "original_file_path": "models/analysis/regional_stg_fulfillment_1.sql", + "path": "sql/models/analysis/regional_stg_fulfillment_1.sql", + "original_file_path": "sql/models/analysis/regional_stg_fulfillment_1.sql", "unique_id": "model.generated_10.regional_stg_fulfillment_1", "fqn": [ "generated_10", @@ -1277,8 +1277,8 @@ "name": "audited_stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/audited_stg_sales_0.sql", - "original_file_path": "models/features/audited_stg_sales_0.sql", + "path": "sql/models/features/audited_stg_sales_0.sql", + "original_file_path": "sql/models/features/audited_stg_sales_0.sql", "unique_id": "model.generated_10.audited_stg_sales_0", "fqn": [ "generated_10", @@ -1346,8 +1346,8 @@ "name": "check_history_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/check_history_stg_inventory_0.sql", - "original_file_path": "models/features/check_history_stg_inventory_0.sql", + "path": "sql/models/features/check_history_stg_inventory_0.sql", + "original_file_path": "sql/models/features/check_history_stg_inventory_0.sql", "unique_id": "model.generated_10.check_history_stg_inventory_0", "fqn": [ "generated_10", @@ -1417,8 +1417,8 @@ "name": "copied_stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/copied_stg_sales_0.sql", - "original_file_path": "models/features/copied_stg_sales_0.sql", + "path": "sql/models/features/copied_stg_sales_0.sql", + "original_file_path": "sql/models/features/copied_stg_sales_0.sql", "unique_id": "model.generated_10.copied_stg_sales_0", "fqn": [ "generated_10", @@ -1486,8 +1486,8 @@ "name": "flagged_stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/flagged_stg_sales_0.sql", - "original_file_path": "models/features/flagged_stg_sales_0.sql", + "path": "sql/models/features/flagged_stg_sales_0.sql", + "original_file_path": "sql/models/features/flagged_stg_sales_0.sql", "unique_id": "model.generated_10.flagged_stg_sales_0", "fqn": [ "generated_10", @@ -1557,8 +1557,8 @@ "name": "guarded_stg_inventory_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/guarded_stg_inventory_1.sql", - "original_file_path": "models/features/guarded_stg_inventory_1.sql", + "path": "sql/models/features/guarded_stg_inventory_1.sql", + "original_file_path": "sql/models/features/guarded_stg_inventory_1.sql", "unique_id": "model.generated_10.guarded_stg_inventory_1", "fqn": [ "generated_10", @@ -1636,8 +1636,8 @@ "name": "merge_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/merge_stg_fulfillment_1.sql", - "original_file_path": "models/features/merge_stg_fulfillment_1.sql", + "path": "sql/models/features/merge_stg_fulfillment_1.sql", + "original_file_path": "sql/models/features/merge_stg_fulfillment_1.sql", "unique_id": "model.generated_10.merge_stg_fulfillment_1", "fqn": [ "generated_10", @@ -1707,8 +1707,8 @@ "name": "product_labels", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/product_labels.sql", - "original_file_path": "models/features/product_labels.sql", + "path": "sql/models/features/product_labels.sql", + "original_file_path": "sql/models/features/product_labels.sql", "unique_id": "model.generated_10.product_labels", "fqn": [ "generated_10", @@ -1776,8 +1776,8 @@ "name": "spaced_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/spaced_stg_fulfillment_1.sql", - "original_file_path": "models/features/spaced_stg_fulfillment_1.sql", + "path": "sql/models/features/spaced_stg_fulfillment_1.sql", + "original_file_path": "sql/models/features/spaced_stg_fulfillment_1.sql", "unique_id": "model.generated_10.spaced_stg_fulfillment_1", "fqn": [ "generated_10", @@ -1851,8 +1851,8 @@ "name": "taxed_stg_inventory_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/taxed_stg_inventory_1.sql", - "original_file_path": "models/features/taxed_stg_inventory_1.sql", + "path": "sql/models/features/taxed_stg_inventory_1.sql", + "original_file_path": "sql/models/features/taxed_stg_inventory_1.sql", "unique_id": "model.generated_10.taxed_stg_inventory_1", "fqn": [ "generated_10", @@ -1920,8 +1920,8 @@ "name": "fulfillment_summary_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/fulfillment/marts/fulfillment_summary_0.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_0.sql", + "path": "sql/models/fulfillment/marts/fulfillment_summary_0.sql", + "original_file_path": "sql/models/fulfillment/marts/fulfillment_summary_0.sql", "unique_id": "model.generated_10.fulfillment_summary_0", "fqn": [ "generated_10", @@ -1996,8 +1996,8 @@ "name": "fulfillment_summary_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/fulfillment/marts/fulfillment_summary_1.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_1.sql", + "path": "sql/models/fulfillment/marts/fulfillment_summary_1.sql", + "original_file_path": "sql/models/fulfillment/marts/fulfillment_summary_1.sql", "unique_id": "model.generated_10.fulfillment_summary_1", "fqn": [ "generated_10", @@ -2072,8 +2072,8 @@ "name": "stg_fulfillment_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/fulfillment/staging/stg_fulfillment_0.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_0.sql", + "path": "sql/models/fulfillment/staging/stg_fulfillment_0.sql", + "original_file_path": "sql/models/fulfillment/staging/stg_fulfillment_0.sql", "unique_id": "model.generated_10.stg_fulfillment_0", "fqn": [ "generated_10", @@ -2156,8 +2156,8 @@ "name": "stg_fulfillment_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/fulfillment/staging/stg_fulfillment_1.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_1.sql", + "path": "sql/models/fulfillment/staging/stg_fulfillment_1.sql", + "original_file_path": "sql/models/fulfillment/staging/stg_fulfillment_1.sql", "unique_id": "model.generated_10.stg_fulfillment_1", "fqn": [ "generated_10", @@ -2240,8 +2240,8 @@ "name": "inventory_summary_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/inventory/marts/inventory_summary_0.sql", - "original_file_path": "models/inventory/marts/inventory_summary_0.sql", + "path": "sql/models/inventory/marts/inventory_summary_0.sql", + "original_file_path": "sql/models/inventory/marts/inventory_summary_0.sql", "unique_id": "model.generated_10.inventory_summary_0", "fqn": [ "generated_10", @@ -2314,7 +2314,7 @@ "type": "sql", "statement": "SELECT 'analytics.inventory_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2354,8 +2354,8 @@ "name": "inventory_summary_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/inventory/marts/inventory_summary_1.sql", - "original_file_path": "models/inventory/marts/inventory_summary_1.sql", + "path": "sql/models/inventory/marts/inventory_summary_1.sql", + "original_file_path": "sql/models/inventory/marts/inventory_summary_1.sql", "unique_id": "model.generated_10.inventory_summary_1", "fqn": [ "generated_10", @@ -2424,8 +2424,8 @@ "name": "stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/inventory/staging/stg_inventory_0.sql", - "original_file_path": "models/inventory/staging/stg_inventory_0.sql", + "path": "sql/models/inventory/staging/stg_inventory_0.sql", + "original_file_path": "sql/models/inventory/staging/stg_inventory_0.sql", "unique_id": "model.generated_10.stg_inventory_0", "fqn": [ "generated_10", @@ -2508,8 +2508,8 @@ "name": "stg_inventory_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/inventory/staging/stg_inventory_1.sql", - "original_file_path": "models/inventory/staging/stg_inventory_1.sql", + "path": "sql/models/inventory/staging/stg_inventory_1.sql", + "original_file_path": "sql/models/inventory/staging/stg_inventory_1.sql", "unique_id": "model.generated_10.stg_inventory_1", "fqn": [ "generated_10", @@ -2592,8 +2592,8 @@ "name": "large_events", "resource_type": "model", "package_name": "generated_10", - "path": "models/rendering/large_events.sql", - "original_file_path": "models/rendering/large_events.sql", + "path": "sql/models/rendering/large_events.sql", + "original_file_path": "sql/models/rendering/large_events.sql", "unique_id": "model.generated_10.large_events", "fqn": [ "generated_10", @@ -2661,8 +2661,8 @@ "name": "latest_raw_events_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/rendering/latest_raw_events_0.sql", - "original_file_path": "models/rendering/latest_raw_events_0.sql", + "path": "sql/models/rendering/latest_raw_events_0.sql", + "original_file_path": "sql/models/rendering/latest_raw_events_0.sql", "unique_id": "model.generated_10.latest_raw_events_0", "fqn": [ "generated_10", @@ -2730,8 +2730,8 @@ "name": "stated_stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/rendering/stated_stg_sales_0.sql", - "original_file_path": "models/rendering/stated_stg_sales_0.sql", + "path": "sql/models/rendering/stated_stg_sales_0.sql", + "original_file_path": "sql/models/rendering/stated_stg_sales_0.sql", "unique_id": "model.generated_10.stated_stg_sales_0", "fqn": [ "generated_10", @@ -2827,8 +2827,8 @@ "name": "unioned_event_ids", "resource_type": "model", "package_name": "generated_10", - "path": "models/rendering/unioned_event_ids.sql", - "original_file_path": "models/rendering/unioned_event_ids.sql", + "path": "sql/models/rendering/unioned_event_ids.sql", + "original_file_path": "sql/models/rendering/unioned_event_ids.sql", "unique_id": "model.generated_10.unioned_event_ids", "fqn": [ "generated_10", @@ -2897,8 +2897,8 @@ "name": "sales_summary_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/sales/marts/sales_summary_0.sql", - "original_file_path": "models/sales/marts/sales_summary_0.sql", + "path": "sql/models/sales/marts/sales_summary_0.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_0.sql", "unique_id": "model.generated_10.sales_summary_0", "fqn": [ "generated_10", @@ -2977,7 +2977,7 @@ "type": "sql", "statement": "SELECT 'analytics.sales_summary_0' AS refreshed_relation, 'Zürich – depot' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -3017,8 +3017,8 @@ "name": "stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/sales/staging/stg_sales_0.sql", - "original_file_path": "models/sales/staging/stg_sales_0.sql", + "path": "sql/models/sales/staging/stg_sales_0.sql", + "original_file_path": "sql/models/sales/staging/stg_sales_0.sql", "unique_id": "model.generated_10.stg_sales_0", "fqn": [ "generated_10", @@ -3093,8 +3093,8 @@ "name": "loaded_products", "resource_type": "source", "package_name": "generated_10", - "path": "sources/managed.yml", - "original_file_path": "sources/managed.yml", + "path": "sql/sources/managed.yml", + "original_file_path": "sql/sources/managed.yml", "unique_id": "source.generated_10.loaded_products", "fqn": [ "generated_10", @@ -3149,8 +3149,8 @@ "name": "raw_events_0", "resource_type": "source", "package_name": "generated_10", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_10.raw_events_0", "fqn": [ "generated_10", @@ -3217,8 +3217,8 @@ "name": "raw_events_1", "resource_type": "source", "package_name": "generated_10", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_10.raw_events_1", "fqn": [ "generated_10", @@ -3285,8 +3285,8 @@ "name": "raw_events_2", "resource_type": "source", "package_name": "generated_10", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_10.raw_events_2", "fqn": [ "generated_10", @@ -3353,8 +3353,8 @@ "name": "adjust_1", "resource_type": "macro", "package_name": "generated_10", - "path": "macros/python/adjust_1.py", - "original_file_path": "macros/python/adjust_1.py", + "path": "sql/macros/python/adjust_1.py", + "original_file_path": "sql/macros/python/adjust_1.py", "unique_id": "macro.generated_10.adjust_1", "macro_sql": "def adjust_1_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_1_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -3379,8 +3379,8 @@ "name": "adjust_1_round", "resource_type": "macro", "package_name": "generated_10", - "path": "macros/python/adjust_1.py", - "original_file_path": "macros/python/adjust_1.py", + "path": "sql/macros/python/adjust_1.py", + "original_file_path": "sql/macros/python/adjust_1.py", "unique_id": "macro.generated_10.adjust_1_round", "macro_sql": "def adjust_1_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_1_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -3403,8 +3403,8 @@ "name": "round_amount", "resource_type": "macro", "package_name": "generated_10", - "path": "macros/python/rounding.py", - "original_file_path": "macros/python/rounding.py", + "path": "sql/macros/python/rounding.py", + "original_file_path": "sql/macros/python/rounding.py", "unique_id": "macro.generated_10.round_amount", "macro_sql": "def round_amount(expression: str, places: int = 2) -> str:\n \"\"\"Round an amount.\"\"\"\n return f\"ROUND({expression}, {places})\"\n", "depends_on": { @@ -3427,10 +3427,10 @@ "name": "taxed", "resource_type": "macro", "package_name": "generated_10", - "path": "macros/python/tax.py", - "original_file_path": "macros/python/tax.py", + "path": "sql/macros/python/tax.py", + "original_file_path": "sql/macros/python/tax.py", "unique_id": "macro.generated_10.taxed", - "macro_sql": "from macros.python.rounding import round_amount\n\n\ndef taxed(expression: str) -> str:\n \"\"\"Add tax to an amount, rounded.\"\"\"\n return round_amount(f\"{expression} * 1.2\")\n", + "macro_sql": "from sql.macros.python.rounding import round_amount\n\n\ndef taxed(expression: str) -> str:\n \"\"\"Add tax to an amount, rounded.\"\"\"\n return round_amount(f\"{expression} * 1.2\")\n", "depends_on": { "macros": [ "macro.generated_10.round_amount" @@ -3453,8 +3453,8 @@ "name": "analysis_region", "resource_type": "macro", "package_name": "generated_10", - "path": "models/analysis/_sqlbuild/_macros/python/regions.py", - "original_file_path": "models/analysis/_sqlbuild/_macros/python/regions.py", + "path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", + "original_file_path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", "unique_id": "macro.generated_10.analysis_region", "macro_sql": "def analysis_region() -> str:\n \"\"\"Return the region rows are assigned to.\"\"\"\n return \"'south'\"\n", "depends_on": { @@ -3463,7 +3463,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/analysis" + "sqlbuild_scope_path": "sql/models/analysis" }, "docs": { "show": true, @@ -3477,8 +3477,8 @@ "name": "adjust_0", "resource_type": "macro", "package_name": "generated_10", - "path": "models/fulfillment/_sqlbuild/macros/python/adjust_0.py", - "original_file_path": "models/fulfillment/_sqlbuild/macros/python/adjust_0.py", + "path": "sql/models/fulfillment/_sqlbuild/macros/python/adjust_0.py", + "original_file_path": "sql/models/fulfillment/_sqlbuild/macros/python/adjust_0.py", "unique_id": "macro.generated_10.adjust_0", "macro_sql": "def adjust_0(ctx, expression: str) -> str:\n \"\"\"Scale an amount by the configured discount.\"\"\"\n rate = ctx.vars[\"discount_rate\"]\n return f\"({expression} * (1 - {rate}))\"\n", "depends_on": { @@ -3487,7 +3487,7 @@ "description": "", "meta": { "sqlbuild_visibility": "inherited", - "sqlbuild_scope_path": "models/fulfillment" + "sqlbuild_scope_path": "sql/models/fulfillment" }, "docs": { "show": true, @@ -3501,8 +3501,8 @@ "name": "adjust_2", "resource_type": "macro", "package_name": "generated_10", - "path": "models/inventory/staging/_sqlbuild/_macros/python/adjust_2.py", - "original_file_path": "models/inventory/staging/_sqlbuild/_macros/python/adjust_2.py", + "path": "sql/models/inventory/staging/_sqlbuild/_macros/python/adjust_2.py", + "original_file_path": "sql/models/inventory/staging/_sqlbuild/_macros/python/adjust_2.py", "unique_id": "macro.generated_10.adjust_2", "macro_sql": "def adjust_2(expression: str) -> str:\n \"\"\"Offset an amount.\"\"\"\n return f\"({expression} + 2 + 1)\"\n", "depends_on": { @@ -3511,7 +3511,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/inventory/staging" + "sqlbuild_scope_path": "sql/models/inventory/staging" }, "docs": { "show": true, @@ -3525,8 +3525,8 @@ "name": "latest_rows", "resource_type": "macro", "package_name": "generated_10", - "path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/relations.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/relations.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/relations.py", "unique_id": "macro.generated_10.latest_rows", "macro_sql": "from sqlbuild.refs import SqlResourceRef\n\n\ndef union_ids(relations: list[SqlResourceRef]) -> str:\n \"\"\"Union the ids of several relations.\"\"\"\n selects = [f\"SELECT id FROM {relation}\" for relation in relations]\n return \" UNION ALL \".join(selects)\n\n\ndef latest_rows(relation: SqlResourceRef, limit: int = 2) -> str:\n \"\"\"Return the newest rows of one relation.\"\"\"\n return f\"(SELECT id, amount FROM {relation} ORDER BY id DESC LIMIT {limit})\"\n", "depends_on": { @@ -3535,7 +3535,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -3549,8 +3549,8 @@ "name": "union_ids", "resource_type": "macro", "package_name": "generated_10", - "path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/relations.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/relations.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/relations.py", "unique_id": "macro.generated_10.union_ids", "macro_sql": "from sqlbuild.refs import SqlResourceRef\n\n\ndef union_ids(relations: list[SqlResourceRef]) -> str:\n \"\"\"Union the ids of several relations.\"\"\"\n selects = [f\"SELECT id FROM {relation}\" for relation in relations]\n return \" UNION ALL \".join(selects)\n\n\ndef latest_rows(relation: SqlResourceRef, limit: int = 2) -> str:\n \"\"\"Return the newest rows of one relation.\"\"\"\n return f\"(SELECT id, amount FROM {relation} ORDER BY id DESC LIMIT {limit})\"\n", "depends_on": { @@ -3559,7 +3559,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -3573,8 +3573,8 @@ "name": "record_refresh", "resource_type": "macro", "package_name": "generated_10__sqlbuild_hooks", - "path": "hooks/sql/record_refresh.sql", - "original_file_path": "hooks/sql/record_refresh.sql", + "path": "sql/hooks/sql/record_refresh.sql", + "original_file_path": "sql/hooks/sql/record_refresh.sql", "unique_id": "macro.generated_10__sqlbuild_hooks.record_refresh", "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "depends_on": { diff --git a/tests/goldens/compiler/seed/11.json b/tests/goldens/compiler/seed/11.json index fb6be39da4..96439886ab 100644 --- a/tests/goldens/compiler/seed/11.json +++ b/tests/goldens/compiler/seed/11.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "MODEL(...) in '/models/fulfillment/marts/fulfillment_summary_0.sql' contains invalid SQLBuild header syntax: expected key at position 267" + "message": "MODEL(...) in '/sql/models/fulfillment/marts/fulfillment_summary_0.sql' contains invalid SQLBuild header syntax: expected key at position 267" } ] }, @@ -20,7 +20,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "MODEL(...) in '/models/fulfillment/marts/fulfillment_summary_0.sql' contains invalid SQLBuild header syntax: expected key at position 267" + "message": "MODEL(...) in '/sql/models/fulfillment/marts/fulfillment_summary_0.sql' contains invalid SQLBuild header syntax: expected key at position 267" } ] }, @@ -34,7 +34,7 @@ "Declaration parsing FAIL ()", "Project assembly FAIL ()", "Project discovery FAIL ()", - "error[D002]: MODEL(...) in '/models/fulfillment/marts/fulfillment_summary_0.sql' contains invalid SQLBuild header syntax: expected key at position 267", + "error[D002]: MODEL(...) in '/sql/models/fulfillment/marts/fulfillment_summary_0.sql' contains invalid SQLBuild header syntax: expected key at position 267", "", "" ] diff --git a/tests/goldens/compiler/seed/2.json b/tests/goldens/compiler/seed/2.json index a3ae59d335..9e2b449c2d 100644 --- a/tests/goldens/compiler/seed/2.json +++ b/tests/goldens/compiler/seed/2.json @@ -229,70 +229,70 @@ "id": "model:check_history_stg_sales_2", "name": "check_history_stg_sales_2", "resource_type": "model", - "relative_path": "models/features/check_history_stg_sales_2.sql", + "relative_path": "sql/models/features/check_history_stg_sales_2.sql", "qualified_name": "analytics.check_history_stg_sales_2" }, { "id": "model:checked_stg_sales_2", "name": "checked_stg_sales_2", "resource_type": "model", - "relative_path": "models/analysis/checked_stg_sales_2.sql", + "relative_path": "sql/models/analysis/checked_stg_sales_2.sql", "qualified_name": "analytics.checked_stg_sales_2" }, { "id": "model:combined_stg_sales_2", "name": "combined_stg_sales_2", "resource_type": "model", - "relative_path": "models/analysis/combined_stg_sales_2.sql", + "relative_path": "sql/models/analysis/combined_stg_sales_2.sql", "qualified_name": "analytics.combined_stg_sales_2" }, { "id": "model:cte_facts_stg_sales_2", "name": "cte_facts_stg_sales_2", "resource_type": "model", - "relative_path": "models/analysis/cte_facts_stg_sales_2.sql", + "relative_path": "sql/models/analysis/cte_facts_stg_sales_2.sql", "qualified_name": "analytics.cte_facts_stg_sales_2" }, { "id": "model:every_stg_sales_2", "name": "every_stg_sales_2", "resource_type": "model", - "relative_path": "models/analysis/every_stg_sales_2.sql", + "relative_path": "sql/models/analysis/every_stg_sales_2.sql", "qualified_name": "analytics.every_stg_sales_2" }, { "id": "model:passed_stg_sales_2", "name": "passed_stg_sales_2", "resource_type": "model", - "relative_path": "models/analysis/passed_stg_sales_2.sql", + "relative_path": "sql/models/analysis/passed_stg_sales_2.sql", "qualified_name": "analytics.passed_stg_sales_2" }, { "id": "model:sales_summary_1", "name": "sales_summary_1", "resource_type": "model", - "relative_path": "models/sales/marts/sales_summary_1.sql", + "relative_path": "sql/models/sales/marts/sales_summary_1.sql", "qualified_name": "analytics.sales_summary_1" }, { "id": "model:stg_sales_2", "name": "stg_sales_2", "resource_type": "model", - "relative_path": "models/sales/staging/stg_sales_2.sql", + "relative_path": "sql/models/sales/staging/stg_sales_2.sql", "qualified_name": "analytics.stg_sales_2" }, { "id": "model:typed_stg_sales_2", "name": "typed_stg_sales_2", "resource_type": "model", - "relative_path": "models/analysis/typed_stg_sales_2.sql", + "relative_path": "sql/models/analysis/typed_stg_sales_2.sql", "qualified_name": "analytics.typed_stg_sales_2" }, { "id": "source:raw_events_0", "name": "raw_events_0", "resource_type": "source", - "relative_path": "sources/raw.yml" + "relative_path": "sql/sources/raw.yml" } ], "edges": [ @@ -341,26 +341,26 @@ } ], "compiled": { - "audits/generic/audited_stg_sales_0/id_present__id.sql": [ + "sql/audits/generic/audited_stg_sales_0/id_present__id.sql": [ "SELECT id", "FROM __ref(\"audited_stg_sales_0\")", "WHERE id IS NULL", "" ], - "audits/generic/checked_stg_sales_2/accepted_values__status.sql": [ + "sql/audits/generic/checked_stg_sales_2/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"checked_stg_sales_2\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/checked_stg_sales_2/expression_is_true.sql": [ + "sql/audits/generic/checked_stg_sales_2/expression_is_true.sql": [ "SELECT *", "FROM __ref(\"checked_stg_sales_2\")", "WHERE NOT (amount >= -1000)", "" ], - "audits/generic/checked_stg_sales_2/relationships__id.sql": [ + "sql/audits/generic/checked_stg_sales_2/relationships__id.sql": [ "SELECT id", "FROM __ref(\"checked_stg_sales_2\")", "WHERE id IS NOT NULL", @@ -371,75 +371,75 @@ " )", "" ], - "audits/generic/sales_summary_0/not_null__id.sql": [ + "sql/audits/generic/sales_summary_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"sales_summary_0\")", "WHERE id IS NULL", "" ], - "audits/generic/sales_summary_1/not_null__id.sql": [ + "sql/audits/generic/sales_summary_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"sales_summary_1\")", "WHERE id IS NULL", "" ], - "audits/generic/stated_stg_sales_1/accepted_values__status.sql": [ + "sql/audits/generic/stated_stg_sales_1/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"stated_stg_sales_1\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/stg_sales_1/not_null__id.sql": [ + "sql/audits/generic/stg_sales_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_sales_1\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_sales_2/not_null__id.sql": [ + "sql/audits/generic/stg_sales_2/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_sales_2\")", "WHERE id IS NULL", "" ], - "functions/python/is_large.sql": [ + "sql/functions/python/is_large.sql": [ "REGISTER PYTHON FUNCTION is_large(DOUBLE) RETURNS BOOLEAN", "" ], - "functions/sql/is_placed.sql": [ + "sql/functions/sql/is_placed.sql": [ "CREATE OR REPLACE MACRO analytics.is_placed(event_status) AS (", "event_status = 'placed'", ")", "" ], - "functions/sql/table_fn__events_above.sql": [ + "sql/functions/sql/table_fn__events_above.sql": [ "CREATE OR REPLACE MACRO analytics.table_fn__events_above(p_minimum) AS TABLE", "SELECT id, amount", "FROM __ref(\"stg_sales_1\")", "WHERE amount > p_minimum", "" ], - "models/analysis/chain_1_stg_sales_1.sql": [ + "sql/models/analysis/chain_1_stg_sales_1.sql": [ "SELECT id, label, amount", "FROM __ref(\"contracted_stg_sales_1\")", "" ], - "models/analysis/chain_2_stg_sales_1.sql": [ + "sql/models/analysis/chain_2_stg_sales_1.sql": [ "SELECT id, UPPER(label) AS label, amount", "FROM __ref(\"chain_1_stg_sales_1\")", "" ], - "models/analysis/chain_3_stg_sales_1.sql": [ + "sql/models/analysis/chain_3_stg_sales_1.sql": [ "SELECT id, label, amount", "FROM __ref(\"chain_2_stg_sales_1\")", "" ], - "models/analysis/checked_stg_sales_2.sql": [ + "sql/models/analysis/checked_stg_sales_2.sql": [ "SELECT id, amount, status", "FROM __ref(\"stg_sales_2\")", "" ], - "models/analysis/combined_stg_sales_2.sql": [ + "sql/models/analysis/combined_stg_sales_2.sql": [ "WITH recent AS (", " SELECT id, created_at FROM __ref(\"stg_sales_2\") WHERE amount > 0", "),", @@ -451,13 +451,13 @@ "SELECT id, created_at FROM older", "" ], - "models/analysis/contracted_stg_sales_1.sql": [ + "sql/models/analysis/contracted_stg_sales_1.sql": [ "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR(40)) AS label,", " amount", "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/cte_facts_stg_sales_2.sql": [ + "sql/models/analysis/cte_facts_stg_sales_2.sql": [ "WITH base AS (", " SELECT id, CAST(amount AS DECIMAL(12, 2)) AS amount, 'event' AS kind,", " COALESCE(status, 'unknown') AS status", @@ -468,22 +468,22 @@ "FROM base", "" ], - "models/analysis/every_open_event.sql": [ + "sql/models/analysis/every_open_event.sql": [ "SELECT *", "FROM __source(\"open_events\")", "" ], - "models/analysis/every_raw_events_0.sql": [ + "sql/models/analysis/every_raw_events_0.sql": [ "SELECT *", "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/every_stg_sales_2.sql": [ + "sql/models/analysis/every_stg_sales_2.sql": [ "SELECT *", "FROM __ref(\"stg_sales_2\")", "" ], - "models/analysis/passed_stg_sales_2.sql": [ + "sql/models/analysis/passed_stg_sales_2.sql": [ "WITH passthrough AS (", " SELECT id, created_at FROM __ref(\"stg_sales_2\")", ")", @@ -491,51 +491,51 @@ "FROM passthrough", "" ], - "models/analysis/pivot_input_stg_sales_1.sql": [ + "sql/models/analysis/pivot_input_stg_sales_1.sql": [ "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR) AS status, amount", "FROM __ref(\"stg_sales_1\")", "" ], - "models/analysis/pivoted_stg_sales_1.sql": [ + "sql/models/analysis/pivoted_stg_sales_1.sql": [ "PIVOT __ref(\"pivot_input_stg_sales_1\")", "ON status", "USING MAX(amount)", "GROUP BY id", "" ], - "models/analysis/typed_stg_sales_2.sql": [ + "sql/models/analysis/typed_stg_sales_2.sql": [ "SELECT id, amount * 2 AS doubled_amount, CAST(status AS VARCHAR) AS status_text,", " created_at, NULL AS missing_note", "FROM __ref(\"stg_sales_2\")", "" ], - "models/features/audited_stg_sales_0.sql": [ + "sql/models/features/audited_stg_sales_0.sql": [ "SELECT id, amount", "FROM __ref(\"stg_sales_0\")", "" ], - "models/features/check_history_stg_sales_2.sql": [ + "sql/models/features/check_history_stg_sales_2.sql": [ "SELECT id, status, amount", "FROM __ref(\"stg_sales_2\")", "" ], - "models/features/copied_stg_sales_0.sql": [ + "sql/models/features/copied_stg_sales_0.sql": [ "SELECT id, status", "FROM __ref(\"stg_sales_0\")", "" ], - "models/features/flagged_stg_sales_0.sql": [ + "sql/models/features/flagged_stg_sales_0.sql": [ "SELECT id, __udf(\"is_placed\")(status) AS is_placed,", " __udf(\"is_large\")(amount) AS is_large", "FROM __ref(\"stg_sales_0\")", "" ], - "models/features/merge_stg_sales_1.sql": [ + "sql/models/features/merge_stg_sales_1.sql": [ "SELECT id, amount, status, created_at", "FROM __ref(\"stg_sales_1\")", "" ], - "models/features/spaced_stg_sales_1.sql": [ + "sql/models/features/spaced_stg_sales_1.sql": [ "-- Généré pour Zürich – depot", "SELECT", "\tid,", @@ -544,31 +544,31 @@ "FROM __ref(\"stg_sales_1\")", "" ], - "models/features/taxed_stg_sales_0.sql": [ + "sql/models/features/taxed_stg_sales_0.sql": [ "SELECT id, ROUND(amount * 1.2, 2) AS taxed, ROUND(amount, 1) AS rounded", "FROM __ref(\"stg_sales_0\")", "" ], - "models/rendering/bounded_stg_sales_0.sql": [ + "sql/models/rendering/bounded_stg_sales_0.sql": [ "SELECT id, amount, created_at", "FROM __ref(\"stg_sales_0\")", "WHERE created_at >= __cursor_start()", " AND created_at < __cursor_end()", "" ], - "models/rendering/large_events.sql": [ + "sql/models/rendering/large_events.sql": [ "SELECT id, amount", "FROM __table_fn(\"table_fn__events_above\")(4)", "" ], - "models/rendering/stated_stg_sales_1.sql": [ + "sql/models/rendering/stated_stg_sales_1.sql": [ "SELECT CAST(id AS INTEGER) AS id, status,", " CASE WHEN amount >= 8 THEN 'HIGH'", " ELSE 'LOW' END AS tier", "FROM __ref(\"stg_sales_1\")", "" ], - "models/sales/marts/sales_summary_0.sql": [ + "sql/models/sales/marts/sales_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -581,7 +581,7 @@ "FROM __ref(\"stg_sales_1\") t", "" ], - "models/sales/marts/sales_summary_1.sql": [ + "sql/models/sales/marts/sales_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -596,7 +596,7 @@ "LEFT JOIN __seed(\"lookup_0\") j2 ON t.id = j2.id", "" ], - "models/sales/marts/sales_summary_2.sql": [ + "sql/models/sales/marts/sales_summary_2.sql": [ "SELECT", " t.id,", " t.amount,", @@ -610,7 +610,7 @@ "LEFT JOIN __seed(\"lookup_0\") j1 ON t.id = j1.id", "" ], - "models/sales/staging/stg_sales_0.sql": [ + "sql/models/sales/staging/stg_sales_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -620,7 +620,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/sales/staging/stg_sales_1.sql": [ + "sql/models/sales/staging/stg_sales_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -631,7 +631,7 @@ "WHERE t.status <> 'placed'", "" ], - "models/sales/staging/stg_sales_2.sql": [ + "sql/models/sales/staging/stg_sales_2.sql": [ "SELECT", " t.id,", " t.amount,", @@ -687,8 +687,8 @@ "name": "chain_1_stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/chain_1_stg_sales_1.sql", - "original_file_path": "models/analysis/chain_1_stg_sales_1.sql", + "path": "sql/models/analysis/chain_1_stg_sales_1.sql", + "original_file_path": "sql/models/analysis/chain_1_stg_sales_1.sql", "unique_id": "model.generated_2.chain_1_stg_sales_1", "fqn": [ "generated_2", @@ -756,8 +756,8 @@ "name": "chain_2_stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/chain_2_stg_sales_1.sql", - "original_file_path": "models/analysis/chain_2_stg_sales_1.sql", + "path": "sql/models/analysis/chain_2_stg_sales_1.sql", + "original_file_path": "sql/models/analysis/chain_2_stg_sales_1.sql", "unique_id": "model.generated_2.chain_2_stg_sales_1", "fqn": [ "generated_2", @@ -825,8 +825,8 @@ "name": "chain_3_stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/chain_3_stg_sales_1.sql", - "original_file_path": "models/analysis/chain_3_stg_sales_1.sql", + "path": "sql/models/analysis/chain_3_stg_sales_1.sql", + "original_file_path": "sql/models/analysis/chain_3_stg_sales_1.sql", "unique_id": "model.generated_2.chain_3_stg_sales_1", "fqn": [ "generated_2", @@ -894,8 +894,8 @@ "name": "checked_stg_sales_2", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/checked_stg_sales_2.sql", - "original_file_path": "models/analysis/checked_stg_sales_2.sql", + "path": "sql/models/analysis/checked_stg_sales_2.sql", + "original_file_path": "sql/models/analysis/checked_stg_sales_2.sql", "unique_id": "model.generated_2.checked_stg_sales_2", "fqn": [ "generated_2", @@ -984,8 +984,8 @@ "name": "combined_stg_sales_2", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/combined_stg_sales_2.sql", - "original_file_path": "models/analysis/combined_stg_sales_2.sql", + "path": "sql/models/analysis/combined_stg_sales_2.sql", + "original_file_path": "sql/models/analysis/combined_stg_sales_2.sql", "unique_id": "model.generated_2.combined_stg_sales_2", "fqn": [ "generated_2", @@ -1053,8 +1053,8 @@ "name": "contracted_stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/contracted_stg_sales_1.sql", - "original_file_path": "models/analysis/contracted_stg_sales_1.sql", + "path": "sql/models/analysis/contracted_stg_sales_1.sql", + "original_file_path": "sql/models/analysis/contracted_stg_sales_1.sql", "unique_id": "model.generated_2.contracted_stg_sales_1", "fqn": [ "generated_2", @@ -1150,8 +1150,8 @@ "name": "cte_facts_stg_sales_2", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/cte_facts_stg_sales_2.sql", - "original_file_path": "models/analysis/cte_facts_stg_sales_2.sql", + "path": "sql/models/analysis/cte_facts_stg_sales_2.sql", + "original_file_path": "sql/models/analysis/cte_facts_stg_sales_2.sql", "unique_id": "model.generated_2.cte_facts_stg_sales_2", "fqn": [ "generated_2", @@ -1256,8 +1256,8 @@ "name": "every_open_event", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/every_open_event.sql", - "original_file_path": "models/analysis/every_open_event.sql", + "path": "sql/models/analysis/every_open_event.sql", + "original_file_path": "sql/models/analysis/every_open_event.sql", "unique_id": "model.generated_2.every_open_event", "fqn": [ "generated_2", @@ -1325,8 +1325,8 @@ "name": "every_raw_events_0", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/every_raw_events_0.sql", - "original_file_path": "models/analysis/every_raw_events_0.sql", + "path": "sql/models/analysis/every_raw_events_0.sql", + "original_file_path": "sql/models/analysis/every_raw_events_0.sql", "unique_id": "model.generated_2.every_raw_events_0", "fqn": [ "generated_2", @@ -1394,8 +1394,8 @@ "name": "every_stg_sales_2", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/every_stg_sales_2.sql", - "original_file_path": "models/analysis/every_stg_sales_2.sql", + "path": "sql/models/analysis/every_stg_sales_2.sql", + "original_file_path": "sql/models/analysis/every_stg_sales_2.sql", "unique_id": "model.generated_2.every_stg_sales_2", "fqn": [ "generated_2", @@ -1463,8 +1463,8 @@ "name": "passed_stg_sales_2", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/passed_stg_sales_2.sql", - "original_file_path": "models/analysis/passed_stg_sales_2.sql", + "path": "sql/models/analysis/passed_stg_sales_2.sql", + "original_file_path": "sql/models/analysis/passed_stg_sales_2.sql", "unique_id": "model.generated_2.passed_stg_sales_2", "fqn": [ "generated_2", @@ -1532,8 +1532,8 @@ "name": "pivot_input_stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/pivot_input_stg_sales_1.sql", - "original_file_path": "models/analysis/pivot_input_stg_sales_1.sql", + "path": "sql/models/analysis/pivot_input_stg_sales_1.sql", + "original_file_path": "sql/models/analysis/pivot_input_stg_sales_1.sql", "unique_id": "model.generated_2.pivot_input_stg_sales_1", "fqn": [ "generated_2", @@ -1629,8 +1629,8 @@ "name": "pivoted_stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/pivoted_stg_sales_1.sql", - "original_file_path": "models/analysis/pivoted_stg_sales_1.sql", + "path": "sql/models/analysis/pivoted_stg_sales_1.sql", + "original_file_path": "sql/models/analysis/pivoted_stg_sales_1.sql", "unique_id": "model.generated_2.pivoted_stg_sales_1", "fqn": [ "generated_2", @@ -1721,8 +1721,8 @@ "name": "typed_stg_sales_2", "resource_type": "model", "package_name": "generated_2", - "path": "models/analysis/typed_stg_sales_2.sql", - "original_file_path": "models/analysis/typed_stg_sales_2.sql", + "path": "sql/models/analysis/typed_stg_sales_2.sql", + "original_file_path": "sql/models/analysis/typed_stg_sales_2.sql", "unique_id": "model.generated_2.typed_stg_sales_2", "fqn": [ "generated_2", @@ -1790,8 +1790,8 @@ "name": "audited_stg_sales_0", "resource_type": "model", "package_name": "generated_2", - "path": "models/features/audited_stg_sales_0.sql", - "original_file_path": "models/features/audited_stg_sales_0.sql", + "path": "sql/models/features/audited_stg_sales_0.sql", + "original_file_path": "sql/models/features/audited_stg_sales_0.sql", "unique_id": "model.generated_2.audited_stg_sales_0", "fqn": [ "generated_2", @@ -1859,8 +1859,8 @@ "name": "check_history_stg_sales_2", "resource_type": "model", "package_name": "generated_2", - "path": "models/features/check_history_stg_sales_2.sql", - "original_file_path": "models/features/check_history_stg_sales_2.sql", + "path": "sql/models/features/check_history_stg_sales_2.sql", + "original_file_path": "sql/models/features/check_history_stg_sales_2.sql", "unique_id": "model.generated_2.check_history_stg_sales_2", "fqn": [ "generated_2", @@ -1930,8 +1930,8 @@ "name": "copied_stg_sales_0", "resource_type": "model", "package_name": "generated_2", - "path": "models/features/copied_stg_sales_0.sql", - "original_file_path": "models/features/copied_stg_sales_0.sql", + "path": "sql/models/features/copied_stg_sales_0.sql", + "original_file_path": "sql/models/features/copied_stg_sales_0.sql", "unique_id": "model.generated_2.copied_stg_sales_0", "fqn": [ "generated_2", @@ -1999,8 +1999,8 @@ "name": "flagged_stg_sales_0", "resource_type": "model", "package_name": "generated_2", - "path": "models/features/flagged_stg_sales_0.sql", - "original_file_path": "models/features/flagged_stg_sales_0.sql", + "path": "sql/models/features/flagged_stg_sales_0.sql", + "original_file_path": "sql/models/features/flagged_stg_sales_0.sql", "unique_id": "model.generated_2.flagged_stg_sales_0", "fqn": [ "generated_2", @@ -2070,8 +2070,8 @@ "name": "merge_stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/features/merge_stg_sales_1.sql", - "original_file_path": "models/features/merge_stg_sales_1.sql", + "path": "sql/models/features/merge_stg_sales_1.sql", + "original_file_path": "sql/models/features/merge_stg_sales_1.sql", "unique_id": "model.generated_2.merge_stg_sales_1", "fqn": [ "generated_2", @@ -2141,8 +2141,8 @@ "name": "spaced_stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/features/spaced_stg_sales_1.sql", - "original_file_path": "models/features/spaced_stg_sales_1.sql", + "path": "sql/models/features/spaced_stg_sales_1.sql", + "original_file_path": "sql/models/features/spaced_stg_sales_1.sql", "unique_id": "model.generated_2.spaced_stg_sales_1", "fqn": [ "generated_2", @@ -2216,8 +2216,8 @@ "name": "taxed_stg_sales_0", "resource_type": "model", "package_name": "generated_2", - "path": "models/features/taxed_stg_sales_0.sql", - "original_file_path": "models/features/taxed_stg_sales_0.sql", + "path": "sql/models/features/taxed_stg_sales_0.sql", + "original_file_path": "sql/models/features/taxed_stg_sales_0.sql", "unique_id": "model.generated_2.taxed_stg_sales_0", "fqn": [ "generated_2", @@ -2285,8 +2285,8 @@ "name": "bounded_stg_sales_0", "resource_type": "model", "package_name": "generated_2", - "path": "models/rendering/bounded_stg_sales_0.sql", - "original_file_path": "models/rendering/bounded_stg_sales_0.sql", + "path": "sql/models/rendering/bounded_stg_sales_0.sql", + "original_file_path": "sql/models/rendering/bounded_stg_sales_0.sql", "unique_id": "model.generated_2.bounded_stg_sales_0", "fqn": [ "generated_2", @@ -2356,8 +2356,8 @@ "name": "large_events", "resource_type": "model", "package_name": "generated_2", - "path": "models/rendering/large_events.sql", - "original_file_path": "models/rendering/large_events.sql", + "path": "sql/models/rendering/large_events.sql", + "original_file_path": "sql/models/rendering/large_events.sql", "unique_id": "model.generated_2.large_events", "fqn": [ "generated_2", @@ -2425,8 +2425,8 @@ "name": "stated_stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/rendering/stated_stg_sales_1.sql", - "original_file_path": "models/rendering/stated_stg_sales_1.sql", + "path": "sql/models/rendering/stated_stg_sales_1.sql", + "original_file_path": "sql/models/rendering/stated_stg_sales_1.sql", "unique_id": "model.generated_2.stated_stg_sales_1", "fqn": [ "generated_2", @@ -2522,8 +2522,8 @@ "name": "sales_summary_0", "resource_type": "model", "package_name": "generated_2", - "path": "models/sales/marts/sales_summary_0.sql", - "original_file_path": "models/sales/marts/sales_summary_0.sql", + "path": "sql/models/sales/marts/sales_summary_0.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_0.sql", "unique_id": "model.generated_2.sales_summary_0", "fqn": [ "generated_2", @@ -2602,7 +2602,7 @@ "type": "sql", "statement": "SELECT 'analytics.sales_summary_0' AS refreshed_relation, '東京 warehouse' AS refresh_label", "name": "record_refresh", - "relative_path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "relative_path": "sql/models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2642,8 +2642,8 @@ "name": "sales_summary_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/sales/marts/sales_summary_1.sql", - "original_file_path": "models/sales/marts/sales_summary_1.sql", + "path": "sql/models/sales/marts/sales_summary_1.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_1.sql", "unique_id": "model.generated_2.sales_summary_1", "fqn": [ "generated_2", @@ -2722,7 +2722,7 @@ "type": "sql", "statement": "SELECT 'analytics.sales_summary_1' AS refreshed_relation, 'Zürich – depot' AS refresh_label", "name": "record_refresh", - "relative_path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "relative_path": "sql/models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2764,8 +2764,8 @@ "name": "sales_summary_2", "resource_type": "model", "package_name": "generated_2", - "path": "models/sales/marts/sales_summary_2.sql", - "original_file_path": "models/sales/marts/sales_summary_2.sql", + "path": "sql/models/sales/marts/sales_summary_2.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_2.sql", "unique_id": "model.generated_2.sales_summary_2", "fqn": [ "generated_2", @@ -2834,7 +2834,7 @@ "type": "sql", "statement": "SELECT 'analytics.sales_summary_2' AS refreshed_relation, 'café ☕ counter' AS refresh_label", "name": "record_refresh", - "relative_path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "relative_path": "sql/models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2875,8 +2875,8 @@ "name": "stg_sales_0", "resource_type": "model", "package_name": "generated_2", - "path": "models/sales/staging/stg_sales_0.sql", - "original_file_path": "models/sales/staging/stg_sales_0.sql", + "path": "sql/models/sales/staging/stg_sales_0.sql", + "original_file_path": "sql/models/sales/staging/stg_sales_0.sql", "unique_id": "model.generated_2.stg_sales_0", "fqn": [ "generated_2", @@ -2949,8 +2949,8 @@ "name": "stg_sales_1", "resource_type": "model", "package_name": "generated_2", - "path": "models/sales/staging/stg_sales_1.sql", - "original_file_path": "models/sales/staging/stg_sales_1.sql", + "path": "sql/models/sales/staging/stg_sales_1.sql", + "original_file_path": "sql/models/sales/staging/stg_sales_1.sql", "unique_id": "model.generated_2.stg_sales_1", "fqn": [ "generated_2", @@ -3033,8 +3033,8 @@ "name": "stg_sales_2", "resource_type": "model", "package_name": "generated_2", - "path": "models/sales/staging/stg_sales_2.sql", - "original_file_path": "models/sales/staging/stg_sales_2.sql", + "path": "sql/models/sales/staging/stg_sales_2.sql", + "original_file_path": "sql/models/sales/staging/stg_sales_2.sql", "unique_id": "model.generated_2.stg_sales_2", "fqn": [ "generated_2", @@ -3117,8 +3117,8 @@ "name": "lookup_0", "resource_type": "seed", "package_name": "generated_2", - "path": "seeds/lookup_0.csv", - "original_file_path": "seeds/lookup_0.csv", + "path": "sql/seeds/lookup_0.csv", + "original_file_path": "sql/seeds/lookup_0.csv", "unique_id": "seed.generated_2.lookup_0", "fqn": [ "generated_2", @@ -3204,8 +3204,8 @@ "name": "open_events", "resource_type": "source", "package_name": "generated_2", - "path": "sources/open.yml", - "original_file_path": "sources/open.yml", + "path": "sql/sources/open.yml", + "original_file_path": "sql/sources/open.yml", "unique_id": "source.generated_2.open_events", "fqn": [ "generated_2", @@ -3235,8 +3235,8 @@ "name": "raw_events_0", "resource_type": "source", "package_name": "generated_2", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_2.raw_events_0", "fqn": [ "generated_2", @@ -3303,8 +3303,8 @@ "name": "round_amount", "resource_type": "macro", "package_name": "generated_2", - "path": "macros/python/rounding.py", - "original_file_path": "macros/python/rounding.py", + "path": "sql/macros/python/rounding.py", + "original_file_path": "sql/macros/python/rounding.py", "unique_id": "macro.generated_2.round_amount", "macro_sql": "def round_amount(expression: str, places: int = 2) -> str:\n \"\"\"Round an amount.\"\"\"\n return f\"ROUND({expression}, {places})\"\n", "depends_on": { @@ -3327,10 +3327,10 @@ "name": "taxed", "resource_type": "macro", "package_name": "generated_2", - "path": "macros/python/tax.py", - "original_file_path": "macros/python/tax.py", + "path": "sql/macros/python/tax.py", + "original_file_path": "sql/macros/python/tax.py", "unique_id": "macro.generated_2.taxed", - "macro_sql": "from macros.python.rounding import round_amount\n\n\ndef taxed(expression: str) -> str:\n \"\"\"Add tax to an amount, rounded.\"\"\"\n return round_amount(f\"{expression} * 1.2\")\n", + "macro_sql": "from sql.macros.python.rounding import round_amount\n\n\ndef taxed(expression: str) -> str:\n \"\"\"Add tax to an amount, rounded.\"\"\"\n return round_amount(f\"{expression} * 1.2\")\n", "depends_on": { "macros": [ "macro.generated_2.round_amount" @@ -3353,8 +3353,8 @@ "name": "adjust_0", "resource_type": "macro", "package_name": "generated_2", - "path": "models/sales/_sqlbuild/macros/python/adjust_0.py", - "original_file_path": "models/sales/_sqlbuild/macros/python/adjust_0.py", + "path": "sql/models/sales/_sqlbuild/macros/python/adjust_0.py", + "original_file_path": "sql/models/sales/_sqlbuild/macros/python/adjust_0.py", "unique_id": "macro.generated_2.adjust_0", "macro_sql": "import os\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Tag an amount with the deployment region.\"\"\"\n region = os.environ.get(\"SQB_DIFFERENTIAL_REGION\", \"east\")\n return f\"({expression} + LENGTH('{region}'))\"\n", "depends_on": { @@ -3363,7 +3363,7 @@ "description": "", "meta": { "sqlbuild_visibility": "inherited", - "sqlbuild_scope_path": "models/sales" + "sqlbuild_scope_path": "sql/models/sales" }, "docs": { "show": true, @@ -3377,8 +3377,8 @@ "name": "adjust_1", "resource_type": "macro", "package_name": "generated_2", - "path": "models/sales/_sqlbuild/macros/python/adjust_1.py", - "original_file_path": "models/sales/_sqlbuild/macros/python/adjust_1.py", + "path": "sql/models/sales/_sqlbuild/macros/python/adjust_1.py", + "original_file_path": "sql/models/sales/_sqlbuild/macros/python/adjust_1.py", "unique_id": "macro.generated_2.adjust_1", "macro_sql": "def adjust_1_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_1_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -3389,7 +3389,7 @@ "description": "", "meta": { "sqlbuild_visibility": "inherited", - "sqlbuild_scope_path": "models/sales" + "sqlbuild_scope_path": "sql/models/sales" }, "docs": { "show": true, @@ -3403,8 +3403,8 @@ "name": "adjust_1_round", "resource_type": "macro", "package_name": "generated_2", - "path": "models/sales/_sqlbuild/macros/python/adjust_1.py", - "original_file_path": "models/sales/_sqlbuild/macros/python/adjust_1.py", + "path": "sql/models/sales/_sqlbuild/macros/python/adjust_1.py", + "original_file_path": "sql/models/sales/_sqlbuild/macros/python/adjust_1.py", "unique_id": "macro.generated_2.adjust_1_round", "macro_sql": "def adjust_1_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_1_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -3413,7 +3413,7 @@ "description": "", "meta": { "sqlbuild_visibility": "inherited", - "sqlbuild_scope_path": "models/sales" + "sqlbuild_scope_path": "sql/models/sales" }, "docs": { "show": true, @@ -3427,8 +3427,8 @@ "name": "record_refresh", "resource_type": "macro", "package_name": "generated_2__sqlbuild_hooks", - "path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "original_file_path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "path": "sql/models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "original_file_path": "sql/models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "unique_id": "macro.generated_2__sqlbuild_hooks.record_refresh", "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "depends_on": { diff --git a/tests/goldens/compiler/seed/3.json b/tests/goldens/compiler/seed/3.json index bd169a87fa..6f08be7c96 100644 --- a/tests/goldens/compiler/seed/3.json +++ b/tests/goldens/compiler/seed/3.json @@ -17,26 +17,26 @@ } ], "compiled": { - "audits/generic/audited_event_totals/amount_floor.sql": [ + "sql/audits/generic/audited_event_totals/amount_floor.sql": [ "SELECT *", "FROM __ref(\"audited_event_totals\")", "WHERE amount < -23", "" ], - "audits/generic/audited_events/accepted_values__id.sql": [ + "sql/audits/generic/audited_events/accepted_values__id.sql": [ "SELECT id", "FROM __source(\"audited_events\")", "WHERE id IS NOT NULL", " AND id NOT IN (1, 2)", "" ], - "audits/generic/audited_events/not_null__id.sql": [ + "sql/audits/generic/audited_events/not_null__id.sql": [ "SELECT id", "FROM __source(\"audited_events\")", "WHERE id IS NULL", "" ], - "audits/generic/audited_events/unique__id.sql": [ + "sql/audits/generic/audited_events/unique__id.sql": [ "SELECT id, COUNT(*) AS duplicate_count", "FROM __source(\"audited_events\")", "WHERE id IS NOT NULL", @@ -44,32 +44,32 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/billing_summary_1/not_null__id.sql": [ + "sql/audits/generic/billing_summary_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"billing_summary_1\")", "WHERE id IS NULL", "" ], - "audits/generic/channel_codes/not_null__id.sql": [ + "sql/audits/generic/channel_codes/not_null__id.sql": [ "SELECT id", "FROM __seed(\"channel_codes\")", "WHERE id IS NULL", "" ], - "audits/generic/checked_stg_billing_1/accepted_values__status.sql": [ + "sql/audits/generic/checked_stg_billing_1/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"checked_stg_billing_1\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/checked_stg_billing_1/expression_is_true.sql": [ + "sql/audits/generic/checked_stg_billing_1/expression_is_true.sql": [ "SELECT *", "FROM __ref(\"checked_stg_billing_1\")", "WHERE NOT (amount >= -1000)", "" ], - "audits/generic/checked_stg_billing_1/relationships__id.sql": [ + "sql/audits/generic/checked_stg_billing_1/relationships__id.sql": [ "SELECT id", "FROM __ref(\"checked_stg_billing_1\")", "WHERE id IS NOT NULL", @@ -80,33 +80,33 @@ " )", "" ], - "audits/generic/configured_events/accepted_values__id.sql": [ + "sql/audits/generic/configured_events/accepted_values__id.sql": [ "SELECT id", "FROM __source(\"configured_events\")", "WHERE id IS NOT NULL", " AND id NOT IN ('1')", "" ], - "audits/generic/configured_stg_billing_1/accepted_values__status.sql": [ + "sql/audits/generic/configured_stg_billing_1/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"configured_stg_billing_1\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'shipped')", "" ], - "audits/generic/configured_stg_billing_1/configured_amount_floor.sql": [ + "sql/audits/generic/configured_stg_billing_1/configured_amount_floor.sql": [ "SELECT *", "FROM __ref(\"configured_stg_billing_1\")", "WHERE amount < -25", "" ], - "audits/generic/configured_stg_billing_1/configured_id_present__id.sql": [ + "sql/audits/generic/configured_stg_billing_1/configured_id_present__id.sql": [ "SELECT id", "FROM __ref(\"configured_stg_billing_1\")", "WHERE id IS NULL", "" ], - "audits/generic/configured_stg_billing_1/unique__id.sql": [ + "sql/audits/generic/configured_stg_billing_1/unique__id.sql": [ "SELECT id, COUNT(*) AS duplicate_count", "FROM __ref(\"configured_stg_billing_1\")", "WHERE id IS NOT NULL", @@ -114,52 +114,52 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/stg_billing_0/not_null__id.sql": [ + "sql/audits/generic/stg_billing_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_billing_0\")", "WHERE id IS NULL", "" ], - "functions/sql/configured_label.sql": [ + "sql/functions/sql/configured_label.sql": [ "CREATE OR REPLACE MACRO main.configured_label(raw_status) AS (", "UPPER(raw_status)", ")", "" ], - "functions/sql/scaled_amount.sql": [ + "sql/functions/sql/scaled_amount.sql": [ "CREATE OR REPLACE MACRO main.scaled_amount(p_amount, p_factor) AS (", "p_amount * p_factor", ")", "" ], - "functions/sql/table_fn__amount_bands.sql": [ + "sql/functions/sql/table_fn__amount_bands.sql": [ "CREATE OR REPLACE MACRO main.table_fn__amount_bands(p_floor) AS TABLE", "SELECT CAST(id AS INTEGER) AS id,", " CASE WHEN amount > p_floor THEN 'high' ELSE 'low' END AS band", "FROM __ref(\"stg_billing_1\")", "" ], - "models/analysis/banded_amounts.sql": [ + "sql/models/analysis/banded_amounts.sql": [ "SELECT bands.id, bands.band", "FROM __table_fn(\"table_fn__amount_bands\")(8.5) AS bands", "" ], - "models/analysis/checked_stg_billing_1.sql": [ + "sql/models/analysis/checked_stg_billing_1.sql": [ "SELECT id, amount, status", "FROM __ref(\"stg_billing_1\")", "" ], - "models/analysis/regional_stg_billing_1.sql": [ + "sql/models/analysis/regional_stg_billing_1.sql": [ "SELECT id, amount, 'east' AS region", "FROM __ref(\"stg_billing_1\")", "" ], - "models/analysis/scaled_stg_billing_1.sql": [ + "sql/models/analysis/scaled_stg_billing_1.sql": [ "SELECT id, __udf(\"scaled_amount\")(amount, 8) AS scaled_amount", "FROM __ref(\"stg_billing_1\")", "" ], - "models/billing/marts/billing_summary_0.sql": [ + "sql/models/billing/marts/billing_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -171,7 +171,7 @@ "LEFT JOIN __ref(\"stg_billing_0\") j1 ON t.id = j1.id", "" ], - "models/billing/marts/billing_summary_1.sql": [ + "sql/models/billing/marts/billing_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -181,7 +181,7 @@ "FROM __ref(\"stg_billing_1\") t", "" ], - "models/billing/staging/stg_billing_0.sql": [ + "sql/models/billing/staging/stg_billing_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -192,7 +192,7 @@ "FROM __source(\"raw_events_2\") t", "" ], - "models/billing/staging/stg_billing_1.sql": [ + "sql/models/billing/staging/stg_billing_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -205,37 +205,37 @@ "WHERE t.status <> 'expédié'", "" ], - "models/features/batched_watermark_stg_billing_1.sql": [ + "sql/models/features/batched_watermark_stg_billing_1.sql": [ "SELECT CAST(created_at AS DATE) AS created_at, SUM(amount) AS amount", "FROM __ref(\"stg_billing_1\")", "GROUP BY CAST(created_at AS DATE)", "" ], - "models/features/hooked_stg_billing_1.sql": [ + "sql/models/features/hooked_stg_billing_1.sql": [ "SELECT id, amount", "FROM __ref(\"stg_billing_1\")", "" ], - "models/features/kept_stg_billing_1.sql": [ + "sql/models/features/kept_stg_billing_1.sql": [ "SELECT id, status, amount * 0.5 AS weighted", "FROM __ref(\"stg_billing_1\")", "WHERE status IN ('取消', 'expédié')", " AND amount * 1.0 IN (0.5, 1.25, 2500.75) OR id > 0", "" ], - "models/rendering/audited_event_totals.sql": [ + "sql/models/rendering/audited_event_totals.sql": [ "SELECT c.label, SUM(e.amount) AS amount", "FROM __source(\"audited_events\") e", "JOIN __seed(\"channel_codes\") c ON e.id = c.id", "GROUP BY c.label", "" ], - "models/rendering/configured_stg_billing_1.sql": [ + "sql/models/rendering/configured_stg_billing_1.sql": [ "SELECT id, amount, status", "FROM __ref(\"stg_billing_1\")", "" ], - "models/rendering/interpolated_stg_billing_0.sql": [ + "sql/models/rendering/interpolated_stg_billing_0.sql": [ "SELECT id,", " '東京 warehouse' AS site,", " $$--東京 warehouse /* $$ AS site_note,", @@ -244,12 +244,12 @@ "FROM __ref(\"stg_billing_0\")", "" ], - "models/rendering/legacy_event_ids.sql": [ + "sql/models/rendering/legacy_event_ids.sql": [ "SELECT id", "FROM __ref(\"stg_billing_1\") AS legacy", "" ], - "models/rendering/policy_stg_billing_1.sql": [ + "sql/models/rendering/policy_stg_billing_1.sql": [ "SELECT id, amount, ('web' || '/dev/generated_duckdb/south' || '@web-orders') AS channel,", " 4 AS minimum_amount,", " 'store' AS fallback_channel", @@ -257,7 +257,7 @@ "WHERE amount >= 4", "" ], - "models/rendering/windowed_stg_billing_0.sql": [ + "sql/models/rendering/windowed_stg_billing_0.sql": [ "SELECT id, created_at", "FROM __ref(\"stg_billing_0\")", "WHERE CAST(created_at AS DATE) >= CAST(@@@window_start AS DATE)", @@ -306,8 +306,8 @@ "name": "banded_amounts", "resource_type": "model", "package_name": "generated_3", - "path": "models/analysis/banded_amounts.sql", - "original_file_path": "models/analysis/banded_amounts.sql", + "path": "sql/models/analysis/banded_amounts.sql", + "original_file_path": "sql/models/analysis/banded_amounts.sql", "unique_id": "model.generated_3.banded_amounts", "fqn": [ "generated_3", @@ -375,8 +375,8 @@ "name": "checked_stg_billing_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/analysis/checked_stg_billing_1.sql", - "original_file_path": "models/analysis/checked_stg_billing_1.sql", + "path": "sql/models/analysis/checked_stg_billing_1.sql", + "original_file_path": "sql/models/analysis/checked_stg_billing_1.sql", "unique_id": "model.generated_3.checked_stg_billing_1", "fqn": [ "generated_3", @@ -465,8 +465,8 @@ "name": "regional_stg_billing_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/analysis/regional_stg_billing_1.sql", - "original_file_path": "models/analysis/regional_stg_billing_1.sql", + "path": "sql/models/analysis/regional_stg_billing_1.sql", + "original_file_path": "sql/models/analysis/regional_stg_billing_1.sql", "unique_id": "model.generated_3.regional_stg_billing_1", "fqn": [ "generated_3", @@ -534,8 +534,8 @@ "name": "scaled_stg_billing_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/analysis/scaled_stg_billing_1.sql", - "original_file_path": "models/analysis/scaled_stg_billing_1.sql", + "path": "sql/models/analysis/scaled_stg_billing_1.sql", + "original_file_path": "sql/models/analysis/scaled_stg_billing_1.sql", "unique_id": "model.generated_3.scaled_stg_billing_1", "fqn": [ "generated_3", @@ -604,8 +604,8 @@ "name": "billing_summary_0", "resource_type": "model", "package_name": "generated_3", - "path": "models/billing/marts/billing_summary_0.sql", - "original_file_path": "models/billing/marts/billing_summary_0.sql", + "path": "sql/models/billing/marts/billing_summary_0.sql", + "original_file_path": "sql/models/billing/marts/billing_summary_0.sql", "unique_id": "model.generated_3.billing_summary_0", "fqn": [ "generated_3", @@ -675,8 +675,8 @@ "name": "billing_summary_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/billing/marts/billing_summary_1.sql", - "original_file_path": "models/billing/marts/billing_summary_1.sql", + "path": "sql/models/billing/marts/billing_summary_1.sql", + "original_file_path": "sql/models/billing/marts/billing_summary_1.sql", "unique_id": "model.generated_3.billing_summary_1", "fqn": [ "generated_3", @@ -749,7 +749,7 @@ "type": "sql", "statement": "SELECT 'main.billing_summary_1' AS refreshed_relation, 'Zürich – depot' AS refresh_label", "name": "record_refresh", - "relative_path": "models/billing/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "relative_path": "sql/models/billing/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -789,8 +789,8 @@ "name": "stg_billing_0", "resource_type": "model", "package_name": "generated_3", - "path": "models/billing/staging/stg_billing_0.sql", - "original_file_path": "models/billing/staging/stg_billing_0.sql", + "path": "sql/models/billing/staging/stg_billing_0.sql", + "original_file_path": "sql/models/billing/staging/stg_billing_0.sql", "unique_id": "model.generated_3.stg_billing_0", "fqn": [ "generated_3", @@ -873,8 +873,8 @@ "name": "stg_billing_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/billing/staging/stg_billing_1.sql", - "original_file_path": "models/billing/staging/stg_billing_1.sql", + "path": "sql/models/billing/staging/stg_billing_1.sql", + "original_file_path": "sql/models/billing/staging/stg_billing_1.sql", "unique_id": "model.generated_3.stg_billing_1", "fqn": [ "generated_3", @@ -947,8 +947,8 @@ "name": "batched_watermark_stg_billing_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/features/batched_watermark_stg_billing_1.sql", - "original_file_path": "models/features/batched_watermark_stg_billing_1.sql", + "path": "sql/models/features/batched_watermark_stg_billing_1.sql", + "original_file_path": "sql/models/features/batched_watermark_stg_billing_1.sql", "unique_id": "model.generated_3.batched_watermark_stg_billing_1", "fqn": [ "generated_3", @@ -1016,8 +1016,8 @@ "name": "hooked_stg_billing_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/features/hooked_stg_billing_1.sql", - "original_file_path": "models/features/hooked_stg_billing_1.sql", + "path": "sql/models/features/hooked_stg_billing_1.sql", + "original_file_path": "sql/models/features/hooked_stg_billing_1.sql", "unique_id": "model.generated_3.hooked_stg_billing_1", "fqn": [ "generated_3", @@ -1070,7 +1070,7 @@ "kwargs": { "channel": "東京 warehouse" }, - "relative_path": "models/features/_sqlbuild/_hooks/python/notify.py", + "relative_path": "sql/models/features/_sqlbuild/_hooks/python/notify.py", "definition_hash": "4669f6863eaccfebdb6aa5286a58eb944d8b0142ea2bc8e6678cce4efb35bf7e", "version_hash": "80b0b3a25244f0def68efcbecd29182bfa91d76b9272c4d2147d08ae88260fa2" } @@ -1102,8 +1102,8 @@ "name": "kept_stg_billing_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/features/kept_stg_billing_1.sql", - "original_file_path": "models/features/kept_stg_billing_1.sql", + "path": "sql/models/features/kept_stg_billing_1.sql", + "original_file_path": "sql/models/features/kept_stg_billing_1.sql", "unique_id": "model.generated_3.kept_stg_billing_1", "fqn": [ "generated_3", @@ -1171,8 +1171,8 @@ "name": "audited_event_totals", "resource_type": "model", "package_name": "generated_3", - "path": "models/rendering/audited_event_totals.sql", - "original_file_path": "models/rendering/audited_event_totals.sql", + "path": "sql/models/rendering/audited_event_totals.sql", + "original_file_path": "sql/models/rendering/audited_event_totals.sql", "unique_id": "model.generated_3.audited_event_totals", "fqn": [ "generated_3", @@ -1241,8 +1241,8 @@ "name": "configured_stg_billing_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/rendering/configured_stg_billing_1.sql", - "original_file_path": "models/rendering/configured_stg_billing_1.sql", + "path": "sql/models/rendering/configured_stg_billing_1.sql", + "original_file_path": "sql/models/rendering/configured_stg_billing_1.sql", "unique_id": "model.generated_3.configured_stg_billing_1", "fqn": [ "generated_3", @@ -1342,8 +1342,8 @@ "name": "interpolated_stg_billing_0", "resource_type": "model", "package_name": "generated_3", - "path": "models/rendering/interpolated_stg_billing_0.sql", - "original_file_path": "models/rendering/interpolated_stg_billing_0.sql", + "path": "sql/models/rendering/interpolated_stg_billing_0.sql", + "original_file_path": "sql/models/rendering/interpolated_stg_billing_0.sql", "unique_id": "model.generated_3.interpolated_stg_billing_0", "fqn": [ "generated_3", @@ -1410,7 +1410,7 @@ "type": "sql", "statement": "SELECT 'main.interpolated_stg_billing_0' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", "name": "announce_refresh", - "relative_path": "models/rendering/_sqlbuild/_hooks/sql/announce_refresh.sql", + "relative_path": "sql/models/rendering/_sqlbuild/_hooks/sql/announce_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -1454,8 +1454,8 @@ "name": "legacy_event_ids", "resource_type": "model", "package_name": "generated_3", - "path": "models/rendering/legacy_event_ids.sql", - "original_file_path": "models/rendering/legacy_event_ids.sql", + "path": "sql/models/rendering/legacy_event_ids.sql", + "original_file_path": "sql/models/rendering/legacy_event_ids.sql", "unique_id": "model.generated_3.legacy_event_ids", "fqn": [ "generated_3", @@ -1523,8 +1523,8 @@ "name": "policy_stg_billing_1", "resource_type": "model", "package_name": "generated_3", - "path": "models/rendering/policy_stg_billing_1.sql", - "original_file_path": "models/rendering/policy_stg_billing_1.sql", + "path": "sql/models/rendering/policy_stg_billing_1.sql", + "original_file_path": "sql/models/rendering/policy_stg_billing_1.sql", "unique_id": "model.generated_3.policy_stg_billing_1", "fqn": [ "generated_3", @@ -1592,8 +1592,8 @@ "name": "windowed_stg_billing_0", "resource_type": "model", "package_name": "generated_3", - "path": "models/rendering/windowed_stg_billing_0.sql", - "original_file_path": "models/rendering/windowed_stg_billing_0.sql", + "path": "sql/models/rendering/windowed_stg_billing_0.sql", + "original_file_path": "sql/models/rendering/windowed_stg_billing_0.sql", "unique_id": "model.generated_3.windowed_stg_billing_0", "fqn": [ "generated_3", @@ -1661,8 +1661,8 @@ "name": "channel_codes", "resource_type": "seed", "package_name": "generated_3", - "path": "seeds/channel_codes.csv", - "original_file_path": "seeds/channel_codes.csv", + "path": "sql/seeds/channel_codes.csv", + "original_file_path": "sql/seeds/channel_codes.csv", "unique_id": "seed.generated_3.channel_codes", "fqn": [ "generated_3", @@ -1748,8 +1748,8 @@ "name": "audited_events", "resource_type": "source", "package_name": "generated_3", - "path": "sources/audited.yml", - "original_file_path": "sources/audited.yml", + "path": "sql/sources/audited.yml", + "original_file_path": "sql/sources/audited.yml", "unique_id": "source.generated_3.audited_events", "fqn": [ "generated_3", @@ -1798,8 +1798,8 @@ "name": "configured_events", "resource_type": "source", "package_name": "generated_3", - "path": "sources/configured.yml", - "original_file_path": "sources/configured.yml", + "path": "sql/sources/configured.yml", + "original_file_path": "sql/sources/configured.yml", "unique_id": "source.generated_3.configured_events", "fqn": [ "generated_3", @@ -1850,8 +1850,8 @@ "name": "raw_events_0", "resource_type": "source", "package_name": "generated_3", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_3.raw_events_0", "fqn": [ "generated_3", @@ -1918,8 +1918,8 @@ "name": "raw_events_1", "resource_type": "source", "package_name": "generated_3", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_3.raw_events_1", "fqn": [ "generated_3", @@ -1986,8 +1986,8 @@ "name": "raw_events_2", "resource_type": "source", "package_name": "generated_3", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_3.raw_events_2", "fqn": [ "generated_3", @@ -2054,8 +2054,8 @@ "name": "analysis_region", "resource_type": "macro", "package_name": "generated_3", - "path": "models/analysis/_sqlbuild/_macros/python/regions.py", - "original_file_path": "models/analysis/_sqlbuild/_macros/python/regions.py", + "path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", + "original_file_path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", "unique_id": "macro.generated_3.analysis_region", "macro_sql": "def analysis_region() -> str:\n \"\"\"Return the region rows are assigned to.\"\"\"\n return \"'east'\"\n", "depends_on": { @@ -2064,7 +2064,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/analysis" + "sqlbuild_scope_path": "sql/models/analysis" }, "docs": { "show": true, @@ -2078,8 +2078,8 @@ "name": "adjust_0", "resource_type": "macro", "package_name": "generated_3", - "path": "models/billing/marts/_sqlbuild/_macros/python/adjust_0.py", - "original_file_path": "models/billing/marts/_sqlbuild/_macros/python/adjust_0.py", + "path": "sql/models/billing/marts/_sqlbuild/_macros/python/adjust_0.py", + "original_file_path": "sql/models/billing/marts/_sqlbuild/_macros/python/adjust_0.py", "unique_id": "macro.generated_3.adjust_0", "macro_sql": "def adjust_0(expression: str) -> str:\n \"\"\"Offset an amount.\"\"\"\n return f\"({expression} + 0 + 1)\"\n", "depends_on": { @@ -2088,7 +2088,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/billing/marts" + "sqlbuild_scope_path": "sql/models/billing/marts" }, "docs": { "show": true, @@ -2102,8 +2102,8 @@ "name": "adjust_1", "resource_type": "macro", "package_name": "generated_3", - "path": "models/billing/staging/_sqlbuild/_macros/python/adjust_1.py", - "original_file_path": "models/billing/staging/_sqlbuild/_macros/python/adjust_1.py", + "path": "sql/models/billing/staging/_sqlbuild/_macros/python/adjust_1.py", + "original_file_path": "sql/models/billing/staging/_sqlbuild/_macros/python/adjust_1.py", "unique_id": "macro.generated_3.adjust_1", "macro_sql": "def adjust_1(ctx, expression: str) -> str:\n \"\"\"Scale an amount by the configured discount.\"\"\"\n rate = ctx.vars[\"discount_rate\"]\n return f\"({expression} * (1 - {rate}))\"\n", "depends_on": { @@ -2112,7 +2112,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/billing/staging" + "sqlbuild_scope_path": "sql/models/billing/staging" }, "docs": { "show": true, @@ -2126,8 +2126,8 @@ "name": "legacy_events", "resource_type": "macro", "package_name": "generated_3", - "path": "models/rendering/_sqlbuild/_macros/python/legacy.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/legacy.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/legacy.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/legacy.py", "unique_id": "macro.generated_3.legacy_events", "macro_sql": "def legacy_events() -> str:\n \"\"\"Return a staged relation the way a migrated project wrote it.\"\"\"\n return '__ref(\"stg_billing_1\")'\n", "depends_on": { @@ -2136,7 +2136,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2150,8 +2150,8 @@ "name": "refresh_note", "resource_type": "macro", "package_name": "generated_3", - "path": "models/rendering/_sqlbuild/_macros/python/notes.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/notes.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/notes.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/notes.py", "unique_id": "macro.generated_3.refresh_note", "macro_sql": "def refresh_note(relation: str) -> str:\n \"\"\"Describe one refreshed relation.\"\"\"\n return f\"'refreshed ' || '{relation}'\"\n", "depends_on": { @@ -2160,7 +2160,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2174,8 +2174,8 @@ "name": "channel_label", "resource_type": "macro", "package_name": "generated_3", - "path": "models/rendering/_sqlbuild/_macros/python/policy.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/policy.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", "unique_id": "macro.generated_3.channel_label", "macro_sql": "import os\n\n\ndef minimum_amount_filter(ctx, column: str) -> str:\n \"\"\"Keep rows at or above the configured minimum amount.\"\"\"\n if ctx.constants[\"minimum_render_amount\"] is None:\n return \"TRUE\"\n return f\"{column} >= {ctx.render_constant('minimum_render_amount')}\"\n\n\ndef channel_label(ctx) -> str:\n \"\"\"Label rows with the web channel, target and adapter.\"\"\"\n channel = ctx.render_enum_member(enum_name=\"render_channel\", member_name=\"WEB\")\n region = ctx.vars[\"region\"]\n return f\"{channel} || '/{ctx.target_name}/{ctx.adapter_name}/{region}'\"\n\n\ndef with_deployment(expression: str) -> str:\n \"\"\"Suffix an expression with the deployment channel from the environment.\"\"\"\n channel = os.environ.get(\"SQB_DIFFERENTIAL_CHANNEL\", \"none\")\n return f\"({expression} || '@{channel}')\"\n", "depends_on": { @@ -2184,7 +2184,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2198,8 +2198,8 @@ "name": "minimum_amount_filter", "resource_type": "macro", "package_name": "generated_3", - "path": "models/rendering/_sqlbuild/_macros/python/policy.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/policy.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", "unique_id": "macro.generated_3.minimum_amount_filter", "macro_sql": "import os\n\n\ndef minimum_amount_filter(ctx, column: str) -> str:\n \"\"\"Keep rows at or above the configured minimum amount.\"\"\"\n if ctx.constants[\"minimum_render_amount\"] is None:\n return \"TRUE\"\n return f\"{column} >= {ctx.render_constant('minimum_render_amount')}\"\n\n\ndef channel_label(ctx) -> str:\n \"\"\"Label rows with the web channel, target and adapter.\"\"\"\n channel = ctx.render_enum_member(enum_name=\"render_channel\", member_name=\"WEB\")\n region = ctx.vars[\"region\"]\n return f\"{channel} || '/{ctx.target_name}/{ctx.adapter_name}/{region}'\"\n\n\ndef with_deployment(expression: str) -> str:\n \"\"\"Suffix an expression with the deployment channel from the environment.\"\"\"\n channel = os.environ.get(\"SQB_DIFFERENTIAL_CHANNEL\", \"none\")\n return f\"({expression} || '@{channel}')\"\n", "depends_on": { @@ -2208,7 +2208,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2222,8 +2222,8 @@ "name": "with_deployment", "resource_type": "macro", "package_name": "generated_3", - "path": "models/rendering/_sqlbuild/_macros/python/policy.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/policy.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", "unique_id": "macro.generated_3.with_deployment", "macro_sql": "import os\n\n\ndef minimum_amount_filter(ctx, column: str) -> str:\n \"\"\"Keep rows at or above the configured minimum amount.\"\"\"\n if ctx.constants[\"minimum_render_amount\"] is None:\n return \"TRUE\"\n return f\"{column} >= {ctx.render_constant('minimum_render_amount')}\"\n\n\ndef channel_label(ctx) -> str:\n \"\"\"Label rows with the web channel, target and adapter.\"\"\"\n channel = ctx.render_enum_member(enum_name=\"render_channel\", member_name=\"WEB\")\n region = ctx.vars[\"region\"]\n return f\"{channel} || '/{ctx.target_name}/{ctx.adapter_name}/{region}'\"\n\n\ndef with_deployment(expression: str) -> str:\n \"\"\"Suffix an expression with the deployment channel from the environment.\"\"\"\n channel = os.environ.get(\"SQB_DIFFERENTIAL_CHANNEL\", \"none\")\n return f\"({expression} || '@{channel}')\"\n", "depends_on": { @@ -2232,7 +2232,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2270,8 +2270,8 @@ "name": "record_refresh", "resource_type": "macro", "package_name": "generated_3__sqlbuild_hooks", - "path": "models/billing/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "original_file_path": "models/billing/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "path": "sql/models/billing/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "original_file_path": "sql/models/billing/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "unique_id": "macro.generated_3__sqlbuild_hooks.record_refresh", "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "depends_on": { @@ -2294,8 +2294,8 @@ "name": "announce_refresh", "resource_type": "macro", "package_name": "generated_3__sqlbuild_hooks", - "path": "models/rendering/_sqlbuild/_hooks/sql/announce_refresh.sql", - "original_file_path": "models/rendering/_sqlbuild/_hooks/sql/announce_refresh.sql", + "path": "sql/models/rendering/_sqlbuild/_hooks/sql/announce_refresh.sql", + "original_file_path": "sql/models/rendering/_sqlbuild/_hooks/sql/announce_refresh.sql", "unique_id": "macro.generated_3__sqlbuild_hooks.announce_refresh", "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "depends_on": { diff --git a/tests/goldens/compiler/seed/4.json b/tests/goldens/compiler/seed/4.json index e9634c1d1c..be904b7b7e 100644 --- a/tests/goldens/compiler/seed/4.json +++ b/tests/goldens/compiler/seed/4.json @@ -17,33 +17,33 @@ } ], "compiled": { - "audits/generic/configured_events/accepted_values__id.sql": [ + "sql/audits/generic/configured_events/accepted_values__id.sql": [ "SELECT id", "FROM __source(\"configured_events\")", "WHERE id IS NOT NULL", " AND id NOT IN ('1')", "" ], - "audits/generic/configured_stg_support_0/accepted_values__status.sql": [ + "sql/audits/generic/configured_stg_support_0/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"configured_stg_support_0\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'shipped')", "" ], - "audits/generic/configured_stg_support_0/configured_amount_floor.sql": [ + "sql/audits/generic/configured_stg_support_0/configured_amount_floor.sql": [ "SELECT *", "FROM __ref(\"configured_stg_support_0\")", "WHERE amount < -30", "" ], - "audits/generic/configured_stg_support_0/configured_id_present__id.sql": [ + "sql/audits/generic/configured_stg_support_0/configured_id_present__id.sql": [ "SELECT id", "FROM __ref(\"configured_stg_support_0\")", "WHERE id IS NULL", "" ], - "audits/generic/configured_stg_support_0/unique__id.sql": [ + "sql/audits/generic/configured_stg_support_0/unique__id.sql": [ "SELECT id, COUNT(*) AS duplicate_count", "FROM __ref(\"configured_stg_support_0\")", "WHERE id IS NOT NULL", @@ -51,44 +51,44 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/guarded_stg_support_0/amount_at_least__amount.sql": [ + "sql/audits/generic/guarded_stg_support_0/amount_at_least__amount.sql": [ "SELECT *", "FROM __ref(\"guarded_stg_support_0\")", "WHERE amount < 0", "" ], - "audits/generic/shaped_stg_support_0/not_null__id.sql": [ + "sql/audits/generic/shaped_stg_support_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"shaped_stg_support_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_support_0/not_null__id.sql": [ + "sql/audits/generic/stg_support_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_support_0\")", "WHERE id IS NULL", "" ], - "audits/generic/support_summary_0/not_null__id.sql": [ + "sql/audits/generic/support_summary_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"support_summary_0\")", "WHERE id IS NULL", "" ], - "audits/singular/support_summary_1_matches.sql": [ + "sql/audits/singular/support_summary_1_matches.sql": [ "SELECT a.id", "FROM __ref(\"support_summary_1\") a", "LEFT JOIN __ref(\"support_summary_0\") b ON a.id = b.id", "WHERE b.id IS NULL", "" ], - "functions/sql/configured_label.sql": [ + "sql/functions/sql/configured_label.sql": [ "CREATE OR REPLACE MACRO ci_checks.configured_label(raw_status) AS (", "UPPER(raw_status)", ")", "" ], - "models/analysis/combined_stg_support_0.sql": [ + "sql/models/analysis/combined_stg_support_0.sql": [ "WITH recent AS (", " SELECT id, created_at FROM __ref(\"stg_support_0\") WHERE amount > 0", "),", @@ -100,22 +100,22 @@ "SELECT id, created_at FROM older", "" ], - "models/analysis/every_open_event.sql": [ + "sql/models/analysis/every_open_event.sql": [ "SELECT *", "FROM __source(\"open_events\")", "" ], - "models/analysis/every_raw_events_0.sql": [ + "sql/models/analysis/every_raw_events_0.sql": [ "SELECT *", "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/every_stg_support_0.sql": [ + "sql/models/analysis/every_stg_support_0.sql": [ "SELECT *", "FROM __ref(\"stg_support_0\")", "" ], - "models/analysis/passed_stg_support_0.sql": [ + "sql/models/analysis/passed_stg_support_0.sql": [ "WITH passthrough AS (", " SELECT id, created_at FROM __ref(\"stg_support_0\")", ")", @@ -123,89 +123,89 @@ "FROM passthrough", "" ], - "models/analysis/pivot_input_stg_support_0.sql": [ + "sql/models/analysis/pivot_input_stg_support_0.sql": [ "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR) AS status, amount", "FROM __ref(\"stg_support_0\")", "" ], - "models/analysis/pivoted_stg_support_0.sql": [ + "sql/models/analysis/pivoted_stg_support_0.sql": [ "PIVOT __ref(\"pivot_input_stg_support_0\")", "ON status", "USING MAX(amount)", "GROUP BY id", "" ], - "models/analysis/quoted_stg_support_0.sql": [ + "sql/models/analysis/quoted_stg_support_0.sql": [ "SELECT \"ID\" AS \"OrderKey\", \"Amount\", \"Status\" AS \"Status\"", "FROM __ref(\"stg_support_0\")", "" ], - "models/analysis/regional_stg_support_0.sql": [ + "sql/models/analysis/regional_stg_support_0.sql": [ "SELECT id, amount, 'north' AS region", "FROM __ref(\"stg_support_0\")", "" ], - "models/analysis/typed_stg_support_0.sql": [ + "sql/models/analysis/typed_stg_support_0.sql": [ "SELECT id, amount * 2 AS doubled_amount, CAST(status AS VARCHAR) AS status_text,", " created_at, NULL AS missing_note", "FROM __ref(\"stg_support_0\")", "" ], - "models/analysis/unanalysed_stg_support_0.sql": [ + "sql/models/analysis/unanalysed_stg_support_0.sql": [ "SELECT a.id, a.amount", "FROM __ref(\"stg_support_0\") AS a", "JOIN __ref(\"stg_support_0\") AS b NEAREST 1 BY DISTANCE abs(a.amount - b.amount)", "" ], - "models/features/append_stg_support_0.sql": [ + "sql/models/features/append_stg_support_0.sql": [ "SELECT id, amount, status, created_at", "FROM __ref(\"stg_support_0\")", "" ], - "models/features/batched_rolling_window_stg_support_0.sql": [ + "sql/models/features/batched_rolling_window_stg_support_0.sql": [ "SELECT CAST(created_at AS DATE) AS created_at, SUM(amount) AS amount", "FROM __ref(\"stg_support_0\")", "GROUP BY CAST(created_at AS DATE)", "" ], - "models/features/guarded_stg_support_0.sql": [ + "sql/models/features/guarded_stg_support_0.sql": [ "SELECT id, amount", "FROM __ref(\"stg_support_0\")", "" ], - "models/features/product_labels.sql": [ + "sql/models/features/product_labels.sql": [ "SELECT id, label", "FROM __source(\"loaded_products\")", "" ], - "models/features/shaped_stg_support_0.sql": [ + "sql/models/features/shaped_stg_support_0.sql": [ "SELECT CAST(id AS INTEGER) AS id, status", "FROM __ref(\"stg_support_0\")", "" ], - "models/features/timestamp_history_stg_support_0.sql": [ + "sql/models/features/timestamp_history_stg_support_0.sql": [ "SELECT id, status, created_at", "FROM __ref(\"stg_support_0\")", "" ], - "models/rendering/bounded_stg_support_0.sql": [ + "sql/models/rendering/bounded_stg_support_0.sql": [ "SELECT id, amount, created_at", "FROM __ref(\"stg_support_0\")", "WHERE created_at >= __cursor_start()", " AND created_at < __cursor_end()", "" ], - "models/rendering/configured_stg_support_0.sql": [ + "sql/models/rendering/configured_stg_support_0.sql": [ "SELECT id, amount, status", "FROM __ref(\"stg_support_0\")", "" ], - "models/rendering/latest_raw_events_0.sql": [ + "sql/models/rendering/latest_raw_events_0.sql": [ "SELECT id, amount", "FROM (SELECT id, amount FROM __source(\"raw_events_0\") ORDER BY id DESC LIMIT 2) AS latest", "" ], - "models/rendering/policy_stg_support_0.sql": [ + "sql/models/rendering/policy_stg_support_0.sql": [ "SELECT id, amount, ('web' || '/ci/generated_duckdb/west' || '@web-orders') AS channel,", " 1 AS minimum_amount,", " 'store' AS fallback_channel", @@ -213,12 +213,12 @@ "WHERE amount >= 1", "" ], - "models/rendering/unioned_event_ids.sql": [ + "sql/models/rendering/unioned_event_ids.sql": [ "SELECT id", "FROM (SELECT id FROM __ref(\"stg_support_0\") UNION ALL SELECT id FROM __ref(\"stg_support_0\")) AS unioned", "" ], - "models/support/marts/support_summary_0.sql": [ + "sql/models/support/marts/support_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -230,7 +230,7 @@ "LEFT JOIN __seed(\"lookup_1\") j1 ON t.id = j1.id", "" ], - "models/support/marts/support_summary_1.sql": [ + "sql/models/support/marts/support_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -246,7 +246,7 @@ "WHERE t.status <> 'returned ✓'", "" ], - "models/support/marts/support_summary_2.sql": [ + "sql/models/support/marts/support_summary_2.sql": [ "SELECT", " t.id,", " t.amount,", @@ -260,7 +260,7 @@ "LEFT JOIN __seed(\"lookup_1\") j1 ON t.id = j1.id", "" ], - "models/support/staging/stg_support_0.sql": [ + "sql/models/support/staging/stg_support_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -340,8 +340,8 @@ "name": "combined_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/combined_stg_support_0.sql", - "original_file_path": "models/analysis/combined_stg_support_0.sql", + "path": "sql/models/analysis/combined_stg_support_0.sql", + "original_file_path": "sql/models/analysis/combined_stg_support_0.sql", "unique_id": "model.generated_4.combined_stg_support_0", "fqn": [ "generated_4", @@ -409,8 +409,8 @@ "name": "every_open_event", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/every_open_event.sql", - "original_file_path": "models/analysis/every_open_event.sql", + "path": "sql/models/analysis/every_open_event.sql", + "original_file_path": "sql/models/analysis/every_open_event.sql", "unique_id": "model.generated_4.every_open_event", "fqn": [ "generated_4", @@ -478,8 +478,8 @@ "name": "every_raw_events_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/every_raw_events_0.sql", - "original_file_path": "models/analysis/every_raw_events_0.sql", + "path": "sql/models/analysis/every_raw_events_0.sql", + "original_file_path": "sql/models/analysis/every_raw_events_0.sql", "unique_id": "model.generated_4.every_raw_events_0", "fqn": [ "generated_4", @@ -547,8 +547,8 @@ "name": "every_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/every_stg_support_0.sql", - "original_file_path": "models/analysis/every_stg_support_0.sql", + "path": "sql/models/analysis/every_stg_support_0.sql", + "original_file_path": "sql/models/analysis/every_stg_support_0.sql", "unique_id": "model.generated_4.every_stg_support_0", "fqn": [ "generated_4", @@ -616,8 +616,8 @@ "name": "passed_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/passed_stg_support_0.sql", - "original_file_path": "models/analysis/passed_stg_support_0.sql", + "path": "sql/models/analysis/passed_stg_support_0.sql", + "original_file_path": "sql/models/analysis/passed_stg_support_0.sql", "unique_id": "model.generated_4.passed_stg_support_0", "fqn": [ "generated_4", @@ -685,8 +685,8 @@ "name": "pivot_input_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/pivot_input_stg_support_0.sql", - "original_file_path": "models/analysis/pivot_input_stg_support_0.sql", + "path": "sql/models/analysis/pivot_input_stg_support_0.sql", + "original_file_path": "sql/models/analysis/pivot_input_stg_support_0.sql", "unique_id": "model.generated_4.pivot_input_stg_support_0", "fqn": [ "generated_4", @@ -782,8 +782,8 @@ "name": "pivoted_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/pivoted_stg_support_0.sql", - "original_file_path": "models/analysis/pivoted_stg_support_0.sql", + "path": "sql/models/analysis/pivoted_stg_support_0.sql", + "original_file_path": "sql/models/analysis/pivoted_stg_support_0.sql", "unique_id": "model.generated_4.pivoted_stg_support_0", "fqn": [ "generated_4", @@ -874,8 +874,8 @@ "name": "quoted_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/quoted_stg_support_0.sql", - "original_file_path": "models/analysis/quoted_stg_support_0.sql", + "path": "sql/models/analysis/quoted_stg_support_0.sql", + "original_file_path": "sql/models/analysis/quoted_stg_support_0.sql", "unique_id": "model.generated_4.quoted_stg_support_0", "fqn": [ "generated_4", @@ -943,8 +943,8 @@ "name": "regional_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/regional_stg_support_0.sql", - "original_file_path": "models/analysis/regional_stg_support_0.sql", + "path": "sql/models/analysis/regional_stg_support_0.sql", + "original_file_path": "sql/models/analysis/regional_stg_support_0.sql", "unique_id": "model.generated_4.regional_stg_support_0", "fqn": [ "generated_4", @@ -1012,8 +1012,8 @@ "name": "typed_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/typed_stg_support_0.sql", - "original_file_path": "models/analysis/typed_stg_support_0.sql", + "path": "sql/models/analysis/typed_stg_support_0.sql", + "original_file_path": "sql/models/analysis/typed_stg_support_0.sql", "unique_id": "model.generated_4.typed_stg_support_0", "fqn": [ "generated_4", @@ -1081,8 +1081,8 @@ "name": "unanalysed_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/analysis/unanalysed_stg_support_0.sql", - "original_file_path": "models/analysis/unanalysed_stg_support_0.sql", + "path": "sql/models/analysis/unanalysed_stg_support_0.sql", + "original_file_path": "sql/models/analysis/unanalysed_stg_support_0.sql", "unique_id": "model.generated_4.unanalysed_stg_support_0", "fqn": [ "generated_4", @@ -1150,8 +1150,8 @@ "name": "append_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/features/append_stg_support_0.sql", - "original_file_path": "models/features/append_stg_support_0.sql", + "path": "sql/models/features/append_stg_support_0.sql", + "original_file_path": "sql/models/features/append_stg_support_0.sql", "unique_id": "model.generated_4.append_stg_support_0", "fqn": [ "generated_4", @@ -1219,8 +1219,8 @@ "name": "batched_rolling_window_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/features/batched_rolling_window_stg_support_0.sql", - "original_file_path": "models/features/batched_rolling_window_stg_support_0.sql", + "path": "sql/models/features/batched_rolling_window_stg_support_0.sql", + "original_file_path": "sql/models/features/batched_rolling_window_stg_support_0.sql", "unique_id": "model.generated_4.batched_rolling_window_stg_support_0", "fqn": [ "generated_4", @@ -1288,8 +1288,8 @@ "name": "guarded_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/features/guarded_stg_support_0.sql", - "original_file_path": "models/features/guarded_stg_support_0.sql", + "path": "sql/models/features/guarded_stg_support_0.sql", + "original_file_path": "sql/models/features/guarded_stg_support_0.sql", "unique_id": "model.generated_4.guarded_stg_support_0", "fqn": [ "generated_4", @@ -1367,8 +1367,8 @@ "name": "product_labels", "resource_type": "model", "package_name": "generated_4", - "path": "models/features/product_labels.sql", - "original_file_path": "models/features/product_labels.sql", + "path": "sql/models/features/product_labels.sql", + "original_file_path": "sql/models/features/product_labels.sql", "unique_id": "model.generated_4.product_labels", "fqn": [ "generated_4", @@ -1436,8 +1436,8 @@ "name": "shaped_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/features/shaped_stg_support_0.sql", - "original_file_path": "models/features/shaped_stg_support_0.sql", + "path": "sql/models/features/shaped_stg_support_0.sql", + "original_file_path": "sql/models/features/shaped_stg_support_0.sql", "unique_id": "model.generated_4.shaped_stg_support_0", "fqn": [ "generated_4", @@ -1524,8 +1524,8 @@ "name": "timestamp_history_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/features/timestamp_history_stg_support_0.sql", - "original_file_path": "models/features/timestamp_history_stg_support_0.sql", + "path": "sql/models/features/timestamp_history_stg_support_0.sql", + "original_file_path": "sql/models/features/timestamp_history_stg_support_0.sql", "unique_id": "model.generated_4.timestamp_history_stg_support_0", "fqn": [ "generated_4", @@ -1595,8 +1595,8 @@ "name": "bounded_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/rendering/bounded_stg_support_0.sql", - "original_file_path": "models/rendering/bounded_stg_support_0.sql", + "path": "sql/models/rendering/bounded_stg_support_0.sql", + "original_file_path": "sql/models/rendering/bounded_stg_support_0.sql", "unique_id": "model.generated_4.bounded_stg_support_0", "fqn": [ "generated_4", @@ -1666,8 +1666,8 @@ "name": "configured_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/rendering/configured_stg_support_0.sql", - "original_file_path": "models/rendering/configured_stg_support_0.sql", + "path": "sql/models/rendering/configured_stg_support_0.sql", + "original_file_path": "sql/models/rendering/configured_stg_support_0.sql", "unique_id": "model.generated_4.configured_stg_support_0", "fqn": [ "generated_4", @@ -1767,8 +1767,8 @@ "name": "latest_raw_events_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/rendering/latest_raw_events_0.sql", - "original_file_path": "models/rendering/latest_raw_events_0.sql", + "path": "sql/models/rendering/latest_raw_events_0.sql", + "original_file_path": "sql/models/rendering/latest_raw_events_0.sql", "unique_id": "model.generated_4.latest_raw_events_0", "fqn": [ "generated_4", @@ -1836,8 +1836,8 @@ "name": "policy_stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/rendering/policy_stg_support_0.sql", - "original_file_path": "models/rendering/policy_stg_support_0.sql", + "path": "sql/models/rendering/policy_stg_support_0.sql", + "original_file_path": "sql/models/rendering/policy_stg_support_0.sql", "unique_id": "model.generated_4.policy_stg_support_0", "fqn": [ "generated_4", @@ -1905,8 +1905,8 @@ "name": "unioned_event_ids", "resource_type": "model", "package_name": "generated_4", - "path": "models/rendering/unioned_event_ids.sql", - "original_file_path": "models/rendering/unioned_event_ids.sql", + "path": "sql/models/rendering/unioned_event_ids.sql", + "original_file_path": "sql/models/rendering/unioned_event_ids.sql", "unique_id": "model.generated_4.unioned_event_ids", "fqn": [ "generated_4", @@ -1974,8 +1974,8 @@ "name": "support_summary_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/support/marts/support_summary_0.sql", - "original_file_path": "models/support/marts/support_summary_0.sql", + "path": "sql/models/support/marts/support_summary_0.sql", + "original_file_path": "sql/models/support/marts/support_summary_0.sql", "unique_id": "model.generated_4.support_summary_0", "fqn": [ "generated_4", @@ -2061,8 +2061,8 @@ "name": "support_summary_1", "resource_type": "model", "package_name": "generated_4", - "path": "models/support/marts/support_summary_1.sql", - "original_file_path": "models/support/marts/support_summary_1.sql", + "path": "sql/models/support/marts/support_summary_1.sql", + "original_file_path": "sql/models/support/marts/support_summary_1.sql", "unique_id": "model.generated_4.support_summary_1", "fqn": [ "generated_4", @@ -2138,8 +2138,8 @@ "name": "support_summary_2", "resource_type": "model", "package_name": "generated_4", - "path": "models/support/marts/support_summary_2.sql", - "original_file_path": "models/support/marts/support_summary_2.sql", + "path": "sql/models/support/marts/support_summary_2.sql", + "original_file_path": "sql/models/support/marts/support_summary_2.sql", "unique_id": "model.generated_4.support_summary_2", "fqn": [ "generated_4", @@ -2215,8 +2215,8 @@ "name": "stg_support_0", "resource_type": "model", "package_name": "generated_4", - "path": "models/support/staging/stg_support_0.sql", - "original_file_path": "models/support/staging/stg_support_0.sql", + "path": "sql/models/support/staging/stg_support_0.sql", + "original_file_path": "sql/models/support/staging/stg_support_0.sql", "unique_id": "model.generated_4.stg_support_0", "fqn": [ "generated_4", @@ -2299,8 +2299,8 @@ "name": "lookup_0", "resource_type": "seed", "package_name": "generated_4", - "path": "seeds/lookup_0.csv", - "original_file_path": "seeds/lookup_0.csv", + "path": "sql/seeds/lookup_0.csv", + "original_file_path": "sql/seeds/lookup_0.csv", "unique_id": "seed.generated_4.lookup_0", "fqn": [ "generated_4", @@ -2384,8 +2384,8 @@ "name": "lookup_1", "resource_type": "seed", "package_name": "generated_4", - "path": "seeds/lookup_1.csv", - "original_file_path": "seeds/lookup_1.csv", + "path": "sql/seeds/lookup_1.csv", + "original_file_path": "sql/seeds/lookup_1.csv", "unique_id": "seed.generated_4.lookup_1", "fqn": [ "generated_4", @@ -2471,8 +2471,8 @@ "name": "configured_events", "resource_type": "source", "package_name": "generated_4", - "path": "sources/configured.yml", - "original_file_path": "sources/configured.yml", + "path": "sql/sources/configured.yml", + "original_file_path": "sql/sources/configured.yml", "unique_id": "source.generated_4.configured_events", "fqn": [ "generated_4", @@ -2523,8 +2523,8 @@ "name": "loaded_products", "resource_type": "source", "package_name": "generated_4", - "path": "sources/managed.yml", - "original_file_path": "sources/managed.yml", + "path": "sql/sources/managed.yml", + "original_file_path": "sql/sources/managed.yml", "unique_id": "source.generated_4.loaded_products", "fqn": [ "generated_4", @@ -2579,8 +2579,8 @@ "name": "open_events", "resource_type": "source", "package_name": "generated_4", - "path": "sources/open.yml", - "original_file_path": "sources/open.yml", + "path": "sql/sources/open.yml", + "original_file_path": "sql/sources/open.yml", "unique_id": "source.generated_4.open_events", "fqn": [ "generated_4", @@ -2610,8 +2610,8 @@ "name": "raw_events_0", "resource_type": "source", "package_name": "generated_4", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_4.raw_events_0", "fqn": [ "generated_4", @@ -2678,8 +2678,8 @@ "name": "analysis_region", "resource_type": "macro", "package_name": "generated_4", - "path": "models/analysis/_sqlbuild/_macros/python/regions.py", - "original_file_path": "models/analysis/_sqlbuild/_macros/python/regions.py", + "path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", + "original_file_path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", "unique_id": "macro.generated_4.analysis_region", "macro_sql": "def analysis_region() -> str:\n \"\"\"Return the region rows are assigned to.\"\"\"\n return \"'north'\"\n", "depends_on": { @@ -2688,7 +2688,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/analysis" + "sqlbuild_scope_path": "sql/models/analysis" }, "docs": { "show": true, @@ -2702,8 +2702,8 @@ "name": "channel_label", "resource_type": "macro", "package_name": "generated_4", - "path": "models/rendering/_sqlbuild/_macros/python/policy.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/policy.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", "unique_id": "macro.generated_4.channel_label", "macro_sql": "import os\n\n\ndef minimum_amount_filter(ctx, column: str) -> str:\n \"\"\"Keep rows at or above the configured minimum amount.\"\"\"\n if ctx.constants[\"minimum_render_amount\"] is None:\n return \"TRUE\"\n return f\"{column} >= {ctx.render_constant('minimum_render_amount')}\"\n\n\ndef channel_label(ctx) -> str:\n \"\"\"Label rows with the web channel, target and adapter.\"\"\"\n channel = ctx.render_enum_member(enum_name=\"render_channel\", member_name=\"WEB\")\n region = ctx.vars[\"region\"]\n return f\"{channel} || '/{ctx.target_name}/{ctx.adapter_name}/{region}'\"\n\n\ndef with_deployment(expression: str) -> str:\n \"\"\"Suffix an expression with the deployment channel from the environment.\"\"\"\n channel = os.environ.get(\"SQB_DIFFERENTIAL_CHANNEL\", \"none\")\n return f\"({expression} || '@{channel}')\"\n", "depends_on": { @@ -2712,7 +2712,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2726,8 +2726,8 @@ "name": "minimum_amount_filter", "resource_type": "macro", "package_name": "generated_4", - "path": "models/rendering/_sqlbuild/_macros/python/policy.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/policy.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", "unique_id": "macro.generated_4.minimum_amount_filter", "macro_sql": "import os\n\n\ndef minimum_amount_filter(ctx, column: str) -> str:\n \"\"\"Keep rows at or above the configured minimum amount.\"\"\"\n if ctx.constants[\"minimum_render_amount\"] is None:\n return \"TRUE\"\n return f\"{column} >= {ctx.render_constant('minimum_render_amount')}\"\n\n\ndef channel_label(ctx) -> str:\n \"\"\"Label rows with the web channel, target and adapter.\"\"\"\n channel = ctx.render_enum_member(enum_name=\"render_channel\", member_name=\"WEB\")\n region = ctx.vars[\"region\"]\n return f\"{channel} || '/{ctx.target_name}/{ctx.adapter_name}/{region}'\"\n\n\ndef with_deployment(expression: str) -> str:\n \"\"\"Suffix an expression with the deployment channel from the environment.\"\"\"\n channel = os.environ.get(\"SQB_DIFFERENTIAL_CHANNEL\", \"none\")\n return f\"({expression} || '@{channel}')\"\n", "depends_on": { @@ -2736,7 +2736,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2750,8 +2750,8 @@ "name": "with_deployment", "resource_type": "macro", "package_name": "generated_4", - "path": "models/rendering/_sqlbuild/_macros/python/policy.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/policy.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/policy.py", "unique_id": "macro.generated_4.with_deployment", "macro_sql": "import os\n\n\ndef minimum_amount_filter(ctx, column: str) -> str:\n \"\"\"Keep rows at or above the configured minimum amount.\"\"\"\n if ctx.constants[\"minimum_render_amount\"] is None:\n return \"TRUE\"\n return f\"{column} >= {ctx.render_constant('minimum_render_amount')}\"\n\n\ndef channel_label(ctx) -> str:\n \"\"\"Label rows with the web channel, target and adapter.\"\"\"\n channel = ctx.render_enum_member(enum_name=\"render_channel\", member_name=\"WEB\")\n region = ctx.vars[\"region\"]\n return f\"{channel} || '/{ctx.target_name}/{ctx.adapter_name}/{region}'\"\n\n\ndef with_deployment(expression: str) -> str:\n \"\"\"Suffix an expression with the deployment channel from the environment.\"\"\"\n channel = os.environ.get(\"SQB_DIFFERENTIAL_CHANNEL\", \"none\")\n return f\"({expression} || '@{channel}')\"\n", "depends_on": { @@ -2760,7 +2760,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2774,8 +2774,8 @@ "name": "latest_rows", "resource_type": "macro", "package_name": "generated_4", - "path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/relations.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/relations.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/relations.py", "unique_id": "macro.generated_4.latest_rows", "macro_sql": "from sqlbuild.refs import SqlResourceRef\n\n\ndef union_ids(relations: list[SqlResourceRef]) -> str:\n \"\"\"Union the ids of several relations.\"\"\"\n selects = [f\"SELECT id FROM {relation}\" for relation in relations]\n return \" UNION ALL \".join(selects)\n\n\ndef latest_rows(relation: SqlResourceRef, limit: int = 2) -> str:\n \"\"\"Return the newest rows of one relation.\"\"\"\n return f\"(SELECT id, amount FROM {relation} ORDER BY id DESC LIMIT {limit})\"\n", "depends_on": { @@ -2784,7 +2784,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2798,8 +2798,8 @@ "name": "union_ids", "resource_type": "macro", "package_name": "generated_4", - "path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/relations.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/relations.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/relations.py", "unique_id": "macro.generated_4.union_ids", "macro_sql": "from sqlbuild.refs import SqlResourceRef\n\n\ndef union_ids(relations: list[SqlResourceRef]) -> str:\n \"\"\"Union the ids of several relations.\"\"\"\n selects = [f\"SELECT id FROM {relation}\" for relation in relations]\n return \" UNION ALL \".join(selects)\n\n\ndef latest_rows(relation: SqlResourceRef, limit: int = 2) -> str:\n \"\"\"Return the newest rows of one relation.\"\"\"\n return f\"(SELECT id, amount FROM {relation} ORDER BY id DESC LIMIT {limit})\"\n", "depends_on": { @@ -2808,7 +2808,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -2822,8 +2822,8 @@ "name": "adjust_2", "resource_type": "macro", "package_name": "generated_4", - "path": "models/support/_sqlbuild/macros/python/adjust_2.py", - "original_file_path": "models/support/_sqlbuild/macros/python/adjust_2.py", + "path": "sql/models/support/_sqlbuild/macros/python/adjust_2.py", + "original_file_path": "sql/models/support/_sqlbuild/macros/python/adjust_2.py", "unique_id": "macro.generated_4.adjust_2", "macro_sql": "def adjust_2_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_2(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_2_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2834,7 +2834,7 @@ "description": "", "meta": { "sqlbuild_visibility": "inherited", - "sqlbuild_scope_path": "models/support" + "sqlbuild_scope_path": "sql/models/support" }, "docs": { "show": true, @@ -2848,8 +2848,8 @@ "name": "adjust_2_round", "resource_type": "macro", "package_name": "generated_4", - "path": "models/support/_sqlbuild/macros/python/adjust_2.py", - "original_file_path": "models/support/_sqlbuild/macros/python/adjust_2.py", + "path": "sql/models/support/_sqlbuild/macros/python/adjust_2.py", + "original_file_path": "sql/models/support/_sqlbuild/macros/python/adjust_2.py", "unique_id": "macro.generated_4.adjust_2_round", "macro_sql": "def adjust_2_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_2(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_2_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2858,7 +2858,7 @@ "description": "", "meta": { "sqlbuild_visibility": "inherited", - "sqlbuild_scope_path": "models/support" + "sqlbuild_scope_path": "sql/models/support" }, "docs": { "show": true, @@ -2872,8 +2872,8 @@ "name": "adjust_0", "resource_type": "macro", "package_name": "generated_4", - "path": "models/support/marts/_sqlbuild/_macros/python/adjust_0.py", - "original_file_path": "models/support/marts/_sqlbuild/_macros/python/adjust_0.py", + "path": "sql/models/support/marts/_sqlbuild/_macros/python/adjust_0.py", + "original_file_path": "sql/models/support/marts/_sqlbuild/_macros/python/adjust_0.py", "unique_id": "macro.generated_4.adjust_0", "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2884,7 +2884,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/support/marts" + "sqlbuild_scope_path": "sql/models/support/marts" }, "docs": { "show": true, @@ -2898,8 +2898,8 @@ "name": "adjust_0_round", "resource_type": "macro", "package_name": "generated_4", - "path": "models/support/marts/_sqlbuild/_macros/python/adjust_0.py", - "original_file_path": "models/support/marts/_sqlbuild/_macros/python/adjust_0.py", + "path": "sql/models/support/marts/_sqlbuild/_macros/python/adjust_0.py", + "original_file_path": "sql/models/support/marts/_sqlbuild/_macros/python/adjust_0.py", "unique_id": "macro.generated_4.adjust_0_round", "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2908,7 +2908,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/support/marts" + "sqlbuild_scope_path": "sql/models/support/marts" }, "docs": { "show": true, @@ -2922,8 +2922,8 @@ "name": "adjust_1", "resource_type": "macro", "package_name": "generated_4", - "path": "models/support/marts/_sqlbuild/_macros/python/adjust_1.py", - "original_file_path": "models/support/marts/_sqlbuild/_macros/python/adjust_1.py", + "path": "sql/models/support/marts/_sqlbuild/_macros/python/adjust_1.py", + "original_file_path": "sql/models/support/marts/_sqlbuild/_macros/python/adjust_1.py", "unique_id": "macro.generated_4.adjust_1", "macro_sql": "def adjust_1_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_1_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2934,7 +2934,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/support/marts" + "sqlbuild_scope_path": "sql/models/support/marts" }, "docs": { "show": true, @@ -2948,8 +2948,8 @@ "name": "adjust_1_round", "resource_type": "macro", "package_name": "generated_4", - "path": "models/support/marts/_sqlbuild/_macros/python/adjust_1.py", - "original_file_path": "models/support/marts/_sqlbuild/_macros/python/adjust_1.py", + "path": "sql/models/support/marts/_sqlbuild/_macros/python/adjust_1.py", + "original_file_path": "sql/models/support/marts/_sqlbuild/_macros/python/adjust_1.py", "unique_id": "macro.generated_4.adjust_1_round", "macro_sql": "def adjust_1_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_1_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -2958,7 +2958,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/support/marts" + "sqlbuild_scope_path": "sql/models/support/marts" }, "docs": { "show": true, diff --git a/tests/goldens/compiler/seed/5.json b/tests/goldens/compiler/seed/5.json index 207323880c..c113784f03 100644 --- a/tests/goldens/compiler/seed/5.json +++ b/tests/goldens/compiler/seed/5.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Model file models/fulfillment/staging/stg_fulfillment_2.sql references unknown model 'missing_model'" + "message": "Model file sql/models/fulfillment/staging/stg_fulfillment_2.sql references unknown model 'missing_model'" } ] }, @@ -20,7 +20,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Model file models/fulfillment/staging/stg_fulfillment_2.sql references unknown model 'missing_model'" + "message": "Model file sql/models/fulfillment/staging/stg_fulfillment_2.sql references unknown model 'missing_model'" } ] }, @@ -37,7 +37,7 @@ "Project assembly OK ()", "Project discovery OK ()", "Compiling project...", - "error[P001]: Model file models/fulfillment/staging/stg_fulfillment_2.sql references unknown model 'missing_model'", + "error[P001]: Model file sql/models/fulfillment/staging/stg_fulfillment_2.sql references unknown model 'missing_model'", "", "" ] diff --git a/tests/goldens/compiler/seed/6.json b/tests/goldens/compiler/seed/6.json index 491deba8ac..c19ac47c93 100644 --- a/tests/goldens/compiler/seed/6.json +++ b/tests/goldens/compiler/seed/6.json @@ -187,28 +187,28 @@ "id": "model:audited_stg_fulfillment_1", "name": "audited_stg_fulfillment_1", "resource_type": "model", - "relative_path": "models/features/audited_stg_fulfillment_1.sql", + "relative_path": "sql/models/features/audited_stg_fulfillment_1.sql", "qualified_name": "main.audited_stg_fulfillment_1" }, { "id": "model:cte_facts_stg_fulfillment_1", "name": "cte_facts_stg_fulfillment_1", "resource_type": "model", - "relative_path": "models/analysis/cte_facts_stg_fulfillment_1.sql", + "relative_path": "sql/models/analysis/cte_facts_stg_fulfillment_1.sql", "qualified_name": "main.cte_facts_stg_fulfillment_1" }, { "id": "model:stg_fulfillment_1", "name": "stg_fulfillment_1", "resource_type": "model", - "relative_path": "models/fulfillment/staging/stg_fulfillment_1.sql", + "relative_path": "sql/models/fulfillment/staging/stg_fulfillment_1.sql", "qualified_name": "main.stg_fulfillment_1" }, { "id": "source:raw_events_0", "name": "raw_events_0", "resource_type": "source", - "relative_path": "sources/raw.yml" + "relative_path": "sql/sources/raw.yml" } ], "edges": [ @@ -233,26 +233,26 @@ } ], "compiled": { - "audits/generic/audited_stg_fulfillment_1/id_present__id.sql": [ + "sql/audits/generic/audited_stg_fulfillment_1/id_present__id.sql": [ "SELECT id", "FROM __ref(\"audited_stg_fulfillment_1\")", "WHERE id IS NULL", "" ], - "audits/generic/checked_stg_fulfillment_2/accepted_values__status.sql": [ + "sql/audits/generic/checked_stg_fulfillment_2/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"checked_stg_fulfillment_2\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/checked_stg_fulfillment_2/expression_is_true.sql": [ + "sql/audits/generic/checked_stg_fulfillment_2/expression_is_true.sql": [ "SELECT *", "FROM __ref(\"checked_stg_fulfillment_2\")", "WHERE NOT (amount >= -1000)", "" ], - "audits/generic/checked_stg_fulfillment_2/relationships__id.sql": [ + "sql/audits/generic/checked_stg_fulfillment_2/relationships__id.sql": [ "SELECT id", "FROM __ref(\"checked_stg_fulfillment_2\")", "WHERE id IS NOT NULL", @@ -263,105 +263,105 @@ " )", "" ], - "audits/generic/sales_summary_0/not_null__id.sql": [ + "sql/audits/generic/sales_summary_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"sales_summary_0\")", "WHERE id IS NULL", "" ], - "audits/generic/shaped_stg_inventory_2/not_null__id.sql": [ + "sql/audits/generic/shaped_stg_inventory_2/not_null__id.sql": [ "SELECT id", "FROM __ref(\"shaped_stg_inventory_2\")", "WHERE id IS NULL", "" ], - "audits/generic/stated_stg_inventory_2/accepted_values__status.sql": [ + "sql/audits/generic/stated_stg_inventory_2/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"stated_stg_inventory_2\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/stg_fulfillment_0/not_null__id.sql": [ + "sql/audits/generic/stg_fulfillment_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_fulfillment_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_fulfillment_1/not_null__id.sql": [ + "sql/audits/generic/stg_fulfillment_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_fulfillment_1\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_fulfillment_2/not_null__id.sql": [ + "sql/audits/generic/stg_fulfillment_2/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_fulfillment_2\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_inventory_0/not_null__id.sql": [ + "sql/audits/generic/stg_inventory_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_inventory_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_inventory_2/not_null__id.sql": [ + "sql/audits/generic/stg_inventory_2/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_inventory_2\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_sales_0/not_null__id.sql": [ + "sql/audits/generic/stg_sales_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_sales_0\")", "WHERE id IS NULL", "" ], - "functions/python/is_large.sql": [ + "sql/functions/python/is_large.sql": [ "REGISTER PYTHON FUNCTION is_large(DOUBLE) RETURNS BOOLEAN", "" ], - "functions/sql/is_placed.sql": [ + "sql/functions/sql/is_placed.sql": [ "CREATE OR REPLACE MACRO main.is_placed(event_status) AS (", "event_status = 'placed'", ")", "" ], - "functions/sql/table_fn__events_above.sql": [ + "sql/functions/sql/table_fn__events_above.sql": [ "CREATE OR REPLACE MACRO main.table_fn__events_above(p_minimum) AS TABLE", "SELECT id, amount", "FROM __ref(\"stg_sales_0\")", "WHERE amount > p_minimum", "" ], - "models/analysis/chain_1_stg_fulfillment_2.sql": [ + "sql/models/analysis/chain_1_stg_fulfillment_2.sql": [ "SELECT id, label, amount", "FROM __ref(\"contracted_stg_fulfillment_2\")", "" ], - "models/analysis/chain_2_stg_fulfillment_2.sql": [ + "sql/models/analysis/chain_2_stg_fulfillment_2.sql": [ "SELECT id, UPPER(label) AS label, amount", "FROM __ref(\"chain_1_stg_fulfillment_2\")", "" ], - "models/analysis/chain_3_stg_fulfillment_2.sql": [ + "sql/models/analysis/chain_3_stg_fulfillment_2.sql": [ "SELECT id, label, amount", "FROM __ref(\"chain_2_stg_fulfillment_2\")", "" ], - "models/analysis/checked_stg_fulfillment_2.sql": [ + "sql/models/analysis/checked_stg_fulfillment_2.sql": [ "SELECT id, amount, status", "FROM __ref(\"stg_fulfillment_2\")", "" ], - "models/analysis/contracted_stg_fulfillment_2.sql": [ + "sql/models/analysis/contracted_stg_fulfillment_2.sql": [ "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR(18)) AS label,", " amount", "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/cte_facts_stg_fulfillment_1.sql": [ + "sql/models/analysis/cte_facts_stg_fulfillment_1.sql": [ "WITH base AS (", " SELECT id, CAST(amount AS DECIMAL(12, 2)) AS amount, 'event' AS kind,", " COALESCE(status, 'unknown') AS status", @@ -372,54 +372,54 @@ "FROM base", "" ], - "models/analysis/regional_stg_fulfillment_0.sql": [ + "sql/models/analysis/regional_stg_fulfillment_0.sql": [ "SELECT id, amount, 'north' AS region", "FROM __ref(\"stg_fulfillment_0\")", "" ], - "models/features/audited_stg_fulfillment_1.sql": [ + "sql/models/features/audited_stg_fulfillment_1.sql": [ "SELECT id, amount", "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/features/batched_rolling_window_stg_sales_0.sql": [ + "sql/models/features/batched_rolling_window_stg_sales_0.sql": [ "SELECT CAST(created_at AS DATE) AS created_at, SUM(amount) AS amount", "FROM __ref(\"stg_sales_0\")", "GROUP BY CAST(created_at AS DATE)", "" ], - "models/features/check_history_stg_inventory_1.sql": [ + "sql/models/features/check_history_stg_inventory_1.sql": [ "SELECT id, status, amount", "FROM __ref(\"stg_inventory_1\")", "" ], - "models/features/copied_stg_fulfillment_2.sql": [ + "sql/models/features/copied_stg_fulfillment_2.sql": [ "SELECT id, status", "FROM __ref(\"stg_fulfillment_2\")", "" ], - "models/features/flagged_stg_sales_0.sql": [ + "sql/models/features/flagged_stg_sales_0.sql": [ "SELECT id, __udf(\"is_placed\")(status) AS is_placed,", " __udf(\"is_large\")(amount) AS is_large", "FROM __ref(\"stg_sales_0\")", "" ], - "models/features/hooked_stg_inventory_1.sql": [ + "sql/models/features/hooked_stg_inventory_1.sql": [ "SELECT id, amount", "FROM __ref(\"stg_inventory_1\")", "" ], - "models/features/merge_stg_inventory_0.sql": [ + "sql/models/features/merge_stg_inventory_0.sql": [ "SELECT id, amount, status, created_at", "FROM __ref(\"stg_inventory_0\")", "" ], - "models/features/shaped_stg_inventory_2.sql": [ + "sql/models/features/shaped_stg_inventory_2.sql": [ "SELECT CAST(id AS INTEGER) AS id, status", "FROM __ref(\"stg_inventory_2\")", "" ], - "models/features/spaced_stg_fulfillment_0.sql": [ + "sql/models/features/spaced_stg_fulfillment_0.sql": [ "-- Généré pour café ☕ counter", "SELECT", "\tid,", @@ -428,12 +428,12 @@ "FROM __ref(\"stg_fulfillment_0\")", "" ], - "models/features/taxed_stg_inventory_0.sql": [ + "sql/models/features/taxed_stg_inventory_0.sql": [ "SELECT id, ROUND(amount * 1.2, 2) AS taxed, ROUND(amount, 1) AS rounded", "FROM __ref(\"stg_inventory_0\")", "" ], - "models/fulfillment/marts/fulfillment_summary_0.sql": [ + "sql/models/fulfillment/marts/fulfillment_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -444,7 +444,7 @@ "FROM __ref(\"stg_fulfillment_0\") t", "" ], - "models/fulfillment/staging/stg_fulfillment_0.sql": [ + "sql/models/fulfillment/staging/stg_fulfillment_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -455,7 +455,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/fulfillment/staging/stg_fulfillment_1.sql": [ + "sql/models/fulfillment/staging/stg_fulfillment_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -465,7 +465,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/fulfillment/staging/stg_fulfillment_2.sql": [ + "sql/models/fulfillment/staging/stg_fulfillment_2.sql": [ "SELECT", " t.id,", " t.amount,", @@ -475,7 +475,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/inventory/marts/inventory_summary_0.sql": [ + "sql/models/inventory/marts/inventory_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -485,7 +485,7 @@ "WHERE t.status <> '取消'", "" ], - "models/inventory/marts/inventory_summary_1.sql": [ + "sql/models/inventory/marts/inventory_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -494,7 +494,7 @@ "FROM __ref(\"stg_inventory_2\") t", "" ], - "models/inventory/staging/stg_inventory_0.sql": [ + "sql/models/inventory/staging/stg_inventory_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -503,7 +503,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/inventory/staging/stg_inventory_1.sql": [ + "sql/models/inventory/staging/stg_inventory_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -512,7 +512,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/inventory/staging/stg_inventory_2.sql": [ + "sql/models/inventory/staging/stg_inventory_2.sql": [ "SELECT", " t.id,", " t.amount,", @@ -522,19 +522,19 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/rendering/large_events.sql": [ + "sql/models/rendering/large_events.sql": [ "SELECT id, amount", "FROM __table_fn(\"table_fn__events_above\")(4)", "" ], - "models/rendering/stated_stg_inventory_2.sql": [ + "sql/models/rendering/stated_stg_inventory_2.sql": [ "SELECT CAST(id AS INTEGER) AS id, status,", " CASE WHEN amount >= 9 THEN 'HIGH'", " ELSE 'LOW' END AS tier", "FROM __ref(\"stg_inventory_2\")", "" ], - "models/sales/marts/sales_summary_0.sql": [ + "sql/models/sales/marts/sales_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -544,7 +544,7 @@ "FROM __ref(\"stg_sales_0\") t", "" ], - "models/sales/marts/sales_summary_1.sql": [ + "sql/models/sales/marts/sales_summary_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -554,7 +554,7 @@ "LEFT JOIN __ref(\"stg_inventory_1\") j1 ON t.id = j1.id", "" ], - "models/sales/staging/stg_sales_0.sql": [ + "sql/models/sales/staging/stg_sales_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -622,8 +622,8 @@ "name": "chain_1_stg_fulfillment_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/analysis/chain_1_stg_fulfillment_2.sql", - "original_file_path": "models/analysis/chain_1_stg_fulfillment_2.sql", + "path": "sql/models/analysis/chain_1_stg_fulfillment_2.sql", + "original_file_path": "sql/models/analysis/chain_1_stg_fulfillment_2.sql", "unique_id": "model.generated_6.chain_1_stg_fulfillment_2", "fqn": [ "generated_6", @@ -691,8 +691,8 @@ "name": "chain_2_stg_fulfillment_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/analysis/chain_2_stg_fulfillment_2.sql", - "original_file_path": "models/analysis/chain_2_stg_fulfillment_2.sql", + "path": "sql/models/analysis/chain_2_stg_fulfillment_2.sql", + "original_file_path": "sql/models/analysis/chain_2_stg_fulfillment_2.sql", "unique_id": "model.generated_6.chain_2_stg_fulfillment_2", "fqn": [ "generated_6", @@ -760,8 +760,8 @@ "name": "chain_3_stg_fulfillment_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/analysis/chain_3_stg_fulfillment_2.sql", - "original_file_path": "models/analysis/chain_3_stg_fulfillment_2.sql", + "path": "sql/models/analysis/chain_3_stg_fulfillment_2.sql", + "original_file_path": "sql/models/analysis/chain_3_stg_fulfillment_2.sql", "unique_id": "model.generated_6.chain_3_stg_fulfillment_2", "fqn": [ "generated_6", @@ -829,8 +829,8 @@ "name": "checked_stg_fulfillment_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/analysis/checked_stg_fulfillment_2.sql", - "original_file_path": "models/analysis/checked_stg_fulfillment_2.sql", + "path": "sql/models/analysis/checked_stg_fulfillment_2.sql", + "original_file_path": "sql/models/analysis/checked_stg_fulfillment_2.sql", "unique_id": "model.generated_6.checked_stg_fulfillment_2", "fqn": [ "generated_6", @@ -919,8 +919,8 @@ "name": "contracted_stg_fulfillment_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/analysis/contracted_stg_fulfillment_2.sql", - "original_file_path": "models/analysis/contracted_stg_fulfillment_2.sql", + "path": "sql/models/analysis/contracted_stg_fulfillment_2.sql", + "original_file_path": "sql/models/analysis/contracted_stg_fulfillment_2.sql", "unique_id": "model.generated_6.contracted_stg_fulfillment_2", "fqn": [ "generated_6", @@ -1016,8 +1016,8 @@ "name": "cte_facts_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_6", - "path": "models/analysis/cte_facts_stg_fulfillment_1.sql", - "original_file_path": "models/analysis/cte_facts_stg_fulfillment_1.sql", + "path": "sql/models/analysis/cte_facts_stg_fulfillment_1.sql", + "original_file_path": "sql/models/analysis/cte_facts_stg_fulfillment_1.sql", "unique_id": "model.generated_6.cte_facts_stg_fulfillment_1", "fqn": [ "generated_6", @@ -1122,8 +1122,8 @@ "name": "regional_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/analysis/regional_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/regional_stg_fulfillment_0.sql", + "path": "sql/models/analysis/regional_stg_fulfillment_0.sql", + "original_file_path": "sql/models/analysis/regional_stg_fulfillment_0.sql", "unique_id": "model.generated_6.regional_stg_fulfillment_0", "fqn": [ "generated_6", @@ -1191,8 +1191,8 @@ "name": "audited_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/audited_stg_fulfillment_1.sql", - "original_file_path": "models/features/audited_stg_fulfillment_1.sql", + "path": "sql/models/features/audited_stg_fulfillment_1.sql", + "original_file_path": "sql/models/features/audited_stg_fulfillment_1.sql", "unique_id": "model.generated_6.audited_stg_fulfillment_1", "fqn": [ "generated_6", @@ -1260,8 +1260,8 @@ "name": "batched_rolling_window_stg_sales_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/batched_rolling_window_stg_sales_0.sql", - "original_file_path": "models/features/batched_rolling_window_stg_sales_0.sql", + "path": "sql/models/features/batched_rolling_window_stg_sales_0.sql", + "original_file_path": "sql/models/features/batched_rolling_window_stg_sales_0.sql", "unique_id": "model.generated_6.batched_rolling_window_stg_sales_0", "fqn": [ "generated_6", @@ -1329,8 +1329,8 @@ "name": "check_history_stg_inventory_1", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/check_history_stg_inventory_1.sql", - "original_file_path": "models/features/check_history_stg_inventory_1.sql", + "path": "sql/models/features/check_history_stg_inventory_1.sql", + "original_file_path": "sql/models/features/check_history_stg_inventory_1.sql", "unique_id": "model.generated_6.check_history_stg_inventory_1", "fqn": [ "generated_6", @@ -1400,8 +1400,8 @@ "name": "copied_stg_fulfillment_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/copied_stg_fulfillment_2.sql", - "original_file_path": "models/features/copied_stg_fulfillment_2.sql", + "path": "sql/models/features/copied_stg_fulfillment_2.sql", + "original_file_path": "sql/models/features/copied_stg_fulfillment_2.sql", "unique_id": "model.generated_6.copied_stg_fulfillment_2", "fqn": [ "generated_6", @@ -1469,8 +1469,8 @@ "name": "flagged_stg_sales_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/flagged_stg_sales_0.sql", - "original_file_path": "models/features/flagged_stg_sales_0.sql", + "path": "sql/models/features/flagged_stg_sales_0.sql", + "original_file_path": "sql/models/features/flagged_stg_sales_0.sql", "unique_id": "model.generated_6.flagged_stg_sales_0", "fqn": [ "generated_6", @@ -1540,8 +1540,8 @@ "name": "hooked_stg_inventory_1", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/hooked_stg_inventory_1.sql", - "original_file_path": "models/features/hooked_stg_inventory_1.sql", + "path": "sql/models/features/hooked_stg_inventory_1.sql", + "original_file_path": "sql/models/features/hooked_stg_inventory_1.sql", "unique_id": "model.generated_6.hooked_stg_inventory_1", "fqn": [ "generated_6", @@ -1594,7 +1594,7 @@ "kwargs": { "channel": "café ☕ counter" }, - "relative_path": "models/features/_sqlbuild/_hooks/python/notify.py", + "relative_path": "sql/models/features/_sqlbuild/_hooks/python/notify.py", "definition_hash": "4669f6863eaccfebdb6aa5286a58eb944d8b0142ea2bc8e6678cce4efb35bf7e", "version_hash": "80b0b3a25244f0def68efcbecd29182bfa91d76b9272c4d2147d08ae88260fa2" } @@ -1626,8 +1626,8 @@ "name": "merge_stg_inventory_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/merge_stg_inventory_0.sql", - "original_file_path": "models/features/merge_stg_inventory_0.sql", + "path": "sql/models/features/merge_stg_inventory_0.sql", + "original_file_path": "sql/models/features/merge_stg_inventory_0.sql", "unique_id": "model.generated_6.merge_stg_inventory_0", "fqn": [ "generated_6", @@ -1697,8 +1697,8 @@ "name": "shaped_stg_inventory_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/shaped_stg_inventory_2.sql", - "original_file_path": "models/features/shaped_stg_inventory_2.sql", + "path": "sql/models/features/shaped_stg_inventory_2.sql", + "original_file_path": "sql/models/features/shaped_stg_inventory_2.sql", "unique_id": "model.generated_6.shaped_stg_inventory_2", "fqn": [ "generated_6", @@ -1785,8 +1785,8 @@ "name": "spaced_stg_fulfillment_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/spaced_stg_fulfillment_0.sql", - "original_file_path": "models/features/spaced_stg_fulfillment_0.sql", + "path": "sql/models/features/spaced_stg_fulfillment_0.sql", + "original_file_path": "sql/models/features/spaced_stg_fulfillment_0.sql", "unique_id": "model.generated_6.spaced_stg_fulfillment_0", "fqn": [ "generated_6", @@ -1860,8 +1860,8 @@ "name": "taxed_stg_inventory_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/features/taxed_stg_inventory_0.sql", - "original_file_path": "models/features/taxed_stg_inventory_0.sql", + "path": "sql/models/features/taxed_stg_inventory_0.sql", + "original_file_path": "sql/models/features/taxed_stg_inventory_0.sql", "unique_id": "model.generated_6.taxed_stg_inventory_0", "fqn": [ "generated_6", @@ -1929,8 +1929,8 @@ "name": "fulfillment_summary_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/fulfillment/marts/fulfillment_summary_0.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_0.sql", + "path": "sql/models/fulfillment/marts/fulfillment_summary_0.sql", + "original_file_path": "sql/models/fulfillment/marts/fulfillment_summary_0.sql", "unique_id": "model.generated_6.fulfillment_summary_0", "fqn": [ "generated_6", @@ -2005,8 +2005,8 @@ "name": "stg_fulfillment_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/fulfillment/staging/stg_fulfillment_0.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_0.sql", + "path": "sql/models/fulfillment/staging/stg_fulfillment_0.sql", + "original_file_path": "sql/models/fulfillment/staging/stg_fulfillment_0.sql", "unique_id": "model.generated_6.stg_fulfillment_0", "fqn": [ "generated_6", @@ -2089,8 +2089,8 @@ "name": "stg_fulfillment_1", "resource_type": "model", "package_name": "generated_6", - "path": "models/fulfillment/staging/stg_fulfillment_1.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_1.sql", + "path": "sql/models/fulfillment/staging/stg_fulfillment_1.sql", + "original_file_path": "sql/models/fulfillment/staging/stg_fulfillment_1.sql", "unique_id": "model.generated_6.stg_fulfillment_1", "fqn": [ "generated_6", @@ -2173,8 +2173,8 @@ "name": "stg_fulfillment_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/fulfillment/staging/stg_fulfillment_2.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_2.sql", + "path": "sql/models/fulfillment/staging/stg_fulfillment_2.sql", + "original_file_path": "sql/models/fulfillment/staging/stg_fulfillment_2.sql", "unique_id": "model.generated_6.stg_fulfillment_2", "fqn": [ "generated_6", @@ -2257,8 +2257,8 @@ "name": "inventory_summary_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/inventory/marts/inventory_summary_0.sql", - "original_file_path": "models/inventory/marts/inventory_summary_0.sql", + "path": "sql/models/inventory/marts/inventory_summary_0.sql", + "original_file_path": "sql/models/inventory/marts/inventory_summary_0.sql", "unique_id": "model.generated_6.inventory_summary_0", "fqn": [ "generated_6", @@ -2327,7 +2327,7 @@ "type": "sql", "statement": "SELECT 'main.inventory_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2367,8 +2367,8 @@ "name": "inventory_summary_1", "resource_type": "model", "package_name": "generated_6", - "path": "models/inventory/marts/inventory_summary_1.sql", - "original_file_path": "models/inventory/marts/inventory_summary_1.sql", + "path": "sql/models/inventory/marts/inventory_summary_1.sql", + "original_file_path": "sql/models/inventory/marts/inventory_summary_1.sql", "unique_id": "model.generated_6.inventory_summary_1", "fqn": [ "generated_6", @@ -2437,7 +2437,7 @@ "type": "sql", "statement": "SELECT 'main.inventory_summary_1' AS refreshed_relation, 'café ☕ counter' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2477,8 +2477,8 @@ "name": "stg_inventory_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/inventory/staging/stg_inventory_0.sql", - "original_file_path": "models/inventory/staging/stg_inventory_0.sql", + "path": "sql/models/inventory/staging/stg_inventory_0.sql", + "original_file_path": "sql/models/inventory/staging/stg_inventory_0.sql", "unique_id": "model.generated_6.stg_inventory_0", "fqn": [ "generated_6", @@ -2561,8 +2561,8 @@ "name": "stg_inventory_1", "resource_type": "model", "package_name": "generated_6", - "path": "models/inventory/staging/stg_inventory_1.sql", - "original_file_path": "models/inventory/staging/stg_inventory_1.sql", + "path": "sql/models/inventory/staging/stg_inventory_1.sql", + "original_file_path": "sql/models/inventory/staging/stg_inventory_1.sql", "unique_id": "model.generated_6.stg_inventory_1", "fqn": [ "generated_6", @@ -2635,8 +2635,8 @@ "name": "stg_inventory_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/inventory/staging/stg_inventory_2.sql", - "original_file_path": "models/inventory/staging/stg_inventory_2.sql", + "path": "sql/models/inventory/staging/stg_inventory_2.sql", + "original_file_path": "sql/models/inventory/staging/stg_inventory_2.sql", "unique_id": "model.generated_6.stg_inventory_2", "fqn": [ "generated_6", @@ -2719,8 +2719,8 @@ "name": "large_events", "resource_type": "model", "package_name": "generated_6", - "path": "models/rendering/large_events.sql", - "original_file_path": "models/rendering/large_events.sql", + "path": "sql/models/rendering/large_events.sql", + "original_file_path": "sql/models/rendering/large_events.sql", "unique_id": "model.generated_6.large_events", "fqn": [ "generated_6", @@ -2788,8 +2788,8 @@ "name": "stated_stg_inventory_2", "resource_type": "model", "package_name": "generated_6", - "path": "models/rendering/stated_stg_inventory_2.sql", - "original_file_path": "models/rendering/stated_stg_inventory_2.sql", + "path": "sql/models/rendering/stated_stg_inventory_2.sql", + "original_file_path": "sql/models/rendering/stated_stg_inventory_2.sql", "unique_id": "model.generated_6.stated_stg_inventory_2", "fqn": [ "generated_6", @@ -2885,8 +2885,8 @@ "name": "sales_summary_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/sales/marts/sales_summary_0.sql", - "original_file_path": "models/sales/marts/sales_summary_0.sql", + "path": "sql/models/sales/marts/sales_summary_0.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_0.sql", "unique_id": "model.generated_6.sales_summary_0", "fqn": [ "generated_6", @@ -2959,7 +2959,7 @@ "type": "sql", "statement": "SELECT 'main.sales_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2999,8 +2999,8 @@ "name": "sales_summary_1", "resource_type": "model", "package_name": "generated_6", - "path": "models/sales/marts/sales_summary_1.sql", - "original_file_path": "models/sales/marts/sales_summary_1.sql", + "path": "sql/models/sales/marts/sales_summary_1.sql", + "original_file_path": "sql/models/sales/marts/sales_summary_1.sql", "unique_id": "model.generated_6.sales_summary_1", "fqn": [ "generated_6", @@ -3063,7 +3063,7 @@ "type": "sql", "statement": "SELECT 'main.sales_summary_1' AS refreshed_relation, 'café ☕ counter' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "sql/hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -3104,8 +3104,8 @@ "name": "stg_sales_0", "resource_type": "model", "package_name": "generated_6", - "path": "models/sales/staging/stg_sales_0.sql", - "original_file_path": "models/sales/staging/stg_sales_0.sql", + "path": "sql/models/sales/staging/stg_sales_0.sql", + "original_file_path": "sql/models/sales/staging/stg_sales_0.sql", "unique_id": "model.generated_6.stg_sales_0", "fqn": [ "generated_6", @@ -3190,8 +3190,8 @@ "name": "raw_events_0", "resource_type": "source", "package_name": "generated_6", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_6.raw_events_0", "fqn": [ "generated_6", @@ -3258,8 +3258,8 @@ "name": "adjust_0", "resource_type": "macro", "package_name": "generated_6", - "path": "macros/python/adjust_0.py", - "original_file_path": "macros/python/adjust_0.py", + "path": "sql/macros/python/adjust_0.py", + "original_file_path": "sql/macros/python/adjust_0.py", "unique_id": "macro.generated_6.adjust_0", "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -3284,8 +3284,8 @@ "name": "adjust_0_round", "resource_type": "macro", "package_name": "generated_6", - "path": "macros/python/adjust_0.py", - "original_file_path": "macros/python/adjust_0.py", + "path": "sql/macros/python/adjust_0.py", + "original_file_path": "sql/macros/python/adjust_0.py", "unique_id": "macro.generated_6.adjust_0_round", "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", "depends_on": { @@ -3308,8 +3308,8 @@ "name": "round_amount", "resource_type": "macro", "package_name": "generated_6", - "path": "macros/python/rounding.py", - "original_file_path": "macros/python/rounding.py", + "path": "sql/macros/python/rounding.py", + "original_file_path": "sql/macros/python/rounding.py", "unique_id": "macro.generated_6.round_amount", "macro_sql": "def round_amount(expression: str, places: int = 2) -> str:\n \"\"\"Round an amount.\"\"\"\n return f\"ROUND({expression}, {places})\"\n", "depends_on": { @@ -3332,10 +3332,10 @@ "name": "taxed", "resource_type": "macro", "package_name": "generated_6", - "path": "macros/python/tax.py", - "original_file_path": "macros/python/tax.py", + "path": "sql/macros/python/tax.py", + "original_file_path": "sql/macros/python/tax.py", "unique_id": "macro.generated_6.taxed", - "macro_sql": "from macros.python.rounding import round_amount\n\n\ndef taxed(expression: str) -> str:\n \"\"\"Add tax to an amount, rounded.\"\"\"\n return round_amount(f\"{expression} * 1.2\")\n", + "macro_sql": "from sql.macros.python.rounding import round_amount\n\n\ndef taxed(expression: str) -> str:\n \"\"\"Add tax to an amount, rounded.\"\"\"\n return round_amount(f\"{expression} * 1.2\")\n", "depends_on": { "macros": [ "macro.generated_6.round_amount" @@ -3358,8 +3358,8 @@ "name": "analysis_region", "resource_type": "macro", "package_name": "generated_6", - "path": "models/analysis/_sqlbuild/_macros/python/regions.py", - "original_file_path": "models/analysis/_sqlbuild/_macros/python/regions.py", + "path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", + "original_file_path": "sql/models/analysis/_sqlbuild/_macros/python/regions.py", "unique_id": "macro.generated_6.analysis_region", "macro_sql": "def analysis_region() -> str:\n \"\"\"Return the region rows are assigned to.\"\"\"\n return \"'north'\"\n", "depends_on": { @@ -3368,7 +3368,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/analysis" + "sqlbuild_scope_path": "sql/models/analysis" }, "docs": { "show": true, @@ -3382,8 +3382,8 @@ "name": "adjust_1", "resource_type": "macro", "package_name": "generated_6", - "path": "models/fulfillment/marts/_sqlbuild/_macros/python/adjust_1.py", - "original_file_path": "models/fulfillment/marts/_sqlbuild/_macros/python/adjust_1.py", + "path": "sql/models/fulfillment/marts/_sqlbuild/_macros/python/adjust_1.py", + "original_file_path": "sql/models/fulfillment/marts/_sqlbuild/_macros/python/adjust_1.py", "unique_id": "macro.generated_6.adjust_1", "macro_sql": "import os\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Tag an amount with the deployment region.\"\"\"\n region = os.environ.get(\"SQB_DIFFERENTIAL_REGION\", \"east\")\n return f\"({expression} + LENGTH('{region}'))\"\n", "depends_on": { @@ -3392,7 +3392,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/fulfillment/marts" + "sqlbuild_scope_path": "sql/models/fulfillment/marts" }, "docs": { "show": true, @@ -3430,8 +3430,8 @@ "name": "record_refresh", "resource_type": "macro", "package_name": "generated_6__sqlbuild_hooks", - "path": "hooks/sql/record_refresh.sql", - "original_file_path": "hooks/sql/record_refresh.sql", + "path": "sql/hooks/sql/record_refresh.sql", + "original_file_path": "sql/hooks/sql/record_refresh.sql", "unique_id": "macro.generated_6__sqlbuild_hooks.record_refresh", "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "depends_on": { diff --git a/tests/goldens/compiler/seed/7.json b/tests/goldens/compiler/seed/7.json index 49c77f29b9..2fe681dea0 100644 --- a/tests/goldens/compiler/seed/7.json +++ b/tests/goldens/compiler/seed/7.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Unknown macro '@py.not_a_macro' in '/models/inventory/marts/inventory_summary_0.sql'. Available macros: adjust_0, adjust_1" + "message": "Unknown macro '@py.not_a_macro' in '/sql/models/inventory/marts/inventory_summary_0.sql'. Available macros: adjust_0, adjust_1" } ] }, @@ -20,7 +20,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Unknown macro '@py.not_a_macro' in '/models/inventory/marts/inventory_summary_0.sql'. Available macros: adjust_0, adjust_1" + "message": "Unknown macro '@py.not_a_macro' in '/sql/models/inventory/marts/inventory_summary_0.sql'. Available macros: adjust_0, adjust_1" } ] }, @@ -37,7 +37,7 @@ "Project assembly OK ()", "Project discovery OK ()", "Compiling project...", - "error[P001]: Unknown macro '@py.not_a_macro' in '/models/inventory/marts/inventory_summary_0.sql'. Available macros: adjust_0, adjust_1", + "error[P001]: Unknown macro '@py.not_a_macro' in '/sql/models/inventory/marts/inventory_summary_0.sql'. Available macros: adjust_0, adjust_1", "", "" ] diff --git a/tests/goldens/compiler/seed/8.json b/tests/goldens/compiler/seed/8.json index d7a3421f73..f74c3c77ac 100644 --- a/tests/goldens/compiler/seed/8.json +++ b/tests/goldens/compiler/seed/8.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "MODEL(...) in '/models/support/marts/support_summary_2.sql' contains invalid SQLBuild header syntax: expected key at position 111" + "message": "MODEL(...) in '/sql/models/support/marts/support_summary_2.sql' contains invalid SQLBuild header syntax: expected key at position 111" } ] }, @@ -20,7 +20,7 @@ "phase": "compile", "severity": "error", "code": "D002", - "message": "MODEL(...) in '/models/support/marts/support_summary_2.sql' contains invalid SQLBuild header syntax: expected key at position 111" + "message": "MODEL(...) in '/sql/models/support/marts/support_summary_2.sql' contains invalid SQLBuild header syntax: expected key at position 111" } ] }, @@ -34,7 +34,7 @@ "Declaration parsing FAIL ()", "Project assembly FAIL ()", "Project discovery FAIL ()", - "error[D002]: MODEL(...) in '/models/support/marts/support_summary_2.sql' contains invalid SQLBuild header syntax: expected key at position 111", + "error[D002]: MODEL(...) in '/sql/models/support/marts/support_summary_2.sql' contains invalid SQLBuild header syntax: expected key at position 111", "", "" ] diff --git a/tests/goldens/compiler/seed/9.json b/tests/goldens/compiler/seed/9.json index 34e0a8f891..865a2696b3 100644 --- a/tests/goldens/compiler/seed/9.json +++ b/tests/goldens/compiler/seed/9.json @@ -17,39 +17,39 @@ } ], "compiled": { - "audits/generic/billing_summary_0/not_null__id.sql": [ + "sql/audits/generic/billing_summary_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"billing_summary_0\")", "WHERE id IS NULL", "" ], - "audits/generic/configured_events/accepted_values__id.sql": [ + "sql/audits/generic/configured_events/accepted_values__id.sql": [ "SELECT id", "FROM __source(\"configured_events\")", "WHERE id IS NOT NULL", " AND id NOT IN ('1')", "" ], - "audits/generic/configured_stg_support_1/accepted_values__status.sql": [ + "sql/audits/generic/configured_stg_support_1/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"configured_stg_support_1\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'shipped')", "" ], - "audits/generic/configured_stg_support_1/configured_amount_floor.sql": [ + "sql/audits/generic/configured_stg_support_1/configured_amount_floor.sql": [ "SELECT *", "FROM __ref(\"configured_stg_support_1\")", "WHERE amount < -37", "" ], - "audits/generic/configured_stg_support_1/configured_id_present__id.sql": [ + "sql/audits/generic/configured_stg_support_1/configured_id_present__id.sql": [ "SELECT id", "FROM __ref(\"configured_stg_support_1\")", "WHERE id IS NULL", "" ], - "audits/generic/configured_stg_support_1/unique__id.sql": [ + "sql/audits/generic/configured_stg_support_1/unique__id.sql": [ "SELECT id, COUNT(*) AS duplicate_count", "FROM __ref(\"configured_stg_support_1\")", "WHERE id IS NOT NULL", @@ -57,61 +57,61 @@ "HAVING COUNT(*) > 1", "" ], - "audits/generic/guarded_stg_billing_0/amount_at_least__amount.sql": [ + "sql/audits/generic/guarded_stg_billing_0/amount_at_least__amount.sql": [ "SELECT *", "FROM __ref(\"guarded_stg_billing_0\")", "WHERE amount < 0", "" ], - "audits/generic/labelled_stg_support_1/tidy_status__status.sql": [ + "sql/audits/generic/labelled_stg_support_1/tidy_status__status.sql": [ "SELECT *", "FROM __ref(\"labelled_stg_support_1\")", "WHERE status <> LOWER(TRIM(status))", "" ], - "audits/generic/stated_stg_support_0/accepted_values__status.sql": [ + "sql/audits/generic/stated_stg_support_0/accepted_values__status.sql": [ "SELECT status", "FROM __ref(\"stated_stg_support_0\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/stg_billing_0/not_null__id.sql": [ + "sql/audits/generic/stg_billing_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_billing_0\")", "WHERE id IS NULL", "" ], - "audits/singular/labelled_channels_match.sql": [ + "sql/audits/singular/labelled_channels_match.sql": [ "SELECT l.id", "FROM __ref(\"labelled_stg_support_1\") l", "JOIN __ref(\"channel_labels\") c ON l.id = c.id", "WHERE l.status = c.channel", "" ], - "functions/python/is_large.sql": [ + "sql/functions/python/is_large.sql": [ "REGISTER PYTHON FUNCTION is_large(DOUBLE) RETURNS BOOLEAN", "" ], - "functions/sql/configured_label.sql": [ + "sql/functions/sql/configured_label.sql": [ "CREATE OR REPLACE MACRO ci_checks.configured_label(raw_status) AS (", "UPPER(raw_status)", ")", "" ], - "functions/sql/is_placed.sql": [ + "sql/functions/sql/is_placed.sql": [ "CREATE OR REPLACE MACRO ci_checks.is_placed(event_status) AS (", "event_status = 'placed'", ")", "" ], - "functions/sql/tidy_status.sql": [ + "sql/functions/sql/tidy_status.sql": [ "CREATE OR REPLACE MACRO ci_checks.tidy_status(raw_status) AS (", "LOWER(TRIM(raw_status))", ")", "" ], - "models/analysis/combined_stg_billing_0.sql": [ + "sql/models/analysis/combined_stg_billing_0.sql": [ "WITH recent AS (", " SELECT id, created_at FROM __ref(\"stg_billing_0\") WHERE amount > 0", "),", @@ -123,22 +123,22 @@ "SELECT id, created_at FROM older", "" ], - "models/analysis/every_open_event.sql": [ + "sql/models/analysis/every_open_event.sql": [ "SELECT *", "FROM __source(\"open_events\")", "" ], - "models/analysis/every_raw_events_1.sql": [ + "sql/models/analysis/every_raw_events_1.sql": [ "SELECT *", "FROM __source(\"raw_events_1\")", "" ], - "models/analysis/every_stg_billing_0.sql": [ + "sql/models/analysis/every_stg_billing_0.sql": [ "SELECT *", "FROM __ref(\"stg_billing_0\")", "" ], - "models/analysis/passed_stg_billing_0.sql": [ + "sql/models/analysis/passed_stg_billing_0.sql": [ "WITH passthrough AS (", " SELECT id, created_at FROM __ref(\"stg_billing_0\")", ")", @@ -146,36 +146,36 @@ "FROM passthrough", "" ], - "models/analysis/pivot_input_stg_support_0.sql": [ + "sql/models/analysis/pivot_input_stg_support_0.sql": [ "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR) AS status, amount", "FROM __ref(\"stg_support_0\")", "" ], - "models/analysis/pivoted_stg_support_0.sql": [ + "sql/models/analysis/pivoted_stg_support_0.sql": [ "PIVOT __ref(\"pivot_input_stg_support_0\")", "ON status", "USING MAX(amount)", "GROUP BY id", "" ], - "models/analysis/quoted_stg_support_0.sql": [ + "sql/models/analysis/quoted_stg_support_0.sql": [ "SELECT \"ID\" AS \"OrderKey\", \"Amount\", \"Status\" AS \"Status\"", "FROM __ref(\"stg_support_0\")", "" ], - "models/analysis/typed_stg_billing_0.sql": [ + "sql/models/analysis/typed_stg_billing_0.sql": [ "SELECT id, amount * 2 AS doubled_amount, CAST(status AS VARCHAR) AS status_text,", " created_at, NULL AS missing_note", "FROM __ref(\"stg_billing_0\")", "" ], - "models/analysis/unanalysed_stg_support_1.sql": [ + "sql/models/analysis/unanalysed_stg_support_1.sql": [ "SELECT a.id, a.amount", "FROM __ref(\"stg_support_1\") AS a", "JOIN __ref(\"stg_support_1\") AS b NEAREST 1 BY DISTANCE abs(a.amount - b.amount)", "" ], - "models/billing/marts/billing_summary_0.sql": [ + "sql/models/billing/marts/billing_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -186,7 +186,7 @@ "WHERE t.status <> 'placed'", "" ], - "models/billing/staging/stg_billing_0.sql": [ + "sql/models/billing/staging/stg_billing_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -197,46 +197,46 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/features/append_stg_support_0.sql": [ + "sql/models/features/append_stg_support_0.sql": [ "SELECT id, amount, status, created_at", "FROM __ref(\"stg_support_0\")", "" ], - "models/features/batched_rolling_window_stg_support_1.sql": [ + "sql/models/features/batched_rolling_window_stg_support_1.sql": [ "SELECT CAST(created_at AS DATE) AS created_at, SUM(amount) AS amount", "FROM __ref(\"stg_support_1\")", "GROUP BY CAST(created_at AS DATE)", "" ], - "models/features/delete_insert_stg_billing_0.sql": [ + "sql/models/features/delete_insert_stg_billing_0.sql": [ "SELECT id, amount, status, created_at", "FROM __ref(\"stg_billing_0\")", "" ], - "models/features/flagged_stg_billing_0.sql": [ + "sql/models/features/flagged_stg_billing_0.sql": [ "SELECT id, __udf(\"is_placed\")(status) AS is_placed,", " __udf(\"is_large\")(amount) AS is_large", "FROM __ref(\"stg_billing_0\")", "" ], - "models/features/guarded_stg_billing_0.sql": [ + "sql/models/features/guarded_stg_billing_0.sql": [ "SELECT id, amount", "FROM __ref(\"stg_billing_0\")", "" ], - "models/features/kept_stg_support_1.sql": [ + "sql/models/features/kept_stg_support_1.sql": [ "SELECT id, status, amount * 0.5 AS weighted", "FROM __ref(\"stg_support_1\")", "WHERE status IN ('取消', 'placed')", " AND amount * 1.0 IN (0.5, 1.25, 2500.75) OR id > 0", "" ], - "models/features/product_labels.sql": [ + "sql/models/features/product_labels.sql": [ "SELECT id, label", "FROM __source(\"loaded_products\")", "" ], - "models/features/spaced_stg_support_0.sql": [ + "sql/models/features/spaced_stg_support_0.sql": [ "-- Généré pour café ☕ counter", "SELECT", "\tid,", @@ -245,40 +245,40 @@ "FROM __ref(\"stg_support_0\")", "" ], - "models/features/timestamp_history_stg_support_1.sql": [ + "sql/models/features/timestamp_history_stg_support_1.sql": [ "SELECT id, status, created_at", "FROM __ref(\"stg_support_1\")", "" ], - "models/rendering/channel_labels.sql": [ + "sql/models/rendering/channel_labels.sql": [ "SELECT id, channel", "FROM __source(\"labelled_channels\")", "" ], - "models/rendering/configured_stg_support_1.sql": [ + "sql/models/rendering/configured_stg_support_1.sql": [ "SELECT id, amount, status", "FROM __ref(\"stg_support_1\")", "" ], - "models/rendering/labelled_stg_support_1.sql": [ + "sql/models/rendering/labelled_stg_support_1.sql": [ "SELECT id, LOWER(TRIM(status)) AS status,", " __udf(\"tidy_status\")(status) AS tidied", "FROM __ref(\"stg_support_1\")", "" ], - "models/rendering/legacy_event_ids.sql": [ + "sql/models/rendering/legacy_event_ids.sql": [ "SELECT id", "FROM __ref(\"stg_support_0\") AS legacy", "" ], - "models/rendering/stated_stg_support_0.sql": [ + "sql/models/rendering/stated_stg_support_0.sql": [ "SELECT CAST(id AS INTEGER) AS id, status,", " CASE WHEN amount >= 2 THEN 'HIGH'", " ELSE 'LOW' END AS tier", "FROM __ref(\"stg_support_0\")", "" ], - "models/support/marts/support_summary_0.sql": [ + "sql/models/support/marts/support_summary_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -288,7 +288,7 @@ "FROM __ref(\"stg_support_0\") t", "" ], - "models/support/staging/stg_support_0.sql": [ + "sql/models/support/staging/stg_support_0.sql": [ "SELECT", " t.id,", " t.amount,", @@ -299,7 +299,7 @@ "FROM __source(\"raw_events_0\") t", "" ], - "models/support/staging/stg_support_1.sql": [ + "sql/models/support/staging/stg_support_1.sql": [ "SELECT", " t.id,", " t.amount,", @@ -397,8 +397,8 @@ "name": "combined_stg_billing_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/combined_stg_billing_0.sql", - "original_file_path": "models/analysis/combined_stg_billing_0.sql", + "path": "sql/models/analysis/combined_stg_billing_0.sql", + "original_file_path": "sql/models/analysis/combined_stg_billing_0.sql", "unique_id": "model.generated_9.combined_stg_billing_0", "fqn": [ "generated_9", @@ -467,8 +467,8 @@ "name": "every_open_event", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/every_open_event.sql", - "original_file_path": "models/analysis/every_open_event.sql", + "path": "sql/models/analysis/every_open_event.sql", + "original_file_path": "sql/models/analysis/every_open_event.sql", "unique_id": "model.generated_9.every_open_event", "fqn": [ "generated_9", @@ -536,8 +536,8 @@ "name": "every_raw_events_1", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/every_raw_events_1.sql", - "original_file_path": "models/analysis/every_raw_events_1.sql", + "path": "sql/models/analysis/every_raw_events_1.sql", + "original_file_path": "sql/models/analysis/every_raw_events_1.sql", "unique_id": "model.generated_9.every_raw_events_1", "fqn": [ "generated_9", @@ -605,8 +605,8 @@ "name": "every_stg_billing_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/every_stg_billing_0.sql", - "original_file_path": "models/analysis/every_stg_billing_0.sql", + "path": "sql/models/analysis/every_stg_billing_0.sql", + "original_file_path": "sql/models/analysis/every_stg_billing_0.sql", "unique_id": "model.generated_9.every_stg_billing_0", "fqn": [ "generated_9", @@ -674,8 +674,8 @@ "name": "passed_stg_billing_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/passed_stg_billing_0.sql", - "original_file_path": "models/analysis/passed_stg_billing_0.sql", + "path": "sql/models/analysis/passed_stg_billing_0.sql", + "original_file_path": "sql/models/analysis/passed_stg_billing_0.sql", "unique_id": "model.generated_9.passed_stg_billing_0", "fqn": [ "generated_9", @@ -743,8 +743,8 @@ "name": "pivot_input_stg_support_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/pivot_input_stg_support_0.sql", - "original_file_path": "models/analysis/pivot_input_stg_support_0.sql", + "path": "sql/models/analysis/pivot_input_stg_support_0.sql", + "original_file_path": "sql/models/analysis/pivot_input_stg_support_0.sql", "unique_id": "model.generated_9.pivot_input_stg_support_0", "fqn": [ "generated_9", @@ -840,8 +840,8 @@ "name": "pivoted_stg_support_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/pivoted_stg_support_0.sql", - "original_file_path": "models/analysis/pivoted_stg_support_0.sql", + "path": "sql/models/analysis/pivoted_stg_support_0.sql", + "original_file_path": "sql/models/analysis/pivoted_stg_support_0.sql", "unique_id": "model.generated_9.pivoted_stg_support_0", "fqn": [ "generated_9", @@ -932,8 +932,8 @@ "name": "quoted_stg_support_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/quoted_stg_support_0.sql", - "original_file_path": "models/analysis/quoted_stg_support_0.sql", + "path": "sql/models/analysis/quoted_stg_support_0.sql", + "original_file_path": "sql/models/analysis/quoted_stg_support_0.sql", "unique_id": "model.generated_9.quoted_stg_support_0", "fqn": [ "generated_9", @@ -1001,8 +1001,8 @@ "name": "typed_stg_billing_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/typed_stg_billing_0.sql", - "original_file_path": "models/analysis/typed_stg_billing_0.sql", + "path": "sql/models/analysis/typed_stg_billing_0.sql", + "original_file_path": "sql/models/analysis/typed_stg_billing_0.sql", "unique_id": "model.generated_9.typed_stg_billing_0", "fqn": [ "generated_9", @@ -1070,8 +1070,8 @@ "name": "unanalysed_stg_support_1", "resource_type": "model", "package_name": "generated_9", - "path": "models/analysis/unanalysed_stg_support_1.sql", - "original_file_path": "models/analysis/unanalysed_stg_support_1.sql", + "path": "sql/models/analysis/unanalysed_stg_support_1.sql", + "original_file_path": "sql/models/analysis/unanalysed_stg_support_1.sql", "unique_id": "model.generated_9.unanalysed_stg_support_1", "fqn": [ "generated_9", @@ -1139,8 +1139,8 @@ "name": "billing_summary_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/billing/marts/billing_summary_0.sql", - "original_file_path": "models/billing/marts/billing_summary_0.sql", + "path": "sql/models/billing/marts/billing_summary_0.sql", + "original_file_path": "sql/models/billing/marts/billing_summary_0.sql", "unique_id": "model.generated_9.billing_summary_0", "fqn": [ "generated_9", @@ -1219,8 +1219,8 @@ "name": "stg_billing_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/billing/staging/stg_billing_0.sql", - "original_file_path": "models/billing/staging/stg_billing_0.sql", + "path": "sql/models/billing/staging/stg_billing_0.sql", + "original_file_path": "sql/models/billing/staging/stg_billing_0.sql", "unique_id": "model.generated_9.stg_billing_0", "fqn": [ "generated_9", @@ -1303,8 +1303,8 @@ "name": "append_stg_support_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/features/append_stg_support_0.sql", - "original_file_path": "models/features/append_stg_support_0.sql", + "path": "sql/models/features/append_stg_support_0.sql", + "original_file_path": "sql/models/features/append_stg_support_0.sql", "unique_id": "model.generated_9.append_stg_support_0", "fqn": [ "generated_9", @@ -1372,8 +1372,8 @@ "name": "batched_rolling_window_stg_support_1", "resource_type": "model", "package_name": "generated_9", - "path": "models/features/batched_rolling_window_stg_support_1.sql", - "original_file_path": "models/features/batched_rolling_window_stg_support_1.sql", + "path": "sql/models/features/batched_rolling_window_stg_support_1.sql", + "original_file_path": "sql/models/features/batched_rolling_window_stg_support_1.sql", "unique_id": "model.generated_9.batched_rolling_window_stg_support_1", "fqn": [ "generated_9", @@ -1441,8 +1441,8 @@ "name": "delete_insert_stg_billing_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/features/delete_insert_stg_billing_0.sql", - "original_file_path": "models/features/delete_insert_stg_billing_0.sql", + "path": "sql/models/features/delete_insert_stg_billing_0.sql", + "original_file_path": "sql/models/features/delete_insert_stg_billing_0.sql", "unique_id": "model.generated_9.delete_insert_stg_billing_0", "fqn": [ "generated_9", @@ -1512,8 +1512,8 @@ "name": "flagged_stg_billing_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/features/flagged_stg_billing_0.sql", - "original_file_path": "models/features/flagged_stg_billing_0.sql", + "path": "sql/models/features/flagged_stg_billing_0.sql", + "original_file_path": "sql/models/features/flagged_stg_billing_0.sql", "unique_id": "model.generated_9.flagged_stg_billing_0", "fqn": [ "generated_9", @@ -1583,8 +1583,8 @@ "name": "guarded_stg_billing_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/features/guarded_stg_billing_0.sql", - "original_file_path": "models/features/guarded_stg_billing_0.sql", + "path": "sql/models/features/guarded_stg_billing_0.sql", + "original_file_path": "sql/models/features/guarded_stg_billing_0.sql", "unique_id": "model.generated_9.guarded_stg_billing_0", "fqn": [ "generated_9", @@ -1662,8 +1662,8 @@ "name": "kept_stg_support_1", "resource_type": "model", "package_name": "generated_9", - "path": "models/features/kept_stg_support_1.sql", - "original_file_path": "models/features/kept_stg_support_1.sql", + "path": "sql/models/features/kept_stg_support_1.sql", + "original_file_path": "sql/models/features/kept_stg_support_1.sql", "unique_id": "model.generated_9.kept_stg_support_1", "fqn": [ "generated_9", @@ -1731,8 +1731,8 @@ "name": "product_labels", "resource_type": "model", "package_name": "generated_9", - "path": "models/features/product_labels.sql", - "original_file_path": "models/features/product_labels.sql", + "path": "sql/models/features/product_labels.sql", + "original_file_path": "sql/models/features/product_labels.sql", "unique_id": "model.generated_9.product_labels", "fqn": [ "generated_9", @@ -1800,8 +1800,8 @@ "name": "spaced_stg_support_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/features/spaced_stg_support_0.sql", - "original_file_path": "models/features/spaced_stg_support_0.sql", + "path": "sql/models/features/spaced_stg_support_0.sql", + "original_file_path": "sql/models/features/spaced_stg_support_0.sql", "unique_id": "model.generated_9.spaced_stg_support_0", "fqn": [ "generated_9", @@ -1875,8 +1875,8 @@ "name": "timestamp_history_stg_support_1", "resource_type": "model", "package_name": "generated_9", - "path": "models/features/timestamp_history_stg_support_1.sql", - "original_file_path": "models/features/timestamp_history_stg_support_1.sql", + "path": "sql/models/features/timestamp_history_stg_support_1.sql", + "original_file_path": "sql/models/features/timestamp_history_stg_support_1.sql", "unique_id": "model.generated_9.timestamp_history_stg_support_1", "fqn": [ "generated_9", @@ -1946,8 +1946,8 @@ "name": "channel_labels", "resource_type": "model", "package_name": "generated_9", - "path": "models/rendering/channel_labels.sql", - "original_file_path": "models/rendering/channel_labels.sql", + "path": "sql/models/rendering/channel_labels.sql", + "original_file_path": "sql/models/rendering/channel_labels.sql", "unique_id": "model.generated_9.channel_labels", "fqn": [ "generated_9", @@ -2015,8 +2015,8 @@ "name": "configured_stg_support_1", "resource_type": "model", "package_name": "generated_9", - "path": "models/rendering/configured_stg_support_1.sql", - "original_file_path": "models/rendering/configured_stg_support_1.sql", + "path": "sql/models/rendering/configured_stg_support_1.sql", + "original_file_path": "sql/models/rendering/configured_stg_support_1.sql", "unique_id": "model.generated_9.configured_stg_support_1", "fqn": [ "generated_9", @@ -2116,8 +2116,8 @@ "name": "labelled_stg_support_1", "resource_type": "model", "package_name": "generated_9", - "path": "models/rendering/labelled_stg_support_1.sql", - "original_file_path": "models/rendering/labelled_stg_support_1.sql", + "path": "sql/models/rendering/labelled_stg_support_1.sql", + "original_file_path": "sql/models/rendering/labelled_stg_support_1.sql", "unique_id": "model.generated_9.labelled_stg_support_1", "fqn": [ "generated_9", @@ -2196,8 +2196,8 @@ "name": "legacy_event_ids", "resource_type": "model", "package_name": "generated_9", - "path": "models/rendering/legacy_event_ids.sql", - "original_file_path": "models/rendering/legacy_event_ids.sql", + "path": "sql/models/rendering/legacy_event_ids.sql", + "original_file_path": "sql/models/rendering/legacy_event_ids.sql", "unique_id": "model.generated_9.legacy_event_ids", "fqn": [ "generated_9", @@ -2265,8 +2265,8 @@ "name": "stated_stg_support_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/rendering/stated_stg_support_0.sql", - "original_file_path": "models/rendering/stated_stg_support_0.sql", + "path": "sql/models/rendering/stated_stg_support_0.sql", + "original_file_path": "sql/models/rendering/stated_stg_support_0.sql", "unique_id": "model.generated_9.stated_stg_support_0", "fqn": [ "generated_9", @@ -2362,8 +2362,8 @@ "name": "support_summary_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/support/marts/support_summary_0.sql", - "original_file_path": "models/support/marts/support_summary_0.sql", + "path": "sql/models/support/marts/support_summary_0.sql", + "original_file_path": "sql/models/support/marts/support_summary_0.sql", "unique_id": "model.generated_9.support_summary_0", "fqn": [ "generated_9", @@ -2432,7 +2432,7 @@ "type": "sql", "statement": "SELECT 'ci_checks.support_summary_0' AS refreshed_relation, 'café ☕ counter' AS refresh_label", "name": "record_refresh", - "relative_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "relative_path": "sql/models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2472,8 +2472,8 @@ "name": "stg_support_0", "resource_type": "model", "package_name": "generated_9", - "path": "models/support/staging/stg_support_0.sql", - "original_file_path": "models/support/staging/stg_support_0.sql", + "path": "sql/models/support/staging/stg_support_0.sql", + "original_file_path": "sql/models/support/staging/stg_support_0.sql", "unique_id": "model.generated_9.stg_support_0", "fqn": [ "generated_9", @@ -2546,8 +2546,8 @@ "name": "stg_support_1", "resource_type": "model", "package_name": "generated_9", - "path": "models/support/staging/stg_support_1.sql", - "original_file_path": "models/support/staging/stg_support_1.sql", + "path": "sql/models/support/staging/stg_support_1.sql", + "original_file_path": "sql/models/support/staging/stg_support_1.sql", "unique_id": "model.generated_9.stg_support_1", "fqn": [ "generated_9", @@ -2622,8 +2622,8 @@ "name": "configured_events", "resource_type": "source", "package_name": "generated_9", - "path": "sources/configured.yml", - "original_file_path": "sources/configured.yml", + "path": "sql/sources/configured.yml", + "original_file_path": "sql/sources/configured.yml", "unique_id": "source.generated_9.configured_events", "fqn": [ "generated_9", @@ -2674,8 +2674,8 @@ "name": "labelled_channels", "resource_type": "source", "package_name": "generated_9", - "path": "sources/labelled.yml", - "original_file_path": "sources/labelled.yml", + "path": "sql/sources/labelled.yml", + "original_file_path": "sql/sources/labelled.yml", "unique_id": "source.generated_9.labelled_channels", "fqn": [ "generated_9", @@ -2724,8 +2724,8 @@ "name": "loaded_products", "resource_type": "source", "package_name": "generated_9", - "path": "sources/managed.yml", - "original_file_path": "sources/managed.yml", + "path": "sql/sources/managed.yml", + "original_file_path": "sql/sources/managed.yml", "unique_id": "source.generated_9.loaded_products", "fqn": [ "generated_9", @@ -2780,8 +2780,8 @@ "name": "open_events", "resource_type": "source", "package_name": "generated_9", - "path": "sources/open.yml", - "original_file_path": "sources/open.yml", + "path": "sql/sources/open.yml", + "original_file_path": "sql/sources/open.yml", "unique_id": "source.generated_9.open_events", "fqn": [ "generated_9", @@ -2811,8 +2811,8 @@ "name": "raw_events_0", "resource_type": "source", "package_name": "generated_9", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_9.raw_events_0", "fqn": [ "generated_9", @@ -2879,8 +2879,8 @@ "name": "raw_events_1", "resource_type": "source", "package_name": "generated_9", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", + "path": "sql/sources/raw.yml", + "original_file_path": "sql/sources/raw.yml", "unique_id": "source.generated_9.raw_events_1", "fqn": [ "generated_9", @@ -2947,8 +2947,8 @@ "name": "adjust_0", "resource_type": "macro", "package_name": "generated_9", - "path": "macros/python/adjust_0.py", - "original_file_path": "macros/python/adjust_0.py", + "path": "sql/macros/python/adjust_0.py", + "original_file_path": "sql/macros/python/adjust_0.py", "unique_id": "macro.generated_9.adjust_0", "macro_sql": "def adjust_0(expression: str) -> str:\n \"\"\"Offset an amount.\"\"\"\n return f\"({expression} + 0 + 1)\"\n", "depends_on": { @@ -2971,8 +2971,8 @@ "name": "tidy_label", "resource_type": "macro", "package_name": "generated_9", - "path": "macros/python/labels.py", - "original_file_path": "macros/python/labels.py", + "path": "sql/macros/python/labels.py", + "original_file_path": "sql/macros/python/labels.py", "unique_id": "macro.generated_9.tidy_label", "macro_sql": "def tidy_label(expression: str) -> str:\n \"\"\"Trim and lower-case a label.\"\"\"\n return f\"LOWER(TRIM({expression}))\"\n", "depends_on": { @@ -2995,8 +2995,8 @@ "name": "legacy_events", "resource_type": "macro", "package_name": "generated_9", - "path": "models/rendering/_sqlbuild/_macros/python/legacy.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/legacy.py", + "path": "sql/models/rendering/_sqlbuild/_macros/python/legacy.py", + "original_file_path": "sql/models/rendering/_sqlbuild/_macros/python/legacy.py", "unique_id": "macro.generated_9.legacy_events", "macro_sql": "def legacy_events() -> str:\n \"\"\"Return a staged relation the way a migrated project wrote it.\"\"\"\n return '__ref(\"stg_support_0\")'\n", "depends_on": { @@ -3005,7 +3005,7 @@ "description": "", "meta": { "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" + "sqlbuild_scope_path": "sql/models/rendering" }, "docs": { "show": true, @@ -3043,8 +3043,8 @@ "name": "record_refresh", "resource_type": "macro", "package_name": "generated_9__sqlbuild_hooks", - "path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "original_file_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "path": "sql/models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "original_file_path": "sql/models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "unique_id": "macro.generated_9__sqlbuild_hooks.record_refresh", "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "depends_on": { diff --git a/tests/goldens/python_oracle/contracts_generated_enforced_implicit_typed_nullability_and_dynamic_contracts.json b/tests/goldens/python_oracle/contracts_generated_enforced_implicit_typed_nullability_and_dynamic_contracts.json index d87c26b267..b3b57be753 100644 --- a/tests/goldens/python_oracle/contracts_generated_enforced_implicit_typed_nullability_and_dynamic_contracts.json +++ b/tests/goldens/python_oracle/contracts_generated_enforced_implicit_typed_nullability_and_dynamic_contracts.json @@ -2,25 +2,25 @@ [ "contracts", { -"None": "4468a1d48f518ca4b4400c5c", -"duckdb": "fb8ce81c5da3b37b19f0ea97", -"postgres": "fb8ce81c5da3b37b19f0ea97", -"snowflake": "fb8ce81c5da3b37b19f0ea97", -"bigquery": "4468a1d48f518ca4b4400c5c", -"databricks": "4468a1d48f518ca4b4400c5c", -"tsql": "4468a1d48f518ca4b4400c5c" +"None": "bfb35286b9400df276a98892", +"duckdb": "48c2434e72cc09301c026004", +"postgres": "48c2434e72cc09301c026004", +"snowflake": "48c2434e72cc09301c026004", +"bigquery": "bfb35286b9400df276a98892", +"databricks": "bfb35286b9400df276a98892", +"tsql": "bfb35286b9400df276a98892" } ], [ "contracts", { -"None": "e298b23cdc712b436ba9140b", -"duckdb": "e298b23cdc712b436ba9140b", -"postgres": "e298b23cdc712b436ba9140b", -"snowflake": "e298b23cdc712b436ba9140b", -"bigquery": "e298b23cdc712b436ba9140b", -"databricks": "e298b23cdc712b436ba9140b", -"tsql": "e298b23cdc712b436ba9140b" +"None": "f686d42da3b98a1e88c866d9", +"duckdb": "f686d42da3b98a1e88c866d9", +"postgres": "f686d42da3b98a1e88c866d9", +"snowflake": "f686d42da3b98a1e88c866d9", +"bigquery": "f686d42da3b98a1e88c866d9", +"databricks": "f686d42da3b98a1e88c866d9", +"tsql": "f686d42da3b98a1e88c866d9" } ], [ @@ -38,13 +38,13 @@ [ "contracts", { -"None": "b1e12cf6dc9584935dabf76a", -"duckdb": "b1e12cf6dc9584935dabf76a", -"postgres": "b1e12cf6dc9584935dabf76a", -"snowflake": "b1e12cf6dc9584935dabf76a", -"bigquery": "b1e12cf6dc9584935dabf76a", -"databricks": "b1e12cf6dc9584935dabf76a", -"tsql": "b1e12cf6dc9584935dabf76a" +"None": "a548672e51b7b6f2a77ad840", +"duckdb": "a548672e51b7b6f2a77ad840", +"postgres": "a548672e51b7b6f2a77ad840", +"snowflake": "a548672e51b7b6f2a77ad840", +"bigquery": "a548672e51b7b6f2a77ad840", +"databricks": "a548672e51b7b6f2a77ad840", +"tsql": "a548672e51b7b6f2a77ad840" } ], [ @@ -62,73 +62,73 @@ [ "contracts", { -"None": "2ea2c17632881c11f524f96c", -"duckdb": "2ea2c17632881c11f524f96c", -"postgres": "2ea2c17632881c11f524f96c", -"snowflake": "2ea2c17632881c11f524f96c", -"bigquery": "2ea2c17632881c11f524f96c", -"databricks": "2ea2c17632881c11f524f96c", -"tsql": "2ea2c17632881c11f524f96c" +"None": "da5804dd4b890175f7253eed", +"duckdb": "da5804dd4b890175f7253eed", +"postgres": "da5804dd4b890175f7253eed", +"snowflake": "da5804dd4b890175f7253eed", +"bigquery": "da5804dd4b890175f7253eed", +"databricks": "da5804dd4b890175f7253eed", +"tsql": "da5804dd4b890175f7253eed" } ], [ "contracts", { -"None": "1c392cf2d73a90f3c80dad28", -"duckdb": "e18a4843a99d4d6b392e62e6", -"postgres": "e18a4843a99d4d6b392e62e6", -"snowflake": "e18a4843a99d4d6b392e62e6", -"bigquery": "1c392cf2d73a90f3c80dad28", -"databricks": "ef256ae041280e749a74f413", -"tsql": "ef256ae041280e749a74f413" +"None": "db517d74194dcae0fc24ab26", +"duckdb": "9c65edf54a252c2cc1944a0a", +"postgres": "9c65edf54a252c2cc1944a0a", +"snowflake": "9c65edf54a252c2cc1944a0a", +"bigquery": "db517d74194dcae0fc24ab26", +"databricks": "14646423458314d0547d59d0", +"tsql": "14646423458314d0547d59d0" } ], [ "contracts", { -"None": "46295ba50f2cde3366f7b416", -"duckdb": "108a218293b3667249e9dd19", -"postgres": "108a218293b3667249e9dd19", -"snowflake": "108a218293b3667249e9dd19", -"bigquery": "108a218293b3667249e9dd19", -"databricks": "46295ba50f2cde3366f7b416", -"tsql": "108a218293b3667249e9dd19" +"None": "a90672771363290fbf9863fb", +"duckdb": "2694180ffe7e63c5a878c7a8", +"postgres": "2694180ffe7e63c5a878c7a8", +"snowflake": "2694180ffe7e63c5a878c7a8", +"bigquery": "2694180ffe7e63c5a878c7a8", +"databricks": "a90672771363290fbf9863fb", +"tsql": "2694180ffe7e63c5a878c7a8" } ], [ "contracts", { -"None": "146e877ec8ad652843abfb41", -"duckdb": "146e877ec8ad652843abfb41", -"postgres": "146e877ec8ad652843abfb41", -"snowflake": "146e877ec8ad652843abfb41", -"bigquery": "146e877ec8ad652843abfb41", -"databricks": "146e877ec8ad652843abfb41", -"tsql": "146e877ec8ad652843abfb41" +"None": "264a978e0272e3e93b169930", +"duckdb": "264a978e0272e3e93b169930", +"postgres": "264a978e0272e3e93b169930", +"snowflake": "264a978e0272e3e93b169930", +"bigquery": "264a978e0272e3e93b169930", +"databricks": "264a978e0272e3e93b169930", +"tsql": "264a978e0272e3e93b169930" } ], [ "contracts", { -"None": "ea50942f07e35c23101a6e90", -"duckdb": "839434d5b73abdf9499ad59e", -"postgres": "839434d5b73abdf9499ad59e", -"snowflake": "013b57a3487bfc47b4ea1985", -"bigquery": "93171de36b7cdbf8cb98f4f9", -"databricks": "93171de36b7cdbf8cb98f4f9", -"tsql": "93171de36b7cdbf8cb98f4f9" +"None": "6fd2e8d599d2023478cc7ab0", +"duckdb": "23c5e134655cca2918e80794", +"postgres": "23c5e134655cca2918e80794", +"snowflake": "4587991d3476dc996af7dd9c", +"bigquery": "5c59db6158178c926ec24097", +"databricks": "5c59db6158178c926ec24097", +"tsql": "5c59db6158178c926ec24097" } ], [ "contracts", { -"None": "05d66700d24bbf96856e543f", -"duckdb": "ab9b0c5c3dd6f54aea71a5f1", -"postgres": "ab9b0c5c3dd6f54aea71a5f1", -"snowflake": "ab9b0c5c3dd6f54aea71a5f1", -"bigquery": "304a4034b8020f8712de3185", -"databricks": "05d66700d24bbf96856e543f", -"tsql": "304a4034b8020f8712de3185" +"None": "83c9beefa6a505463a85664c", +"duckdb": "49b2390989f477c6cca28e95", +"postgres": "49b2390989f477c6cca28e95", +"snowflake": "49b2390989f477c6cca28e95", +"bigquery": "4a4cdeb90a68cc3e05c46155", +"databricks": "83c9beefa6a505463a85664c", +"tsql": "4a4cdeb90a68cc3e05c46155" } ], [ @@ -147,84 +147,84 @@ "contracts", { "None": "8bcca84f9b1f7524d977d096", -"duckdb": "f5caf46b08c258cc0379d7f0", -"postgres": "f5caf46b08c258cc0379d7f0", -"snowflake": "f5caf46b08c258cc0379d7f0", -"bigquery": "a932012ddaf72dbb7a5600e1", -"databricks": "3fbfd492b77ec7500f792854", -"tsql": "a932012ddaf72dbb7a5600e1" +"duckdb": "846eeb8d235cdf5e7059b6ad", +"postgres": "846eeb8d235cdf5e7059b6ad", +"snowflake": "846eeb8d235cdf5e7059b6ad", +"bigquery": "c2d8bc4dd54fc1ac5d768333", +"databricks": "c73b1778238b3699ef0e5552", +"tsql": "c2d8bc4dd54fc1ac5d768333" } ], [ "contracts", { -"None": "56b5543509d06fb1c21041d1", -"duckdb": "a0b8e7d3875bf00e35b31b3a", -"postgres": "a0b8e7d3875bf00e35b31b3a", -"snowflake": "a0b8e7d3875bf00e35b31b3a", -"bigquery": "56b5543509d06fb1c21041d1", -"databricks": "56b5543509d06fb1c21041d1", -"tsql": "432f00f3da7c20ccd3f577b8" +"None": "27cbfaef810f1f30999b249f", +"duckdb": "95ef5fc6f2896da1c165b799", +"postgres": "95ef5fc6f2896da1c165b799", +"snowflake": "95ef5fc6f2896da1c165b799", +"bigquery": "27cbfaef810f1f30999b249f", +"databricks": "27cbfaef810f1f30999b249f", +"tsql": "4abc44fc54f2a49a79ffb297" } ], [ "contracts", { -"None": "b079fa87ec3327c35e724edc", -"duckdb": "c332cbe9d45bff687e91f93b", -"postgres": "c332cbe9d45bff687e91f93b", -"snowflake": "c332cbe9d45bff687e91f93b", -"bigquery": "c332cbe9d45bff687e91f93b", -"databricks": "b079fa87ec3327c35e724edc", -"tsql": "b079fa87ec3327c35e724edc" +"None": "0eacd580520f0775086967f7", +"duckdb": "c28e1b8af403703e2f66b91f", +"postgres": "c28e1b8af403703e2f66b91f", +"snowflake": "c28e1b8af403703e2f66b91f", +"bigquery": "c28e1b8af403703e2f66b91f", +"databricks": "0eacd580520f0775086967f7", +"tsql": "0eacd580520f0775086967f7" } ], [ "contracts", { -"None": "5a5871fa04d9a20d7711baf0", -"duckdb": "d321e9f172844d14d14f673b", -"postgres": "d321e9f172844d14d14f673b", -"snowflake": "d321e9f172844d14d14f673b", -"bigquery": "5a5871fa04d9a20d7711baf0", -"databricks": "d321e9f172844d14d14f673b", -"tsql": "d321e9f172844d14d14f673b" +"None": "1c340d903866f2dcc018e289", +"duckdb": "56dc6a5d03afedaec1491e79", +"postgres": "56dc6a5d03afedaec1491e79", +"snowflake": "56dc6a5d03afedaec1491e79", +"bigquery": "1c340d903866f2dcc018e289", +"databricks": "56dc6a5d03afedaec1491e79", +"tsql": "56dc6a5d03afedaec1491e79" } ], [ "contracts", { -"None": "fcab746844cd91fb6013c212", -"duckdb": "c977930632cd22e603ff63c5", -"postgres": "c977930632cd22e603ff63c5", -"snowflake": "c977930632cd22e603ff63c5", -"bigquery": "c977930632cd22e603ff63c5", -"databricks": "688b71a51fef751ef9030e7f", -"tsql": "c977930632cd22e603ff63c5" +"None": "9a5d1edb8106c2248d1d82d9", +"duckdb": "9cb09bc77b215ed90829ddb0", +"postgres": "9cb09bc77b215ed90829ddb0", +"snowflake": "9cb09bc77b215ed90829ddb0", +"bigquery": "9cb09bc77b215ed90829ddb0", +"databricks": "3f1f75a9cc0941fdf9b3e549", +"tsql": "9cb09bc77b215ed90829ddb0" } ], [ "contracts", { -"None": "b9d3101365e641510618cd78", -"duckdb": "28f367dbe9edd587d885c1b0", -"postgres": "28f367dbe9edd587d885c1b0", -"snowflake": "28f367dbe9edd587d885c1b0", -"bigquery": "c5a75f9cfcaa4e7fab58ab34", -"databricks": "c5a75f9cfcaa4e7fab58ab34", -"tsql": "c5a75f9cfcaa4e7fab58ab34" +"None": "77fef1d1a0b23f6fad000a51", +"duckdb": "505c8117a1a80aa69d1d1104", +"postgres": "505c8117a1a80aa69d1d1104", +"snowflake": "505c8117a1a80aa69d1d1104", +"bigquery": "446fb44001796d492729066e", +"databricks": "446fb44001796d492729066e", +"tsql": "446fb44001796d492729066e" } ], [ "contracts", { "None": "346a296ad1a69553ae2e11a1", -"duckdb": "98b119ddd61340fcdf4830fb", -"postgres": "98b119ddd61340fcdf4830fb", -"snowflake": "98b119ddd61340fcdf4830fb", -"bigquery": "98b119ddd61340fcdf4830fb", +"duckdb": "d59003c9e4535fbd58137aa3", +"postgres": "d59003c9e4535fbd58137aa3", +"snowflake": "d59003c9e4535fbd58137aa3", +"bigquery": "d59003c9e4535fbd58137aa3", "databricks": "346a296ad1a69553ae2e11a1", -"tsql": "98b119ddd61340fcdf4830fb" +"tsql": "d59003c9e4535fbd58137aa3" } ], [ @@ -254,13 +254,13 @@ [ "contracts", { -"None": "905364c274a12a2c2babf099", -"duckdb": "869e1c4232a27a6852792cc2", -"postgres": "869e1c4232a27a6852792cc2", -"snowflake": "869e1c4232a27a6852792cc2", -"bigquery": "a0c38fc940179b1197e2d11d", -"databricks": "905364c274a12a2c2babf099", -"tsql": "1f41fb19621270965d677570" +"None": "c61d78463df42b7187c212de", +"duckdb": "36c48738475fcf20b2a7caf2", +"postgres": "36c48738475fcf20b2a7caf2", +"snowflake": "36c48738475fcf20b2a7caf2", +"bigquery": "fa7c73e5e0c290b6bbd5acaf", +"databricks": "c61d78463df42b7187c212de", +"tsql": "ad68f4a284d63dd79b70635b" } ], [ @@ -271,7 +271,7 @@ "postgres": "b3283bf184bb082f364b8537", "snowflake": "b3283bf184bb082f364b8537", "bigquery": "b3283bf184bb082f364b8537", -"databricks": "a2dffd29b4f083e47c096d79", +"databricks": "566d790a86eca027025c713a", "tsql": "b3283bf184bb082f364b8537" } ], @@ -314,49 +314,49 @@ [ "contracts", { -"None": "52cdcd511bf9153b96f8c816", -"duckdb": "52cdcd511bf9153b96f8c816", -"postgres": "52cdcd511bf9153b96f8c816", -"snowflake": "52cdcd511bf9153b96f8c816", -"bigquery": "52cdcd511bf9153b96f8c816", -"databricks": "52cdcd511bf9153b96f8c816", -"tsql": "52cdcd511bf9153b96f8c816" +"None": "ba1961d88fa9bc263c8f82aa", +"duckdb": "ba1961d88fa9bc263c8f82aa", +"postgres": "ba1961d88fa9bc263c8f82aa", +"snowflake": "ba1961d88fa9bc263c8f82aa", +"bigquery": "ba1961d88fa9bc263c8f82aa", +"databricks": "ba1961d88fa9bc263c8f82aa", +"tsql": "ba1961d88fa9bc263c8f82aa" } ], [ "contracts", { -"None": "2d6a82bfe80342be2bb552ef", -"duckdb": "8ff067c990a41011273611c2", -"postgres": "6a14752b404ff8337dbb4c51", -"snowflake": "b1eba4d04aa9dfe0a2d0865b", -"bigquery": "2d6a82bfe80342be2bb552ef", -"databricks": "2d6a82bfe80342be2bb552ef", -"tsql": "2d6a82bfe80342be2bb552ef" +"None": "2f7bbb2ccfe388709d4b9b71", +"duckdb": "625c6ab7691a5833af4c2ea4", +"postgres": "e1ccacfc8068de31f547173e", +"snowflake": "23a48ce310720a05e10aa716", +"bigquery": "2f7bbb2ccfe388709d4b9b71", +"databricks": "2f7bbb2ccfe388709d4b9b71", +"tsql": "2f7bbb2ccfe388709d4b9b71" } ], [ "contracts", { -"None": "67cc42e5fd32018ec01cf44c", -"duckdb": "67cc42e5fd32018ec01cf44c", -"postgres": "67cc42e5fd32018ec01cf44c", -"snowflake": "67cc42e5fd32018ec01cf44c", -"bigquery": "67cc42e5fd32018ec01cf44c", -"databricks": "67cc42e5fd32018ec01cf44c", -"tsql": "67cc42e5fd32018ec01cf44c" +"None": "b68655cc15f4feafc615efe7", +"duckdb": "b68655cc15f4feafc615efe7", +"postgres": "b68655cc15f4feafc615efe7", +"snowflake": "b68655cc15f4feafc615efe7", +"bigquery": "b68655cc15f4feafc615efe7", +"databricks": "b68655cc15f4feafc615efe7", +"tsql": "b68655cc15f4feafc615efe7" } ], [ "contracts", { -"None": "795e8287da2b98c9c22de3dc", -"duckdb": "6f3824fb29e0dde7383108c6", -"postgres": "21635e15f68b0683f29535b2", -"snowflake": "21635e15f68b0683f29535b2", -"bigquery": "6f3824fb29e0dde7383108c6", -"databricks": "6f3824fb29e0dde7383108c6", -"tsql": "21635e15f68b0683f29535b2" +"None": "a5daac3d0628523354bcb233", +"duckdb": "d1e3c27d8c86d57b976b29f2", +"postgres": "9a633ec3d22ed39b6f359ec7", +"snowflake": "9a633ec3d22ed39b6f359ec7", +"bigquery": "d1e3c27d8c86d57b976b29f2", +"databricks": "d1e3c27d8c86d57b976b29f2", +"tsql": "9a633ec3d22ed39b6f359ec7" } ], [ @@ -386,13 +386,13 @@ [ "contracts", { -"None": "36ccf7779e90a958c5dcad96", -"duckdb": "36ccf7779e90a958c5dcad96", -"postgres": "36ccf7779e90a958c5dcad96", -"snowflake": "36ccf7779e90a958c5dcad96", -"bigquery": "36ccf7779e90a958c5dcad96", -"databricks": "36ccf7779e90a958c5dcad96", -"tsql": "36ccf7779e90a958c5dcad96" +"None": "4dbe34dabc426ca76aee33c8", +"duckdb": "4dbe34dabc426ca76aee33c8", +"postgres": "4dbe34dabc426ca76aee33c8", +"snowflake": "4dbe34dabc426ca76aee33c8", +"bigquery": "4dbe34dabc426ca76aee33c8", +"databricks": "4dbe34dabc426ca76aee33c8", +"tsql": "4dbe34dabc426ca76aee33c8" } ], [ @@ -410,25 +410,25 @@ [ "contracts", { -"None": "e1a7960080040014cb5afaec", -"duckdb": "a95fa25696abf1140e7c0000", -"postgres": "a95fa25696abf1140e7c0000", -"snowflake": "a95fa25696abf1140e7c0000", -"bigquery": "e1a7960080040014cb5afaec", -"databricks": "e1a7960080040014cb5afaec", -"tsql": "a95fa25696abf1140e7c0000" +"None": "376bc727fbf222e7fa0e3aad", +"duckdb": "112d5157527fad3c5f6d6885", +"postgres": "112d5157527fad3c5f6d6885", +"snowflake": "112d5157527fad3c5f6d6885", +"bigquery": "376bc727fbf222e7fa0e3aad", +"databricks": "376bc727fbf222e7fa0e3aad", +"tsql": "112d5157527fad3c5f6d6885" } ], [ "contracts", { -"None": "103d29f4aef0090a36226ef7", -"duckdb": "dc82b458627503ca4311361b", -"postgres": "dc82b458627503ca4311361b", -"snowflake": "dfe34264a6edca41378b9402", -"bigquery": "b0c0b670609049fee2ff6f77", -"databricks": "103d29f4aef0090a36226ef7", -"tsql": "dc82b458627503ca4311361b" +"None": "555e245833e7a34afe942ebe", +"duckdb": "a2d393590109690ae47d2a79", +"postgres": "a2d393590109690ae47d2a79", +"snowflake": "7c77132a4005cbe5f2caa9b7", +"bigquery": "34de39e803796bfde536f8c0", +"databricks": "555e245833e7a34afe942ebe", +"tsql": "a2d393590109690ae47d2a79" } ], [ @@ -446,37 +446,37 @@ [ "contracts", { -"None": "f4c3b90723d3035642621697", -"duckdb": "f4c3b90723d3035642621697", -"postgres": "48f4d5904e4ba757feadf37f", -"snowflake": "f4c3b90723d3035642621697", -"bigquery": "f4c3b90723d3035642621697", -"databricks": "f4c3b90723d3035642621697", -"tsql": "48f4d5904e4ba757feadf37f" +"None": "93fa1f32e42b03867c79e594", +"duckdb": "93fa1f32e42b03867c79e594", +"postgres": "c4a875a9dc1909a445a74784", +"snowflake": "93fa1f32e42b03867c79e594", +"bigquery": "93fa1f32e42b03867c79e594", +"databricks": "93fa1f32e42b03867c79e594", +"tsql": "c4a875a9dc1909a445a74784" } ], [ "contracts", { -"None": "4d049c17ef65d5f879915793", -"duckdb": "5fcd211d1b9c6dd59fb52d91", -"postgres": "2a167c9cb4bdcef7cfbcd99a", -"snowflake": "2a167c9cb4bdcef7cfbcd99a", -"bigquery": "d270f17ca2b64c571cb98bbd", -"databricks": "1ab94ef2126776626e8e801d", -"tsql": "4d049c17ef65d5f879915793" +"None": "4472da1ffc3c0e2007845555", +"duckdb": "3e9a58585f3d25590fe57f88", +"postgres": "805a5b00a7108ce6b51f0ec6", +"snowflake": "805a5b00a7108ce6b51f0ec6", +"bigquery": "e22d7578ebfd2c8c167c309e", +"databricks": "7be16a6a422e816c75e7e7da", +"tsql": "4472da1ffc3c0e2007845555" } ], [ "contracts", { -"None": "896ce437f811f03b69f82839", -"duckdb": "d7722781d12891e5bd225237", -"postgres": "d7722781d12891e5bd225237", -"snowflake": "d7722781d12891e5bd225237", -"bigquery": "896ce437f811f03b69f82839", -"databricks": "896ce437f811f03b69f82839", -"tsql": "896ce437f811f03b69f82839" +"None": "b7630d0b16049ff3e1196648", +"duckdb": "59960c7c612713fd5fbb8345", +"postgres": "59960c7c612713fd5fbb8345", +"snowflake": "59960c7c612713fd5fbb8345", +"bigquery": "b7630d0b16049ff3e1196648", +"databricks": "b7630d0b16049ff3e1196648", +"tsql": "b7630d0b16049ff3e1196648" } ], [ @@ -494,37 +494,37 @@ [ "contracts", { -"None": "2f4d4854052e5b2c341be511", -"duckdb": "2f4d4854052e5b2c341be511", -"postgres": "352658b79bb1cfd0ad1faf6e", -"snowflake": "352658b79bb1cfd0ad1faf6e", -"bigquery": "2f4d4854052e5b2c341be511", -"databricks": "2f4d4854052e5b2c341be511", -"tsql": "2f4d4854052e5b2c341be511" +"None": "a486efec55b33d15c46fcc08", +"duckdb": "a486efec55b33d15c46fcc08", +"postgres": "df4319e591abdfd110655a68", +"snowflake": "df4319e591abdfd110655a68", +"bigquery": "a486efec55b33d15c46fcc08", +"databricks": "a486efec55b33d15c46fcc08", +"tsql": "a486efec55b33d15c46fcc08" } ], [ "contracts", { -"None": "670c69c37d74aceab22e1515", -"duckdb": "670c69c37d74aceab22e1515", -"postgres": "670c69c37d74aceab22e1515", -"snowflake": "670c69c37d74aceab22e1515", -"bigquery": "670c69c37d74aceab22e1515", -"databricks": "670c69c37d74aceab22e1515", -"tsql": "670c69c37d74aceab22e1515" +"None": "edf7414fdc6765e57aee00b9", +"duckdb": "edf7414fdc6765e57aee00b9", +"postgres": "edf7414fdc6765e57aee00b9", +"snowflake": "edf7414fdc6765e57aee00b9", +"bigquery": "edf7414fdc6765e57aee00b9", +"databricks": "edf7414fdc6765e57aee00b9", +"tsql": "edf7414fdc6765e57aee00b9" } ], [ "contracts", { -"None": "140bc939bff7e716152dd27f", -"duckdb": "140bc939bff7e716152dd27f", -"postgres": "140bc939bff7e716152dd27f", -"snowflake": "140bc939bff7e716152dd27f", -"bigquery": "c9b6c5f365bc3fe054e4faf2", -"databricks": "140bc939bff7e716152dd27f", -"tsql": "140bc939bff7e716152dd27f" +"None": "283ec21c2e8340570d8af8a3", +"duckdb": "283ec21c2e8340570d8af8a3", +"postgres": "283ec21c2e8340570d8af8a3", +"snowflake": "283ec21c2e8340570d8af8a3", +"bigquery": "ead9c805b7b0b00cce601939", +"databricks": "283ec21c2e8340570d8af8a3", +"tsql": "283ec21c2e8340570d8af8a3" } ], [ @@ -542,61 +542,61 @@ [ "contracts", { -"None": "c969edb8ec7bbec85e3606d2", -"duckdb": "6f1634dc604b82f58c1d760f", -"postgres": "6f1634dc604b82f58c1d760f", -"snowflake": "6f1634dc604b82f58c1d760f", -"bigquery": "c969edb8ec7bbec85e3606d2", -"databricks": "c969edb8ec7bbec85e3606d2", -"tsql": "fbf2dae89852040b6ad88287" +"None": "8d6a1a3ccda708cd9d4abb06", +"duckdb": "e86d9a6b878419635c96b5eb", +"postgres": "e86d9a6b878419635c96b5eb", +"snowflake": "e86d9a6b878419635c96b5eb", +"bigquery": "8d6a1a3ccda708cd9d4abb06", +"databricks": "8d6a1a3ccda708cd9d4abb06", +"tsql": "9ee5ba29879ef83ddf083e79" } ], [ "contracts", { -"None": "2e2853705c0438a8d2843b23", -"duckdb": "2e2853705c0438a8d2843b23", -"postgres": "2e2853705c0438a8d2843b23", -"snowflake": "2e2853705c0438a8d2843b23", -"bigquery": "2e2853705c0438a8d2843b23", -"databricks": "2e2853705c0438a8d2843b23", -"tsql": "2e2853705c0438a8d2843b23" +"None": "9ef5b8ed4af5f7370494da23", +"duckdb": "9ef5b8ed4af5f7370494da23", +"postgres": "9ef5b8ed4af5f7370494da23", +"snowflake": "9ef5b8ed4af5f7370494da23", +"bigquery": "9ef5b8ed4af5f7370494da23", +"databricks": "9ef5b8ed4af5f7370494da23", +"tsql": "9ef5b8ed4af5f7370494da23" } ], [ "contracts", { -"None": "54f2b01fc9a9c16112ec1383", -"duckdb": "f7a56e3326d02b7968c8ffe8", -"postgres": "a9bdcb7ee2642092b9c2e2ae", -"snowflake": "a9bdcb7ee2642092b9c2e2ae", -"bigquery": "667b5495d0a7267e742cdf83", -"databricks": "ac04ad46924f4659fa3494b0", -"tsql": "ac04ad46924f4659fa3494b0" +"None": "adac502a32777dfdc334d967", +"duckdb": "23fbda29261dc6ade623ece5", +"postgres": "6a888cfbf4b93b32e97f23f7", +"snowflake": "6a888cfbf4b93b32e97f23f7", +"bigquery": "99933d8d0ceed79a06fbcbab", +"databricks": "9b9f6c6156409f197e83fb10", +"tsql": "9b9f6c6156409f197e83fb10" } ], [ "contracts", { -"None": "73203819b605274b38ecbfc1", -"duckdb": "1931b18fcefdffb99b7a688e", -"postgres": "b86830e946240d5b5ea2ddfb", -"snowflake": "2ac8be57d53f848825b50251", -"bigquery": "9fe54d0db7dd91047e65e441", -"databricks": "1931b18fcefdffb99b7a688e", -"tsql": "559bc7c88585130792649498" +"None": "d453cd484a6e7d3c50e55a98", +"duckdb": "24737eb4e0bc50362281f4b3", +"postgres": "e375cd1d101f4be4de6bb9f0", +"snowflake": "645ffc343e6c90f6d5e08ef7", +"bigquery": "60117b6a82b9962ede80233f", +"databricks": "24737eb4e0bc50362281f4b3", +"tsql": "8d9a4423d6dca5cdc2aba4c1" } ], [ "contracts", { -"None": "bb67625de7198e2dc8e3b23b", -"duckdb": "2a42e291118d5fa419ada6b8", -"postgres": "2a42e291118d5fa419ada6b8", -"snowflake": "6e5f3057275c88687658bb88", -"bigquery": "bb67625de7198e2dc8e3b23b", -"databricks": "2a42e291118d5fa419ada6b8", -"tsql": "2a42e291118d5fa419ada6b8" +"None": "160c8d6e8c2e7929272c131c", +"duckdb": "89bfed600b982ce0ec9414b3", +"postgres": "89bfed600b982ce0ec9414b3", +"snowflake": "bb80b18459235408c77b6a93", +"bigquery": "160c8d6e8c2e7929272c131c", +"databricks": "89bfed600b982ce0ec9414b3", +"tsql": "89bfed600b982ce0ec9414b3" } ], [ @@ -614,13 +614,13 @@ [ "contracts", { -"None": "0a6c32f28f1f118fce837b44", -"duckdb": "ce8519ac3ae2285f86bace8f", -"postgres": "ce8519ac3ae2285f86bace8f", -"snowflake": "ce8519ac3ae2285f86bace8f", -"bigquery": "94d3833106fff9f1cd81f8ca", -"databricks": "94d3833106fff9f1cd81f8ca", -"tsql": "0a6c32f28f1f118fce837b44" +"None": "776b7aac09a2712d31a29003", +"duckdb": "a40f94387772a57cebe3dbc2", +"postgres": "a40f94387772a57cebe3dbc2", +"snowflake": "a40f94387772a57cebe3dbc2", +"bigquery": "be6e639b730e88dd3490e5ec", +"databricks": "be6e639b730e88dd3490e5ec", +"tsql": "776b7aac09a2712d31a29003" } ], [ @@ -628,10 +628,10 @@ { "None": "b0f4ff7bdb22e70450bb554d", "duckdb": "b0f4ff7bdb22e70450bb554d", -"postgres": "5bfc18d5575fdbfd78f984f8", -"snowflake": "5bfc18d5575fdbfd78f984f8", +"postgres": "08807fadd742e90ce0d5f7b7", +"snowflake": "08807fadd742e90ce0d5f7b7", "bigquery": "b0f4ff7bdb22e70450bb554d", -"databricks": "5bfc18d5575fdbfd78f984f8", +"databricks": "08807fadd742e90ce0d5f7b7", "tsql": "b0f4ff7bdb22e70450bb554d" } ], @@ -662,13 +662,13 @@ [ "contracts", { -"None": "c5796b1c6cdb1a297bae8709", -"duckdb": "8aaa2d458624305a775a549c", -"postgres": "8aaa2d458624305a775a549c", -"snowflake": "8aaa2d458624305a775a549c", -"bigquery": "c5796b1c6cdb1a297bae8709", -"databricks": "7fa6d9440f21a20015a8c4af", -"tsql": "c01c95754b2dfa4678b0cb01" +"None": "99c387984ba9fda7fc173047", +"duckdb": "8875c34d1fe76436e8d5ab6e", +"postgres": "8875c34d1fe76436e8d5ab6e", +"snowflake": "8875c34d1fe76436e8d5ab6e", +"bigquery": "99c387984ba9fda7fc173047", +"databricks": "50bf7fe6781dab5940c66ba3", +"tsql": "85ad87b2f8814f571a354c5f" } ], [ @@ -698,13 +698,13 @@ [ "contracts", { -"None": "b69ef1eaba1124a7e710d482", -"duckdb": "b69ef1eaba1124a7e710d482", -"postgres": "b69ef1eaba1124a7e710d482", -"snowflake": "b69ef1eaba1124a7e710d482", -"bigquery": "b69ef1eaba1124a7e710d482", -"databricks": "b69ef1eaba1124a7e710d482", -"tsql": "b69ef1eaba1124a7e710d482" +"None": "aa4ae4414ce383ce9cedf778", +"duckdb": "aa4ae4414ce383ce9cedf778", +"postgres": "aa4ae4414ce383ce9cedf778", +"snowflake": "aa4ae4414ce383ce9cedf778", +"bigquery": "aa4ae4414ce383ce9cedf778", +"databricks": "aa4ae4414ce383ce9cedf778", +"tsql": "aa4ae4414ce383ce9cedf778" } ], [ diff --git a/tests/goldens/python_oracle/explicit_references_edge_projects.json b/tests/goldens/python_oracle/explicit_references_edge_projects.json index 9698d7b89a..98c73b4bcb 100644 --- a/tests/goldens/python_oracle/explicit_references_edge_projects.json +++ b/tests/goldens/python_oracle/explicit_references_edge_projects.json @@ -1,54 +1,54 @@ [ [ "explicit_references", -"d2b46fdc6296bf91b06813dc" +"e89cca66882c0668a2efb34d" ], [ "explicit_references", -"e33fe6067ae76da5913f184d" +"5e5accdfa61b0855b4c16c93" ], [ "explicit_references", -"1379c25c88bdd8284a703c2a" +"d7cb7fa91595894a2011afa2" ], [ "explicit_references", -"5b87fefa2541f55bdd6cdaf7" +"9687d5038bc5edd6549971c6" ], [ "explicit_references", -"18216c9b230d59f93e117e5b" +"8d133c2b601d3f7af1e32396" ], [ "explicit_references", -"a6a84faa791220995194fc21" +"c05d7ad48551335dddeddfd8" ], [ "explicit_references", -"f04e803ab1bf78c5b0d874e3" +"56c4c38f26d63968af18bea7" ], [ "explicit_references", -"1b7104ea4c42a572777c1ffb" +"fee59bf65ce35f7d24a86296" ], [ "explicit_references", -"a9461cb64efcfc87f387dd4e" +"43610aaef1e7a3d98dad573b" ], [ "explicit_references", -"92e4d194703692bbf96d85a3" +"be38b3e6b8a8d2e1c110f99a" ], [ "explicit_references", -"7e3caa377591a83b80f4d859" +"e579d33aae222b66683811e2" ], [ "explicit_references", -"aec22e4d642969f541fa5af9" +"ec4c00f6d459a027d370c942" ], [ "explicit_references", -"7fc02502af1a2ec677aed239" +"bf4db6e840af644c320a3b1e" ] ] diff --git a/tests/goldens/python_oracle/macro_expansion_nested_argument_scan_edges.json b/tests/goldens/python_oracle/macro_expansion_nested_argument_scan_edges.json index b8b1af7b18..ee0de70b13 100644 --- a/tests/goldens/python_oracle/macro_expansion_nested_argument_scan_edges.json +++ b/tests/goldens/python_oracle/macro_expansion_nested_argument_scan_edges.json @@ -1,23 +1,23 @@ [ [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"e5bbf689186f3c18d715ba20" +"af64378f6ed75d9e3d0dfd70" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"5915a019257cf7407eee15d3" +"2746dc280073b2b84df023d9" ], [ "macro_expansion", -"5915a019257cf7407eee15d3" +"2746dc280073b2b84df023d9" ], [ "macro_expansion", @@ -25,27 +25,27 @@ ], [ "macro_expansion", -"27d4e68d24829c448fc5db69" +"2de59788ec0bf16dca05d35f" ], [ "macro_expansion", -"c04d82d3e06bc4e64a5a4de1" +"33cd37d909e1dc7ca3c40b4e" ], [ "macro_expansion", -"5915a019257cf7407eee15d3" +"2746dc280073b2b84df023d9" ], [ "macro_expansion", -"d31152c290a88cf4b3d9ed4c" +"cad1b065e4ee3a72c2f61f76" ], [ "macro_expansion", -"190febf661200a407d59746e" +"af1d83a0e5324e4026e68916" ], [ "macro_expansion", -"46a35bc0512271fd917753b4" +"39822f4aa823a6e9212f481d" ], [ "macro_expansion", @@ -53,27 +53,27 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"c04d82d3e06bc4e64a5a4de1" +"33cd37d909e1dc7ca3c40b4e" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"f859a8e6ed3219c398caed65" +"1e45f9913932ad8f3f543a0d" ], [ "macro_expansion", -"3a0174e0036ca09a54d7d4ef" +"cbd881278c24675b121fbdbd" ], [ "macro_expansion", diff --git a/tests/goldens/python_oracle/macro_expansion_seeded_fragments.json b/tests/goldens/python_oracle/macro_expansion_seeded_fragments.json index 68a8d300b4..c3f48a21fc 100644 --- a/tests/goldens/python_oracle/macro_expansion_seeded_fragments.json +++ b/tests/goldens/python_oracle/macro_expansion_seeded_fragments.json @@ -1,43 +1,43 @@ [ [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -45,7 +45,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -53,7 +53,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -61,7 +61,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -69,11 +69,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -89,19 +89,19 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -109,15 +109,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -133,7 +133,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -141,23 +141,23 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -169,7 +169,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -177,7 +177,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -189,7 +189,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -197,15 +197,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -217,7 +217,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -225,7 +225,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -233,7 +233,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -241,27 +241,27 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -269,7 +269,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -277,15 +277,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -297,11 +297,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -325,7 +325,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -341,7 +341,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -349,23 +349,23 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -373,7 +373,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -385,7 +385,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -405,15 +405,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -421,15 +421,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -461,7 +461,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -469,19 +469,19 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -497,7 +497,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -505,15 +505,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -521,19 +521,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -553,19 +553,19 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -585,11 +585,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -597,7 +597,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -625,7 +625,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -637,7 +637,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -645,19 +645,19 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -669,15 +669,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -689,7 +689,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -705,7 +705,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -713,11 +713,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -737,11 +737,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -749,7 +749,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -757,11 +757,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -769,7 +769,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -781,23 +781,23 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -805,7 +805,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -813,19 +813,19 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -845,7 +845,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -857,55 +857,55 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -913,11 +913,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -925,15 +925,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -949,11 +949,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -965,7 +965,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -973,15 +973,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -989,7 +989,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -997,11 +997,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1009,7 +1009,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -1017,11 +1017,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -1029,7 +1029,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -1037,15 +1037,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1053,7 +1053,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -1061,7 +1061,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -1069,7 +1069,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1077,19 +1077,19 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -1101,7 +1101,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -1121,7 +1121,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -1129,35 +1129,35 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1177,23 +1177,23 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1201,7 +1201,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1209,7 +1209,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1217,11 +1217,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1229,11 +1229,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -1249,31 +1249,31 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1281,7 +1281,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -1289,23 +1289,23 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -1317,19 +1317,19 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1337,19 +1337,19 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1357,7 +1357,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -1365,7 +1365,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1373,7 +1373,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1381,11 +1381,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -1393,7 +1393,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -1405,11 +1405,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1417,7 +1417,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -1425,7 +1425,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -1437,19 +1437,19 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -1457,7 +1457,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -1465,15 +1465,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -1481,23 +1481,23 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -1509,19 +1509,19 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -1541,7 +1541,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1549,19 +1549,19 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -1569,35 +1569,35 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -1605,11 +1605,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1617,7 +1617,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -1625,11 +1625,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -1637,11 +1637,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -1653,11 +1653,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -1665,7 +1665,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -1681,7 +1681,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -1697,7 +1697,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1705,7 +1705,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -1725,7 +1725,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -1737,7 +1737,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -1745,11 +1745,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -1765,11 +1765,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1777,19 +1777,19 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1797,7 +1797,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1805,11 +1805,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1817,7 +1817,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1833,7 +1833,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -1845,11 +1845,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -1861,11 +1861,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1877,11 +1877,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1889,15 +1889,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -1905,7 +1905,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -1913,7 +1913,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -1921,7 +1921,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1933,11 +1933,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -1945,7 +1945,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -1957,7 +1957,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -1965,11 +1965,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -2005,7 +2005,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2013,27 +2013,27 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2041,15 +2041,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2065,11 +2065,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2077,7 +2077,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -2085,11 +2085,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2101,15 +2101,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2145,15 +2145,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2161,19 +2161,19 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2181,7 +2181,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -2193,19 +2193,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2213,35 +2213,35 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -2261,7 +2261,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2269,7 +2269,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2277,7 +2277,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2285,7 +2285,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2297,15 +2297,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2321,7 +2321,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -2337,11 +2337,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2349,27 +2349,27 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2377,15 +2377,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -2405,7 +2405,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2413,15 +2413,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2429,11 +2429,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2441,11 +2441,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -2453,7 +2453,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -2461,11 +2461,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -2481,11 +2481,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -2493,19 +2493,19 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -2517,11 +2517,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2533,7 +2533,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2541,7 +2541,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2549,7 +2549,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2557,11 +2557,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2569,7 +2569,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2581,7 +2581,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2597,11 +2597,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -2609,11 +2609,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -2621,11 +2621,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2641,7 +2641,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2661,11 +2661,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -2677,15 +2677,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2693,7 +2693,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -2705,15 +2705,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2721,7 +2721,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2729,11 +2729,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2741,7 +2741,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2749,7 +2749,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -2761,15 +2761,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2777,11 +2777,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -2793,15 +2793,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -2809,7 +2809,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -2817,15 +2817,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2837,7 +2837,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -2845,15 +2845,15 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -2865,7 +2865,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -2877,7 +2877,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2885,11 +2885,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -2897,15 +2897,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2913,11 +2913,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -2925,7 +2925,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -2937,7 +2937,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -2945,11 +2945,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2961,7 +2961,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -2973,23 +2973,23 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -2997,23 +2997,23 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -3021,11 +3021,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -3041,7 +3041,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3053,7 +3053,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3061,7 +3061,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -3081,7 +3081,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3089,7 +3089,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3101,11 +3101,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3117,7 +3117,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -3125,15 +3125,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3145,7 +3145,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3161,15 +3161,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3181,11 +3181,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3193,7 +3193,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3201,7 +3201,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3217,7 +3217,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -3225,15 +3225,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3241,7 +3241,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -3249,7 +3249,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3261,7 +3261,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -3285,7 +3285,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -3301,11 +3301,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3313,11 +3313,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -3325,7 +3325,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3333,15 +3333,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3353,31 +3353,31 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -3385,7 +3385,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3401,7 +3401,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3437,11 +3437,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3449,11 +3449,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -3461,11 +3461,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3473,15 +3473,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -3493,23 +3493,23 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3517,15 +3517,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3537,7 +3537,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -3545,23 +3545,23 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3573,7 +3573,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3581,7 +3581,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -3589,15 +3589,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3605,27 +3605,27 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3633,7 +3633,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3645,7 +3645,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3657,7 +3657,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3665,19 +3665,19 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -3689,15 +3689,15 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3709,7 +3709,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3725,7 +3725,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3757,7 +3757,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -3769,11 +3769,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3781,15 +3781,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3801,11 +3801,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3825,7 +3825,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3833,15 +3833,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3849,11 +3849,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -3861,11 +3861,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3877,7 +3877,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -3889,7 +3889,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -3897,11 +3897,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3917,7 +3917,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -3933,15 +3933,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -3953,7 +3953,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -3961,7 +3961,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -3973,19 +3973,19 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -3997,11 +3997,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4017,11 +4017,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4037,11 +4037,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4053,15 +4053,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -4069,7 +4069,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -4085,31 +4085,31 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4117,15 +4117,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4133,7 +4133,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -4145,15 +4145,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4177,11 +4177,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -4189,7 +4189,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -4197,7 +4197,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4205,15 +4205,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -4221,11 +4221,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4237,7 +4237,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4245,7 +4245,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4253,15 +4253,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -4269,11 +4269,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4281,27 +4281,27 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -4329,11 +4329,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -4349,19 +4349,19 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -4373,7 +4373,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4381,7 +4381,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -4389,39 +4389,39 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4433,15 +4433,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4453,7 +4453,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4461,7 +4461,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4469,11 +4469,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4489,7 +4489,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -4497,7 +4497,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4509,7 +4509,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -4517,11 +4517,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4533,11 +4533,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -4545,7 +4545,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -4553,11 +4553,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4565,7 +4565,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -4573,15 +4573,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4589,7 +4589,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -4601,7 +4601,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4609,7 +4609,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4629,11 +4629,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -4645,7 +4645,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4653,11 +4653,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -4669,23 +4669,23 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4697,7 +4697,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4709,11 +4709,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4721,7 +4721,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4733,7 +4733,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4757,7 +4757,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4769,11 +4769,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4781,19 +4781,19 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -4801,11 +4801,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4813,7 +4813,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4829,15 +4829,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -4853,11 +4853,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4873,23 +4873,23 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4897,7 +4897,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4913,7 +4913,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4925,15 +4925,15 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -4965,7 +4965,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -4977,11 +4977,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -4989,7 +4989,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -4997,7 +4997,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -5005,23 +5005,23 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -5029,27 +5029,27 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -5057,7 +5057,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5069,19 +5069,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -5089,31 +5089,31 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -5121,15 +5121,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -5141,11 +5141,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -5161,11 +5161,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5177,11 +5177,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -5189,15 +5189,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -5209,7 +5209,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -5217,11 +5217,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -5229,15 +5229,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -5245,31 +5245,31 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -5285,11 +5285,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -5297,7 +5297,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -5305,11 +5305,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -5329,11 +5329,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -5369,7 +5369,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5377,15 +5377,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -5401,7 +5401,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -5413,7 +5413,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5421,19 +5421,19 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -5449,15 +5449,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5469,7 +5469,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -5501,7 +5501,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -5509,11 +5509,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -5521,7 +5521,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -5537,31 +5537,31 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -5573,7 +5573,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -5581,23 +5581,23 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -5605,7 +5605,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5613,7 +5613,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -5621,7 +5621,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -5641,11 +5641,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5661,11 +5661,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5677,11 +5677,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -5697,15 +5697,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -5713,15 +5713,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5729,27 +5729,27 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -5761,15 +5761,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -5777,11 +5777,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5789,11 +5789,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -5801,19 +5801,19 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -5821,11 +5821,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -5837,7 +5837,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -5849,11 +5849,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -5861,11 +5861,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -5873,7 +5873,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -5885,11 +5885,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -5905,27 +5905,27 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -5933,7 +5933,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -5945,11 +5945,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -5977,7 +5977,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -5985,11 +5985,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -5997,11 +5997,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6013,15 +6013,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6029,11 +6029,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6045,11 +6045,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6061,7 +6061,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6073,15 +6073,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6089,7 +6089,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -6097,7 +6097,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6105,7 +6105,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6113,11 +6113,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6125,11 +6125,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6145,35 +6145,35 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6181,7 +6181,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6189,11 +6189,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -6201,7 +6201,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -6221,15 +6221,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -6237,7 +6237,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -6249,7 +6249,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -6265,7 +6265,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6273,11 +6273,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -6285,11 +6285,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -6297,7 +6297,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6305,15 +6305,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6325,11 +6325,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6341,7 +6341,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6349,11 +6349,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6365,7 +6365,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6373,7 +6373,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -6381,19 +6381,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -6413,7 +6413,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -6421,7 +6421,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6433,7 +6433,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6441,7 +6441,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6461,15 +6461,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -6477,15 +6477,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6493,23 +6493,23 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6517,15 +6517,15 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6541,7 +6541,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -6553,7 +6553,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6565,7 +6565,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -6577,7 +6577,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -6589,11 +6589,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6605,23 +6605,23 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -6633,7 +6633,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6649,7 +6649,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -6661,7 +6661,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6677,15 +6677,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -6697,19 +6697,19 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6721,15 +6721,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6737,11 +6737,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6761,7 +6761,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6777,15 +6777,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -6793,7 +6793,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -6801,7 +6801,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -6809,19 +6809,19 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -6841,7 +6841,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6849,7 +6849,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6861,27 +6861,27 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6889,15 +6889,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6905,11 +6905,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -6917,7 +6917,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -6933,15 +6933,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6949,7 +6949,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -6957,15 +6957,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -6973,7 +6973,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -6989,19 +6989,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -7009,11 +7009,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7021,15 +7021,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -7045,7 +7045,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7053,7 +7053,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -7065,11 +7065,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7093,15 +7093,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -7109,7 +7109,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -7121,11 +7121,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -7137,11 +7137,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -7153,11 +7153,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7173,7 +7173,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7189,7 +7189,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -7197,11 +7197,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -7209,11 +7209,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -7221,7 +7221,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7237,7 +7237,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -7245,15 +7245,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -7265,7 +7265,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -7273,7 +7273,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -7289,7 +7289,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -7301,7 +7301,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -7309,7 +7309,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7321,7 +7321,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -7329,15 +7329,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7353,7 +7353,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -7361,11 +7361,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -7389,11 +7389,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -7413,7 +7413,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7421,7 +7421,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -7429,11 +7429,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7441,19 +7441,19 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -7465,7 +7465,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -7473,7 +7473,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -7481,19 +7481,19 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -7501,19 +7501,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -7529,7 +7529,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -7537,7 +7537,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -7561,27 +7561,27 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7597,7 +7597,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7605,19 +7605,19 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7625,7 +7625,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7633,7 +7633,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7645,7 +7645,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7653,27 +7653,27 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7681,39 +7681,39 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -7721,27 +7721,27 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -7761,15 +7761,15 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -7777,7 +7777,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -7785,11 +7785,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -7797,23 +7797,23 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7821,31 +7821,31 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7861,7 +7861,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -7873,11 +7873,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -7889,15 +7889,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -7913,15 +7913,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -7929,15 +7929,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -7945,7 +7945,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7953,7 +7953,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -7965,19 +7965,19 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -7989,11 +7989,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8001,19 +8001,19 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -8021,47 +8021,47 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -8073,7 +8073,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -8081,7 +8081,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -8097,7 +8097,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -8105,7 +8105,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -8117,7 +8117,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8125,11 +8125,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8137,7 +8137,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8145,7 +8145,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8153,15 +8153,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -8169,15 +8169,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -8185,7 +8185,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8193,7 +8193,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -8201,7 +8201,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -8209,7 +8209,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -8217,11 +8217,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -8229,11 +8229,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8241,15 +8241,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -8265,15 +8265,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -8281,19 +8281,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -8301,7 +8301,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8317,11 +8317,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8341,23 +8341,23 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8365,15 +8365,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8381,7 +8381,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -8393,7 +8393,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -8409,7 +8409,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -8429,7 +8429,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -8437,7 +8437,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8449,19 +8449,19 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -8473,7 +8473,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -8481,11 +8481,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8501,15 +8501,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -8517,7 +8517,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8537,7 +8537,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8545,15 +8545,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -8561,7 +8561,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -8589,7 +8589,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -8605,7 +8605,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -8617,23 +8617,23 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -8641,15 +8641,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -8657,7 +8657,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8673,7 +8673,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -8681,7 +8681,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -8713,19 +8713,19 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8757,7 +8757,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8773,7 +8773,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -8781,7 +8781,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -8793,7 +8793,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -8801,11 +8801,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8817,7 +8817,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -8829,19 +8829,19 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -8857,11 +8857,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -8873,7 +8873,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -8889,23 +8889,23 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -8913,15 +8913,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -8933,11 +8933,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -8945,7 +8945,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -8961,11 +8961,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -8981,19 +8981,19 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9017,7 +9017,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9025,7 +9025,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9041,7 +9041,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9049,11 +9049,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -9061,7 +9061,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9077,11 +9077,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -9093,15 +9093,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9109,15 +9109,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9133,11 +9133,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -9145,7 +9145,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9153,15 +9153,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -9189,7 +9189,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -9201,7 +9201,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -9209,11 +9209,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9225,11 +9225,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -9241,19 +9241,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9261,7 +9261,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -9269,47 +9269,47 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -9317,27 +9317,27 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9345,7 +9345,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -9357,7 +9357,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9373,7 +9373,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9381,11 +9381,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9429,11 +9429,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -9449,11 +9449,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9465,7 +9465,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -9473,7 +9473,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9481,7 +9481,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9489,7 +9489,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -9509,7 +9509,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9525,7 +9525,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9533,7 +9533,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -9541,19 +9541,19 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -9561,11 +9561,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -9577,7 +9577,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9585,11 +9585,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9621,7 +9621,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -9633,7 +9633,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9641,7 +9641,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -9649,7 +9649,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9657,7 +9657,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9669,7 +9669,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -9685,7 +9685,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -9693,7 +9693,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9705,11 +9705,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9729,7 +9729,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -9745,7 +9745,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9753,7 +9753,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -9761,7 +9761,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -9769,15 +9769,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9793,7 +9793,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9809,15 +9809,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -9837,19 +9837,19 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -9861,15 +9861,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -9877,7 +9877,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9885,7 +9885,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9897,11 +9897,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -9913,15 +9913,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -9933,11 +9933,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9945,15 +9945,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -9961,7 +9961,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -9969,7 +9969,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -9977,7 +9977,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10001,7 +10001,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10017,7 +10017,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10025,15 +10025,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10041,7 +10041,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -10049,35 +10049,35 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -10089,7 +10089,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10097,15 +10097,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -10113,7 +10113,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -10121,15 +10121,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10141,7 +10141,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10149,23 +10149,23 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10177,15 +10177,15 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10197,39 +10197,39 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10237,15 +10237,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10253,15 +10253,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10273,19 +10273,19 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10293,7 +10293,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -10305,7 +10305,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -10313,7 +10313,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -10325,7 +10325,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10333,7 +10333,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -10353,7 +10353,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -10365,11 +10365,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -10377,7 +10377,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -10389,7 +10389,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10401,15 +10401,15 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10417,7 +10417,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10433,7 +10433,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10441,11 +10441,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10453,15 +10453,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10473,11 +10473,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10485,11 +10485,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -10505,15 +10505,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10521,7 +10521,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -10529,27 +10529,27 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10561,19 +10561,19 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -10581,11 +10581,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -10593,7 +10593,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10601,15 +10601,15 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10617,15 +10617,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -10641,15 +10641,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -10661,11 +10661,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10677,7 +10677,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -10685,11 +10685,11 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -10705,15 +10705,15 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10729,11 +10729,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10745,7 +10745,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -10757,7 +10757,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -10769,23 +10769,23 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10809,11 +10809,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10825,19 +10825,19 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -10845,23 +10845,23 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10873,19 +10873,19 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10893,7 +10893,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -10905,7 +10905,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -10913,11 +10913,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10929,19 +10929,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -10949,7 +10949,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -10957,7 +10957,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -10969,7 +10969,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -10981,7 +10981,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -10993,7 +10993,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11005,11 +11005,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -11025,11 +11025,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -11041,7 +11041,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11049,11 +11049,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -11061,7 +11061,7 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -11069,27 +11069,27 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -11101,7 +11101,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11109,67 +11109,67 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -11181,27 +11181,27 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -11209,7 +11209,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -11217,7 +11217,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -11229,11 +11229,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11249,7 +11249,7 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -11261,7 +11261,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11269,11 +11269,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -11281,11 +11281,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11297,15 +11297,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11321,7 +11321,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11329,7 +11329,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -11337,7 +11337,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11353,7 +11353,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11365,11 +11365,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -11377,7 +11377,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -11385,7 +11385,7 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", @@ -11393,11 +11393,11 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -11405,7 +11405,7 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -11429,11 +11429,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11441,11 +11441,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -11457,19 +11457,19 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -11481,7 +11481,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -11489,7 +11489,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11505,7 +11505,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11521,11 +11521,11 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -11533,15 +11533,15 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11549,35 +11549,35 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -11589,7 +11589,7 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11597,11 +11597,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -11609,15 +11609,15 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -11629,27 +11629,27 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11661,23 +11661,23 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -11693,11 +11693,11 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", @@ -11705,11 +11705,11 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -11717,15 +11717,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11733,11 +11733,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -11745,27 +11745,27 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11773,7 +11773,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -11789,11 +11789,11 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -11817,7 +11817,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -11829,15 +11829,15 @@ ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -11845,11 +11845,11 @@ ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -11861,7 +11861,7 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", @@ -11869,7 +11869,7 @@ ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", @@ -11877,19 +11877,19 @@ ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", @@ -11897,51 +11897,51 @@ ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"59bd19da177bdcca2991c194" +"688f61201f9739c633a49660" ], [ "macro_expansion", -"466d31b36c8f142dabdc4f0e" +"7f6a4c18a236b0b2cc6ef0f6" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", @@ -11949,15 +11949,15 @@ ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", @@ -11965,31 +11965,31 @@ ], [ "macro_expansion", -"061b5458a42a4e05f5131050" +"8e90a4482ed02a15dba0cd4c" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"d854865f66ff931381b7c33b" +"ec6529850aed4b0f8b0cb443" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"9d73235e25255db601e49309" +"e99b113b1dbf603c16ae81d4" ], [ "macro_expansion", -"71d960f853b797a03adda165" +"30f7681451a4ab14b06cbbb0" ], [ "macro_expansion", -"a20db18db5999d40aaa03a20" +"37a9cc7c24980a036c7a3e04" ], [ "macro_expansion", diff --git a/tests/goldens/python_oracle/metadata_formerly_deferred_non_ascii_names_and_comments_new_and_unknown_dialects.json b/tests/goldens/python_oracle/metadata_formerly_deferred_non_ascii_names_and_comments_new_and_unknown_dialects.json index 0a6f9332f5..e876fc7a6e 100644 --- a/tests/goldens/python_oracle/metadata_formerly_deferred_non_ascii_names_and_comments_new_and_unknown_dialects.json +++ b/tests/goldens/python_oracle/metadata_formerly_deferred_non_ascii_names_and_comments_new_and_unknown_dialects.json @@ -2,40 +2,40 @@ [ "metadata", { -"duckdb": "f94d387a4480c13db319fdad", -"clickhouse": "83431f6feced32f7db4143a6", -"tsql": "cababa3a33d5afcabd8f3fb8", -"None": "545e3d1911e6be891c082594", +"duckdb": "165f6efd37a1fe9972ceb48f", +"clickhouse": "a961cd9f4e5694eba021fa72", +"tsql": "2fdf192c80ff80324d597b82", +"None": "6c574e0e8b608e32bc30c4c8", "nonsense": "6f6079f31e12e028922d40f2" } ], [ "metadata", { -"duckdb": "0ed0773a2a4a6fca23c1dcac", -"clickhouse": "c9f66e2829627aeb5e4728db", -"tsql": "c9f66e2829627aeb5e4728db", -"None": "b5eb71b7238452018577953d", +"duckdb": "cfeebd21e532c611e2fa91ab", +"clickhouse": "b549b6df7979bf00783984bd", +"tsql": "b549b6df7979bf00783984bd", +"None": "37851c731ad00aebc37881bd", "nonsense": "6f6079f31e12e028922d40f2" } ], [ "metadata", { -"duckdb": "30c78fd5afb3d05479d6c4ca", -"clickhouse": "a86fc9ef8fd7f46e7110dff4", -"tsql": "a86fc9ef8fd7f46e7110dff4", -"None": "52fa4030275d4145d23acad6", +"duckdb": "9ab94f7e9b4726a9e939d3d7", +"clickhouse": "03ce1914439e10f67ee7d10b", +"tsql": "03ce1914439e10f67ee7d10b", +"None": "e072f6610b2cb2b69df055af", "nonsense": "6f6079f31e12e028922d40f2" } ], [ "metadata", { -"duckdb": "55da090c1795767af58252eb", -"clickhouse": "9225fd40168382c4100e98c3", -"tsql": "9225fd40168382c4100e98c3", -"None": "f500a1f934f47f35fb2c5ff4", +"duckdb": "4fcbddfaf98b2d2d02fa7b47", +"clickhouse": "060ec9de7f034ed24116c9be", +"tsql": "060ec9de7f034ed24116c9be", +"None": "cc9256e2756429a21fa68114", "nonsense": "6f6079f31e12e028922d40f2" } ] diff --git a/tests/goldens/python_oracle/metadata_generated_function_calls_config_references_cursors_audits_and_sql_tests.json b/tests/goldens/python_oracle/metadata_generated_function_calls_config_references_cursors_audits_and_sql_tests.json index 39fd0c942d..5e22d425ad 100644 --- a/tests/goldens/python_oracle/metadata_generated_function_calls_config_references_cursors_audits_and_sql_tests.json +++ b/tests/goldens/python_oracle/metadata_generated_function_calls_config_references_cursors_audits_and_sql_tests.json @@ -2,73 +2,73 @@ [ "metadata", { -"duckdb": "1c2a3eebe1d7ed12373eee03", -"postgres": "8e36fb23554087db46727693", -"snowflake": "8e36fb23554087db46727693", -"bigquery": "03e76c987d9b715a01607418" +"duckdb": "2a7ed24018e688f1f6f67fa4", +"postgres": "1ea219c4195c77ba52a23384", +"snowflake": "1ea219c4195c77ba52a23384", +"bigquery": "702e206fa8cb8dd79bbaf4cb" } ], [ "metadata", { -"duckdb": "5b11b1dec11561480d6dc43f", -"postgres": "abcdd5e3fcbe2daefb74f57b", -"snowflake": "abcdd5e3fcbe2daefb74f57b", -"bigquery": "27ba56206f3fd3e08e404003" +"duckdb": "384b0b4e2fa703698e7e90d8", +"postgres": "1c5392d818971e32514eaca6", +"snowflake": "1c5392d818971e32514eaca6", +"bigquery": "2787d3275ae9e07140b088d7" } ], [ "metadata", { -"duckdb": "7f34dcf40c6392f554ea91da", -"postgres": "2e203d99e28ab5cbdfd8cfb6", -"snowflake": "2e203d99e28ab5cbdfd8cfb6", -"bigquery": "6188d55225fc3355ee350d93" +"duckdb": "d0f4fe3e45ef45a05e7b47bd", +"postgres": "f3675240119ac95069d4ad17", +"snowflake": "f3675240119ac95069d4ad17", +"bigquery": "d3a5fd5fd88e386bb5e5d794" } ], [ "metadata", { -"duckdb": "5248ff1ce3518aeed27d1ecd", -"postgres": "94e4aae33c04503253db41a4", -"snowflake": "94e4aae33c04503253db41a4", -"bigquery": "c582c97bec0387c38abb4d4d" +"duckdb": "de4eb54edbd1affd34c7e0b7", +"postgres": "b8e0f937560fdee42d1dba33", +"snowflake": "b8e0f937560fdee42d1dba33", +"bigquery": "862cd84310738effefd07fe7" } ], [ "metadata", { -"duckdb": "f58eecbca144a88bbd6c7eef", -"postgres": "ad4229629c684797c3e9e363", -"snowflake": "ad4229629c684797c3e9e363", -"bigquery": "d1229780b7935d9acac4c6fa" +"duckdb": "57e5c6a1b9ecb484b84bf050", +"postgres": "3fda58644720488594b092a6", +"snowflake": "3fda58644720488594b092a6", +"bigquery": "8e8e9fe584b3473ddba6c936" } ], [ "metadata", { -"duckdb": "6c87da536a646aeb646ad807", -"postgres": "eb74286ed7c0e52a3fe8a992", -"snowflake": "eb74286ed7c0e52a3fe8a992", -"bigquery": "96b011c7d66946c301340908" +"duckdb": "3e4e5aa70abd3e145154ea61", +"postgres": "6626deb67b0e2b5cda22077d", +"snowflake": "6626deb67b0e2b5cda22077d", +"bigquery": "75779e37556d1a8bfad73b23" } ], [ "metadata", { -"duckdb": "30c095b3a216c510c92743c5", -"postgres": "83535238d4bee99c5079d1f1", -"snowflake": "83535238d4bee99c5079d1f1", -"bigquery": "76c9a91c06ccf970b8cf8823" +"duckdb": "cc0f55a782898fa80cad902d", +"postgres": "08e1e64c830a8eca8b8ec006", +"snowflake": "08e1e64c830a8eca8b8ec006", +"bigquery": "0076bbc9a9ac0dd3bdb34ec3" } ], [ "metadata", { -"duckdb": "31c36219fc8d6894d50fd2a6", -"postgres": "c6df91db98ed3db9d24d2dfc", -"snowflake": "c6df91db98ed3db9d24d2dfc", -"bigquery": "7b052937b7f3b212908fa289" +"duckdb": "b53f68c56f4b0a55203d7fdd", +"postgres": "20754f7ac8e31e395df0db04", +"snowflake": "20754f7ac8e31e395df0db04", +"bigquery": "626dc8e01eb00d7e1f5f79dd" } ] ] diff --git a/tests/goldens/python_oracle/project_assembly_error_and_python_value_edges.json b/tests/goldens/python_oracle/project_assembly_error_and_python_value_edges.json index ef859e81ae..a69c297de7 100644 --- a/tests/goldens/python_oracle/project_assembly_error_and_python_value_edges.json +++ b/tests/goldens/python_oracle/project_assembly_error_and_python_value_edges.json @@ -57,7 +57,7 @@ ], [ "project_assembly", -"b19f63e95a8202c7dba72047" +"2e1a39810994975b288fe0ab" ], [ "project_assembly", diff --git a/tests/goldens/python_oracle/semantic_formerly_deferred_dialects_added_to_the_native_parser_build.json b/tests/goldens/python_oracle/semantic_formerly_deferred_dialects_added_to_the_native_parser_build.json index b7f0367835..7b3bb3c613 100644 --- a/tests/goldens/python_oracle/semantic_formerly_deferred_dialects_added_to_the_native_parser_build.json +++ b/tests/goldens/python_oracle/semantic_formerly_deferred_dialects_added_to_the_native_parser_build.json @@ -2,19 +2,19 @@ [ "completion", { -"tsql": "d54ac41b7924d8d3eb4b07de", -"databricks": "d54ac41b7924d8d3eb4b07de", -"sqlite": "d54ac41b7924d8d3eb4b07de", -"clickhouse": "d54ac41b7924d8d3eb4b07de" +"tsql": "f395ebc8b868621bb822bf12", +"databricks": "f395ebc8b868621bb822bf12", +"sqlite": "f395ebc8b868621bb822bf12", +"clickhouse": "f395ebc8b868621bb822bf12" } ], [ "completion", { -"tsql": "af4024cbb0b1022278fb0039", -"databricks": "af4024cbb0b1022278fb0039", -"sqlite": "af4024cbb0b1022278fb0039", -"clickhouse": "af4024cbb0b1022278fb0039" +"tsql": "38f56c345838162afa3fd349", +"databricks": "38f56c345838162afa3fd349", +"sqlite": "38f56c345838162afa3fd349", +"clickhouse": "38f56c345838162afa3fd349" } ] ] diff --git a/tests/goldens/python_oracle/semantic_formerly_deferred_non_ascii_names_comments_and_line_separators.json b/tests/goldens/python_oracle/semantic_formerly_deferred_non_ascii_names_comments_and_line_separators.json index 5444cbb2b4..b5fdc8b5c5 100644 --- a/tests/goldens/python_oracle/semantic_formerly_deferred_non_ascii_names_comments_and_line_separators.json +++ b/tests/goldens/python_oracle/semantic_formerly_deferred_non_ascii_names_comments_and_line_separators.json @@ -2,37 +2,37 @@ [ "completion", { -"duckdb": "a9ceb826a6c9cc3caf987bb7", -"postgres": "a9ceb826a6c9cc3caf987bb7", -"snowflake": "a9ceb826a6c9cc3caf987bb7", -"bigquery": "a9ceb826a6c9cc3caf987bb7" +"duckdb": "7e5f136439256b9b604a614d", +"postgres": "7e5f136439256b9b604a614d", +"snowflake": "7e5f136439256b9b604a614d", +"bigquery": "7e5f136439256b9b604a614d" } ], [ "completion", { -"duckdb": "c10085934861ac2acdf66683", -"postgres": "8dfa54b86c900f9b548d3a0d", -"snowflake": "c10085934861ac2acdf66683", -"bigquery": "ee8f0e9b7ecf29cbf883f458" +"duckdb": "14a995cbfd32855e0d6859ce", +"postgres": "f5704f44e5e366bc13273586", +"snowflake": "14a995cbfd32855e0d6859ce", +"bigquery": "19c520b1c0ac1dd2bb791628" } ], [ "completion", { -"duckdb": "d94e71acae817a60f01b0955", -"postgres": "17cebe026f75d716827cfa80", -"snowflake": "d94e71acae817a60f01b0955", -"bigquery": "d94e71acae817a60f01b0955" +"duckdb": "58b42ce4f6e271352c2be92c", +"postgres": "862a26b047fd4e3b822ed366", +"snowflake": "58b42ce4f6e271352c2be92c", +"bigquery": "58b42ce4f6e271352c2be92c" } ], [ "completion", { -"duckdb": "25bf8e4b2677f3273106dee9", -"postgres": "25bf8e4b2677f3273106dee9", -"snowflake": "25bf8e4b2677f3273106dee9", -"bigquery": "25bf8e4b2677f3273106dee9" +"duckdb": "d720f86280d442339f1810fc", +"postgres": "d720f86280d442339f1810fc", +"snowflake": "d720f86280d442339f1810fc", +"bigquery": "d720f86280d442339f1810fc" } ] ] diff --git a/tests/goldens/python_oracle/semantic_generated_typos_aliases_temporal_comparisons_type_errors_and_opt_outs.json b/tests/goldens/python_oracle/semantic_generated_typos_aliases_temporal_comparisons_type_errors_and_opt_outs.json index 60a301ba58..3dac00ca7e 100644 --- a/tests/goldens/python_oracle/semantic_generated_typos_aliases_temporal_comparisons_type_errors_and_opt_outs.json +++ b/tests/goldens/python_oracle/semantic_generated_typos_aliases_temporal_comparisons_type_errors_and_opt_outs.json @@ -2,73 +2,73 @@ [ "completion", { -"duckdb": "ff77b0f7c0cca5db3021485f", -"postgres": "0de896ddd8f99c8c157c0d6a", -"snowflake": "45200ddc74b94812a0aca571", -"bigquery": "fd5541de4ab52c998f7e13c5" +"duckdb": "3b53e31f7789b12c351e70ad", +"postgres": "0ab02f06063217b92327950b", +"snowflake": "2318b91039018b4a3164240c", +"bigquery": "4e8948a4818c10316368cf3b" } ], [ "completion", { -"duckdb": "a88cbfc47aa1a11a62c671bb", -"postgres": "a88cbfc47aa1a11a62c671bb", -"snowflake": "2c23a32e69460308d4893f41", -"bigquery": "a88cbfc47aa1a11a62c671bb" +"duckdb": "049c9f44af271f1671c0d693", +"postgres": "049c9f44af271f1671c0d693", +"snowflake": "e66501e31f1688f725ca5086", +"bigquery": "049c9f44af271f1671c0d693" } ], [ "completion", { -"duckdb": "559b4f8d9d535a8c20a43a68", -"postgres": "d106cb543e7422050fa8359b", -"snowflake": "a7a5c49a1a12ea6a55928d58", -"bigquery": "391905a2f2b3241b9f017c1d" +"duckdb": "45e78724305a52267f1d3423", +"postgres": "9d502de09ddad66f43a7c3f8", +"snowflake": "add5feeccc8d2dba69dc5a9c", +"bigquery": "b5e77b2ffb8aa1f613505a50" } ], [ "completion", { -"duckdb": "43a694212f8a1c90b7c5c429", -"postgres": "43a694212f8a1c90b7c5c429", -"snowflake": "43a694212f8a1c90b7c5c429", -"bigquery": "1af1a3ae03db4c1e15297421" +"duckdb": "7d0e0619b4034e0b8024005a", +"postgres": "7d0e0619b4034e0b8024005a", +"snowflake": "7d0e0619b4034e0b8024005a", +"bigquery": "2224aed946b7d13999e735ef" } ], [ "completion", { -"duckdb": "7a4e919059d5f2d759a79a0e", -"postgres": "d72ca349ece74a31d78bf4e7", -"snowflake": "2e5d4d0063e8d8db7563cc53", -"bigquery": "0bffda198dbb4f007269080c" +"duckdb": "535511ac8361b7d1c248e8fd", +"postgres": "0428999ead2d9c7c0c7cadeb", +"snowflake": "9d6752d035c34baba0d93a7d", +"bigquery": "a862719c2e82805b39d72a84" } ], [ "completion", { -"duckdb": "dabfee6327264ab0daad3f28", -"postgres": "dabfee6327264ab0daad3f28", -"snowflake": "77d73ac56b19811a2e044eb4", -"bigquery": "6ace0baa2efb70168eb18aad" +"duckdb": "103f1703b39a4bef73811e1a", +"postgres": "103f1703b39a4bef73811e1a", +"snowflake": "0668778f4267a281ee603591", +"bigquery": "05a0a4424dfd97267e463926" } ], [ "completion", { -"duckdb": "4d6653aafceb276d132e3d5a", -"postgres": "d1b31ce62eb1e851e6c477f5", -"snowflake": "49f8133ce7dc3332de1928b8", -"bigquery": "f7432c7f32261cd8ed0b5055" +"duckdb": "b4048264e34ae82da3701ca8", +"postgres": "03d4d1b8b1b427498b9e6b7b", +"snowflake": "07fa0a3192f0b0da14658d8c", +"bigquery": "e0b75ffd6f35233ee18740c6" } ], [ "completion", { -"duckdb": "5a5c63115bf816432297ed36", -"postgres": "9b6637d1334d254103ed3484", -"snowflake": "5a5c63115bf816432297ed36", -"bigquery": "15a3513a31fb5749f5951af1" +"duckdb": "3490f5945e13d872abee3d1a", +"postgres": "f1c45c845f9ca3db469fe2c8", +"snowflake": "3490f5945e13d872abee3d1a", +"bigquery": "44587cd2b2ef9c463c88e17a" } ] ] diff --git a/tests/goldens/python_oracle/semantic_session_analysis_session_corpus_with_pivots_stars_and_set_operations.json b/tests/goldens/python_oracle/semantic_session_analysis_session_corpus_with_pivots_stars_and_set_operations.json index 762c265800..a6d1250fd5 100644 --- a/tests/goldens/python_oracle/semantic_session_analysis_session_corpus_with_pivots_stars_and_set_operations.json +++ b/tests/goldens/python_oracle/semantic_session_analysis_session_corpus_with_pivots_stars_and_set_operations.json @@ -1,18 +1,18 @@ [ [ "completion", -"35d296fba04d42e8f80a8890" +"51155388e82cf138811ea2eb" ], [ "completion", -"3aad41e644c8686d46386e0f" +"a5dd2f1b3ac8128d162e7fdb" ], [ "completion", -"d9a8a7b2e5f069f7d2929181" +"5425d3ba760e6d1b82d27107" ], [ "completion", -"25ffb9349c369aefd7ed217a" +"475fa3e53e31a80ba7ecc5c3" ] ] diff --git a/tests/goldens/python_oracle/semantic_session_failing_semantics_corpus.json b/tests/goldens/python_oracle/semantic_session_failing_semantics_corpus.json index 4f5cebd40c..bc68b05509 100644 --- a/tests/goldens/python_oracle/semantic_session_failing_semantics_corpus.json +++ b/tests/goldens/python_oracle/semantic_session_failing_semantics_corpus.json @@ -1,26 +1,26 @@ [ [ "completion", -"659db5c5fe2701a52cd97fc9" +"8d678c8480f4fea959405504" ], [ "completion", -"5174486fe569433a8352e2e4" +"8217a08150c82cd1aa7deaa7" ], [ "completion", -"13bd1dee1f37387417f64189" +"2a4c79d038c318d0ad8110bf" ], [ "completion", -"66c18726bbd8d3691d66b1cc" +"a24fba9ad5bbad1e496cd51c" ], [ "completion", -"c415c9c7d7720b8a20b96cbc" +"2f0e782424308e9764b39e0a" ], [ "completion", -"3800f4f18b512e99ed4f6618" +"c2d15d914003b847e565216d" ] ] diff --git a/tests/goldens/python_oracle/sql_test_assembly_a_decimal_case_parameter_the_default_context_overflows.json b/tests/goldens/python_oracle/sql_test_assembly_a_decimal_case_parameter_the_default_context_overflows.json index 82e0cdc498..f1d042da69 100644 --- a/tests/goldens/python_oracle/sql_test_assembly_a_decimal_case_parameter_the_default_context_overflows.json +++ b/tests/goldens/python_oracle/sql_test_assembly_a_decimal_case_parameter_the_default_context_overflows.json @@ -2,9 +2,9 @@ [ "sql_test_assembly", { +"sql_tests": "74234e98afe7498fb5daf1f3", "diagnostics": "74234e98afe7498fb5daf1f3", -"raised": "eda90da258aa7debe1d39bd6", -"sql_tests": "74234e98afe7498fb5daf1f3" +"raised": "eda90da258aa7debe1d39bd6" } ] ] diff --git a/tests/goldens/python_oracle/sql_test_assembly_a_macro_test_over_a_model_with_a_non_ascii_name_after.json b/tests/goldens/python_oracle/sql_test_assembly_a_macro_test_over_a_model_with_a_non_ascii_name_after.json index c25ac28ec6..8879737d99 100644 --- a/tests/goldens/python_oracle/sql_test_assembly_a_macro_test_over_a_model_with_a_non_ascii_name_after.json +++ b/tests/goldens/python_oracle/sql_test_assembly_a_macro_test_over_a_model_with_a_non_ascii_name_after.json @@ -3,7 +3,7 @@ "sql_test_assembly", { "sql_tests": "601883520be21497efb0a9ee", -"diagnostics": "6ef2576fb654edcf29f33018", +"diagnostics": "705f722a649e52658214c618", "raised": "74234e98afe7498fb5daf1f3" } ] diff --git a/tests/goldens/python_oracle/sql_test_assembly_a_mock_reading_a_deeply_nested_helper_whose_nested_cte_shadows_another.json b/tests/goldens/python_oracle/sql_test_assembly_a_mock_reading_a_deeply_nested_helper_whose_nested_cte_shadows_another.json index 6e39dc54e1..a33647989b 100644 --- a/tests/goldens/python_oracle/sql_test_assembly_a_mock_reading_a_deeply_nested_helper_whose_nested_cte_shadows_another.json +++ b/tests/goldens/python_oracle/sql_test_assembly_a_mock_reading_a_deeply_nested_helper_whose_nested_cte_shadows_another.json @@ -2,9 +2,9 @@ [ "sql_test_assembly", { -"diagnostics": "4c9a3579d5b9f3bbd6adb8ea", -"raised": "74234e98afe7498fb5daf1f3", -"sql_tests": "85aa78137e27cd6c6ebae02b" +"sql_tests": "85aa78137e27cd6c6ebae02b", +"diagnostics": "9dc86aa5b5c2b0007212fddd", +"raised": "74234e98afe7498fb5daf1f3" } ] ] diff --git a/tests/goldens/python_oracle/sql_test_assembly_an_unread_helper_with_an_invalid_reference_call.json b/tests/goldens/python_oracle/sql_test_assembly_an_unread_helper_with_an_invalid_reference_call.json index 2b239b36a4..7e9d3d9f8c 100644 --- a/tests/goldens/python_oracle/sql_test_assembly_an_unread_helper_with_an_invalid_reference_call.json +++ b/tests/goldens/python_oracle/sql_test_assembly_an_unread_helper_with_an_invalid_reference_call.json @@ -2,9 +2,9 @@ [ "sql_test_assembly", { -"diagnostics": "3d02d9756b4ddb9d01407647", -"raised": "74234e98afe7498fb5daf1f3", -"sql_tests": "04c58ad3582f31de5ebe5178" +"sql_tests": "04c58ad3582f31de5ebe5178", +"diagnostics": "93ee613347387e4917572d11", +"raised": "74234e98afe7498fb5daf1f3" } ] ] diff --git a/tests/goldens/python_oracle/sql_test_assembly_decimal_case_parameters_the_default_context_rounds_and_flushes.json b/tests/goldens/python_oracle/sql_test_assembly_decimal_case_parameters_the_default_context_rounds_and_flushes.json index 2f305241b4..d0b43db21a 100644 --- a/tests/goldens/python_oracle/sql_test_assembly_decimal_case_parameters_the_default_context_rounds_and_flushes.json +++ b/tests/goldens/python_oracle/sql_test_assembly_decimal_case_parameters_the_default_context_rounds_and_flushes.json @@ -2,9 +2,9 @@ [ "sql_test_assembly", { -"diagnostics": "4c9a3579d5b9f3bbd6adb8ea", -"raised": "74234e98afe7498fb5daf1f3", -"sql_tests": "c9fdab56e644c9475570663d" +"sql_tests": "c9fdab56e644c9475570663d", +"diagnostics": "9dc86aa5b5c2b0007212fddd", +"raised": "74234e98afe7498fb5daf1f3" } ] ] diff --git a/tests/goldens/python_oracle/sql_test_assembly_model_direct_parameterized_and_mock_reads_helper_tests.json b/tests/goldens/python_oracle/sql_test_assembly_model_direct_parameterized_and_mock_reads_helper_tests.json index d4e95ea9a5..cd3e215508 100644 --- a/tests/goldens/python_oracle/sql_test_assembly_model_direct_parameterized_and_mock_reads_helper_tests.json +++ b/tests/goldens/python_oracle/sql_test_assembly_model_direct_parameterized_and_mock_reads_helper_tests.json @@ -2,33 +2,33 @@ [ "sql_test_assembly", { -"diagnostics": "38d030765c7b731a9dc4a02c", -"raised": "74234e98afe7498fb5daf1f3", -"sql_tests": "19342e1031f6db6a58950a78" +"sql_tests": "19342e1031f6db6a58950a78", +"diagnostics": "8167db451d0378e107cb938d", +"raised": "74234e98afe7498fb5daf1f3" } ], [ "sql_test_assembly", { -"diagnostics": "85355a904cd57506ada88c26", -"raised": "74234e98afe7498fb5daf1f3", -"sql_tests": "14481c815b4a801c38562317" +"sql_tests": "14481c815b4a801c38562317", +"diagnostics": "75471e383377cba1742fa447", +"raised": "74234e98afe7498fb5daf1f3" } ], [ "sql_test_assembly", { -"diagnostics": "63ab94227f6c63702ceb04e6", -"raised": "74234e98afe7498fb5daf1f3", -"sql_tests": "eb8781590978f943d4cda3a2" +"sql_tests": "eb8781590978f943d4cda3a2", +"diagnostics": "ea2cf52456d9b7949c4cc7ad", +"raised": "74234e98afe7498fb5daf1f3" } ], [ "sql_test_assembly", { -"diagnostics": "e1b911e742090996c12323e4", -"raised": "74234e98afe7498fb5daf1f3", -"sql_tests": "9a64536c2908bed9e46d362e" +"sql_tests": "9a64536c2908bed9e46d362e", +"diagnostics": "fef5dc3d21d85330e743ac9d", +"raised": "74234e98afe7498fb5daf1f3" } ] ] diff --git a/tests/goldens/python_oracle/sql_test_assembly_non_ascii_test_contents_case_folded_reads_and_located_diagnostics.json b/tests/goldens/python_oracle/sql_test_assembly_non_ascii_test_contents_case_folded_reads_and_located_diagnostics.json index 4be417e428..64d61b048a 100644 --- a/tests/goldens/python_oracle/sql_test_assembly_non_ascii_test_contents_case_folded_reads_and_located_diagnostics.json +++ b/tests/goldens/python_oracle/sql_test_assembly_non_ascii_test_contents_case_folded_reads_and_located_diagnostics.json @@ -2,9 +2,9 @@ [ "sql_test_assembly", { -"diagnostics": "72bb5771315980f5478711a6", -"raised": "74234e98afe7498fb5daf1f3", -"sql_tests": "ba1a28153c7e0394be6b4d5e" +"sql_tests": "ba1a28153c7e0394be6b4d5e", +"diagnostics": "6e3121b72c6eea02c30a31ed", +"raised": "74234e98afe7498fb5daf1f3" } ] ] diff --git a/tests/integration/scripts/build_features/helpers.py b/tests/integration/scripts/build_features/helpers.py index 325ef69cc0..c0fa368845 100644 --- a/tests/integration/scripts/build_features/helpers.py +++ b/tests/integration/scripts/build_features/helpers.py @@ -39,6 +39,7 @@ def write_workspace(root: Path, test_case: BuildFeaturesTestCase) -> None: _write( root / "crates" / "sqlbuild-cli" / "Cargo.toml", '[package]\nname = "sqlbuild-cli"\nversion = "0.1.0"\nedition = "2021"\n\n' + "[features]\nui = []\n\n" '[dependencies]\nshared = { path = "../shared" }\nderive = { path = "../derive" }\n', ) _write(root / "crates" / "sqlbuild-cli" / "src" / "lib.rs", "") diff --git a/tests/integration/src/sqlbuild/cli/commands/_helpers/refactor/test_command.py b/tests/integration/src/sqlbuild/cli/commands/_helpers/refactor/test_command.py index 1e39018122..94059d49d3 100644 --- a/tests/integration/src/sqlbuild/cli/commands/_helpers/refactor/test_command.py +++ b/tests/integration/src/sqlbuild/cli/commands/_helpers/refactor/test_command.py @@ -18,19 +18,19 @@ '[connection]\ndatabase = "orders.duckdb"\n\n' '[targets.dev]\nschema = "analytics"\n' ), - "seeds/orders.csv": "order_id,amount\n1,25\n2,40\n", - "seeds/orders.yml": ( + "sql/seeds/orders.csv": "order_id,amount\n1,25\n2,40\n", + "sql/seeds/orders.yml": ( "seeds:\n" " - name: orders\n description: Test seed orders.\n" " columns:\n" " - name: order_id\n type: INTEGER\n" " - name: amount\n type: INTEGER\n" ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( "MODEL (description 'Test model.',\n materialized view,\n);\n\n" 'SELECT\n order_id,\n amount\nFROM __seed("orders")\n' ), - "models/marts/fact_orders.sql": ( + "sql/models/marts/fact_orders.sql": ( "MODEL (description 'Test model.',\n materialized table,\n);\n\n" 'SELECT\n order_id,\n amount\nFROM __ref("stg_orders")\n' ), @@ -45,7 +45,7 @@ command=CliCommand.MV, target="model:fact_orders", new_name=None, - destination="models/finance/fact_orders.sql", + destination="sql/models/finance/fact_orders.sql", expected_lines=( "Planned edits to 1 file.", "Writing 1 file...", @@ -121,7 +121,7 @@ def test_given_refactor_when_running_then_progress_messages_agree_in_number( target="stg_orders.amount", new_name="revenue", destination=None, - expected_path="models/marts/fact_orders.sql", + expected_path="sql/models/marts/fact_orders.sql", expected_fragment="revenue AS amount", expected_missing_paths=(), ), @@ -130,10 +130,10 @@ def test_given_refactor_when_running_then_progress_messages_agree_in_number( command=CliCommand.MV, target="fact_orders", new_name=None, - destination="models/finance/", - expected_path="models/finance/fact_orders.sql", + destination="sql/models/finance/", + expected_path="sql/models/finance/fact_orders.sql", expected_fragment='FROM __ref("stg_orders")', - expected_missing_paths=("models/marts/fact_orders.sql",), + expected_missing_paths=("sql/models/marts/fact_orders.sql",), ), ], ids=lambda case: case.description, diff --git a/tests/integration/src/sqlbuild/cli/commands/main/_test_helpers.py b/tests/integration/src/sqlbuild/cli/commands/main/_test_helpers.py index f3e0abd857..121846fadc 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/_test_helpers.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/_test_helpers.py @@ -10,14 +10,16 @@ _WARM_TARGET_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "shop"\nadapter = "duckdb"\n', - "models/sales/orders.sql": ( + "sql/models/sales/orders.sql": ( "MODEL (description 'Test model orders.', columns (order_id (type INTEGER, " "audits [not_null])));\nSELECT 1 AS order_id\n" ), - "models/sales/daily/totals.sql": ( + "sql/models/sales/daily/totals.sql": ( "MODEL (description 'Test model totals.');\nSELECT order_id FROM __ref(\"orders\")\n" ), - "models/inventory.sql": "MODEL (description 'Test model inventory.');\nSELECT 2 AS item_id\n", + "sql/models/inventory.sql": ( + "MODEL (description 'Test model inventory.');\nSELECT 2 AS item_id\n" + ), } @@ -69,19 +71,19 @@ def pruned_entries(*, entries: dict[str, Path], names: tuple[str, ...]) -> tuple def write_stale_target_entries(*, compiled_dir: Path, outside_dir: Path) -> dict[str, Path]: """Add a stale nested artifact, an empty folder, and a link to an outside folder.""" - stale_file: Path = compiled_dir / "models" / "legacy" / "archive" / "returns.sql" + stale_file: Path = compiled_dir / "sql" / "models" / "legacy" / "archive" / "returns.sql" stale_file.parent.mkdir(parents=True) stale_file.write_text("SELECT 'stale'\n", encoding="utf-8") - empty_directory: Path = compiled_dir / "models" / "empty" / "nested" + empty_directory: Path = compiled_dir / "sql" / "models" / "empty" / "nested" empty_directory.mkdir(parents=True) - outside_dir.mkdir() + outside_dir.mkdir(parents=True) (outside_dir / "kept.sql").write_text("SELECT 'kept'\n", encoding="utf-8") - link: Path = compiled_dir / "models" / "linked" / "shared" + link: Path = compiled_dir / "sql" / "models" / "linked" / "shared" link.parent.mkdir(parents=True) link.symlink_to(outside_dir, target_is_directory=True) return { - "legacy": compiled_dir / "models" / "legacy", - "empty": compiled_dir / "models" / "empty", + "legacy": compiled_dir / "sql" / "models" / "legacy", + "empty": compiled_dir / "sql" / "models" / "empty", "link": link, "outside_file": outside_dir / "kept.sql", } diff --git a/tests/integration/src/sqlbuild/cli/commands/main/compile_outputs/helpers.py b/tests/integration/src/sqlbuild/cli/commands/main/compile_outputs/helpers.py index 90a40c207b..888b1e0b12 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/compile_outputs/helpers.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/compile_outputs/helpers.py @@ -40,15 +40,15 @@ class _StagingEveryProject(PreparedCompileArtifacts): 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN021"]\n' ), **{ - f"models/orders_{name}.sql": OUTPUT_MODEL_HEADER.format(name=name) + f"sql/models/orders_{name}.sql": OUTPUT_MODEL_HEADER.format(name=name) + "SELECT CAST(1 AS INTEGER) AS order_id\n" for name in ("east", "north", "west") }, } -EDITED_MODEL: str = "models/orders_north.sql" -DELETED_MODEL: str = "models/orders_west.sql" +EDITED_MODEL: str = "sql/models/orders_north.sql" +DELETED_MODEL: str = "sql/models/orders_west.sql" TOUCH_BACK_NS: int = 3_600_000_000_000 -BLOCKED_ARTIFACT: str = "target/compiled/models/orders_north.sql" +BLOCKED_ARTIFACT: str = "target/compiled/sql/models/orders_north.sql" HELPER_MODULE_DIRECTORY: str = "site_packages" HELPER_MODULE: str = "orders_reuse_helper" TRACKED_VARIABLE: str = "SQLBUILD_ORDERS_REGION" @@ -56,8 +56,8 @@ class _StagingEveryProject(PreparedCompileArtifacts): SURROGATE_SELECTOR: str = "orders\udcff" SURROGATE_HOOK_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "hooks/python/notify.py": ( + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "sql/hooks/python/notify.py": ( "from sqlbuild.hooks import hook\n\n\n@hook\ndef notify_complete(ctx):\n" ' """Notify "q" \\\\ café \\udcff\\U0001F600\\ud83d\\ude00\\ud83d end."""\n' " return None\n" @@ -70,11 +70,11 @@ def nested_payload_hook_files(*, depth: int) -> dict[str, str]: return { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table, post_hooks [python(\"notify\", " f"payload: {'[' * depth}1{']' * depth})]);\nSELECT 1 AS order_id\n" ), - "hooks/python/notify.py": ( + "sql/hooks/python/notify.py": ( "from sqlbuild.hooks import hook\n\n\n@hook\ndef notify(ctx, payload):\n" ' """Notify."""\n return None\n' ), @@ -251,7 +251,7 @@ def block_stored_compiles(project_dir: Path, monkeypatch: pytest.MonkeyPatch) -> del monkeypatch for path in stored_compile_files(project_dir=project_dir): path.unlink() - path.mkdir() + path.mkdir(parents=True) _ = (path / "keep.txt").write_text("kept\n", encoding="utf-8") @@ -259,7 +259,7 @@ def load_helper_module(*, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> No """Import a helper module from outside the project, as an installed package would be.""" directory: Path = tmp_path / HELPER_MODULE_DIRECTORY - directory.mkdir() + directory.mkdir(parents=True) _ = (directory / f"{HELPER_MODULE}.py").write_text("ORDERS = 1\n", encoding="utf-8") monkeypatch.syspath_prepend(str(directory)) monkeypatch.delitem(sys.modules, HELPER_MODULE, raising=False) @@ -311,7 +311,7 @@ def block_artifact(*, project_dir: Path) -> Path: blocked: Path = project_dir / BLOCKED_ARTIFACT blocked.unlink() - blocked.mkdir() + blocked.mkdir(parents=True) _ = (blocked / "keep.txt").write_text("kept\n", encoding="utf-8") model: Path = project_dir / EDITED_MODEL _ = model.write_text( diff --git a/tests/integration/src/sqlbuild/cli/commands/main/compile_outputs/test_native_compile_outputs.py b/tests/integration/src/sqlbuild/cli/commands/main/compile_outputs/test_native_compile_outputs.py index d7f421d062..f9637ea34e 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/compile_outputs/test_native_compile_outputs.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/compile_outputs/test_native_compile_outputs.py @@ -30,8 +30,8 @@ _SEQUENCE_STEPS: tuple[str, ...] = ("cold", "warm", "touch", "retouch", "edit", "delete") _PUBLICATION_ERROR: str = ( "[Errno 21] Is a directory: " - "'/target/.sqlbuild-staging-/compiled/models/orders_north.sql' -> " - "'/target/compiled/models/orders_north.sql'" + "'/target/.sqlbuild-staging-/compiled/sql/models/orders_north.sql' -> " + "'/target/compiled/sql/models/orders_north.sql'" ) @@ -95,7 +95,7 @@ def test_given_artifact_path_blocked_when_publishing_staged_artifacts_then_compi ) blocked: Path = block_artifact(project_dir=tmp_path) untouched: dict[str, bytes] = artifacts_except( - files=published[2], name="models/orders_north.sql" + files=published[2], name="sql/models/orders_north.sql" ) with pytest.raises(IsADirectoryError) as raised: diff --git a/tests/integration/src/sqlbuild/cli/commands/main/helpers.py b/tests/integration/src/sqlbuild/cli/commands/main/helpers.py index 379a373b66..d95bf1b334 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/helpers.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/helpers.py @@ -46,6 +46,7 @@ RepeatedJsonParseTestCase, ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files from tests.unit.src.sqlbuild.rule_engine._helpers.run.helpers import rebuild_identity STAGE_CAPTURE_SUFFIX: str = ".json" @@ -92,8 +93,10 @@ def write_staging_directory(*, target_dir: Path, name: str) -> Path: """Write one artifact staging directory with a staged model file.""" directory: Path = target_dir / name - (directory / "compiled" / "models").mkdir(parents=True) - (directory / "compiled" / "models" / "orders.sql").write_text("SELECT 1\n", encoding="utf-8") + (directory / "compiled" / "sql" / "models").mkdir(parents=True) + (directory / "compiled" / "sql" / "models" / "orders.sql").write_text( + "SELECT 1\n", encoding="utf-8" + ) return directory @@ -104,8 +107,8 @@ def write_prepared_artifacts_project(*, project_dir: Path, model_count: int) -> 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = ["SQLCLEAN021"]\n', encoding="utf-8", ) - models: Path = project_dir / "models" - models.mkdir() + models: Path = project_dir / "sql" / "models" + models.mkdir(parents=True) for index in range(model_count): (models / f"orders_{index:03}.sql").write_text( "MODEL (description 'Test model.', materialized table, contract enforced, " @@ -129,9 +132,9 @@ def write_test_planning_project( (project_dir / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "duckdb"\n{rules_config}', encoding="utf-8" ) - models: Path = project_dir / "models" + models: Path = project_dir / "sql" / "models" tests: Path = project_dir / "tests" / "unit" - models.mkdir() + models.mkdir(parents=True) tests.mkdir(parents=True) header: str = ( "MODEL (description 'Test model.', materialized table, contract enforced, " @@ -270,8 +273,8 @@ def write_compile_startup_project(project_dir: Path) -> None: (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - models_dir: Path = project_dir / "models" - models_dir.mkdir() + models_dir: Path = project_dir / "sql" / "models" + models_dir.mkdir(parents=True) (models_dir / "orders.sql").write_text( "MODEL (description 'Test model orders.', materialized table);\nSELECT 1 AS order_id\n", encoding="utf-8", @@ -282,13 +285,13 @@ def write_from_values_format_project(*, tmp_path: Path, adapter: str) -> tuple[P """Write a format project containing an authored values relation.""" project_dir: Path = tmp_path / adapter - project_dir.mkdir() + project_dir.mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "{adapter}"\n\n[rules]\nselect = ["SQLCLEAN039"]\n', encoding="utf-8", ) - models: Path = project_dir / "models" - models.mkdir() + models: Path = project_dir / "sql" / "models" + models.mkdir(parents=True) (models / "customers.sql").write_text( 'MODEL (description "Customers.");\nSELECT 1 AS customer_key, 1 AS order_count\n', encoding="utf-8", @@ -341,10 +344,10 @@ def prepare_contract_project(tmp_path: Path, *, prod_connection_toml: str = "") ), encoding="utf-8", ) - models: Path = tmp_path / "models" - sources: Path = tmp_path / "sources" - models.mkdir() - sources.mkdir() + models: Path = tmp_path / "sql" / "models" + sources: Path = tmp_path / "sql" / "sources" + models.mkdir(parents=True) + sources.mkdir(parents=True) _ = (models / "orders.sql").write_text( """MODEL (description "Test model orders.", materialized table @@ -380,7 +383,7 @@ def prepare_contract_project(tmp_path: Path, *, prod_connection_toml: str = "") def add_second_contract_source(*, project_dir: Path, database: Path) -> None: """Add another physical source declared in the existing source YAML file.""" - source_path: Path = project_dir / "sources" / "raw.yml" + source_path: Path = project_dir / "sql" / "sources" / "raw.yml" _ = source_path.write_text( source_path.read_text(encoding="utf-8") + """ - name: raw_customers @@ -454,7 +457,7 @@ def install_live_retention_fake( def write_retention_policy_project(*, project_dir: Path, target_lines: tuple[str, ...]) -> None: """Write a DuckDB project with one table and one view under a prod target.""" - (project_dir / "models").mkdir(parents=True, exist_ok=True) + (project_dir / "sql" / "models").mkdir(parents=True, exist_ok=True) _ = (project_dir / "sqlbuild_project.toml").write_text( "\n".join( ( @@ -475,11 +478,11 @@ def write_retention_policy_project(*, project_dir: Path, target_lines: tuple[str ), encoding="utf-8", ) - _ = (project_dir / "models" / "orders.sql").write_text( + _ = (project_dir / "sql" / "models" / "orders.sql").write_text( "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id\n", encoding="utf-8", ) - _ = (project_dir / "models" / "order_view.sql").write_text( + _ = (project_dir / "sql" / "models" / "order_view.sql").write_text( 'MODEL (description "Test model order_view.", ' 'materialized view);\n\nSELECT order_id FROM __ref("orders")\n', encoding="utf-8", @@ -521,15 +524,15 @@ def write_dropped_relation_project( ) -> Path: """Write a DuckDB project with raw order sources, one seed, and one model.""" - (project_dir / "models").mkdir(parents=True, exist_ok=True) - (project_dir / "sources").mkdir(parents=True, exist_ok=True) - (project_dir / "seeds").mkdir(parents=True, exist_ok=True) + (project_dir / "sql" / "models").mkdir(parents=True, exist_ok=True) + (project_dir / "sql" / "sources").mkdir(parents=True, exist_ok=True) + (project_dir / "sql" / "seeds").mkdir(parents=True, exist_ok=True) _ = (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n\n[connection]\ndatabase = "orders.duckdb"\n' + settings_toml, encoding="utf-8", ) - _ = (project_dir / "sources" / "raw.yml").write_text( + _ = (project_dir / "sql" / "sources" / "raw.yml").write_text( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" @@ -539,10 +542,10 @@ def write_dropped_relation_project( " table: raw_customers\n", encoding="utf-8", ) - _ = (project_dir / "seeds" / "order_statuses.csv").write_text( + _ = (project_dir / "sql" / "seeds" / "order_statuses.csv").write_text( "status_code,status_name\n1,placed\n2,shipped\n", encoding="utf-8" ) - _ = (project_dir / "seeds" / "lookups.yml").write_text( + _ = (project_dir / "sql" / "seeds" / "lookups.yml").write_text( "seeds:\n" " - name: order_statuses\n description: Test seed order_statuses.\n" " columns:\n" @@ -552,7 +555,9 @@ def write_dropped_relation_project( " type: VARCHAR\n", encoding="utf-8", ) - _ = (project_dir / "models" / f"{model_name}.sql").write_text(model_sql, encoding="utf-8") + _ = (project_dir / "sql" / "models" / f"{model_name}.sql").write_text( + model_sql, encoding="utf-8" + ) db_path: Path = project_dir / "orders.duckdb" execute_duckdb_sql( db_path=db_path, @@ -656,8 +661,8 @@ def compile_duckdb_query( """Compile one DuckDB model query and return the exit and diagnostic codes.""" (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text(f"MODEL (description 'Test model orders.');\n{query}") exit_code: int = main(["--project-dir", str(tmp_path), "compile", "--json", "--no-cache"]) result: dict[str, object] = json.loads(capsys.readouterr().out) @@ -673,7 +678,7 @@ def write_boundary_project(*, project_dir: Path, test_case: ExpansionBoundaryTes 'name = "orders"\nadapter = "duckdb"\n[connection]\ndatabase = "orders.duckdb"\n' '[vars]\nnegative = "-1"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( f"MODEL (description 'Orders.', materialized table{test_case.model_config});\n" f"{test_case.model_sql}\n" ), @@ -688,13 +693,13 @@ def write_expression_source_project( ) -> None: """Write a DuckDB project with one typed expression source and one reading model.""" - (project_dir / "sources").mkdir(parents=True) - (project_dir / "models").mkdir() + (project_dir / "sql" / "sources").mkdir(parents=True) + (project_dir / "sql" / "models").mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[connection]\ndatabase = "orders.duckdb"\n', encoding="utf-8", ) - (project_dir / "sources" / "orders.yml").write_text( + (project_dir / "sql" / "sources" / "orders.yml").write_text( "sources:\n" " - name: typed_orders\n description: Test source typed_orders.\n" f' expression: "{source_expression}"\n' @@ -703,7 +708,7 @@ def write_expression_source_project( " type: INTEGER\n", encoding="utf-8", ) - (project_dir / "models" / "orders.sql").write_text(model_sql, encoding="utf-8") + (project_dir / "sql" / "models" / "orders.sql").write_text(model_sql, encoding="utf-8") def source_rebinding_analyses() -> int: @@ -741,7 +746,7 @@ def write_repeated_json_parse_project( encoding="utf-8", ) files: tuple[tuple[str, str], ...] = ( - ("models/order_events.sql", f"{test_case.header}{test_case.sql}"), + ("sql/models/order_events.sql", f"{test_case.header}{test_case.sql}"), *test_case.extra_files, ) for relative_path, contents in files: @@ -837,8 +842,8 @@ def write_snowflake_warehouse_project( encoding="utf-8", ) (project_dir / "sqlbuild_local.toml").write_text(local_config, encoding="utf-8") - (project_dir / "models").mkdir() - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models").mkdir(parents=True) + (project_dir / "sql" / "models" / "orders.sql").write_text( "MODEL (description 'Orders.', materialized table);\nSELECT 1 AS order_id\n", encoding="utf-8", ) @@ -847,9 +852,9 @@ def write_snowflake_warehouse_project( def write_default_connection_project(*, project_dir: Path, project_toml: str) -> None: """Write a one-model DuckDB project with the given project config.""" - (project_dir / "models").mkdir() + (project_dir / "sql" / "models").mkdir(parents=True) _ = (project_dir / "sqlbuild_project.toml").write_text(project_toml, encoding="utf-8") - _ = (project_dir / "models" / "orders.sql").write_text( + _ = (project_dir / "sql" / "models" / "orders.sql").write_text( 'MODEL (description "Orders.", materialized table);\n\nSELECT 1 AS order_id\n', encoding="utf-8", ) @@ -858,7 +863,7 @@ def write_default_connection_project(*, project_dir: Path, project_toml: str) -> def write_default_connection_sql_test(*, project_dir: Path) -> None: """Add a downstream model and a SQL test that mocks its orders dependency.""" - _ = (project_dir / "models" / "order_totals.sql").write_text( + _ = (project_dir / "sql" / "models" / "order_totals.sql").write_text( 'MODEL (description "Order totals.", materialized table);\n\n' 'SELECT order_id FROM __ref("orders")\n', encoding="utf-8", @@ -887,14 +892,14 @@ def write_project_files(*, project_dir: Path, files: dict[str, str]) -> None: 'name = "orders"\nadapter = "duckdb"\n\n[vars]\nfloor = "2"\n\n' '[rules]\nselect = ["SQLCLEAN005"]\n' ), - "models/_macros/python/cents.py": ( + "sql/models/_macros/python/cents.py": ( 'def cents(expression: str) -> str:\n """Convert to cents."""\n' ' return f"({expression} * 100)"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders");\nSELECT 1 AS order_id, CAST(5 AS DOUBLE) AS amount\n' ), - "models/order_cents.sql": ( + "sql/models/order_cents.sql": ( 'MODEL (description "Order amounts in cents");\n' 'WITH floored AS (SELECT order_id, @py.cents("amount") AS amount_cents, ' '@@floor AS floor_amount FROM __ref("orders")), spare AS (SELECT 1 AS one)\n' @@ -932,7 +937,7 @@ def write_custom_host_project(*, project_dir: Path, model_count: int, rule_body: encoding="utf-8", ) for index in range(model_count): - model: Path = project_dir / "models" / f"orders_{index:03d}.sql" + model: Path = project_dir / "sql" / "models" / f"orders_{index:03d}.sql" model.parent.mkdir(parents=True, exist_ok=True) model.write_text( f'MODEL (description "Orders {index}");\nSELECT {index} AS order_id\n', @@ -997,14 +1002,15 @@ def write_provider_asset_project(*, project_dir: Path, annotation: str) -> None: 'name = "orders_assets"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "orders.duckdb"\n' ), - "providers/orders.py": PROVIDER_SOURCE, - "python/orders.py": ( - "from providers.orders import OrdersProvider\n" + "python/providers/orders.py": PROVIDER_SOURCE, + **node_module_files( + "python/nodes/orders.py", + "from python.providers.orders import OrdersProvider\n" "from sqlbuild.assets import asset\n\n\n" "@asset\n" f"def refresh_orders(ctx, orders_provider: {annotation}):\n" ' """Refresh the order snapshot."""\n' - " return None\n" + " return None\n", ), } for relative_path, text in files.items(): @@ -1017,8 +1023,8 @@ def write_header_project(project_dir: Path, models: dict[str, str], project_toml """Write a DuckDB project with one SQL model file per name.""" _ = (project_dir / "sqlbuild_project.toml").write_text(project_toml) - model_dir: Path = project_dir / "models" - model_dir.mkdir() + model_dir: Path = project_dir / "sql" / "models" + model_dir.mkdir(parents=True) for name, contents in models.items(): _ = (model_dir / f"{name}.sql").write_text(contents) @@ -1053,8 +1059,8 @@ def typed_config_reads(*, project_dir: Path, extra_header: str) -> int: '[targets.dev]\nschema = "main"\n', encoding="utf-8", ) - models_dir: Path = project_dir / "models" - models_dir.mkdir() + models_dir: Path = project_dir / "sql" / "models" + models_dir.mkdir(parents=True) for index, own_config in enumerate((', materialized table, tags ["daily"]', "", "")): (models_dir / f"orders_{index}.sql").write_text( f'MODEL (description "Orders {index}."{own_config}{extra_header});\n\n' @@ -1096,8 +1102,8 @@ def write_orders_project(project_dir: Path) -> None: '[connections.local]\ndatabase = ":memory:"\n\n[targets.dev]\nschema = "main"\n', encoding="utf-8", ) - models_dir: Path = project_dir / "models" - models_dir.mkdir() + models_dir: Path = project_dir / "sql" / "models" + models_dir.mkdir(parents=True) (models_dir / "orders.sql").write_text( 'MODEL (description "Orders.", materialized table, contract enforced, ' 'columns (order_id (type "INTEGER"), loaded_at (type "INTEGER")));\n\n' @@ -1139,8 +1145,8 @@ def write_formatted_cache_project(*, project_dir: Path) -> None: (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - models_dir: Path = project_dir / "models" - models_dir.mkdir() + models_dir: Path = project_dir / "sql" / "models" + models_dir.mkdir(parents=True) name: str sql: str for name, sql in FORMAT_CACHE_UNFORMATTED_MODELS.items(): @@ -1170,7 +1176,7 @@ def check_format_with_work( def edit_cached_orders_model(project_dir: Path, _monkeypatch: pytest.MonkeyPatch) -> None: """Make one cached model unformatted again.""" - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( FORMAT_CACHE_UNFORMATTED_MODELS["orders.sql"], encoding="utf-8" ) @@ -1234,8 +1240,10 @@ def write_project_scratch_rules(project_dir: Path) -> None: 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["XSQBRSCR"]\n\n' "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n" ), - "models/orders.sql": 'MODEL (description "Orders");\nSELECT 1 AS order_id\n', - "models/customers.sql": ('MODEL (description "Customers");\nSELECT 1 AS customer_id\n'), + "sql/models/orders.sql": 'MODEL (description "Orders");\nSELECT 1 AS order_id\n', + "sql/models/customers.sql": ( + 'MODEL (description "Customers");\nSELECT 1 AS customer_id\n' + ), "rules/scratch.py": PROJECT_SCRATCH_RULES, }, ) @@ -1245,12 +1253,12 @@ def write_enum_project(*, root: Path, model_sql: str, contract: str) -> None: """Write an orders project whose model fills an `order_status` column from `model_sql`.""" (root / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - (root / "models" / "_enums").mkdir(parents=True) - (root / "models" / "_enums" / "order_status.sql").write_text( + (root / "sql" / "models" / "_enums").mkdir(parents=True) + (root / "sql" / "models" / "_enums" / "order_status.sql").write_text( 'ENUM (name order_status, members (OPEN "open", CLOSED "closed"));\n' ) - (root / "sources").mkdir() - (root / "sources" / "orders.yml").write_text( + (root / "sql" / "sources").mkdir(parents=True) + (root / "sql" / "sources" / "orders.yml").write_text( "sources:\n" " - name: web_orders\n description: Web orders.\n contract: enforced\n" ' expression: "(SELECT CAST(1 AS INTEGER) AS order_id)"\n' @@ -1259,7 +1267,7 @@ def write_enum_project(*, root: Path, model_sql: str, contract: str) -> None: ' expression: "(SELECT CAST(2 AS INTEGER) AS order_id)"\n' " columns:\n - name: order_id\n type: INTEGER\n" ) - (root / "models" / "orders.sql").write_text( + (root / "sql" / "models" / "orders.sql").write_text( f"MODEL (\n description 'Orders from every channel.',\n contract {contract},\n" " columns (\n order_id (type INTEGER),\n status (type order_status),\n ),\n);\n\n" f"{model_sql}" @@ -1286,9 +1294,9 @@ def refund_rates_project(first_step: str) -> dict[str, str]: """Weekly orders, refund-rate models and the SQL macro whose first CTE is `first_step`.""" return { - "models/weekly_orders.sql": _WEEKLY_ORDERS, - "models/refund_rates.sql": _REFUND_RATES, - "models/_macros/sql/weekly_rates.sql": _weekly_rates(first_step), + "sql/models/weekly_orders.sql": _WEEKLY_ORDERS, + "sql/models/refund_rates.sql": _REFUND_RATES, + "sql/models/_macros/sql/weekly_rates.sql": _weekly_rates(first_step), } @@ -1311,14 +1319,14 @@ def write_endless_scenario_project(project_dir: Path) -> Path: "[connection]\n" 'database = "scenario_signals.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n" " description: Raw orders.\n" " schema: main\n" " table: raw_orders\n" ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals.', materialized table, sql_analysis false);\n\n" f"SELECT SUM(o.amount) + {_ENDLESS_ORDER_TOTAL} AS total_amount " 'FROM __source("raw_orders") AS o\n' @@ -1390,8 +1398,8 @@ def write_prompting_project(project_dir: Path, *, connect: str, files: dict[str, '[targets.development]\nschema = "main"\n' "[rules]\nselect = []\n" ), - "adapters/duckdb_sign_in.py": adapter, - "models/customers.sql": ( + "python/adapters/duckdb_sign_in.py": adapter, + "sql/models/customers.sql": ( "MODEL (description 'Customers.', materialized table);\nSELECT 1 AS customer_id\n" ), } | files @@ -1513,7 +1521,7 @@ def write_python_rules_project(*, project_dir: Path, fixture: str, rules_toml: s "sqlbuild_project.toml": ( f'name = "orders"\nadapter = "duckdb"\n\n[rules]\n{rules_toml}' ), - "models/orders.sql": 'MODEL (description "Orders");\nSELECT 1 AS order_id\n', + "sql/models/orders.sql": 'MODEL (description "Orders");\nSELECT 1 AS order_id\n', }, ) @@ -1523,21 +1531,21 @@ def write_python_rules_project(*, project_dir: Path, fixture: str, rules_toml: s ) RUN_RECORD_PROJECT_FILES: dict[str, str] = { - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\nSELECT 1 AS order_id\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" 'SELECT order_id FROM __ref("stg_orders")\n' ), - "models/broken_orders.sql": ( + "sql/models/broken_orders.sql": ( "MODEL (description 'Fails at run time.', materialized table);\n" "SELECT CAST('x' AS INTEGER) AS order_id\n" ), "orchestration/jobs/nightly_job.toml": ( 'name = "nightly_job"\ndescription = "Orders."\nselect = "+orders"\n' ), - "python/crash.py": ( + "python/nodes/crash/asset.py": ( '"""A task that kills its process, as a crash or kill -9 would."""\n\n' "import os\n\n" "from sqlbuild.assets import asset\n\n\n" @@ -1546,7 +1554,7 @@ def write_python_rules_project(*, project_dir: Path, fixture: str, rules_toml: s ' """End the process without unwinding."""\n\n' " os._exit(137)\n" ), - "python/fail.py": ( + "python/nodes/fail/asset.py": ( '"""A task that raises, so the build exits non-zero."""\n\n' "from sqlbuild.assets import asset\n\n\n" "@asset()\n" @@ -1558,55 +1566,55 @@ def write_python_rules_project(*, project_dir: Path, fixture: str, rules_toml: s RUN_RECORD_MARTS_FILES: dict[str, str] = { - "models/marts/revenue.sql": ( + "sql/models/marts/revenue.sql": ( "MODEL (description 'Revenue in the marts schema.', materialized table);\n" "SELECT 10 AS amount\n" ), - "models/marts/daily_events.sql": ( + "sql/models/marts/daily_events.sql": ( "MODEL (description 'Loaded events in the marts schema.', materialized table);\n" 'SELECT event_id FROM __source("landed_events")\n' ), - "python/loaders/events.py": ( + "python/nodes/loaders/events/loader.py": ( "from sqlbuild.loaders import loader\n\n\n" "@loader\n" "def landed_events(ctx):\n" ' """Load one event."""\n\n' ' return [{"event_id": 1}]\n' ), - "sources/landed.yml": ( + "sql/sources/landed.yml": ( "sources:\n - name: landed_events\n description: Loaded events.\n schema: landing\n" " managed: true\n write_strategy: table\n columns:\n" " - name: event_id\n type: INTEGER\n" ), - "models/upper/revenue_upper.sql": ( + "sql/models/upper/revenue_upper.sql": ( "MODEL (description 'Revenue under an upper-case schema name.', materialized table);\n" "SELECT 20 AS amount\n" ), - "models/marts/doubled.sql": ( + "sql/models/marts/doubled.sql": ( "MODEL (description 'Calls a function in its own schema.', materialized table);\n" 'SELECT __udf("udf__doubled")(2) AS amount\n' ), - "functions/sql/udf__doubled.sql": ( + "sql/functions/sql/udf__doubled.sql": ( 'FUNCTION (\n description "Twice its argument",\n arguments (value INTEGER),\n' " returns INTEGER,\n schema udfs,\n);\nvalue * 2\n" ), - "models/marts/slow_total.sql": ( + "sql/models/marts/slow_total.sql": ( "MODEL (description 'Runs past a one-second deadline.', materialized table);\n" "SELECT COUNT(*) AS total FROM range(100000000000)\n" ), - "models/archive/old_orders.sql": ( + "sql/models/archive/old_orders.sql": ( "MODEL (description 'A disabled model in its own schema.', materialized table,\n" " enabled false, schema archive);\nSELECT 1 AS order_id\n" ), - "python/noop.py": ( + "python/nodes/noop/asset.py": ( '"""An asset that writes no relation."""\n\n' "from sqlbuild.assets import asset\n\n\n" "@asset()\n" "def noop(ctx):\n" ' """Do nothing."""\n' ), - "seeds/regions.csv": "region_id\n1\n", - "seeds/regions.yml": ( + "sql/seeds/regions.csv": "region_id\n1\n", + "sql/seeds/regions.yml": ( "seeds:\n - name: regions\n description: Regions.\n columns:\n" " - name: region_id\n type: INTEGER\n" ), @@ -1786,12 +1794,12 @@ def write_job_warehouse_project(*, project_dir: Path) -> None: write_project_files( project_dir=project_dir, files={ - "models/stg.sql": _job_warehouse_model(""), - "models/orders.sql": _job_warehouse_model(' FROM __ref("stg")'), - "models/orders_daily.sql": _job_warehouse_model(' FROM __ref("orders")'), - "models/refunds.sql": _job_warehouse_model(' FROM __ref("orders_daily")'), - "models/summary.sql": _job_warehouse_model(' FROM __ref("refunds")'), - "python/assets.py": ( + "sql/models/stg.sql": _job_warehouse_model(""), + "sql/models/orders.sql": _job_warehouse_model(' FROM __ref("stg")'), + "sql/models/orders_daily.sql": _job_warehouse_model(' FROM __ref("orders")'), + "sql/models/refunds.sql": _job_warehouse_model(' FROM __ref("orders_daily")'), + "sql/models/summary.sql": _job_warehouse_model(' FROM __ref("refunds")'), + "python/nodes/refresh_marker/asset.py": ( "from sqlbuild.assets import asset\n\n\n@asset\ndef refresh_marker(ctx):\n" ' """Refresh."""\n ctx.execute_sql("SELECT \'task marker\'")\n' ), @@ -1891,15 +1899,15 @@ def run_cli_exit_code(argv: tuple[str, ...], project_dir: Path) -> int: 'name = "demo"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' '[connection]\ndatabase = "demo.duckdb"\n\n[targets.dev]\n' ), - "functions/sql/udf__band.sql": ( + "sql/functions/sql/udf__band.sql": ( "FUNCTION (description 'Band.', arguments (amount INT), returns VARCHAR);\n" "CASE WHEN amount >= 20 THEN 'large' ELSE 'small' END\n" ), - "models/parity_lookup.sql": ( + "sql/models/parity_lookup.sql": ( "MODEL (description 'Lookup.', materialized table, " "columns (id (type INTEGER, audits [not_null])));\nSELECT CAST(NULL AS INTEGER) AS id\n" ), - "models/parity_events.sql": ( + "sql/models/parity_events.sql": ( "MODEL (description 'Events.', materialized incremental, incremental_strategy append);\n" 'SELECT 1 AS event_id, __udf("udf__band")(5) AS band\n' ), @@ -1907,7 +1915,7 @@ def run_cli_exit_code(argv: tuple[str, ...], project_dir: Path) -> int: "TEST();\n\nWITH\n__ref__parity_lookup AS (SELECT 1 AS id),\n" "__expected__parity_events AS (SELECT 99 AS event_id, 'x' AS band)\nSELECT 1\n" ), - "audits/singular/events_have_lookups.sql": ( + "sql/audits/singular/events_have_lookups.sql": ( 'AUDIT (name "events_have_lookups", severity error);\n' 'SELECT e.event_id FROM __ref("parity_events") e ' 'LEFT JOIN __ref("parity_lookup") l ON e.event_id = l.id WHERE l.id IS NULL\n' @@ -1967,7 +1975,7 @@ def unit_test_sql(*models: str) -> str: _DYNAMIC_FILES: dict[str, str] = { - "models/daily_orders.sql": ( + "sql/models/daily_orders.sql": ( "MODEL (description 'Daily orders.', materialized dynamic, refresh (lag 1h));\n" "SELECT 1 AS id\n" ), @@ -1998,8 +2006,8 @@ def dynamic_refresh_warehouses(executed_sql: list[str]) -> tuple[str, ...]: import time from pathlib import Path -from providers.gateway import GatewayProvider -from providers.journal import JournalProvider +from python.providers.gateway import GatewayProvider +from python.providers.journal import JournalProvider from sqlbuild.assets import AssetContext, asset from sqlbuild.discovery import Discovered, Item, discover @@ -2048,8 +2056,8 @@ def setup(self, ctx) -> None: time.sleep(3600) """ _SINK_FUNCTION: str = """\ -from providers.journal import JournalProvider -from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink +from python.providers.journal import JournalProvider +from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink @lifecycle_event_sink @@ -2070,12 +2078,13 @@ def sink_project(tmp_path: Path, *, parameters: str, body: str) -> Path: project_dir=project, files={ "sqlbuild_project.toml": _SINK_PROJECT_TOML, - "python/steps.py": _SINK_STEPS.format( - directory=str(tmp_path), parameters=parameters, body=body + **node_module_files( + "python/nodes/steps.py", + _SINK_STEPS.format(directory=str(tmp_path), parameters=parameters, body=body), ), - "providers/journal.py": _SINK_JOURNAL.format(directory=str(tmp_path)), - "providers/gateway.py": _SINK_GATEWAY.format(directory=str(tmp_path)), - "sinks/journal.py": _SINK_FUNCTION, + "python/providers/journal.py": _SINK_JOURNAL.format(directory=str(tmp_path)), + "python/providers/gateway.py": _SINK_GATEWAY.format(directory=str(tmp_path)), + "python/event_sinks/journal.py": _SINK_FUNCTION, }, ) return project diff --git a/tests/integration/src/sqlbuild/cli/commands/main/model_migrations/helpers.py b/tests/integration/src/sqlbuild/cli/commands/main/model_migrations/helpers.py index 0491c81693..915c33020e 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/model_migrations/helpers.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/model_migrations/helpers.py @@ -173,11 +173,11 @@ def write_project( project_dir.mkdir(parents=True, exist_ok=True) (project_dir / "sqlbuild_project.toml").write_text(project_toml, encoding="utf-8") - sources_dir: Path = project_dir / "sources" - sources_dir.mkdir(exist_ok=True) + sources_dir: Path = project_dir / "sql" / "sources" + sources_dir.mkdir(parents=True, exist_ok=True) (sources_dir / "raw.yml").write_text(RAW_SOURCES_YML, encoding="utf-8") - models_dir: Path = project_dir / "models" - models_dir.mkdir(exist_ok=True) + models_dir: Path = project_dir / "sql" / "models" + models_dir.mkdir(parents=True, exist_ok=True) existing: Path for existing in models_dir.glob("*.sql"): existing.unlink() diff --git a/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/helpers.py b/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/helpers.py index 13c53d30a5..ebe6f1bde3 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/helpers.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/helpers.py @@ -159,22 +159,22 @@ def matching(statements: tuple[str, ...], predicate: Callable[[str], bool]) -> t "[connection]\n" f'database = "{ORDERS_DATABASE}"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n" " table: raw_orders\n" ), - "models/orders_table.sql": _MODEL_HEADER.format( + "sql/models/orders_table.sql": _MODEL_HEADER.format( name="orders_table", config=(" materialized table,\n columns (order_id (audits [not_null])),\n"), ) + _ORDERS_SELECT, - "models/orders_view.sql": _MODEL_HEADER.format( + "sql/models/orders_view.sql": _MODEL_HEADER.format( name="orders_view", config=" materialized view,\n" ) + 'SELECT order_id, amount FROM __ref("orders_table")\n', - "models/orders_merge.sql": _MODEL_HEADER.format( + "sql/models/orders_merge.sql": _MODEL_HEADER.format( name="orders_merge", config=( " materialized incremental,\n" @@ -187,7 +187,7 @@ def matching(statements: tuple[str, ...], predicate: Callable[[str], bool]) -> t ), ) + _ORDERS_SELECT, - "models/orders_daily.sql": _MODEL_HEADER.format( + "sql/models/orders_daily.sql": _MODEL_HEADER.format( name="orders_daily", config=( " materialized incremental,\n" @@ -337,7 +337,7 @@ def scenario_relation_name(project_dir: Path, suffix: str) -> str: def revise_model(project_dir: Path, name: str) -> None: """Change one model's definition by adding a constant column.""" - model: Path = project_dir / "models" / f"{name}.sql" + model: Path = project_dir / "sql" / "models" / f"{name}.sql" _ = model.write_text( model.read_text(encoding="utf-8").replace("SELECT ", "SELECT 1 AS revision, ", 1), encoding="utf-8", @@ -347,7 +347,7 @@ def revise_model(project_dir: Path, name: str) -> None: def add_post_hook(project_dir: Path, name: str, sql: str) -> str: """Give one model an inline SQL post hook, returning its original definition.""" - model: Path = project_dir / "models" / f"{name}.sql" + model: Path = project_dir / "sql" / "models" / f"{name}.sql" original: str = model.read_text(encoding="utf-8") _ = model.write_text( re.sub( @@ -363,7 +363,7 @@ def add_post_hook(project_dir: Path, name: str, sql: str) -> str: def add_upstream_reads(project_dir: Path, name: str, upstream: tuple[str, ...]) -> None: """Make one model read ``upstream`` without changing its rows, so it builds after them.""" - model: Path = project_dir / "models" / f"{name}.sql" + model: Path = project_dir / "sql" / "models" / f"{name}.sql" filters: str = " AND ".join( f'NOT EXISTS (SELECT 1 FROM __ref("{reference}") WHERE FALSE)' for reference in upstream ) diff --git a/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/test_guarded_cases.py b/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/test_guarded_cases.py index e985e12248..77b24a83dd 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/test_guarded_cases.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/test_guarded_cases.py @@ -114,7 +114,7 @@ def test_given_fingerprint_table_dropped_mid_build_when_building_then_later_mode code, output, counts, _ = run_counted(project_dir=project_dir, args=("build",), capsys=capsys) after_loss: dict[str, int] = fingerprint_rows(project_dir) - _ = (project_dir / "models" / f"{test_case.hooked_model}.sql").write_text( + _ = (project_dir / "sql" / "models" / f"{test_case.hooked_model}.sql").write_text( original, encoding="utf-8" ) third_code, third_output, _, _ = run_counted( diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_audit_command_storage.py b/tests/integration/src/sqlbuild/cli/commands/main/test_audit_command_storage.py index 651dff425e..34f1dedf95 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_audit_command_storage.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_audit_command_storage.py @@ -53,8 +53,8 @@ def test_given_a_target_schema_when_auditing_alone_then_history_is_stored_where_ _ = (tmp_path / "sqlbuild_project.toml").write_text( _PROJECT + test_case.target_toml, encoding="utf-8" ) - (tmp_path / "models").mkdir() - _ = (tmp_path / "models" / "orders.sql").write_text(_ORDERS_MODEL, encoding="utf-8") + (tmp_path / "sql" / "models").mkdir(parents=True) + _ = (tmp_path / "sql" / "models" / "orders.sql").write_text(_ORDERS_MODEL, encoding="utf-8") assert main(["--no-color", "--project-dir", str(tmp_path), "build"]) == 0 _ = capsys.readouterr() diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_build_test_planning.py b/tests/integration/src/sqlbuild/cli/commands/main/test_build_test_planning.py index 442c3acad1..8eb63d6802 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_build_test_planning.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_build_test_planning.py @@ -13,7 +13,7 @@ "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = "demo.duckdb"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " materialized table,\n" " contract enforced,\n" @@ -24,7 +24,7 @@ ");\n\n" "SELECT 1 AS order_id, 5 AS amount\n" ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( 'MODEL (description "Test model order_totals.", materialized table);\n\nSELECT order_id, amount * 2 AS doubled FROM __ref("orders")\n' ), "tests/unit/test_order_totals.sql": ( diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_command_interruption.py b/tests/integration/src/sqlbuild/cli/commands/main/test_command_interruption.py index e38dee4e50..02f123d04f 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_command_interruption.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_command_interruption.py @@ -95,7 +95,7 @@ _LINE, settle_seconds=1.5, files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( f"MODEL (description 'Orders.', materialized table);\n{_ENDLESS}\n" ) }, @@ -117,7 +117,7 @@ "Value: ", _LINE, presses=2, - files={"python/assets/reader.py": _READING_ASSET}, + files={"python/nodes/assets/reader/asset.py": _READING_ASSET}, expected_within_seconds=5.0, ), ], diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_compile.py b/tests/integration/src/sqlbuild/cli/commands/main/test_compile.py index 380744a427..fd8b881920 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_compile.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_compile.py @@ -44,10 +44,10 @@ def test_given_typed_dependency_when_compiling_cte_then_preserves_binding_and_ou capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - models: Path = tmp_path / "models" - models.mkdir() - sources: Path = tmp_path / "sources" - sources.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) + sources: Path = tmp_path / "sql" / "sources" + sources.mkdir(parents=True) (sources / "orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n contract: enforced\n" ' expression: "(SELECT CAST(1 AS BIGINT) AS order_id)"\n' @@ -80,8 +80,8 @@ def test_given_multiple_typed_model_headers_when_compiling_then_cli_preserves_he (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - models_dir: Path = tmp_path / "models" - models_dir.mkdir() + models_dir: Path = tmp_path / "sql" / "models" + models_dir.mkdir(parents=True) (models_dir / "staged_orders.sql").write_text( "MODEL (description 'Test model staged_orders.',\n" " materialized table,\n" @@ -110,7 +110,7 @@ def test_given_multiple_typed_model_headers_when_compiling_then_cli_preserves_he assert exit_code == 0 assert summary["models"] == test_case.expected_count assert summary["errors"] == 0 - assert (tmp_path / "target" / "compiled" / "models" / "orders.sql").is_file() + assert (tmp_path / "target" / "compiled" / "sql" / "models" / "orders.sql").is_file() @pytest.mark.parametrize( @@ -130,7 +130,7 @@ def test_given_model_macro_when_compiling_with_sql_rules_then_expands_once_and_p (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = ["SQLCLEAN001"]\n' ) - macro_dir: Path = tmp_path / "models" / "orders" / "_sqlbuild" / "_macros" / "python" + macro_dir: Path = tmp_path / "sql" / "models" / "orders" / "_sqlbuild" / "_macros" / "python" macro_dir.mkdir(parents=True) (macro_dir / "missing_value.py").write_text( "from pathlib import Path\n" @@ -140,7 +140,7 @@ def test_given_model_macro_when_compiling_with_sql_rules_then_expands_once_and_p " counter.write_text(str(count + 1))\n" " return 'NULL'\n" ) - (tmp_path / "models" / "orders" / "orders.sql").write_text( + (tmp_path / "sql" / "models" / "orders" / "orders.sql").write_text( "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id WHERE 1 = @py.missing_value()\n" ) exit_code: int = main(["--project-dir", str(tmp_path), "compile", "--json", "--no-cache"]) @@ -170,8 +170,8 @@ def test_given_unicode_model_when_compiling_twice_then_cli_preserves_unchanged_a (tmp_path / "sqlbuild_project.toml").write_text( 'name = "inventory"\nadapter = "duckdb"\n', encoding="utf-8" ) - model_path: Path = tmp_path / "models" / "products.sql" - model_path.parent.mkdir() + model_path: Path = tmp_path / "sql" / "models" / "products.sql" + model_path.parent.mkdir(parents=True) model_path.write_text( "MODEL (description 'Test model products.', materialized table);\nSELECT 'café' AS product_name \n\n", encoding="utf-8", @@ -181,7 +181,7 @@ def test_given_unicode_model_when_compiling_twice_then_cli_preserves_unchanged_a ["--project-dir", str(tmp_path), "--no-color", "compile", "--no-cache"] ) _ = capsys.readouterr() - artifact_path: Path = tmp_path / "target" / "compiled" / "models" / "products.sql" + artifact_path: Path = tmp_path / "target" / "compiled" / "sql" / "models" / "products.sql" unchanged_mtime_ns: int = 1_000_000_000 os.utime(artifact_path, ns=(unchanged_mtime_ns, unchanged_mtime_ns)) second_exit_code: int = main( @@ -232,8 +232,8 @@ def test_given_supported_snowflake_aggregation_when_compiling_then_project_succe (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "order_summary.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "order_summary.sql" + model.parent.mkdir(parents=True) model.write_text( f"MODEL (description 'Test model order_summary.', database warehouse, schema analytics);\n\n{test_case.query_sql}", encoding="utf-8", @@ -276,8 +276,8 @@ def test_given_nullable_output_when_compiling_contract_then_only_schema_nullabil (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (description 'Test model orders.',\n" " contract enforced,\n" @@ -311,14 +311,23 @@ def test_given_relative_project_directory_when_compiling_then_private_macro_is_v capsys: pytest.CaptureFixture[str], ) -> None: project_dir: Path = tmp_path / "project" - (project_dir / "models" / "orders" / "_sqlbuild" / "_macros" / "python").mkdir(parents=True) + (project_dir / "sql" / "models" / "orders" / "_sqlbuild" / "_macros" / "python").mkdir( + parents=True + ) (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) ( - project_dir / "models" / "orders" / "_sqlbuild" / "_macros" / "python" / "order_id.py" + project_dir + / "sql" + / "models" + / "orders" + / "_sqlbuild" + / "_macros" + / "python" + / "order_id.py" ).write_text('def order_id() -> str:\n return "CAST(1 AS INTEGER)"\n', encoding="utf-8") - (project_dir / "models" / "orders" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders" / "orders.sql").write_text( "MODEL (description 'Test model orders.', materialized table);\nSELECT @py.order_id() AS order_id\n", encoding="utf-8", ) @@ -347,8 +356,8 @@ def test_given_sql_test_chain_when_compiling_then_native_planner_writes_complete 'name = "orders"\nadapter = "duckdb"\n\n[settings]\nsql_analysis = true\n', encoding="utf-8", ) - models_dir: Path = tmp_path / "models" - models_dir.mkdir() + models_dir: Path = tmp_path / "sql" / "models" + models_dir.mkdir(parents=True) (models_dir / "stg_orders.sql").write_text( 'MODEL (description "Test model stg_orders.", materialized table);\nSELECT order_id, amount FROM __source("raw_orders")\n', encoding="utf-8", @@ -357,8 +366,8 @@ def test_given_sql_test_chain_when_compiling_then_native_planner_writes_complete 'MODEL (description "Test model orders.", materialized table);\nSELECT order_id, amount FROM __ref("stg_orders")\n', encoding="utf-8", ) - sources_dir: Path = tmp_path / "sources" - sources_dir.mkdir() + sources_dir: Path = tmp_path / "sql" / "sources" + sources_dir.mkdir(parents=True) (sources_dir / "raw_orders.yml").write_text( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n schema: main\n table: raw_orders\n", encoding="utf-8", diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_model_headers.py b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_model_headers.py index bc0919fdc0..0072f03237 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_model_headers.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_model_headers.py @@ -72,7 +72,7 @@ "c_orders": MACRO_COLUMN_MODEL, }, expected_message=( - "models/b_orders.sql model has duplicate column 'ID' " + "sql/models/b_orders.sql model has duplicate column 'ID' " "(column names are case-insensitive)" ), ), @@ -80,7 +80,7 @@ description="a nullable not_null column stops before a later duplicate column", models={"b_orders": NULLABLE_NOT_NULL_MODEL, "c_orders": DUPLICATE_COLUMN_MODEL}, expected_message=( - "models/b_orders.sql column 'id' cannot set nullable = true and audit not_null" + "sql/models/b_orders.sql column 'id' cannot set nullable = true and audit not_null" ), ), FirstModelErrorTestCase( @@ -110,7 +110,7 @@ def test_given_several_failing_models_when_compiling_then_the_first_in_model_ord amount_type="VARCHAR", amount_description="'${label}'", expected_location={ - "path": "models/a_orders.sql", + "path": "sql/models/a_orders.sql", "line": 3, "column": 3, "end_line": 3, @@ -122,7 +122,7 @@ def test_given_several_failing_models_when_compiling_then_the_first_in_model_ord amount_type="'${amount_type}'", amount_description="'Order amount'", expected_location={ - "path": "models/a_orders.sql", + "path": "sql/models/a_orders.sql", "line": 3, "column": 3, "end_line": 3, diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_native_facts.py b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_native_facts.py index 2c61d74947..d98e0ac9f8 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_native_facts.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_native_facts.py @@ -70,8 +70,8 @@ def test_given_derived_native_facts_when_compiling_then_contract_and_execution_a capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_DERIVED_RELATION_PROJECT) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( "MODEL (description 'Test model orders.', contract enforced, columns (order_id (type BIGINT, nullable false)));\n" + test_case.query_sql @@ -83,7 +83,9 @@ def test_given_derived_native_facts_when_compiling_then_contract_and_execution_a assert exit_code == test_case.expected_exit_code assert tuple(item["code"] for item in diagnostics) == test_case.expected_diagnostics - compiled_sql: str = (tmp_path / "target" / "compiled" / "models" / "orders.sql").read_text() + compiled_sql: str = ( + tmp_path / "target" / "compiled" / "sql" / "models" / "orders.sql" + ).read_text() with duckdb.connect() as connection: rows: tuple[tuple[int, ...], ...] = tuple(connection.execute(compiled_sql).fetchall()) assert rows == test_case.expected_rows @@ -118,8 +120,8 @@ def test_given_star_over_inferred_upstream_when_compiling_then_downstream_bindin capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_DERIVED_RELATION_PROJECT) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "staged_orders.sql").write_text( "MODEL (description 'Test model staged_orders.');\nSELECT 1 AS order_id" ) @@ -161,16 +163,16 @@ def test_given_star_over_derived_table_when_compiling_then_lineage_matches_proje capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_DERIVED_RELATION_PROJECT) - seeds: Path = tmp_path / "seeds" - seeds.mkdir() + seeds: Path = tmp_path / "sql" / "seeds" + seeds.mkdir(parents=True) (seeds / "order_labels.csv").write_text("order_id,label\n1,first\n") (seeds / "order_labels.yml").write_text( "seeds:\n - name: order_labels\n description: Test seed order_labels.\n columns:\n" " - name: order_id\n type: INTEGER\n" " - name: label\n type: VARCHAR\n" ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "staged_orders.sql").write_text( "MODEL (description 'Test model staged_orders.');\nSELECT 1 AS order_id, CAST(10 AS DOUBLE) AS amount" ) @@ -236,8 +238,8 @@ def test_given_snapshot_reader_when_compiling_then_validity_columns_are_known( capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "customer_snapshot.sql").write_text( "MODEL (description 'Test model customer_snapshot.', materialized snapshot, unique_key [customer_id], snapshot_strategy timestamp, " f"updated_at updated_at{test_case.snapshot_config});\n" @@ -288,7 +290,9 @@ def test_given_duckdb_keyword_function_when_compiling_then_compiled_sql_executes assert exit_code == test_case.expected_exit_code assert codes == test_case.expected_diagnostics - compiled_sql: str = (tmp_path / "target" / "compiled" / "models" / "orders.sql").read_text() + compiled_sql: str = ( + tmp_path / "target" / "compiled" / "sql" / "models" / "orders.sql" + ).read_text() with duckdb.connect() as connection: assert len(connection.execute(compiled_sql).fetchall()) == 1 @@ -340,10 +344,10 @@ def test_given_input_and_output_share_name_when_compiling_then_lineage_keeps_inp capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - models: Path = tmp_path / "models" - models.mkdir() - sources: Path = tmp_path / "sources" - sources.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) + sources: Path = tmp_path / "sql" / "sources" + sources.mkdir(parents=True) (sources / "orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n contract: enforced\n" " expression: orders_input\n columns:\n" @@ -373,7 +377,7 @@ def test_given_input_and_output_share_name_when_compiling_then_lineage_keeps_inp # order_id, amount, and the physical status column, for five edges in total. assert lineage["edge_count"] == test_case.expected_edge_count compiled_sql: str = ( - tmp_path / "target" / "compiled" / "models" / "order_totals.sql" + tmp_path / "target" / "compiled" / "sql" / "models" / "order_totals.sql" ).read_text() with duckdb.connect() as connection: connection.execute( @@ -446,8 +450,8 @@ def test_given_bound_wildcard_or_using_join_when_compiling_then_facts_match_exec capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_DERIVED_RELATION_PROJECT) - sources: Path = tmp_path / "sources" - sources.mkdir() + sources: Path = tmp_path / "sql" / "sources" + sources.mkdir(parents=True) (sources / "orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n contract: enforced\n" " expression: orders_input\n columns:\n" @@ -455,8 +459,8 @@ def test_given_bound_wildcard_or_using_join_when_compiling_then_facts_match_exec " - name: category\n type: VARCHAR\n" " - name: amount\n type: DOUBLE\n" ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "selected_orders.sql").write_text( f"MODEL (description 'Test model selected_orders.', contract enforced, columns ({test_case.output_contract}));\n" + test_case.query_sql @@ -469,7 +473,9 @@ def test_given_bound_wildcard_or_using_join_when_compiling_then_facts_match_exec compiled_models: list[dict[str, object]] = cast(list[dict[str, object]], resources["models"]) lineage: dict[str, object] = cast(dict[str, object], compiled_models[0]["lineage"]) assert lineage["edge_count"] == test_case.expected_edges - sql: str = (tmp_path / "target" / "compiled" / "models" / "selected_orders.sql").read_text() + sql: str = ( + tmp_path / "target" / "compiled" / "sql" / "models" / "selected_orders.sql" + ).read_text() with duckdb.connect() as connection: connection.execute( "CREATE TABLE orders_input (order_id BIGINT, category VARCHAR, amount DOUBLE)" @@ -499,16 +505,16 @@ def test_given_object_wildcard_when_compiling_then_lineage_preserves_payload_inp (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n[defaults]\ndatabase = "warehouse"\nschema = "analytics"\n' ) - sources: Path = tmp_path / "sources" - sources.mkdir() + sources: Path = tmp_path / "sql" / "sources" + sources.mkdir(parents=True) (sources / "orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n contract: enforced\n" " expression: orders_input\n columns:\n" " - name: order_id\n type: BIGINT\n" " - name: amount\n type: DOUBLE\n" ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "selected_orders.sql").write_text( "MODEL (description 'Test model selected_orders.', contract enforced, columns (order_id (type BIGINT, nullable true)));\n" + test_case.query_sql diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_prepared_artifacts.py b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_prepared_artifacts.py index 1ebc4f3c5d..7f8522b5e2 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_prepared_artifacts.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_prepared_artifacts.py @@ -194,8 +194,8 @@ def test_given_existing_artifacts_when_rules_fail_then_staged_changes_are_not_pu config_path: Path = tmp_path / "sqlbuild_project.toml" config: str = 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = ["SQLCLEAN021"]\n' config_path.write_text(config, encoding="utf-8") - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) header: str = "MODEL (description 'Test model.', materialized table, contract enforced, columns (order_id (type INTEGER)));\n" for index in range(test_case.model_count): (models / f"orders_{index:03}.sql").write_text( @@ -217,13 +217,13 @@ def test_given_existing_artifacts_when_rules_fail_then_staged_changes_are_not_pu modified_times: dict[Path, int] = {path: path.stat().st_mtime_ns for path in before} assert len(before) == test_case.model_count assert staging_directories(tmp_path / "target") == [] - stale: Path = compiled / "models" / "obsolete.sql" + stale: Path = compiled / "sql" / "models" / "obsolete.sql" stale.write_text("SELECT 0\n", encoding="utf-8") (models / "orders_000.sql").write_text( header + "SELECT CAST(2 AS INTEGER) AS order_id\n", encoding="utf-8" ) rules: Path = tmp_path / "rules" - rules.mkdir() + rules.mkdir(parents=True) (rules / "orders.py").write_text( "from sqlbuild.rules import Finding, Model, RuleContext, rule\n" '@rule(code="XSQBRARCH001", message="Model rejected", remediation="Update the model.")\n' @@ -237,11 +237,13 @@ def test_given_existing_artifacts_when_rules_fail_then_staged_changes_are_not_pu assert main(arguments) == 1 failed: dict[str, object] = json.loads(capsys.readouterr().out) assert failed["has_errors"] is True - changed: Path = compiled / "models" / "orders_000.sql" + changed: Path = compiled / "sql" / "models" / "orders_000.sql" assert {path: path.read_bytes() for path in before} == before - assert (tmp_path / "target" / "compiled-failed" / "models" / "orders_000.sql").read_bytes() == ( + assert ( + tmp_path / "target" / "compiled-failed" / "sql" / "models" / "orders_000.sql" + ).read_bytes() == ( b"-- sqb: compile failed for this model; not buildable\n" - b"-- XSQBRARCH001 at models/orders_000.sql:1:1: Model rejected\n" + b"-- XSQBRARCH001 at sql/models/orders_000.sql:1:1: Model rejected\n" b"SELECT CAST(2 AS INTEGER) AS order_id\n" ) assert stale.exists() @@ -294,7 +296,9 @@ def test_given_leftover_staging_when_compiling_then_only_abandoned_staging_is_re assert exit_code == 0 assert payload["has_errors"] is False assert tuple(remaining) == test_case.expected_remaining - assert len(list((target / "compiled" / "models").glob("*.sql"))) == test_case.model_count + assert ( + len(list((target / "compiled" / "sql" / "models").glob("*.sql"))) == test_case.model_count + ) @pytest.mark.skipif( @@ -314,11 +318,11 @@ def test_given_compiled_dir_on_other_filesystem_when_compiling_then_artifacts_ar write_prepared_artifacts_project(project_dir=tmp_path, model_count=test_case.model_count) with TemporaryDirectory(dir=_SECOND_FILESYSTEM) as other_filesystem: compiled: Path = Path(other_filesystem) / "compiled" - compiled.mkdir() - (tmp_path / "target").mkdir() + compiled.mkdir(parents=True) + (tmp_path / "target").mkdir(parents=True) (tmp_path / "target" / "compiled").symlink_to(compiled, target_is_directory=True) exit_code: int = main(["--project-dir", str(tmp_path), "compile", "--no-cache", "--json"]) - published: list[Path] = sorted((compiled / "models").glob("*.sql")) + published: list[Path] = sorted((compiled / "sql" / "models").glob("*.sql")) leftovers: list[str] = sorted(path.name for path in compiled.rglob(".*")) with duckdb.connect() as connection: last_value: object = connection.execute( diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_rule_failures.py b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_rule_failures.py index f9732b5574..68b23ef642 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_rule_failures.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_rule_failures.py @@ -47,7 +47,7 @@ _FAILING: str = 'SELECT o.order_id, status FROM __ref("orders") AS o' _FAILED_OPEN_ORDERS: bytes = ( b"-- sqb: compile failed for this model; not buildable\n" - b"-- SQLCLEAN028 at models/open_orders.sql:6:20: " + b"-- SQLCLEAN028 at sql/models/open_orders.sql:6:20: " b"Single-relation query mixes qualified and unqualified columns\n" b'SELECT o.order_id, status FROM __ref("orders") AS o\n' ) @@ -92,17 +92,17 @@ open_orders_sql=_FAILING, expected_exit_code=1, expected_compiled={ - "models/open_orders.sql": _PASSING_OPEN_ORDERS, - "models/orders.sql": _ORDERS_SQL, - "models/retired_orders.sql": _ORDERS_SQL, + "sql/models/open_orders.sql": _PASSING_OPEN_ORDERS, + "sql/models/orders.sql": _ORDERS_SQL, + "sql/models/retired_orders.sql": _ORDERS_SQL, }, expected_failed={ - "models/open_orders.sql": _FAILED_OPEN_ORDERS, - "models/orders.sql": _ORDERS_SQL, + "sql/models/open_orders.sql": _FAILED_OPEN_ORDERS, + "sql/models/orders.sql": _ORDERS_SQL, }, expected_manifest=False, expected_output_fragment=( - "Failed SQL: target/compiled-failed/models/open_orders.sql\n" + "Failed SQL: target/compiled-failed/sql/models/open_orders.sql\n" " Wrote: target/compiled-failed/\n" ), ), @@ -111,10 +111,10 @@ open_orders_sql=_PASSING.replace("o.status", "o.status AS order_status"), expected_exit_code=0, expected_compiled={ - "models/open_orders.sql": _PASSING_OPEN_ORDERS.replace( + "sql/models/open_orders.sql": _PASSING_OPEN_ORDERS.replace( b"o.status", b"o.status AS order_status" ), - "models/orders.sql": _ORDERS_SQL, + "sql/models/orders.sql": _ORDERS_SQL, }, expected_failed={}, expected_manifest=True, @@ -132,9 +132,9 @@ def test_given_rule_findings_when_compiling_then_failed_sql_is_written_beside_co project_dir=tmp_path, files={ "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": _ORDERS, - "models/open_orders.sql": open_orders_model(_PASSING), - "models/retired_orders.sql": _ORDERS, + "sql/models/orders.sql": _ORDERS, + "sql/models/open_orders.sql": open_orders_model(_PASSING), + "sql/models/retired_orders.sql": _ORDERS, }, ) compile_args: list[str] = [ @@ -149,9 +149,9 @@ def test_given_rule_findings_when_compiling_then_failed_sql_is_written_beside_co assert (tmp_path / "target" / "manifest.json").exists() write_project_files( project_dir=tmp_path, - files={"models/open_orders.sql": open_orders_model(test_case.open_orders_sql)}, + files={"sql/models/open_orders.sql": open_orders_model(test_case.open_orders_sql)}, ) - (tmp_path / "models" / "retired_orders.sql").unlink() + (tmp_path / "sql" / "models" / "retired_orders.sql").unlink() exit_code: int = main(compile_args) @@ -176,7 +176,7 @@ def test_given_rule_findings_when_compiling_then_failed_sql_is_written_beside_co expected_artifacts={ "compiled_sql_dir": "target/compiled-failed/", "manifest": None, - "failed_model_sql": ["target/compiled-failed/models/open_orders.sql"], + "failed_model_sql": ["target/compiled-failed/sql/models/open_orders.sql"], }, ), ], @@ -189,8 +189,8 @@ def test_given_manifest_requested_when_rules_fail_then_json_reports_no_manifest( project_dir=tmp_path, files={ "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": _ORDERS, - "models/open_orders.sql": open_orders_model(_FAILING), + "sql/models/orders.sql": _ORDERS, + "sql/models/open_orders.sql": open_orders_model(_FAILING), }, ) @@ -241,9 +241,9 @@ def test_given_failing_and_passing_compiles_when_alternating_then_compiled_faile project_dir=tmp_path, files={ "sqlbuild_project.toml": _PROJECT, - "models/customers.sql": _CUSTOMERS, - "models/orders.sql": _ORDERS, - "models/open_orders.sql": open_orders_model(_PASSING), + "sql/models/customers.sql": _CUSTOMERS, + "sql/models/orders.sql": _ORDERS, + "sql/models/open_orders.sql": open_orders_model(_PASSING), }, ) compiled: Path = tmp_path / "target" / "compiled" @@ -274,59 +274,62 @@ def edited(files: dict[str, str]) -> None: compiled_once(0) first_pass: dict[str, bytes] = artifact_tree(compiled) failing: dict[str, bytes] = { - "models/customers.sql": b"SELECT 1 AS customer_id\n", - "models/open_orders.sql": _FAILED_OPEN_ORDERS, - "models/orders.sql": _ORDERS_SQL, + "sql/models/customers.sql": b"SELECT 1 AS customer_id\n", + "sql/models/open_orders.sql": _FAILED_OPEN_ORDERS, + "sql/models/orders.sql": _ORDERS_SQL, } assert sorted(first_pass) == [ - "models/customers.sql", - "models/open_orders.sql", - "models/orders.sql", + "sql/models/customers.sql", + "sql/models/open_orders.sql", + "sql/models/orders.sql", ] assert not failed.exists() edited( - {"models/open_orders.sql": open_orders_model(_FAILING), "models/new_orders.sql": _ORDERS} + { + "sql/models/open_orders.sql": open_orders_model(_FAILING), + "sql/models/new_orders.sql": _ORDERS, + } ) compiled_once(1) assert artifact_tree(compiled) == first_pass - assert artifact_tree(failed) == {**failing, "models/new_orders.sql": _ORDERS_SQL} + assert artifact_tree(failed) == {**failing, "sql/models/new_orders.sql": _ORDERS_SQL} - (tmp_path / "models" / "new_orders.sql").unlink() + (tmp_path / "sql" / "models" / "new_orders.sql").unlink() compiled_once(1) rewarmed(1) assert artifact_tree(compiled) == first_pass assert artifact_tree(failed) == failing - edited({"models/open_orders.sql": open_orders_model(_PASSING)}) + edited({"sql/models/open_orders.sql": open_orders_model(_PASSING)}) compiled_once(0) assert not failed.exists() assert artifact_tree(compiled) == first_pass - edited({"models/open_orders.sql": open_orders_model(_FAILING)}) + edited({"sql/models/open_orders.sql": open_orders_model(_FAILING)}) compiled_once(1) assert artifact_tree(failed) == failing assert artifact_tree(compiled) == first_pass - edited({"models/customers.sql": _CUSTOMERS.replace("1 AS", "2 AS")}) + edited({"sql/models/customers.sql": _CUSTOMERS.replace("1 AS", "2 AS")}) compiled_once(1) rewarmed(1) assert artifact_tree(failed) == { **failing, - "models/customers.sql": b"SELECT 2 AS customer_id\n", + "sql/models/customers.sql": b"SELECT 2 AS customer_id\n", } assert artifact_tree(compiled) == first_pass - edited({"models/open_orders.sql": open_orders_model(_PASSING)}) + edited({"sql/models/open_orders.sql": open_orders_model(_PASSING)}) compiled_once(0) rewarmed(0) assert not failed.exists() assert artifact_tree(compiled) == { **first_pass, - "models/customers.sql": b"SELECT 2 AS customer_id\n", + "sql/models/customers.sql": b"SELECT 2 AS customer_id\n", } - edited({"models/customers.sql": _CUSTOMERS}) + edited({"sql/models/customers.sql": _CUSTOMERS}) compiled_once(0) rewarmed(0) assert not failed.exists() @@ -369,12 +372,12 @@ def test_given_resources_edited_while_rules_fail_when_the_fix_passes_then_compil project_dir: Path = tmp_path / "project" files: dict[str, str] = { "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": _ORDERS, - "models/order_totals.sql": _TOTALS, - "models/open_orders.sql": open_orders_model(_PASSING), + "sql/models/orders.sql": _ORDERS, + "sql/models/order_totals.sql": _TOTALS, + "sql/models/open_orders.sql": open_orders_model(_PASSING), "tests/unit/test_order_totals.sql": _TOTALS_TEST, - "functions/sql/is_large.sql": _LARGE_FUNCTION, - "audits/singular/positive_totals.sql": _TOTALS_AUDIT, + "sql/functions/sql/is_large.sql": _LARGE_FUNCTION, + "sql/audits/singular/positive_totals.sql": _TOTALS_AUDIT, } write_project_files(project_dir=project_dir, files=files) compile_args: list[str] = ["--project-dir", str(project_dir), "compile", *test_case.extra_args] @@ -383,12 +386,13 @@ def test_given_resources_edited_while_rules_fail_when_the_fix_passes_then_compil def fixed_after_failing(name: str, edits: dict[str, str]) -> tuple[str, dict[str, bytes]]: write_project_files( project_dir=project_dir, - files={**edits, "models/open_orders.sql": open_orders_model(_FAILING)}, + files={**edits, "sql/models/open_orders.sql": open_orders_model(_FAILING)}, ) assert main(compile_args) == 1 _ = capsys.readouterr() write_project_files( - project_dir=project_dir, files={"models/open_orders.sql": open_orders_model(_PASSING)} + project_dir=project_dir, + files={"sql/models/open_orders.sql": open_orders_model(_PASSING)}, ) exit_code: int = main(compile_args) stdout, stderr = capsys.readouterr() @@ -408,25 +412,25 @@ def fixed_after_failing(name: str, edits: dict[str, str]) -> tuple[str, dict[str "after_test_edit", { "tests/unit/test_order_totals.sql": _TOTALS_TEST.replace("10 AS total", "20 AS total"), - "functions/sql/is_large.sql": _LARGE_FUNCTION.replace("> 100", "> 200"), + "sql/functions/sql/is_large.sql": _LARGE_FUNCTION.replace("> 100", "> 200"), }, ) model_edit_stderr, after_model_edit = fixed_after_failing( "after_model_edit", { - "models/order_totals.sql": _TOTALS.replace("* 10", "* 20"), - "audits/singular/positive_totals.sql": _TOTALS_AUDIT.replace("< 0", "<= 0"), + "sql/models/order_totals.sql": _TOTALS.replace("* 10", "* 20"), + "sql/audits/singular/positive_totals.sql": _TOTALS_AUDIT.replace("< 0", "<= 0"), }, ) assert test_case.expected_after_failure_fragment in test_edit_stderr assert test_case.expected_after_failure_fragment in model_edit_stderr assert changed_artifacts(passing, after_test_edit) == [ - "functions/sql/is_large.sql", + "sql/functions/sql/is_large.sql", "tests/order_totals/order_totals_case.sql", ] assert changed_artifacts(after_test_edit, after_model_edit) == [ - "audits/singular/positive_totals.sql", - "models/order_totals.sql", + "sql/audits/singular/positive_totals.sql", + "sql/models/order_totals.sql", "tests/order_totals/order_totals_case.sql", ] diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_warm_target.py b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_warm_target.py index 45dc6dac01..226f4fe3d1 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_compile_warm_target.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_compile_warm_target.py @@ -70,9 +70,9 @@ def test_given_warm_target_with_stale_entries_when_compiling_then_preserves_unch [ WarmTargetEditTestCase( "one_model_edited", - edited_path="models/inventory.sql", + edited_path="sql/models/inventory.sql", edited_contents="MODEL (description 'Test model inventory.');\nSELECT 3 AS item_id\n", - expected_changed=("models/inventory.sql",), + expected_changed=("sql/models/inventory.sql",), ) ], ids=lambda case: case.description, diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_config_byte_order_mark.py b/tests/integration/src/sqlbuild/cli/commands/main/test_config_byte_order_mark.py index 6d8dfbbccb..30b8ef4926 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_config_byte_order_mark.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_config_byte_order_mark.py @@ -29,8 +29,8 @@ def test_given_config_with_byte_order_mark_when_running_commands_then_they_succe (tmp_path / "sqlbuild_local.toml").write_text( "\ufeff[settings]\nsql_analysis = true\n", encoding="utf-8" ) - (tmp_path / "models").mkdir() - (tmp_path / "models" / "orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql" / "models" / "orders.sql").write_text( "MODEL (description 'One row per order.', materialized table);\n\nSELECT 1 AS order_id\n" ) diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_contract_command.py b/tests/integration/src/sqlbuild/cli/commands/main/test_contract_command.py index d7b44ca166..9a4b81a4a9 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_contract_command.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_contract_command.py @@ -35,7 +35,7 @@ def test_given_physical_drift_when_diffing_contracts_then_reports_without_writin capsys: pytest.CaptureFixture[str], ) -> None: database: Path = prepare_contract_project(tmp_path) - original_model: str = (tmp_path / "models" / "orders.sql").read_text(encoding="utf-8") + original_model: str = (tmp_path / "sql" / "models" / "orders.sql").read_text(encoding="utf-8") exit_code: int = main( [ @@ -57,7 +57,9 @@ def test_given_physical_drift_when_diffing_contracts_then_reports_without_writin assert "missing_declaration" in output assert "model:orders" in output assert "source:raw_orders" in output - assert (tmp_path / "models" / "orders.sql").read_text(encoding="utf-8") == original_model + assert (tmp_path / "sql" / "models" / "orders.sql").read_text( + encoding="utf-8" + ) == original_model assert database.is_file() @@ -96,8 +98,8 @@ def test_given_missing_declarations_when_generating_additively_then_preserves_me assert exit_code == test_case.expected_exit_code assert "0 contract difference(s)" in capsys.readouterr().out - model_sql: str = (tmp_path / "models" / "orders.sql").read_text(encoding="utf-8") - source_yaml: str = (tmp_path / "sources" / "raw.yml").read_text(encoding="utf-8") + model_sql: str = (tmp_path / "sql" / "models" / "orders.sql").read_text(encoding="utf-8") + source_yaml: str = (tmp_path / "sql" / "sources" / "raw.yml").read_text(encoding="utf-8") assert "id (type INTEGER)" in model_sql assert "name (type VARCHAR)" in model_sql assert "-- keep model metadata" in model_sql @@ -165,7 +167,7 @@ def test_given_parameterized_physical_type_when_generating_then_writes_valid_mod capsys: pytest.CaptureFixture[str], ) -> None: database: Path = prepare_contract_project(tmp_path) - model_path: Path = tmp_path / "models" / "orders.sql" + model_path: Path = tmp_path / "sql" / "models" / "orders.sql" _ = model_path.write_text( "MODEL (description 'Test model orders.', materialized table);\n" "SELECT CAST(1 AS INTEGER) AS id, CAST(1 AS DECIMAL(10,2)) AS amount\n", @@ -261,7 +263,7 @@ def test_given_multiple_sources_in_one_file_when_generating_then_all_edits_are_r ] ) - source_yaml: str = (tmp_path / "sources" / "raw.yml").read_text(encoding="utf-8") + source_yaml: str = (tmp_path / "sql" / "sources" / "raw.yml").read_text(encoding="utf-8") assert exit_code == test_case.expected_exit_code assert "0 contract difference(s)" in capsys.readouterr().out assert "type: 'BIGINT'" in source_yaml @@ -287,7 +289,7 @@ def test_given_conflicting_contract_when_overwriting_then_physical_shape_replace capsys: pytest.CaptureFixture[str], ) -> None: _ = prepare_contract_project(tmp_path) - model_path: Path = tmp_path / "models" / "orders.sql" + model_path: Path = tmp_path / "sql" / "models" / "orders.sql" _ = model_path.write_text( """MODEL (description "Test model orders.", materialized table @@ -449,7 +451,7 @@ def test_given_unavailable_inspection_target_credentials_when_generating_then_va f'database = "${{ENV:{missing_variable}}}"\n' ), ) - model_path: Path = tmp_path / "models" / "orders.sql" + model_path: Path = tmp_path / "sql" / "models" / "orders.sql" exit_code: int = main( [ @@ -489,13 +491,13 @@ def test_given_shared_schema_when_one_binding_differs_then_write_fails_closed( capsys: pytest.CaptureFixture[str], ) -> None: _ = prepare_contract_project(tmp_path) - schema_path: Path = tmp_path / "schemas" / "order.sql" - schema_path.parent.mkdir() + schema_path: Path = tmp_path / "sql" / "schemas" / "order.sql" + schema_path.parent.mkdir(parents=True) _ = schema_path.write_text( "SCHEMA (name order, columns (id (type INTEGER)));\n", encoding="utf-8", ) - model_path: Path = tmp_path / "models" / "orders.sql" + model_path: Path = tmp_path / "sql" / "models" / "orders.sql" _ = model_path.write_text( "MODEL (materialized table, model_schema order);\n" "SELECT CAST(1 AS INTEGER) AS id, CAST('a' AS VARCHAR) AS name\n", @@ -541,7 +543,7 @@ def test_given_source_conflicts_when_overwriting_then_preserves_retained_metadat capsys: pytest.CaptureFixture[str], ) -> None: _ = prepare_contract_project(tmp_path) - source_path: Path = tmp_path / "sources" / "raw.yml" + source_path: Path = tmp_path / "sql" / "sources" / "raw.yml" _ = source_path.write_text( """sources: - name: raw_orders @@ -601,7 +603,7 @@ def test_given_cli_vars_when_writing_then_validation_recompile_uses_same_values( capsys: pytest.CaptureFixture[str], ) -> None: _ = prepare_contract_project(tmp_path) - model_path: Path = tmp_path / "models" / "orders.sql" + model_path: Path = tmp_path / "sql" / "models" / "orders.sql" _ = model_path.write_text( "MODEL (description 'Test model orders.', materialized table);\n" "SELECT CAST(@@identifier AS INTEGER) AS id, CAST('a' AS VARCHAR) AS name\n", @@ -645,7 +647,7 @@ def test_given_unresolved_additive_type_conflict_when_writing_then_file_is_not_r capsys: pytest.CaptureFixture[str], ) -> None: _ = prepare_contract_project(tmp_path) - model_path: Path = tmp_path / "models" / "orders.sql" + model_path: Path = tmp_path / "sql" / "models" / "orders.sql" _ = model_path.write_text( "MODEL (description 'Test model orders.', materialized table, columns (id (type BIGINT), name (type VARCHAR)));\n" "SELECT CAST(1 AS INTEGER) AS id, CAST('a' AS VARCHAR) AS name\n", @@ -691,12 +693,12 @@ def test_given_relative_project_directory_when_diffing_contract_then_private_mac capsys: pytest.CaptureFixture[str], ) -> None: project_dir: Path = tmp_path / "project" - project_dir.mkdir() + project_dir.mkdir(parents=True) _ = prepare_contract_project(project_dir) - root_model_path: Path = project_dir / "models" / "orders.sql" + root_model_path: Path = project_dir / "sql" / "models" / "orders.sql" root_model_path.unlink() - model_path: Path = project_dir / "models" / "orders" / "orders.sql" - model_path.parent.mkdir() + model_path: Path = project_dir / "sql" / "models" / "orders" / "orders.sql" + model_path.parent.mkdir(parents=True) _ = model_path.write_text( "MODEL (description 'Test model orders.', materialized table);\nSELECT @py.order_id() AS id, CAST('a' AS VARCHAR) AS name\n", encoding="utf-8", @@ -744,7 +746,7 @@ def test_given_indentless_source_columns_when_generating_then_preserves_metadata capsys: pytest.CaptureFixture[str], ) -> None: _ = prepare_contract_project(tmp_path) - source_path: Path = tmp_path / "sources" / "raw.yml" + source_path: Path = tmp_path / "sql" / "sources" / "raw.yml" _ = source_path.write_text( """sources: - name: raw_orders diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_default_connection.py b/tests/integration/src/sqlbuild/cli/commands/main/test_default_connection.py index 726428d9cc..1a411ebec1 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_default_connection.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_default_connection.py @@ -287,8 +287,10 @@ def test_given_freshness_without_strategy_or_type_when_observing_then_both_are_i capsys: pytest.CaptureFixture[str], ) -> None: write_default_connection_project(project_dir=tmp_path, project_toml=_ONE_CONNECTION_PROJECT) - (tmp_path / "sources").mkdir() - _ = (tmp_path / "sources" / "raw.yml").write_text(test_case.sources_yaml, encoding="utf-8") + (tmp_path / "sql" / "sources").mkdir(parents=True) + _ = (tmp_path / "sql" / "sources" / "raw.yml").write_text( + test_case.sources_yaml, encoding="utf-8" + ) execute_duckdb_sql( db_path=tmp_path / "shop.duckdb", sql=( diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_dollar_quoted_literals.py b/tests/integration/src/sqlbuild/cli/commands/main/test_dollar_quoted_literals.py index a105be6cc8..da27d05bcc 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_dollar_quoted_literals.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_dollar_quoted_literals.py @@ -52,8 +52,8 @@ def test_given_dollar_quoted_literal_when_building_then_literal_is_preserved_and 'name = "orders"\nadapter = "duckdb"\n\n[connection]\ndatabase = "orders.duckdb"\n', encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( 'MODEL (description "Orders", materialized table);\nSELECT 1 AS order_id\n', encoding="utf-8", diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_expansion_boundaries.py b/tests/integration/src/sqlbuild/cli/commands/main/test_expansion_boundaries.py index 6b0371161f..895713c4f5 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_expansion_boundaries.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_expansion_boundaries.py @@ -21,10 +21,10 @@ ) _NEG: dict[str, str] = { - "models/_macros/python/neg.py": 'def neg():\n """Return minus one."""\n return "-1"\n' + "sql/models/_macros/python/neg.py": 'def neg():\n """Return minus one."""\n return "-1"\n' } _NOTED: dict[str, str] = { - "models/_macros/python/noted.py": ( + "sql/models/_macros/python/noted.py": ( 'def noted():\n """Return one with a note."""\n return "1 -- one"\n' ) } @@ -50,7 +50,7 @@ "SELECT 5 -@py.blank()-2 AS x, 7 AS y", ((7, 7),), files={ - "models/_macros/python/blank.py": ( + "sql/models/_macros/python/blank.py": ( 'def blank():\n """Return nothing."""\n return ""\n' ) }, @@ -60,7 +60,7 @@ "SELECT 4 AS @py.stem()_count", ((4,),), files={ - "models/_macros/python/stem.py": ( + "sql/models/_macros/python/stem.py": ( 'def stem():\n """Return a stem."""\n return "orders"\n' ) }, @@ -69,13 +69,13 @@ "a negative constant", 'SELECT -@const("minus_one") AS x, 7 AS y', ((1, 7),), - files={"models/_constants/minus_one.sql": "CONSTANT (name minus_one, value -1);\n"}, + files={"sql/models/_constants/minus_one.sql": "CONSTANT (name minus_one, value -1);\n"}, ), ExpansionBoundaryTestCase( "a negative enum member", 'SELECT -@enum("sign").DOWN AS x, 7 AS y', ((1, 7),), - files={"models/_enums/sign.sql": "ENUM (name sign, members (DOWN -1, UP 1));\n"}, + files={"sql/models/_enums/sign.sql": "ENUM (name sign, members (DOWN -1, UP 1));\n"}, ), ExpansionBoundaryTestCase( "a negative variable", @@ -87,7 +87,7 @@ "SELECT -@sql.negative_one() AS x, 7 AS y", ((1, 7),), files={ - "models/_macros/sql/negative_one.sql": ( + "sql/models/_macros/sql/negative_one.sql": ( 'MACRO (\n description "Minus one",\n);\n\n-1\n' ) }, @@ -98,7 +98,7 @@ ((1, 7),), model_config=", audits [x_is (value -1)]", files={ - "audits/generic/x_is.sql": ( + "sql/audits/generic/x_is.sql": ( "AUDIT ();\nSELECT * FROM @relation WHERE x <> -@value AND y > 0\n" ) }, @@ -109,7 +109,7 @@ ((1, 7),), model_config=', post_hooks [sql("note_value", value: -1)]', files={ - "hooks/sql/note_value.sql": ( + "sql/hooks/sql/note_value.sql": ( 'HOOK (description "Read a value");\nSELECT -@value AS x, 7 AS y\n' ) }, @@ -119,7 +119,7 @@ 'SELECT x, 7 AS y FROM __ref("amounts")', ((1, 7),), files={ - "models/amounts.sql": ( + "sql/models/amounts.sql": ( "MODEL (description 'Amounts.', materialized table);\nSELECT 1 AS x\n" ), "tests/unit/test_orders.sql": ( @@ -136,7 +136,7 @@ 'SELECT x, 7 AS y FROM __source("amounts") WHERE x = 2', ((2, 7),), files={ - "sources/amounts.yml": ( + "sql/sources/amounts.yml": ( "sources:\n - name: amounts\n description: Amounts.\n" ' expression: "(SELECT * FROM (VALUES (1), (2)) AS v(x)) -- amounts"\n' ) @@ -147,7 +147,7 @@ "SELECT @sql.same(2 + 3 -- five\n) AS x, 7 AS y", ((5, 7),), files={ - "models/_macros/sql/same.sql": ( + "sql/models/_macros/sql/same.sql": ( 'MACRO (\n description "The amount",\n arguments (amount INTEGER),\n);\n\n' "@amount\n" ) diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_format.py b/tests/integration/src/sqlbuild/cli/commands/main/test_format.py index 09fcbec0f7..5a41f23b8a 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_format.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_format.py @@ -93,8 +93,8 @@ def test_given_authored_function_spelling_when_formatting_then_only_layout_chang (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "{test_case.adapter}"\n' ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Order flags");\n' f'select {test_case.authored_expression} as order_flag from __source("raw_orders")\n' @@ -121,8 +121,8 @@ def test_given_commented_lateral_alias_when_formatting_then_canonical_sql_is_wri ) -> None: """A comment plus generated AS used to decline the entire larger query silently.""" (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "snowflake"\n') - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) columns: str = ", ".join(f"parsed.order_attribute_{index}" for index in range(47)) model.write_text( 'MODEL (description "Order items");\n' @@ -176,8 +176,8 @@ def test_given_typed_null_input_when_fixture_formatting_then_canonical_empty_fix '\n[connection]\ndatabase = "orders.duckdb"\n', encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "stg_orders.sql").write_text( "MODEL (\n" ' description "Staged orders",\n' @@ -239,8 +239,8 @@ def test_given_sql_test_string_when_formatting_then_project_still_compiles( (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\nSELECT order_id, order_label FROM __ref("stg_orders")\n', encoding="utf-8", @@ -286,7 +286,7 @@ def test_given_table_function_argument_when_formatting_then_intrinsic_restores_a (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - function: Path = tmp_path / "functions" / "sql" / "expand_order.sql" + function: Path = tmp_path / "sql" / "functions" / "sql" / "expand_order.sql" function.parent.mkdir(parents=True) function.write_text( """FUNCTION ( @@ -299,8 +299,8 @@ def test_given_table_function_argument_when_formatting_then_intrinsic_restores_a """, encoding="utf-8", ) - model: Path = tmp_path / "models" / "expanded_orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "expanded_orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Expanded orders");\nselect expanded.order_id from orders as ' 'source_orders cross join __table_fn("expand_order")(source_orders.order_id) as expanded\n', @@ -333,8 +333,8 @@ def test_given_explicit_null_ordering_when_formatting_then_clause_is_preserved( (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\n' 'select order_id from __ref("stg_orders") order by order_id nulls last\n', @@ -371,8 +371,8 @@ def test_given_exact_contract_casts_when_formatting_then_rule_still_passes( 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQBRCONTRACT105"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (\n" ' description "Typed orders",\n' @@ -435,8 +435,8 @@ def test_given_description_width_when_formatting_then_wrapped_model_compiles( f'name = "orders"\nadapter = "duckdb"\n[format]\nline_width = {test_case.line_width}\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( f'MODEL (\n description "{test_case.authored_description}"\n);\nSELECT 1 AS order_id\n', encoding="utf-8", @@ -474,8 +474,8 @@ def test_given_trailing_comments_when_formatting_twice_then_second_run_changes_n 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) header: str = 'MODEL (description "Orders placed by customers.");\n\n' - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text(header + test_case.body, encoding="utf-8") first_exit: int = main(["--project-dir", str(tmp_path), "format", "--no-cache"]) @@ -505,8 +505,8 @@ def test_given_schema_column_when_formatting_then_header_remains_valid_and_idemp (tmp_path / "sqlbuild_project.toml").write_text( 'name = "catalog"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "catalog_objects.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "catalog_objects.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (\n" ' description "Catalog objects.",\n' @@ -552,8 +552,8 @@ def test_given_unparseable_file_when_formatting_then_file_is_untouched_and_fault (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text(test_case.authored_sql, encoding="utf-8") exit_code: int = main(["--project-dir", str(tmp_path), "format"]) @@ -596,8 +596,8 @@ def test_given_native_formatter_decline_when_formatting_then_whole_file_is_uncha (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "{test_case.adapter}"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (\n" ' description "Orders.", \n' @@ -650,8 +650,8 @@ def test_given_inline_typed_null_fixture_when_formatting_then_one_pass_is_idempo (tmp_path / "sqlbuild_project.toml").write_text( 'name = "customers"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "customers.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "customers.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (\n" ' description "Customers.",\n' @@ -709,8 +709,8 @@ def test_given_redundant_typed_null_after_multi_projection_when_formatting_then_ (tmp_path / "sqlbuild_project.toml").write_text( 'name = "customer_segments"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "customer_clusters.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "customer_clusters.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (\n" ' description "Customer clusters.",\n' @@ -876,8 +876,8 @@ def test_given_format_selectors_when_scoping_then_paths_and_default_exclusions_a (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "customers.sql").write_text( 'MODEL (description "Customers.", materialized table, ' "columns (customer_id (type INTEGER),));\n" @@ -959,8 +959,8 @@ def test_given_missing_description_when_formatting_then_check_and_write_fault( (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text(test_case.authored_sql, encoding="utf-8") text_exit: int = main(["--project-dir", str(tmp_path), "format", "--check"]) @@ -990,51 +990,51 @@ def test_given_missing_description_when_formatting_then_check_and_write_fault( [ FormatPathArgumentsIntegrationTestCase( description="positional file formats only that file", - arguments=("models/marts/orders.sql",), + arguments=("sql/models/marts/orders.sql",), expected_exit_code=0, - expected_formatted=("models/marts/orders.sql",), - expected_unchanged=("models/staging/stg_orders.sql",), + expected_formatted=("sql/models/marts/orders.sql",), + expected_unchanged=("sql/models/staging/stg_orders.sql",), expected_output_fragment="1 files", ), FormatPathArgumentsIntegrationTestCase( description="bare file path in select formats only that file", - arguments=("--select", "models/staging/stg_orders.sql"), + arguments=("--select", "sql/models/staging/stg_orders.sql"), expected_exit_code=0, - expected_formatted=("models/staging/stg_orders.sql",), - expected_unchanged=("models/marts/orders.sql",), + expected_formatted=("sql/models/staging/stg_orders.sql",), + expected_unchanged=("sql/models/marts/orders.sql",), expected_output_fragment="1 files", ), FormatPathArgumentsIntegrationTestCase( description="positional folder formats every file below it", - arguments=("models",), + arguments=("sql/models",), expected_exit_code=0, - expected_formatted=("models/marts/orders.sql", "models/staging/stg_orders.sql"), + expected_formatted=("sql/models/marts/orders.sql", "sql/models/staging/stg_orders.sql"), expected_unchanged=(), expected_output_fragment="2 files", ), FormatPathArgumentsIntegrationTestCase( description="missing positional path is a clear error", - arguments=("models/marts/missing.sql",), + arguments=("sql/models/marts/missing.sql",), expected_exit_code=1, expected_formatted=(), - expected_unchanged=("models/marts/orders.sql", "models/staging/stg_orders.sql"), - expected_output_fragment="format path 'models/marts/missing.sql' does not exist", + expected_unchanged=("sql/models/marts/orders.sql", "sql/models/staging/stg_orders.sql"), + expected_output_fragment="format path 'sql/models/marts/missing.sql' does not exist", ), FormatPathArgumentsIntegrationTestCase( description="path outside formatted folders lists the valid roots", arguments=("sqlbuild_project.toml",), expected_exit_code=1, expected_formatted=(), - expected_unchanged=("models/marts/orders.sql", "models/staging/stg_orders.sql"), - expected_output_fragment="use a path under models/, tests/", + expected_unchanged=("sql/models/marts/orders.sql", "sql/models/staging/stg_orders.sql"), + expected_output_fragment="use a path under sql/, tests/", ), FormatPathArgumentsIntegrationTestCase( description="unknown path selector root lists the formatter roots", arguments=("--select", "path:seeds"), expected_exit_code=1, expected_formatted=(), - expected_unchanged=("models/marts/orders.sql", "models/staging/stg_orders.sql"), - expected_output_fragment="'functions/'", + expected_unchanged=("sql/models/marts/orders.sql", "sql/models/staging/stg_orders.sql"), + expected_output_fragment="'sql/', 'tests/'", ), ], ids=lambda case: case.description, @@ -1048,7 +1048,7 @@ def test_given_file_paths_when_formatting_then_only_named_files_change( (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - for relative_path in ("models/marts/orders.sql", "models/staging/stg_orders.sql"): + for relative_path in ("sql/models/marts/orders.sql", "sql/models/staging/stg_orders.sql"): (tmp_path / relative_path).parent.mkdir(parents=True, exist_ok=True) (tmp_path / relative_path).write_text(_UNFORMATTED_ORDERS_SQL, encoding="utf-8") monkeypatch.chdir(tmp_path) @@ -1093,8 +1093,8 @@ def test_given_leading_cte_comment_when_formatting_then_comment_rule_still_passe 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN033"]\n', encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "raw_orders.sql").write_text( 'MODEL (description "Test model raw_orders.", materialized view);\n\nSELECT 1 AS order_id, 2 AS customer_id\n', encoding="utf-8", @@ -1138,14 +1138,14 @@ def test_given_backtick_identifier_apostrophe_when_formatting_then_macro_call_st (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "{test_case.adapter}"\n', encoding="utf-8" ) - macros: Path = tmp_path / "models" / "_macros" / "python" + macros: Path = tmp_path / "sql" / "models" / "_macros" / "python" macros.mkdir(parents=True) (macros / "labels.py").write_text( 'def label(expression: str) -> str:\n """Return one column expression."""\n' " return expression\n", encoding="utf-8", ) - model_path: Path = tmp_path / "models" / "orders.sql" + model_path: Path = tmp_path / "sql" / "models" / "orders.sql" model_path.write_text( 'MODEL (description "Orders", database warehouse, schema analytics);\n\n' 'select `customer\'s id` as customer_id, @py.label("order_id") as order_id ' @@ -1191,8 +1191,8 @@ def test_given_dollar_quoted_apostrophe_when_formatting_then_reference_survives_ '[targets.prod]\nconnection = "local"\nschema = "prod"\n', encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( 'MODEL (description "Orders", materialized table);\n\nSELECT 1 AS order_id\n', encoding="utf-8", @@ -1239,8 +1239,8 @@ def test_given_select_all_and_implicit_aliases_when_formatting_then_only_layout_ (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "{test_case.adapter}"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) authored: str = " ".join(test_case.expected_body.lower().split()) model.write_text(f'MODEL (description "Orders");\n\n{authored}\n', encoding="utf-8") @@ -1354,8 +1354,8 @@ def test_given_project_line_width_when_formatting_then_long_lines_wrap_and_proje '[targets.prod]\nconnection = "local"\nschema = "prod"\n', encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders_with_a_long_name.sql").write_text( 'MODEL (description "Orders", materialized table);\n\n' "SELECT\n 1 AS order_id,\n 5 AS amount,\n NULL AS fallback_amount,\n 1 AS tax\n", diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_format_cache.py b/tests/integration/src/sqlbuild/cli/commands/main/test_format_cache.py index aedf6b9359..b5fe61ac7b 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_format_cache.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_format_cache.py @@ -155,7 +155,7 @@ def test_given_file_with_fault_when_checking_twice_then_fault_is_reported_both_t capsys: pytest.CaptureFixture[str], ) -> None: write_formatted_cache_project(project_dir=tmp_path) - products: Path = tmp_path / "models" / "products.sql" + products: Path = tmp_path / "sql" / "models" / "products.sql" _ = products.write_text( products.read_text(encoding="utf-8").replace(test_case.removed_text, ""), encoding="utf-8", diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_format_fix.py b/tests/integration/src/sqlbuild/cli/commands/main/test_format_fix.py index 64d94ccdc7..24991f54ca 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_format_fix.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_format_fix.py @@ -40,8 +40,8 @@ def test_given_bare_union_when_fixing_then_preserves_output_and_is_idempotent( test_case: FormatCompileIntegrationTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) original = 'MODEL (description "Orders");\nSELECT 1 AS order_id UNION SELECT 2 AS order_id\n' model.write_text(original) assert main(["--project-dir", str(tmp_path), "format", "--fix", "--check", "--json"]) == 1 @@ -65,8 +65,8 @@ def test_given_null_comparison_when_fixing_then_refuses_semantics_change( test_case: FormatCompileIntegrationTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id WHERE 1 = NULL\n') main(["--project-dir", str(tmp_path), "format", "--fix", "--json"]) payload: dict[str, Any] = json.loads(capsys.readouterr().out) @@ -85,8 +85,8 @@ def test_given_unanalysed_model_when_fixing_then_verification_preserves_original test_case: FormatCompileIntegrationTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "customers.sql").write_text( 'MODEL (description "Customers");\nSELECT 1 AS customer_id\n' ) @@ -139,8 +139,8 @@ def test_given_safe_native_fix_when_formatting_then_compiler_and_query_results_a test_case: SemanticFixTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders", schema analytics);\n' + test_case.sql) assert main(["--project-dir", str(tmp_path), "format", "--fix", "--json"]) == 0 payload: dict[str, Any] = json.loads(capsys.readouterr().out) @@ -200,8 +200,8 @@ def test_given_dialect_sensitive_rewrite_when_fixing_then_requires_semantic_proo (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "{test_case.dialect}"\n' ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders", database example, schema analytics);\n' + test_case.sql ) @@ -222,8 +222,8 @@ def test_given_one_unverifiable_file_when_fixing_then_only_that_file_keeps_its_o test_case: FormatCompileIntegrationTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) verified: Path = models / "orders.sql" verified.write_text( 'MODEL (description "Orders");\nSELECT 1 AS order_id UNION SELECT 2 AS order_id\n' @@ -267,10 +267,10 @@ def test_given_existing_errors_and_unexpandable_file_when_fixing_then_other_file test_case: FormatCompileIntegrationTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - models: Path = tmp_path / "models" - models.mkdir() - (tmp_path / "macros" / "python").mkdir(parents=True) - (tmp_path / "macros" / "python" / "relations.py").write_text( + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) + (tmp_path / "sql" / "macros" / "python").mkdir(parents=True) + (tmp_path / "sql" / "macros" / "python" / "relations.py").write_text( "def orders_relation() -> str:\n return '__ref(\"orders\")'\n" ) fixable: Path = models / "orders.sql" @@ -320,8 +320,8 @@ def test_given_only_unverifiable_fixes_when_fixing_then_every_refusal_is_listed_ test_case: FormatCompileIntegrationTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( 'MODEL (description "Orders");\nSELECT 1 AS order_id WHERE 1 = NULL\n' ) @@ -399,8 +399,8 @@ def test_given_unused_cte_output_when_fixing_then_model_rows_are_unchanged( test_case: UnusedOutputDifferentialCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_DIFFERENTIAL_TOML) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "raw_orders.sql").write_text(_DIFFERENTIAL_RAW_SQL) (models / "summary.sql").write_text( 'MODEL (description "Summary");\n' @@ -433,11 +433,11 @@ def test_given_macro_and_crlf_source_when_fixing_then_previews_preserve_bytes_an test_case: FormatCompileIntegrationTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - macros: Path = tmp_path / "macros" / "python" + macros: Path = tmp_path / "sql" / "macros" / "python" macros.mkdir(parents=True) (macros / "values.py").write_text('def order_value():\n return "1"\n') - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) original: bytes = ( b'MODEL (description "Orders");\r\n' b"SELECT @py.order_value() AS order_id UNION SELECT 2 AS order_id\r\n" diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_format_preservation.py b/tests/integration/src/sqlbuild/cli/commands/main/test_format_preservation.py index e4a353483d..0230ea8660 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_format_preservation.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_format_preservation.py @@ -101,10 +101,10 @@ def test_given_authored_syntax_when_formatting_then_spelling_and_idempotence_are test_case: FormatterSyntaxTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_WINDOW_SYNTAX_PROJECT_TOML) - macros: Path = tmp_path / "models" / "_macros" / "python" + macros: Path = tmp_path / "sql" / "models" / "_macros" / "python" macros.mkdir(parents=True) (macros / "orders.py").write_text(test_case.macro_source) - model: Path = tmp_path / "models" / "order_summary.sql" + model: Path = tmp_path / "sql" / "models" / "order_summary.sql" model.write_text( 'MODEL (description "Order summary", database warehouse, schema analytics);\n-- Order query.\n' + test_case.sql @@ -134,8 +134,8 @@ def test_given_computed_variant_key_when_formatting_then_preserves_syntax_and_co test_case: FormatterSyntaxTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "snowflake"\n') - model: Path = tmp_path / "models" / "order_summary.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "order_summary.sql" + model.parent.mkdir(parents=True) original: str = ( 'MODEL (description "Order summary", database warehouse, schema analytics); \n' + test_case.sql @@ -202,8 +202,8 @@ def test_given_sqlbuild_call_when_formatting_then_authored_spelling_is_preserved test_case: FormatterSyntaxTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - model: Path = tmp_path / "models" / "order_summary.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "order_summary.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Order summary");\n' + test_case.sql + "\n") assert main(["--project-dir", str(tmp_path), "format", "--json"]) == 0 capsys.readouterr() @@ -239,7 +239,7 @@ def test_given_cte_macros_and_comments_when_formatting_then_layout_and_rules_sta (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = ["SQLCLEAN033"]\n' ) - macros: Path = tmp_path / "models" / "_macros" / "python" + macros: Path = tmp_path / "sql" / "models" / "_macros" / "python" macros.mkdir(parents=True) (macros / "ctes.py").write_text( "def make_ctes(name: str, source: str) -> str:\n" @@ -247,7 +247,7 @@ def test_given_cte_macros_and_comments_when_formatting_then_layout_and_rules_sta "def other_ctes(name: str, source: str) -> str:\n" " return make_ctes(name, source)\n" ) - model: Path = tmp_path / "models" / "order_summary.sql" + model: Path = tmp_path / "sql" / "models" / "order_summary.sql" model.write_text('MODEL (description "Order summary");\n' + test_case.sql + "\n") assert main(["--project-dir", str(tmp_path), "compile", "--no-cache"]) == 0 capsys.readouterr() @@ -301,13 +301,13 @@ def test_given_multibyte_text_before_restorations_when_formatting_then_output_is test_case: FormatterSyntaxTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "snowflake"\n') - macros: Path = tmp_path / "models" / "_macros" / "python" + macros: Path = tmp_path / "sql" / "models" / "_macros" / "python" macros.mkdir(parents=True) (macros / "orders.py").write_text( "def copy_orders(name: str, source: str) -> str:\n" ' return f"{name} AS (SELECT * FROM {source})"\n' ) - model: Path = tmp_path / "models" / "order_summary.sql" + model: Path = tmp_path / "sql" / "models" / "order_summary.sql" model.write_text( 'MODEL (description "Orders é € 😀");\n' + test_case.sql + "\n", encoding="utf-8" ) @@ -326,7 +326,7 @@ def test_given_multibyte_text_before_restorations_when_formatting_then_output_is [ ExpressionMacroFormatTestCase( "project macro", - "macros/sql", + "sql/macros/sql", # A project macro needs consumers in more than one folder to stay a project macro. ("staging", "marts"), _NORMALISE_NAME_HEADER + _NORMALISE_NAME_AUTHORED, @@ -334,14 +334,14 @@ def test_given_multibyte_text_before_restorations_when_formatting_then_output_is ), ExpressionMacroFormatTestCase( "scoped macro", - "models/staging/_sqlbuild/_macros/sql", + "sql/models/staging/_sqlbuild/_macros/sql", ("staging",), _NORMALISE_NAME_HEADER + _NORMALISE_NAME_AUTHORED, _NORMALISE_NAME_HEADER + _NORMALISE_NAME_FORMATTED, ), ExpressionMacroFormatTestCase( "multi-line string after a backslash-escaped quote", - "models/staging/_sqlbuild/_macros/sql", + "sql/models/staging/_sqlbuild/_macros/sql", ("staging",), _NORMALISE_NAME_HEADER + "CONCAT(\n @column_name,\n 'O\\'Brien\n kept indent',\n 'tail'\n)\n", @@ -350,7 +350,7 @@ def test_given_multibyte_text_before_restorations_when_formatting_then_output_is ), ExpressionMacroFormatTestCase( "Databricks multi-line string after a backslash-escaped quote", - "models/staging/_sqlbuild/_macros/sql", + "sql/models/staging/_sqlbuild/_macros/sql", ("staging",), _NORMALISE_NAME_HEADER + "CONCAT(\n @column_name,\n 'O\\'Brien\n kept indent',\n 'tail'\n)\n", @@ -360,7 +360,7 @@ def test_given_multibyte_text_before_restorations_when_formatting_then_output_is ), ExpressionMacroFormatTestCase( "DuckDB multi-line E-string after a backslash-escaped quote", - "models/staging/_sqlbuild/_macros/sql", + "sql/models/staging/_sqlbuild/_macros/sql", ("staging",), _NORMALISE_NAME_HEADER + "CONCAT(\n @column_name,\n E'O\\'Brien\n kept indent',\n 'tail'\n)\n", @@ -381,7 +381,7 @@ def test_given_expression_macro_when_formatting_then_body_is_laid_out_once( macro.parent.mkdir(parents=True) macro.write_text(test_case.authored_macro) for folder in test_case.consumer_folders: - model: Path = tmp_path / "models" / folder / f"{folder}_customer_names.sql" + model: Path = tmp_path / "sql" / "models" / folder / f"{folder}_customer_names.sql" model.parent.mkdir(parents=True, exist_ok=True) model.write_text( 'MODEL (description "Customer names", database warehouse, schema analytics);\n' diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_format_writes.py b/tests/integration/src/sqlbuild/cli/commands/main/test_format_writes.py index 8e9562a0be..a3ab3998d5 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_format_writes.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_format_writes.py @@ -58,11 +58,11 @@ def test_given_unwritable_file_when_formatting_then_later_files_are_left_as_auth files: list[Path] = [] directory: str for directory in test_case.directories: - (tmp_path / "models" / directory).mkdir(parents=True) - model: Path = tmp_path / "models" / directory / "orders.sql" + (tmp_path / "sql" / "models" / directory).mkdir(parents=True) + model: Path = tmp_path / "sql" / "models" / directory / "orders.sql" model.write_text(_UNFORMATTED_SQL, encoding="utf-8") files.append(model) - locked: Path = tmp_path / "models" / test_case.locked_directory + locked: Path = tmp_path / "sql" / "models" / test_case.locked_directory locked.chmod(stat.S_IRUSR | stat.S_IXUSR) try: with pytest.raises(test_case.expected_error, match=re.escape(str(locked / "orders.sql"))): @@ -75,7 +75,7 @@ def test_given_unwritable_file_when_formatting_then_later_files_are_left_as_auth tuple(path.read_text(encoding="utf-8") != _UNFORMATTED_SQL for path in files) == test_case.expected_replaced ) - assert [path.name for path in (tmp_path / "models").rglob(".*")] == [] + assert [path.name for path in (tmp_path / "sql" / "models").rglob(".*")] == [] if __name__ == "__main__": diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_ignored_cancel.py b/tests/integration/src/sqlbuild/cli/commands/main/test_ignored_cancel.py index 8b9e955965..12d2734b1d 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_ignored_cancel.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_ignored_cancel.py @@ -15,12 +15,13 @@ MidSubmitCancelTestCase, ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _STEPS: str = '''\ import time from pathlib import Path -from providers.marker import MarkerProvider +from python.providers.marker import MarkerProvider from sqlbuild.assets import AssetContext, asset from sqlbuild.discovery import Discovered, Item, discover @@ -66,7 +67,7 @@ def teardown(self) -> None: ''' _HUNG_STEPS: str = """\ -from providers.gateway import GatewayProvider +from python.providers.gateway import GatewayProvider from sqlbuild.assets import AssetContext, asset from sqlbuild.discovery import Discovered, Item, discover @@ -157,9 +158,9 @@ def test_given_steps_ignoring_cancel_when_signalled_then_the_command_exits_witho "sqlbuild_project.toml": f'name = "fulfilment"\nadapter = "{test_case.adapter}"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "python/steps.py": _STEPS.format(directory=str(tmp_path)), - "providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), - "adapters/duckdb_unrecorded.py": _UNRECORDED_ADAPTER, + "python/nodes/steps/asset.py": _STEPS.format(directory=str(tmp_path)), + "python/providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), + "python/adapters/duckdb_unrecorded.py": _UNRECORDED_ADAPTER, }, ) log: Path = tmp_path / "build.log" @@ -218,8 +219,8 @@ def test_given_a_step_in_a_provider_setup_that_never_returns_when_cancelled_then "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "python/steps.py": _HUNG_STEPS, - "providers/gateway.py": _HUNG_PROVIDER.format(directory=str(tmp_path)), + "python/nodes/steps/asset.py": _HUNG_STEPS, + "python/providers/gateway.py": _HUNG_PROVIDER.format(directory=str(tmp_path)), }, ) log: Path = tmp_path / "build.log" @@ -280,9 +281,9 @@ def test_given_a_cancel_inside_a_steps_submit_when_steps_ignore_it_then_both_are "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "python/steps.py": _STEPS.format(directory=str(tmp_path)), - "python/slow_submit.py": _SLOW_SUBMIT, - "providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), + "python/nodes/steps/asset.py": _STEPS.format(directory=str(tmp_path)), + **node_module_files("python/nodes/slow_submit.py", _SLOW_SUBMIT), + "python/providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), }, ) log: Path = tmp_path / "build.log" diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_job_selectors.py b/tests/integration/src/sqlbuild/cli/commands/main/test_job_selectors.py index d6d35709d4..4ff0f59549 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_job_selectors.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_job_selectors.py @@ -15,15 +15,15 @@ 'name = "demo"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' '[connection]\ndatabase = "demo.duckdb"\n\n[targets.dev]\n\n[targets.prod]\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table, tags [staging]);\n" "SELECT 1 AS order_id\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table, tags [finance]);\n" 'SELECT order_id FROM __ref("stg_orders")\n' ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Customers.', materialized table);\nSELECT 7 AS customer_id\n" ), } diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_job_settings.py b/tests/integration/src/sqlbuild/cli/commands/main/test_job_settings.py index 0028592a07..e99e961174 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_job_settings.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_job_settings.py @@ -30,22 +30,22 @@ '[connection]\ndatabase = "demo.duckdb"\n\n[targets.dev]\n\n[targets.prod]\n\n' '[settings]\nconcurrency = 4\n\n[vars]\namount = "1"\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n" "SELECT CAST(@@amount AS INTEGER) AS order_id\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" 'SELECT order_id FROM __ref("stg_orders")\n' ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Customers.', materialized table);\nSELECT 7 AS customer_id\n" ), - "models/order_events.sql": ( + "sql/models/order_events.sql": ( "MODEL (description 'Order events.', materialized incremental, " "incremental_strategy append);\nSELECT 1 AS event_id\n" ), - "models/refund_events.sql": ( + "sql/models/refund_events.sql": ( "MODEL (description 'Refund events.', materialized incremental, " "incremental_strategy append);\nSELECT 1 AS event_id\n" ), @@ -76,7 +76,7 @@ 'name = "events_job_group"\ndescription = "Events."\n' 'jobs = ["events_job", "refund_events_job"]\n' ), - "models/lenient_model.sql": ( + "sql/models/lenient_model.sql": ( "MODEL (description 'Lenient.', materialized table, " "columns (id (type INTEGER, audits [not_null])));\nSELECT CAST(NULL AS INTEGER) AS id\n" ), @@ -89,7 +89,7 @@ "[settings]\nload_sources = false\n" ), **{ - f"models/slow_{name}.sql": ( + f"sql/models/slow_{name}.sql": ( f"MODEL (description 'Slow {name}.', materialized table);\n" "SELECT sum(i * i % 7) AS total FROM range(25000000) AS t(i)\n" ) @@ -125,10 +125,10 @@ ), } _LENIENT_PAIR_FILES: dict[str, str] = { - "models/lenient_peer.sql": ( + "sql/models/lenient_peer.sql": ( "MODEL (description 'Lenient peer.', materialized table);\nSELECT 1 AS id\n" ), - "audits/singular/lenient_pair.sql": ( + "sql/audits/singular/lenient_pair.sql": ( 'AUDIT (name "lenient_pair", severity error);\n' 'SELECT p.id FROM __ref("lenient_peer") p ' 'LEFT JOIN __ref("lenient_model") m ON p.id = m.id WHERE m.id IS NULL\n' diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_load_command.py b/tests/integration/src/sqlbuild/cli/commands/main/test_load_command.py index c6a4ec1216..e0bc1cdfc4 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_load_command.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_load_command.py @@ -91,7 +91,7 @@ def raw_orders(ctx): _BUILD_RUN_AUTO_LOAD_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -104,7 +104,7 @@ def raw_orders(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -112,8 +112,10 @@ def raw_orders(ctx): '''Test loader raw_orders.''' return [{"order_id": 7, "status": "loaded"}] """, - "models/stg_orders.sql": ( - 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT order_id, status FROM __source("raw_orders")' + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", + "sql/models/stg_orders.sql": ( + 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT ' + 'order_id, status FROM __source("raw_orders")' ), } @@ -142,11 +144,14 @@ def raw_orders(ctx): schema = "prod" """.strip() + "\n", - "sources/raw.yml": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["sources/raw.yml"], - "python/loaders/raw_orders.py": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES[ - "python/loaders/raw_orders.py" + "sql/sources/raw.yml": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["sql/sources/raw.yml"], + "python/nodes/loaders/raw_orders/loader.py": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES[ + "python/nodes/loaders/raw_orders/loader.py" ], - "models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["models/stg_orders.sql"], + "python/nodes/loaders/raw_orders/__init__.py": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES[ + "python/nodes/loaders/raw_orders/__init__.py" + ], + "sql/models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["sql/models/stg_orders.sql"], } _SOURCE_DEFERRAL_MISSING_PROJECT_FILES: dict[str, str] = { @@ -227,7 +232,7 @@ def raw_orders(ctx): schema = "dev" """.strip() + "\n", - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -238,13 +243,14 @@ def raw_orders(ctx): type: VARCHAR """.strip() + "\n", - "models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["models/stg_orders.sql"], + "sql/models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["sql/models/stg_orders.sql"], } _SOURCE_DEFERRAL_UNSELECTED_MANAGED_PROJECT_FILES: dict[str, str] = { **_SOURCE_DEFERRAL_MISSING_PROJECT_FILES, - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT order_id, status FROM __ref("stg_orders")' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT ' + 'order_id, status FROM __ref("stg_orders")' ), } @@ -273,7 +279,7 @@ def raw_orders(ctx): _SOURCE_DEFERRAL_LOADER_DAG_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _SOURCE_DEFERRAL_PROJECT_FILES["sqlbuild_project.toml"], - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -286,29 +292,38 @@ def raw_orders(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": """ -from sqlbuild.loaders import loader - -@loader( - write_strategy="table", - columns=[ - {"name": "order_id", "type": "INTEGER"}, - {"name": "status", "type": "VARCHAR"}, - ], -) -def fetch_orders(ctx): - '''Test loader fetch_orders.''' - return [{"order_id": 7, "status": "intermediate"}] - -@loader(depends_on=[fetch_orders]) -def raw_orders(ctx): - '''Test loader raw_orders.''' - rows = ctx.query( - f"SELECT order_id, status FROM {ctx.loader(fetch_orders).destination}" - ).fetchall() - return [{"order_id": row[0], "status": "loaded-" + row[1]} for row in rows] -""", - "models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["models/stg_orders.sql"], + "python/nodes/loaders/raw_orders/fetch_orders/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader(\n" + ' write_strategy="table",\n' + " columns=[\n" + ' {"name": "order_id", "type": "INTEGER"},\n' + ' {"name": "status", "type": "VARCHAR"},\n' + " ],\n" + ")\n" + "def fetch_orders(ctx):\n" + " '''Test loader fetch_orders.'''\n" + ' return [{"order_id": 7, "status": "intermediate"}]\n' + ), + "python/nodes/loaders/raw_orders/raw_orders/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw_orders.fetch_orders.loader import fetch_orders\n" + "\n" + "\n" + "@loader(depends_on=[fetch_orders])\n" + "def raw_orders(ctx):\n" + " '''Test loader raw_orders.'''\n" + " rows = ctx.query(\n" + ' f"SELECT order_id, status FROM {ctx.loader(fetch_orders).destination}"\n' + " ).fetchall()\n" + ' return [{"order_id": row[0], "status": "loaded-" + row[1]} for row in rows]\n' + ), + "python/nodes/loaders/raw_orders/__init__.py": ( + "from .fetch_orders.loader import fetch_orders\nfrom .raw_orders.loader import raw_orders\n" + ), + "sql/models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["sql/models/stg_orders.sql"], } _SOURCE_DEFERRAL_EXPLICIT_SCHEMA_PROJECT_FILES: dict[str, str] = { @@ -325,7 +340,7 @@ def raw_orders(ctx): loader_schema = "raw_dev" """.strip() + "\n", - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -340,10 +355,13 @@ def raw_orders(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES[ - "python/loaders/raw_orders.py" + "python/nodes/loaders/raw_orders/loader.py": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES[ + "python/nodes/loaders/raw_orders/loader.py" + ], + "python/nodes/loaders/raw_orders/__init__.py": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES[ + "python/nodes/loaders/raw_orders/__init__.py" ], - "models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["models/stg_orders.sql"], + "sql/models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["sql/models/stg_orders.sql"], } _SOURCE_LOADER_COLLISION_PROJECT_FILES: dict[str, str] = { @@ -369,7 +387,7 @@ def raw_orders(ctx): _SOURCE_DEFERRAL_EXPRESSION_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _SOURCE_DEFERRAL_PROJECT_FILES["sqlbuild_project.toml"], - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -384,15 +402,18 @@ def raw_orders(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES[ - "python/loaders/raw_orders.py" + "python/nodes/loaders/raw_orders/loader.py": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES[ + "python/nodes/loaders/raw_orders/loader.py" ], - "models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["models/stg_orders.sql"], + "python/nodes/loaders/raw_orders/__init__.py": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES[ + "python/nodes/loaders/raw_orders/__init__.py" + ], + "sql/models/stg_orders.sql": _BUILD_RUN_AUTO_LOAD_PROJECT_FILES["sql/models/stg_orders.sql"], } _SOURCE_DEFERRAL_SQL_FUNCTION_PROJECT_FILES: dict[str, str] = { **_SOURCE_DEFERRAL_PROJECT_FILES, - "functions/sql/order_statuses.sql": """ + "sql/functions/sql/order_statuses.sql": """ FUNCTION (description "Test function order_statuses.", returns table ( order_id INTEGER, @@ -430,7 +451,7 @@ def raw_orders(ctx): _SOURCE_DEFERRAL_AUDIT_PROJECT_FILES: dict[str, str] = { **_SOURCE_DEFERRAL_PROJECT_FILES, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -444,7 +465,7 @@ def raw_orders(ctx): type: VARCHAR """.strip() + "\n", - "audits/generic/source_status.sql": """ + "sql/audits/generic/source_status.sql": """ AUDIT (); SELECT order_id FROM @relation WHERE status != 'prod-audit' @@ -454,7 +475,7 @@ def raw_orders(ctx): _SOURCE_DEFERRAL_BUILD_WITH_FUNCTION_PROJECT_FILES: dict[str, str] = { **_SOURCE_DEFERRAL_PROJECT_FILES, - "functions/sql/order_statuses.sql": """ + "sql/functions/sql/order_statuses.sql": """ FUNCTION (description "Test function order_statuses.", returns table ( order_id INTEGER, @@ -503,14 +524,15 @@ def raw_orders(ctx): _BUILD_RUN_AUTO_LOAD_SELECTION_PROJECT_FILES: dict[str, str] = { **_BUILD_RUN_AUTO_LOAD_PROJECT_FILES, - "models/fact_orders.sql": ( - 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT order_id, status FROM __ref("stg_orders")' + "sql/models/fact_orders.sql": ( + 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT ' + 'order_id, status FROM __ref("stg_orders")' ), } _BUILD_RUN_AUTO_LOAD_FAILURE_PROJECT_FILES: dict[str, str] = { **_BUILD_RUN_AUTO_LOAD_PROJECT_FILES, - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -518,11 +540,12 @@ def raw_orders(ctx): '''Test loader raw_orders.''' raise RuntimeError("loader exploded") """, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", } _BUILD_RUN_AUTO_LOAD_RELOAD_PROJECT_FILES: dict[str, str] = { **_BUILD_RUN_AUTO_LOAD_PROJECT_FILES, - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -531,11 +554,12 @@ def raw_orders(ctx): status = "reload" if ctx.is_reload else "incremental" return [{"order_id": 7, "status": status}] """, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", } _BUILD_RUN_AUTO_LOAD_TWO_SOURCE_PROJECT_FILES: dict[str, str] = { **_BUILD_RUN_AUTO_LOAD_PROJECT_FILES, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -557,7 +581,7 @@ def raw_orders(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_customers.py": """ + "python/nodes/loaders/raw_customers/loader.py": """ from sqlbuild.loaders import loader @loader @@ -565,14 +589,15 @@ def raw_customers(ctx): '''Test loader raw_customers.''' return [{"customer_id": 10, "name": "Ada"}] """, - "models/stg_customers.sql": ( - 'MODEL (description "Test model stg_customers.", materialized table);\n\nSELECT customer_id, name FROM __source("raw_customers")' + "sql/models/stg_customers.sql": ( + 'MODEL (description "Test model stg_customers.", materialized table);\n\nSELECT ' + 'customer_id, name FROM __source("raw_customers")' ), } _BUILD_RUN_AUTO_LOAD_SELF_MANAGED_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -584,7 +609,7 @@ def raw_customers(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -595,8 +620,10 @@ def raw_orders(ctx): "SELECT 7 AS order_id, 'self-managed' AS status" ) """, - "models/stg_orders.sql": ( - 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT order_id, status FROM __source("raw_orders")' + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", + "sql/models/stg_orders.sql": ( + 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT ' + 'order_id, status FROM __source("raw_orders")' ), } @@ -607,7 +634,7 @@ def raw_orders(ctx): "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = "demo.duckdb"\n' ), - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -620,7 +647,7 @@ def raw_orders(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -632,6 +659,7 @@ def raw_orders(ctx): {"order_id": 2, "status": "shipped"}, ] """, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, expected_exit_code=0, expected_rows=((1, "placed"), (2, "shipped")), @@ -659,7 +687,7 @@ def raw_orders(ctx): "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = "demo.duckdb"\n' ), - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -676,7 +704,7 @@ def raw_orders(ctx): write_strategy: table """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -684,7 +712,8 @@ def raw_orders(ctx): '''Test loader raw_orders.''' return [{"order_id": 3, "status": "selected"}] """, - "python/loaders/raw_events.py": """ + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", + "python/nodes/loaders/raw_events/loader.py": """ from sqlbuild.loaders import loader @loader @@ -721,7 +750,7 @@ def raw_events(ctx): "[targets.dev.vars]\n" 'tier = "dev"\n' ), - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -734,7 +763,7 @@ def raw_events(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -751,6 +780,7 @@ def raw_orders(ctx): "status": status, }] """, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, expected_exit_code=0, expected_rows=((4, "dev:cli:yes:True"),), @@ -1307,8 +1337,8 @@ def test_given_invalid_managed_source_target_config_when_planning_then_errors( "INSERT INTO prod.raw_orders VALUES (19, 'artifact-prod')", ), select=("stg_orders",), - compiled_relative_paths=("target/compiled/models/stg_orders.sql",), - runtime_relative_paths=("target/run/models/stg_orders.sql",), + compiled_relative_paths=("target/compiled/sql/models/stg_orders.sql",), + runtime_relative_paths=("target/run/sql/models/stg_orders.sql",), expected_sql_fragments=("prod.raw_orders",), unexpected_sql_fragments=("dev.raw_orders",), ), @@ -1322,8 +1352,8 @@ def test_given_invalid_managed_source_target_config_when_planning_then_errors( "INSERT INTO prod.raw_orders VALUES (20, 'function-artifact')", ), select=("order_statuses",), - compiled_relative_paths=("target/compiled/functions/sql/order_statuses.sql",), - runtime_relative_paths=("target/run/functions/sql/order_statuses.sql",), + compiled_relative_paths=("target/compiled/sql/functions/sql/order_statuses.sql",), + runtime_relative_paths=("target/run/sql/functions/sql/order_statuses.sql",), expected_sql_fragments=("prod.raw_orders",), unexpected_sql_fragments=("dev.raw_orders",), ), @@ -1338,7 +1368,7 @@ def test_given_invalid_managed_source_target_config_when_planning_then_errors( ), select=("stg_orders",), compiled_relative_paths=( - "target/compiled/audits/generic/raw_orders/source_status.sql", + "target/compiled/sql/audits/generic/raw_orders/source_status.sql", ), runtime_relative_paths=(), expected_sql_fragments=("prod.raw_orders",), @@ -1885,7 +1915,7 @@ def test_given_build_skips_loader_when_manifest_is_written_then_marks_source_aut "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = "demo.duckdb"\n' ), - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -1898,7 +1928,7 @@ def test_given_build_skips_loader_when_manifest_is_written_then_marks_source_aut type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -1910,6 +1940,7 @@ def raw_orders(ctx): {"order_id": 2, "status": "shipped"}, ] """, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, expected_exit_code=0, expected_rows=((1, "placed"), (2, "shipped")), @@ -1937,7 +1968,7 @@ def raw_orders(ctx): "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = "demo.duckdb"\n' ), - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -1954,7 +1985,7 @@ def raw_orders(ctx): write_strategy: table """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -1962,7 +1993,8 @@ def raw_orders(ctx): '''Test loader raw_orders.''' return [{"order_id": 3, "status": "selected"}] """, - "python/loaders/raw_events.py": """ + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", + "python/nodes/loaders/raw_events/loader.py": """ from sqlbuild.loaders import loader @loader @@ -1999,7 +2031,7 @@ def raw_events(ctx): "[targets.dev.vars]\n" 'tier = "dev"\n' ), - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -2012,7 +2044,7 @@ def raw_events(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2029,6 +2061,7 @@ def raw_orders(ctx): "status": status, }] """, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, expected_exit_code=0, expected_rows=((4, "dev:cli:yes:True"),), @@ -2105,7 +2138,7 @@ def test_given_source_loader_when_running_load_then_writes_source_table( "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = "demo.duckdb"\n' ), - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -2118,7 +2151,7 @@ def test_given_source_loader_when_running_load_then_writes_source_table( type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2130,6 +2163,7 @@ def raw_orders(ctx): {"order_id": 2, "status": "shipped"}, ] """, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, expected_exit_code=0, expected_rows=((1, "placed"), (2, "shipped")), @@ -2157,7 +2191,7 @@ def raw_orders(ctx): "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = "demo.duckdb"\n' ), - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -2174,7 +2208,7 @@ def raw_orders(ctx): write_strategy: table """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2182,7 +2216,8 @@ def raw_orders(ctx): '''Test loader raw_orders.''' return [{"order_id": 3, "status": "selected"}] """, - "python/loaders/raw_events.py": """ + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", + "python/nodes/loaders/raw_events/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2219,7 +2254,7 @@ def raw_events(ctx): "[targets.dev.vars]\n" 'tier = "dev"\n' ), - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -2232,7 +2267,7 @@ def raw_events(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2249,6 +2284,7 @@ def raw_orders(ctx): "status": status, }] """, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, expected_exit_code=0, expected_rows=((4, "dev:cli:yes:True"),), @@ -2362,7 +2398,7 @@ def test_given_source_loader_when_running_pipeline_then_drops_stale_staging_firs description="append creates target then appends rows using current cursor value", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_append_events description: Test source raw_append_events. @@ -2376,7 +2412,7 @@ def test_given_source_loader_when_running_pipeline_then_drops_stale_staging_firs type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2387,6 +2423,7 @@ def raw_append_events(ctx): next_id = int(ctx.current_cursor_value) + 1 return [{"event_id": next_id, "cursor_seen": str(ctx.current_cursor_value)}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_append_events\n", }, select_sql="SELECT event_id, cursor_seen FROM raw_append_events ORDER BY event_id", expected_rows=((1, "none"), (2, "1")), @@ -2395,7 +2432,7 @@ def raw_append_events(ctx): description="merge updates existing rows and inserts new rows using cursor value", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_merge_customers description: Test source raw_merge_customers. @@ -2412,7 +2449,7 @@ def raw_append_events(ctx): type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2428,6 +2465,7 @@ def raw_merge_customers(ctx): {"customer_id": 3, "name": "new", "updated_at": 2}, ] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_merge_customers\n", }, select_sql=( "SELECT customer_id, name, updated_at FROM raw_merge_customers ORDER BY customer_id" @@ -2438,7 +2476,7 @@ def raw_merge_customers(ctx): description="merge supports composite unique keys", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_merge_composite description: Test source raw_merge_composite. @@ -2457,7 +2495,7 @@ def raw_merge_customers(ctx): type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2470,6 +2508,7 @@ def raw_merge_composite(ctx): {"entity_id": 1, "source": "feed", "value": "inserted", "version": 2}, ] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_merge_composite\n", }, select_sql=( "SELECT entity_id, source, value, version FROM raw_merge_composite ORDER BY source" @@ -2480,7 +2519,7 @@ def raw_merge_composite(ctx): description="delete insert replaces loaded cursor range and preserves outside rows", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_delete_insert_events description: Test source raw_delete_insert_events. @@ -2494,7 +2533,7 @@ def raw_merge_composite(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2512,6 +2551,7 @@ def raw_delete_insert_events(ctx): {"event_id": 3, "status": "new-range"}, ] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_delete_insert_events\n", }, select_sql=( "SELECT event_id, status FROM raw_delete_insert_events ORDER BY event_id, status" @@ -2527,7 +2567,7 @@ def raw_delete_insert_events(ctx): description="delete insert supports timestamp cursor ranges", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_delete_insert_ts description: Test source raw_delete_insert_ts. @@ -2541,7 +2581,7 @@ def raw_delete_insert_events(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from datetime import datetime from sqlbuild.loaders import loader @@ -2561,6 +2601,7 @@ def raw_delete_insert_ts(ctx): {"event_at": datetime(2026, 1, 1, 2, 0, 0), "status": "new-range"}, ] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_delete_insert_ts\n", }, select_sql=( "SELECT strftime(event_at, '%Y-%m-%d %H:%M:%S'), status " @@ -2577,7 +2618,7 @@ def raw_delete_insert_ts(ctx): description="delete insert empty rerun leaves existing target unchanged", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_delete_insert_empty description: Test source raw_delete_insert_empty. @@ -2591,7 +2632,7 @@ def raw_delete_insert_ts(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2604,6 +2645,7 @@ def raw_delete_insert_empty(ctx): ] return [] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_delete_insert_empty\n", }, select_sql="SELECT event_id, status FROM raw_delete_insert_empty ORDER BY event_id", expected_rows=((1, "existing"), (2, "existing")), @@ -2615,7 +2657,7 @@ def raw_delete_insert_empty(ctx): description="current cursor value is none when no cursor column is configured", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_no_cursor description: Test source raw_no_cursor. @@ -2628,7 +2670,7 @@ def raw_delete_insert_empty(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader run_count = 0 @@ -2640,6 +2682,7 @@ def raw_no_cursor(ctx): run_count += 1 return [{"run_number": run_count, "cursor_seen": str(ctx.current_cursor_value)}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_no_cursor\n", }, select_sql="SELECT run_number, cursor_seen FROM raw_no_cursor ORDER BY run_number", expected_rows=((1, "None"), (1, "None")), @@ -2648,7 +2691,7 @@ def raw_no_cursor(ctx): description="current cursor value is none when existing target is empty", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_empty_cursor description: Test source raw_empty_cursor. @@ -2662,7 +2705,7 @@ def raw_no_cursor(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2670,6 +2713,7 @@ def raw_empty_cursor(ctx): '''Test loader raw_empty_cursor.''' return [{"event_id": 1, "cursor_seen": str(ctx.current_cursor_value)}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_empty_cursor\n", }, select_sql="SELECT event_id, cursor_seen FROM raw_empty_cursor ORDER BY event_id", expected_rows=((1, "None"),), @@ -2680,7 +2724,7 @@ def raw_empty_cursor(ctx): description="current cursor value is none when target does not exist", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_missing_cursor_target description: Test source raw_missing_cursor_target. @@ -2694,7 +2738,7 @@ def raw_empty_cursor(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2702,6 +2746,7 @@ def raw_missing_cursor_target(ctx): '''Test loader raw_missing_cursor_target.''' return [{"event_id": 1, "cursor_seen": str(ctx.current_cursor_value)}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_missing_cursor_target\n", }, select_sql=( "SELECT event_id, cursor_seen FROM raw_missing_cursor_target ORDER BY event_id" @@ -2713,7 +2758,7 @@ def raw_missing_cursor_target(ctx): RELOAD_CONTEXT_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_reload_context description: Test source raw_reload_context. @@ -2724,7 +2769,7 @@ def raw_missing_cursor_target(ctx): type: BOOLEAN """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2732,11 +2777,12 @@ def raw_reload_context(ctx): '''Test loader raw_reload_context.''' return [{"is_reload": ctx.is_reload}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_reload_context\n", } CURSOR_OVERRIDE_CONTEXT_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_cursor_overrides description: Test source raw_cursor_overrides. @@ -2753,7 +2799,7 @@ def raw_reload_context(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2766,6 +2812,7 @@ def raw_cursor_overrides(ctx): "end_int": None if ctx.end_cursor_int is None else str(ctx.end_cursor_int), }] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_cursor_overrides\n", } @@ -2776,7 +2823,7 @@ def raw_cursor_overrides(ctx): description="append creates target then appends rows using current cursor value", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_append_events description: Test source raw_append_events. @@ -2790,7 +2837,7 @@ def raw_cursor_overrides(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2801,6 +2848,7 @@ def raw_append_events(ctx): next_id = int(ctx.current_cursor_value) + 1 return [{"event_id": next_id, "cursor_seen": str(ctx.current_cursor_value)}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_append_events\n", }, select_sql="SELECT event_id, cursor_seen FROM raw_append_events ORDER BY event_id", expected_rows=((1, "none"), (2, "1")), @@ -2809,7 +2857,7 @@ def raw_append_events(ctx): description="merge updates existing rows and inserts new rows using cursor value", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_merge_customers description: Test source raw_merge_customers. @@ -2826,7 +2874,7 @@ def raw_append_events(ctx): type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2842,6 +2890,7 @@ def raw_merge_customers(ctx): {"customer_id": 3, "name": "new", "updated_at": 2}, ] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_merge_customers\n", }, select_sql=( "SELECT customer_id, name, updated_at FROM raw_merge_customers ORDER BY customer_id" @@ -2852,7 +2901,7 @@ def raw_merge_customers(ctx): description="merge supports composite unique keys", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_merge_composite description: Test source raw_merge_composite. @@ -2871,7 +2920,7 @@ def raw_merge_customers(ctx): type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2884,6 +2933,7 @@ def raw_merge_composite(ctx): {"entity_id": 1, "source": "feed", "value": "inserted", "version": 2}, ] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_merge_composite\n", }, select_sql=( "SELECT entity_id, source, value, version FROM raw_merge_composite ORDER BY source" @@ -2894,7 +2944,7 @@ def raw_merge_composite(ctx): description="delete insert replaces loaded cursor range and preserves outside rows", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_delete_insert_events description: Test source raw_delete_insert_events. @@ -2908,7 +2958,7 @@ def raw_merge_composite(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -2926,6 +2976,7 @@ def raw_delete_insert_events(ctx): {"event_id": 3, "status": "new-range"}, ] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_delete_insert_events\n", }, select_sql=( "SELECT event_id, status FROM raw_delete_insert_events ORDER BY event_id, status" @@ -2941,7 +2992,7 @@ def raw_delete_insert_events(ctx): description="delete insert supports timestamp cursor ranges", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_delete_insert_ts description: Test source raw_delete_insert_ts. @@ -2955,7 +3006,7 @@ def raw_delete_insert_events(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from datetime import datetime from sqlbuild.loaders import loader @@ -2975,6 +3026,7 @@ def raw_delete_insert_ts(ctx): {"event_at": datetime(2026, 1, 1, 2, 0, 0), "status": "new-range"}, ] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_delete_insert_ts\n", }, select_sql=( "SELECT strftime(event_at, '%Y-%m-%d %H:%M:%S'), status " @@ -2991,7 +3043,7 @@ def raw_delete_insert_ts(ctx): description="delete insert empty rerun leaves existing target unchanged", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_delete_insert_empty description: Test source raw_delete_insert_empty. @@ -3005,7 +3057,7 @@ def raw_delete_insert_ts(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -3018,6 +3070,7 @@ def raw_delete_insert_empty(ctx): ] return [] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_delete_insert_empty\n", }, select_sql="SELECT event_id, status FROM raw_delete_insert_empty ORDER BY event_id", expected_rows=((1, "existing"), (2, "existing")), @@ -3055,14 +3108,16 @@ def test_given_source_loader_write_strategy_when_running_load_twice_then_writes_ description="append creates target first then inserts on rerun", project_files=WRITE_STRATEGY_CASE_FIXTURES[0].project_files, expected_first_run_fragments=( - "CREATE OR REPLACE TABLE raw_append_events AS SELECT * FROM raw_append_events__staging", + "CREATE OR REPLACE TABLE raw_append_events AS SELECT * FROM " + "raw_append_events__staging", ), expected_second_run_fragments=( 'INSERT INTO raw_append_events ("event_id", "cursor_seen") ' "SELECT * FROM raw_append_events__staging", ), absent_second_run_fragments=( - "CREATE OR REPLACE TABLE raw_append_events AS SELECT * FROM raw_append_events__staging", + "CREATE OR REPLACE TABLE raw_append_events AS SELECT * FROM " + "raw_append_events__staging", ), ), LoadCommandWriteStrategyLifecycleTestCase( @@ -3100,8 +3155,10 @@ def test_given_source_loader_write_strategy_when_running_load_twice_then_writes_ ), expected_second_run_fragments=( 'SELECT MIN("event_id"), MAX("event_id") FROM raw_delete_insert_events__staging', - "DELETE FROM raw_delete_insert_events WHERE \"event_id\" >= '2' AND \"event_id\" < '4'", - "INSERT INTO raw_delete_insert_events SELECT * FROM raw_delete_insert_events__staging", + "DELETE FROM raw_delete_insert_events WHERE \"event_id\" >= '2' AND " + "\"event_id\" < '4'", + "INSERT INTO raw_delete_insert_events SELECT * FROM " + "raw_delete_insert_events__staging", ), absent_second_run_fragments=( "CREATE OR REPLACE TABLE raw_delete_insert_events AS SELECT * FROM " @@ -3298,7 +3355,7 @@ def delete_insert_cursor_spy( description="current cursor value is none when no cursor column is configured", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_no_cursor description: Test source raw_no_cursor. @@ -3311,7 +3368,7 @@ def delete_insert_cursor_spy( type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader run_count = 0 @@ -3323,6 +3380,7 @@ def raw_no_cursor(ctx): run_count += 1 return [{"run_number": run_count, "cursor_seen": str(ctx.current_cursor_value)}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_no_cursor\n", }, select_sql="SELECT run_number, cursor_seen FROM raw_no_cursor ORDER BY run_number", expected_rows=((1, "None"), (1, "None")), @@ -3331,7 +3389,7 @@ def raw_no_cursor(ctx): description="current cursor value is none when existing target is empty", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_empty_cursor description: Test source raw_empty_cursor. @@ -3345,7 +3403,7 @@ def raw_no_cursor(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -3353,6 +3411,7 @@ def raw_empty_cursor(ctx): '''Test loader raw_empty_cursor.''' return [{"event_id": 1, "cursor_seen": str(ctx.current_cursor_value)}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_empty_cursor\n", }, select_sql="SELECT event_id, cursor_seen FROM raw_empty_cursor ORDER BY event_id", expected_rows=((1, "None"),), @@ -3363,7 +3422,7 @@ def raw_empty_cursor(ctx): description="current cursor value is none when target does not exist", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_missing_cursor_target description: Test source raw_missing_cursor_target. @@ -3377,7 +3436,7 @@ def raw_empty_cursor(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -3385,6 +3444,7 @@ def raw_missing_cursor_target(ctx): '''Test loader raw_missing_cursor_target.''' return [{"event_id": 1, "cursor_seen": str(ctx.current_cursor_value)}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_missing_cursor_target\n", }, select_sql=( "SELECT event_id, cursor_seen FROM raw_missing_cursor_target ORDER BY event_id" @@ -3584,7 +3644,7 @@ def test_given_cursor_override_flags_when_running_load_then_passes_typed_context description="uses bounded concurrent connections and preserves result order", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_a description: Test source raw_a. @@ -3615,32 +3675,53 @@ def test_given_cursor_override_flags_when_running_load_then_passes_typed_context type: BIGINT """.strip() + "\n", - "python/loaders/raw.py": """ -import threading -import time - -from sqlbuild.loaders import loader - -barrier = threading.Barrier(2) - -@loader -def raw_a(ctx): - '''Test loader raw_a.''' - barrier.wait(timeout=1) - time.sleep(0.05) - return [{"source_name": "raw_a", "connection_id": id(ctx.connection)}] - -@loader -def raw_b(ctx): - '''Test loader raw_b.''' - barrier.wait(timeout=1) - return [{"source_name": "raw_b", "connection_id": id(ctx.connection)}] - -@loader -def raw_c(ctx): - '''Test loader raw_c.''' - return [{"source_name": "raw_c", "connection_id": id(ctx.connection)}] -""", + "python/nodes/loaders/raw/raw_a/loader.py": ( + "import threading\n" + "import time\n" + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw._sync import barrier\n" + "\n" + "\n" + "@loader\n" + "def raw_a(ctx):\n" + " '''Test loader raw_a.'''\n" + " barrier.wait(timeout=1)\n" + " time.sleep(0.05)\n" + ' return [{"source_name": "raw_a", "connection_id": id(ctx.connection)}]\n' + ), + "python/nodes/loaders/raw/raw_b/loader.py": ( + "import threading\n" + "import time\n" + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw._sync import barrier\n" + "\n" + "\n" + "@loader\n" + "def raw_b(ctx):\n" + " '''Test loader raw_b.'''\n" + " barrier.wait(timeout=1)\n" + ' return [{"source_name": "raw_b", "connection_id": id(ctx.connection)}]\n' + ), + "python/nodes/loaders/raw/raw_c/loader.py": ( + "import threading\n" + "import time\n" + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw._sync import barrier\n" + "\n" + "\n" + "@loader\n" + "def raw_c(ctx):\n" + " '''Test loader raw_c.'''\n" + ' return [{"source_name": "raw_c", "connection_id": id(ctx.connection)}]\n' + ), + "python/nodes/loaders/raw/_sync.py": ( + "import threading\n\nbarrier = threading.Barrier(2)\n" + ), + "python/nodes/loaders/raw/__init__.py": ( + "from .raw_a.loader import raw_a\n" + "from .raw_b.loader import raw_b\n" + "from .raw_c.loader import raw_c\n" + ), }, max_concurrency=2, expected_connection_count=2, @@ -3709,7 +3790,7 @@ def test_given_multiple_source_loaders_when_running_pipeline_then_uses_concurren description="runs independent loader branches concurrently before dependent source", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_join description: Test source raw_join. @@ -3720,38 +3801,61 @@ def test_given_multiple_source_loaders_when_running_pipeline_then_uses_concurren type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ -import threading -import time - -from sqlbuild.loaders import loader - -barrier = threading.Barrier(2) -finished = set() -lock = threading.Lock() - -@loader(write_strategy='table', columns=[{'name': 'id', 'type': 'INTEGER'}]) -def fetch_a(ctx): - '''Test loader fetch_a.''' - barrier.wait(timeout=1) - time.sleep(0.05) - with lock: - finished.add('a') - return [{'id': 1}] - -@loader(write_strategy='table', columns=[{'name': 'id', 'type': 'INTEGER'}]) -def fetch_b(ctx): - '''Test loader fetch_b.''' - barrier.wait(timeout=1) - with lock: - finished.add('b') - return [{'id': 2}] - -@loader(depends_on=[fetch_a, fetch_b]) -def raw_join(ctx): - '''Test loader raw_join.''' - return [{'upstream_count': len(finished)}] -""", + "python/nodes/loaders/raw/fetch_a/loader.py": ( + "import threading\n" + "import time\n" + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw._sync import barrier, finished, lock\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[{'name': 'id', 'type': 'INTEGER'}])\n" + "def fetch_a(ctx):\n" + " '''Test loader fetch_a.'''\n" + " barrier.wait(timeout=1)\n" + " time.sleep(0.05)\n" + " with lock:\n" + " finished.add('a')\n" + " return [{'id': 1}]\n" + ), + "python/nodes/loaders/raw/fetch_b/loader.py": ( + "import threading\n" + "import time\n" + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw._sync import barrier, finished, lock\n" + "\n" + "\n" + "@loader(write_strategy='table', columns=[{'name': 'id', 'type': 'INTEGER'}])\n" + "def fetch_b(ctx):\n" + " '''Test loader fetch_b.'''\n" + " barrier.wait(timeout=1)\n" + " with lock:\n" + " finished.add('b')\n" + " return [{'id': 2}]\n" + ), + "python/nodes/loaders/raw/raw_join/loader.py": ( + "import threading\n" + "import time\n" + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.raw._sync import barrier, finished, lock\n" + "from python.nodes.loaders.raw.fetch_a.loader import fetch_a\n" + "from python.nodes.loaders.raw.fetch_b.loader import fetch_b\n" + "\n" + "\n" + "@loader(depends_on=[fetch_a, fetch_b])\n" + "def raw_join(ctx):\n" + " '''Test loader raw_join.'''\n" + " return [{'upstream_count': len(finished)}]\n" + ), + "python/nodes/loaders/raw/_sync.py": ( + "import threading\n\nbarrier = threading.Barrier(2)\n" + "finished = set()\n" + "lock = threading.Lock()\n" + ), + "python/nodes/loaders/raw/__init__.py": ( + "from .fetch_a.loader import fetch_a\n" + "from .fetch_b.loader import fetch_b\n" + "from .raw_join.loader import raw_join\n" + ), }, max_concurrency=2, expected_connection_count=2, @@ -3834,7 +3938,7 @@ def test_given_loader_dag_when_running_pipeline_then_independent_branches_overla description="loads generator rows with declared missing and inferred extra columns", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_inferred description: Test source raw_inferred. @@ -3847,7 +3951,7 @@ def test_given_loader_dag_when_running_pipeline_then_independent_branches_overla type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from datetime import date, datetime from sqlbuild.loaders import loader @@ -3866,6 +3970,7 @@ def raw_inferred(ctx): "service_date": date(2026, 5, 21), } """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_inferred\n", }, expected_row=( 1, @@ -3932,7 +4037,7 @@ def test_given_generator_loader_with_inferred_columns_when_running_load_then_wri description="decimals keep their precision and declared columns take any value", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_inferred description: Test source raw_inferred. @@ -3943,7 +4048,7 @@ def test_given_generator_loader_with_inferred_columns_when_running_load_then_wri type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from decimal import Decimal from uuid import UUID @@ -3955,6 +4060,7 @@ def raw_inferred(ctx): yield {"order_ref": UUID("12345678-1234-5678-1234-567812345678"), "price": Decimal("12.50")} yield {"order_ref": None, "price": Decimal("1234.5")} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_inferred\n", }, expected_row=("12345678-1234-5678-1234-567812345678", Decimal("12.50")), expected_column_types={"order_ref": "VARCHAR", "price": "DECIMAL(6,2)"}, @@ -3963,7 +4069,7 @@ def raw_inferred(ctx): description="wide decimals stay exact beside values written with an exponent", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_inferred description: Test source raw_inferred. @@ -3974,7 +4080,7 @@ def raw_inferred(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from decimal import Decimal from sqlbuild.loaders import loader @@ -3985,6 +4091,7 @@ def raw_inferred(ctx): yield {"order_ref": "a_wide", "price": Decimal("12345678901234567890.123")} yield {"order_ref": "b_tiny", "price": Decimal("1E-7")} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_inferred\n", }, expected_row=("a_wide", Decimal("12345678901234567890.123")), expected_column_types={"order_ref": "VARCHAR", "price": "DECIMAL(27,7)"}, @@ -4026,7 +4133,7 @@ def test_given_decimal_and_declared_values_when_running_load_then_keeps_their_ty description="loads every row yielded by a generator loader", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_multi_yield description: Test source raw_multi_yield. @@ -4039,7 +4146,7 @@ def test_given_decimal_and_declared_values_when_running_load_then_keeps_their_ty type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4048,6 +4155,7 @@ def raw_multi_yield(ctx): yield {"id": 1, "status": "first"} yield {"id": 2, "status": "second"} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_multi_yield\n", }, expected_rows=((1, "first"), (2, "second")), ), @@ -4083,7 +4191,7 @@ def test_given_generator_loader_yields_multiple_rows_when_running_load_then_writ description="loads generator rows in batches and preserves late extra columns", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_batched_yield description: Test source raw_batched_yield. @@ -4097,7 +4205,7 @@ def test_given_generator_loader_yields_multiple_rows_when_running_load_then_writ type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4107,6 +4215,7 @@ def raw_batched_yield(ctx): yield {"id": 2, "status": "second", "late_flag": True} yield {"id": 3, "status": "third", "late_flag": False} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_batched_yield\n", }, expected_rows=((1, "first", None), (2, "second", True), (3, "third", False)), expected_column_types={"id": "INTEGER", "status": "VARCHAR", "late_flag": "BOOLEAN"}, @@ -4179,7 +4288,7 @@ def test_given_generator_loader_uses_batch_size_when_running_pipeline_then_appen description="loads missing known columns as null in later batches", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_missing_known description: Test source raw_missing_known. @@ -4193,7 +4302,7 @@ def test_given_generator_loader_uses_batch_size_when_running_pipeline_then_appen type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4202,6 +4311,7 @@ def raw_missing_known(ctx): yield {"id": 1, "status": "first"} yield {"id": 2} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_missing_known\n", }, select_sql="SELECT id, status FROM raw_missing_known ORDER BY id", table_name="raw_missing_known", @@ -4213,7 +4323,7 @@ def raw_missing_known(ctx): description="loads empty generator into declared table through batched path", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_empty_generator description: Test source raw_empty_generator. @@ -4227,7 +4337,7 @@ def raw_missing_known(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4236,6 +4346,7 @@ def raw_empty_generator(ctx): if False: yield {"id": 1, "status": "unreachable"} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_empty_generator\n", }, select_sql="SELECT COUNT(*) FROM raw_empty_generator", table_name="raw_empty_generator", @@ -4247,7 +4358,7 @@ def raw_empty_generator(ctx): description="loads late all null column when typed value arrives later", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_late_null description: Test source raw_late_null. @@ -4259,7 +4370,7 @@ def raw_empty_generator(ctx): type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4268,6 +4379,7 @@ def raw_late_null(ctx): yield {"id": 1, "late_note": None} yield {"id": 2, "late_note": "filled"} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_late_null\n", }, select_sql="SELECT id, late_note FROM raw_late_null ORDER BY id", table_name="raw_late_null", @@ -4279,7 +4391,7 @@ def raw_late_null(ctx): description="loads multi-row batches before appending final partial batch", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_batch_size_two description: Test source raw_batch_size_two. @@ -4291,7 +4403,7 @@ def raw_late_null(ctx): type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4301,6 +4413,7 @@ def raw_batch_size_two(ctx): yield {"id": 2} yield {"id": 3} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_batch_size_two\n", }, select_sql="SELECT id FROM raw_batch_size_two ORDER BY id", table_name="raw_batch_size_two", @@ -4313,7 +4426,7 @@ def raw_batch_size_two(ctx): description="uses default batch size when source does not declare one", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_default_batch description: Test source raw_default_batch. @@ -4324,7 +4437,7 @@ def raw_batch_size_two(ctx): type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4334,6 +4447,7 @@ def raw_default_batch(ctx): yield {"id": 2} yield {"id": 3} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_default_batch\n", }, select_sql="SELECT id FROM raw_default_batch ORDER BY id", table_name="raw_default_batch", @@ -4404,7 +4518,7 @@ def test_given_batched_loader_variants_when_running_pipeline_then_writes_expecte description="formats large load row counts with commas in human output", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_many_rows description: Test source raw_many_rows. @@ -4415,7 +4529,7 @@ def test_given_batched_loader_variants_when_running_pipeline_then_writes_expecte type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4424,6 +4538,7 @@ def raw_many_rows(ctx): for value in range(1001): yield {"id": value} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_many_rows\n", }, expected_exit_code=0, expected_rows=(), @@ -4467,7 +4582,7 @@ def test_given_loader_writes_many_rows_when_running_load_then_formats_human_row_ description="loads empty returned rows into declared empty table", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_empty description: Test source raw_empty. @@ -4480,7 +4595,7 @@ def test_given_loader_writes_many_rows_when_running_load_then_formats_human_row_ type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4488,6 +4603,7 @@ def raw_empty(ctx): '''Test loader raw_empty.''' return [] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_empty\n", }, expected_column_types={"id": "INTEGER", "status": "VARCHAR"}, ), @@ -4530,7 +4646,7 @@ def test_given_loader_returns_empty_rows_when_running_load_then_writes_empty_dec description="self managed loader can return nothing without write strategy", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_self_managed description: Test source raw_self_managed. @@ -4540,7 +4656,7 @@ def test_given_loader_returns_empty_rows_when_running_load_then_writes_empty_dec type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4548,6 +4664,7 @@ def raw_self_managed(ctx): '''Test loader raw_self_managed.''' ctx.execute_sql("CREATE OR REPLACE TABLE raw_self_managed AS SELECT 1 AS id") """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_self_managed\n", }, select_sql="SELECT id FROM raw_self_managed", expected_rows=((1,),), @@ -4586,7 +4703,7 @@ def test_given_self_managed_loader_when_running_load_then_uses_loader_written_ta description="fails clearly when returned rows contain conflicting inferred types", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_conflict description: Test source raw_conflict. @@ -4594,7 +4711,7 @@ def test_given_self_managed_loader_when_running_load_then_uses_loader_written_ta write_strategy: table """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4605,6 +4722,7 @@ def raw_conflict(ctx): {"id": "two"}, ] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_conflict\n", }, expected_exit_code=1, expected_stdout_fragment="conflicting types for column 'id'", @@ -4613,7 +4731,7 @@ def raw_conflict(ctx): description="fails clearly when an undeclared column holds an unrecognised type", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_unknown_type description: Test source raw_unknown_type. @@ -4621,7 +4739,7 @@ def raw_conflict(ctx): write_strategy: table """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from uuid import UUID from sqlbuild.loaders import loader @@ -4631,6 +4749,7 @@ def raw_unknown_type(ctx): '''Test loader raw_unknown_type.''' return [{"id": 1, "order_ref": UUID("12345678-1234-5678-1234-567812345678")}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_unknown_type\n", }, expected_exit_code=1, expected_stdout_fragment=( @@ -4642,7 +4761,7 @@ def raw_unknown_type(ctx): description="fails clearly when a later batch needs a wider decimal", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_wider_decimal description: Test source raw_wider_decimal. @@ -4651,7 +4770,7 @@ def raw_unknown_type(ctx): load_batch_size: 1 """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from decimal import Decimal from sqlbuild.loaders import loader @@ -4662,6 +4781,7 @@ def raw_wider_decimal(ctx): yield {"price": Decimal("1.5")} yield {"price": Decimal("123.25")} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_wider_decimal\n", }, expected_exit_code=1, expected_stdout_fragment=( @@ -4673,14 +4793,14 @@ def raw_wider_decimal(ctx): description="fails when loader returns rows without write strategy", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_missing_strategy description: Test source raw_missing_strategy. managed: true """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4688,6 +4808,7 @@ def raw_missing_strategy(ctx): '''Test loader raw_missing_strategy.''' return [{"id": 1}] """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_missing_strategy\n", }, expected_exit_code=1, expected_stdout_fragment="returned rows but source has no write_strategy", @@ -4696,7 +4817,7 @@ def raw_missing_strategy(ctx): description="fails when loader returns nothing with write strategy", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_unexpected_none description: Test source raw_unexpected_none. @@ -4704,7 +4825,7 @@ def raw_missing_strategy(ctx): write_strategy: table """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4712,6 +4833,7 @@ def raw_unexpected_none(ctx): '''Test loader raw_unexpected_none.''' return None """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_unexpected_none\n", }, expected_exit_code=1, expected_stdout_fragment=( @@ -4745,7 +4867,7 @@ def test_given_loader_returns_conflicting_types_when_running_load_then_fails_cle description="drops staging and preserves target when a later loader batch fails", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_batched_conflict description: Test source raw_batched_conflict. @@ -4754,7 +4876,7 @@ def test_given_loader_returns_conflicting_types_when_running_load_then_fails_cle load_batch_size: 1 """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4763,6 +4885,7 @@ def raw_batched_conflict(ctx): yield {"id": 1} yield {"id": "two"} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_batched_conflict\n", }, staging_table_name="raw_batched_conflict__staging", expected_staging_exists=False, @@ -4777,7 +4900,7 @@ def raw_batched_conflict(ctx): description="drops staging when a later loader batch returns non dict row", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_batched_non_dict description: Test source raw_batched_non_dict. @@ -4786,7 +4909,7 @@ def raw_batched_conflict(ctx): load_batch_size: 1 """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4795,6 +4918,7 @@ def raw_batched_non_dict(ctx): yield {"id": 1} yield ("id", 2) """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_batched_non_dict\n", }, staging_table_name="raw_batched_non_dict__staging", expected_staging_exists=False, @@ -4804,7 +4928,7 @@ def raw_batched_non_dict(ctx): description="leaves append target unchanged when a later loader batch fails", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_append_failure description: Test source raw_append_failure. @@ -4816,7 +4940,7 @@ def raw_batched_non_dict(ctx): type: INTEGER """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4825,6 +4949,7 @@ def raw_append_failure(ctx): yield {"id": 1} yield {"id": "two"} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_append_failure\n", }, staging_table_name="raw_append_failure__staging", expected_staging_exists=False, @@ -4839,7 +4964,7 @@ def raw_append_failure(ctx): description="leaves merge target unchanged when a later loader batch fails", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_merge_failure description: Test source raw_merge_failure. @@ -4854,7 +4979,7 @@ def raw_append_failure(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4863,6 +4988,7 @@ def raw_merge_failure(ctx): yield {"id": 1, "status": "new"} yield {"id": "two", "status": "bad"} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_merge_failure\n", }, staging_table_name="raw_merge_failure__staging", expected_staging_exists=False, @@ -4877,7 +5003,7 @@ def raw_merge_failure(ctx): description="leaves delete insert target unchanged when a later loader batch fails", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_delete_insert_failure description: Test source raw_delete_insert_failure. @@ -4892,7 +5018,7 @@ def raw_merge_failure(ctx): type: VARCHAR """.strip() + "\n", - "python/loaders/raw.py": """ + "python/nodes/loaders/raw/loader.py": """ from sqlbuild.loaders import loader @loader @@ -4901,6 +5027,7 @@ def raw_delete_insert_failure(ctx): yield {"id": 1, "status": "new"} yield {"id": "two", "status": "bad"} """, + "python/nodes/loaders/raw/__init__.py": "from .loader import raw_delete_insert_failure\n", }, staging_table_name="raw_delete_insert_failure__staging", expected_staging_exists=False, @@ -4969,7 +5096,7 @@ def test_given_later_loader_batch_fails_when_running_load_then_drops_staging( description="raises when selected source does not exist", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -4977,7 +5104,8 @@ def test_given_later_loader_batch_fails_when_running_load_then_drops_staging( write_strategy: table """.strip() + "\n", - "python/loaders/raw_orders.py": _RAW_ORDERS_LOADER, + "python/nodes/loaders/raw_orders/loader.py": _RAW_ORDERS_LOADER, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, select=("missing_source",), exclude=(), @@ -4989,7 +5117,7 @@ def test_given_later_loader_batch_fails_when_running_load_then_drops_staging( description="raises when selected source is unmanaged", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_customers description: Test source raw_customers. @@ -5007,7 +5135,7 @@ def test_given_later_loader_batch_fails_when_running_load_then_drops_staging( description="raises when excluded source does not exist", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -5015,7 +5143,8 @@ def test_given_later_loader_batch_fails_when_running_load_then_drops_staging( write_strategy: table """.strip() + "\n", - "python/loaders/raw_orders.py": _RAW_ORDERS_LOADER, + "python/nodes/loaders/raw_orders/loader.py": _RAW_ORDERS_LOADER, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, select=(), exclude=("missing_source",), @@ -5027,7 +5156,7 @@ def test_given_later_loader_batch_fails_when_running_load_then_drops_staging( description="raises when excluded source is unmanaged", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -5038,7 +5167,8 @@ def test_given_later_loader_batch_fails_when_running_load_then_drops_staging( expression: SELECT 1 AS customer_id """.strip() + "\n", - "python/loaders/raw_orders.py": _RAW_ORDERS_LOADER, + "python/nodes/loaders/raw_orders/loader.py": _RAW_ORDERS_LOADER, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, select=(), exclude=("raw_customers",), @@ -5076,7 +5206,7 @@ def test_given_invalid_load_selectors_when_running_load_then_it_raises_clear_err description="succeeds without connecting when project has no managed sources", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_customers description: Test source raw_customers. @@ -5098,7 +5228,7 @@ def test_given_invalid_load_selectors_when_running_load_then_it_raises_clear_err description="succeeds without connecting when all managed sources are excluded", project_files={ "sqlbuild_project.toml": _PROJECT_FILE, - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -5106,7 +5236,8 @@ def test_given_invalid_load_selectors_when_running_load_then_it_raises_clear_err write_strategy: table """.strip() + "\n", - "python/loaders/raw_orders.py": _RAW_ORDERS_LOADER, + "python/nodes/loaders/raw_orders/loader.py": _RAW_ORDERS_LOADER, + "python/nodes/loaders/raw_orders/__init__.py": "from .loader import raw_orders\n", }, select=(), exclude=("raw_orders",), diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_macro_slot_qualification.py b/tests/integration/src/sqlbuild/cli/commands/main/test_macro_slot_qualification.py index d4776644b9..4c7186baaf 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_macro_slot_qualification.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_macro_slot_qualification.py @@ -53,25 +53,25 @@ ), expected_exit_code=1, expected_fragments=( - "--> models/_macros/sql/weekly_rates.sql:8:5", + "--> sql/models/_macros/sql/weekly_rates.sql:8:5", "to qualify it, read through an alias: `FROM @rel AS s`, then `s.@rel.column`", ), - absent_fragments=("--> models/refund_rates.sql",), + absent_fragments=("--> sql/models/refund_rates.sql",), ), MacroSlotQualificationTestCase( description="an expression macro's plain reads pass beside bare caller columns", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n description "One row per order",\n materialized table,\n);\n\n' "SELECT 1 AS order_id, CAST(10 AS DOUBLE) AS amount, " "CAST(1 AS DOUBLE) AS discount\n" ), - "models/_macros/sql/net_amount.sql": ( + "sql/models/_macros/sql/net_amount.sql": ( 'MACRO (\n description "Order amount after discount",\n' " arguments (orders RELATION (amount DOUBLE, discount DOUBLE)),\n);\n\n" "@orders.amount - @orders.discount\n" ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( 'MODEL (\n description "Net amount per order",\n materialized table,\n);\n\n' "SELECT order_id, @sql.net_amount(orders) AS net\n" 'FROM __ref("orders") AS orders\n' @@ -84,17 +84,17 @@ MacroSlotQualificationTestCase( description="an expression macro's plain reads pass beside hand-qualified columns", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n description "One row per order",\n materialized table,\n);\n\n' "SELECT 1 AS order_id, CAST(10 AS DOUBLE) AS amount, " "CAST(1 AS DOUBLE) AS discount\n" ), - "models/_macros/sql/net_amount.sql": ( + "sql/models/_macros/sql/net_amount.sql": ( 'MACRO (\n description "Order amount after discount",\n' " arguments (orders RELATION (amount DOUBLE, discount DOUBLE)),\n);\n\n" "@orders.amount - @orders.discount\n" ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( 'MODEL (\n description "Net amount per order",\n materialized table,\n);\n\n' "SELECT o.order_id, @sql.net_amount(o) AS net\n" 'FROM __ref("orders") AS o\n' @@ -107,55 +107,55 @@ MacroSlotQualificationTestCase( description="an expression macro's bare column beside a hand-qualified column fails", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n description "One row per order",\n materialized table,\n);\n\n' "SELECT 1 AS order_id, 'open' AS status\n" ), - "models/_macros/sql/status_value.sql": ( + "sql/models/_macros/sql/status_value.sql": ( 'MACRO (\n description "The order status",\n returns VARCHAR,\n);\n\nstatus\n' ), - "models/open_orders.sql": ( + "sql/models/open_orders.sql": ( 'MODEL (\n description "Open orders",\n materialized table,\n);\n\n' 'SELECT o.order_id, @sql.status_value() AS s FROM __ref("orders") AS o\n' ), }, expected_exit_code=1, - expected_fragments=("error[SQLCLEAN028]", "--> models/open_orders.sql"), + expected_fragments=("error[SQLCLEAN028]", "--> sql/models/open_orders.sql"), absent_fragments=(), ), MacroSlotQualificationTestCase( description="a column-list macro's bare output beside a hand-qualified column fails", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n description "One row per order",\n materialized table,\n);\n\n' "SELECT 1 AS order_id, 'open' AS status\n" ), - "models/_macros/sql/order_status.sql": ( + "sql/models/_macros/sql/order_status.sql": ( 'MACRO (\n description "The order status column",\n);\n\nSELECT status\n' ), - "models/open_orders.sql": ( + "sql/models/open_orders.sql": ( 'MODEL (\n description "Open orders",\n materialized table,\n);\n\n' 'SELECT o.order_id, @sql.order_status() FROM __ref("orders") AS o\n' ), }, expected_exit_code=1, - expected_fragments=("error[SQLCLEAN028]", "--> models/open_orders.sql"), + expected_fragments=("error[SQLCLEAN028]", "--> sql/models/open_orders.sql"), absent_fragments=(), ), MacroSlotQualificationTestCase( description="a caller that mixes styles itself still fails", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n description "One row per order",\n materialized table,\n);\n\n' "SELECT 1 AS order_id, 'open' AS status\n" ), - "models/open_orders.sql": ( + "sql/models/open_orders.sql": ( 'MODEL (\n description "Open orders",\n materialized table,\n);\n\n' 'SELECT o.order_id, status FROM __ref("orders") AS o\n' ), }, expected_exit_code=1, - expected_fragments=("error[SQLCLEAN028]", "--> models/open_orders.sql"), + expected_fragments=("error[SQLCLEAN028]", "--> sql/models/open_orders.sql"), absent_fragments=(), ), ], diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_repeated_json_parse.py b/tests/integration/src/sqlbuild/cli/commands/main/test_repeated_json_parse.py index ea95f31645..552d1c5a93 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_repeated_json_parse.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_repeated_json_parse.py @@ -62,7 +62,7 @@ expected_detail="JSON(e.payload) is parsed 2 times in one SELECT.", extra_files=( ( - "macros/python/fields.py", + "sql/macros/python/fields.py", "def order_id_field(ctx):\n return \"json(e.payload)->>'order_id'\"\n", ), ), diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_rule_exception_policy.py b/tests/integration/src/sqlbuild/cli/commands/main/test_rule_exception_policy.py index 3f81a09054..2e9f2611f6 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_rule_exception_policy.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_rule_exception_policy.py @@ -14,18 +14,18 @@ ) _EXCEPTION: str = ( - '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\npath = "models/customers.sql"\n' + '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\npath = "sql/models/customers.sql"\n' 'reason = "The sample intentionally keeps one row."\n' ) _IGNORE: str = ( - '[[rules.rule_ignores]]\nrules = ["SQLCLEAN004"]\npaths = ["models/**"]\n' + '[[rules.rule_ignores]]\nrules = ["SQLCLEAN004"]\npaths = ["sql/models/**"]\n' 'reason = "Samples intentionally keep one row."\n' ) _DIRECTIVE: str = "-- sqb: ignore SQLCLEAN004 because the sample intentionally keeps one row\n" _PRINTED_ENTRY: str = ( "[[rules.rule_exceptions]]\n" ' rule = "SQLCLEAN004"\n' - ' path = "models/customers.sql"\n' + ' path = "sql/models/customers.sql"\n' ' reason = "the sample intentionally keeps one row"' ) _REMOVED: str = "sets [rules] allow_exceptions, which SQLBuild no longer supports" @@ -91,8 +91,8 @@ def test_given_rule_exception_mechanism_when_compiling_then_only_configuration_a f"{test_case.rules_toml}", encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "customers.sql").write_text( "MODEL (description 'Customer sample.');\n" "WITH customers AS (SELECT 1 AS customer_id)\n" @@ -138,8 +138,8 @@ def test_given_exception_policy_when_formatting_then_it_is_validated_like_compil f"{test_case.setting}\n", encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "customers.sql").write_text( "MODEL (description 'Customer sample.');\n" "WITH customers AS (\n SELECT 1 AS customer_id\n)\n\n" diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_rules.py b/tests/integration/src/sqlbuild/cli/commands/main/test_rules.py index 9662e05e3a..4f6b22d5c2 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_rules.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_rules.py @@ -82,7 +82,7 @@ @rule( code="XSQBRCACHE001", message="Models must live in the final directory", - remediation="Move this model beneath models/final/.", + remediation="Move this model beneath sql/models/final/.", ) def final_directory(*, model: Model, ctx: RuleContext) -> list[Finding]: return [] if "final" in model.path.parts else [ctx.finding(subject=model)] @@ -92,7 +92,7 @@ def final_directory(*, model: Model, ctx: RuleContext) -> list[Finding]: (PYTHON_RULES_FIXTURES / "expected_findings.json").read_text(encoding="utf-8") ) _PYTHON_RULES_SELECT: str = f"select = {json.dumps(_PYTHON_RULES_EXPECTED['select'])}\n" -_PYTHON_ALERT_PATH: str = "hooks/python/alert.py" +_PYTHON_ALERT_PATH: str = "sql/hooks/python/alert.py" _PYTHON_ALERT: str = (PYTHON_RULES_FIXTURES / "violations" / _PYTHON_ALERT_PATH).read_text( encoding="utf-8" ) @@ -166,7 +166,7 @@ def project_facts(*, project: Project, ctx: RuleContext) -> list[Finding]: ",".join(item.name for item in ctx.declarations.public_constants), str(len(ctx.declarations.enums)), str(len(ctx.declarations.constants)), - _names(facts.tree.resources_under("models/marts")), + _names(facts.tree.resources_under("sql/models/marts")), ) return [ctx.finding(subject=facts.models[0], message="|".join(parts))] """ @@ -176,22 +176,22 @@ def project_facts(*, project: Project, ctx: RuleContext) -> list[Finding]: "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n" ), "rules/surface.py": _SURFACE_RULES, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" ' expression: "(SELECT 1 AS id, CAST(10.5 AS DOUBLE) AS amount)"\n' ), - "seeds/regions.csv": "region_id,name\n1,north\n", - "seeds/regions.yml": ( + "sql/seeds/regions.csv": "region_id,name\n1,north\n", + "sql/seeds/regions.yml": ( "seeds:\n - name: regions\n description: Regions.\n columns:\n" " - name: region_id\n type: INTEGER\n - name: name\n type: VARCHAR\n" ), - "models/staging/_sqlbuild/_constants/policy.sql": ( + "sql/models/staging/_sqlbuild/_constants/policy.sql": ( "CONSTANT (name minimum_amount, value 7);\n" ), - "models/staging/_sqlbuild/_enums/order_status.sql": ( + "sql/models/staging/_sqlbuild/_enums/order_status.sql": ( "ENUM (name order_status, members [PAID, OPEN]);\n" ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( "MODEL (description 'Staged orders.', contract enforced, columns (\n" " order_id (type INTEGER, nullable false, description 'Order key',\n" " audits [not_null, accepted_values (values [1, 2], severity warn)]),\n" @@ -199,7 +199,7 @@ def project_facts(*, project: Project, ctx: RuleContext) -> list[Finding]: 'SELECT CAST(id AS INTEGER) AS order_id, amount, @enum("order_status").PAID AS status\n' 'FROM __source("raw_orders") WHERE amount > @const("minimum_amount")\n' ), - "models/marts/order_totals.sql": ( + "sql/models/marts/order_totals.sql": ( 'MODEL (description "Order totals", materialized table);\n\n' 'SELECT o.order_id, o.amount * 2 AS doubled_amount FROM __ref("stg_orders") AS o\n' ), @@ -210,16 +210,16 @@ def project_facts(*, project: Project, ctx: RuleContext) -> list[Finding]: ), } _SURFACE_STAGING_EDIT: dict[str, str] = { - "models/staging/stg_orders.sql": _SURFACE_FILES["models/staging/stg_orders.sql"].replace( - "AS order_id, amount,", "AS order_id,\n amount," - ) + "sql/models/staging/stg_orders.sql": _SURFACE_FILES[ + "sql/models/staging/stg_orders.sql" + ].replace("AS order_id, amount,", "AS order_id,\n amount,") } _EARLY_LINT_SLOW_HOOKS: int = 8 _EARLY_LINT_SLOW_EXPANSION_S: float = 0.5 _EARLY_LINT_EXPANSION_DELAYS_S: dict[str, float] = {"orders": 0.0} _EARLY_LINT_FINDINGS: tuple[tuple[str, str, int | None, int | None], ...] = ( - ("SQLCLEAN005", "models/order_cents.sql", 2, 119), + ("SQLCLEAN005", "sql/models/order_cents.sql", 2, 119), ) @@ -263,7 +263,7 @@ def test_given_conflicting_model_layer_metadata_when_compiling_then_rules_report '"SQBRPROJECT104", "SQBRPROJECT105", "SQBRPROJECT106"]\n', encoding="utf-8", ) - model_dir: Path = tmp_path / "models" / "commerce" / "intermediate" / "enriched" + model_dir: Path = tmp_path / "sql" / "models" / "commerce" / "intermediate" / "enriched" model_dir.mkdir(parents=True) (model_dir / "commerce__mart_v__int_v_orders.sql").write_text( "MODEL (\n" @@ -274,8 +274,8 @@ def test_given_conflicting_model_layer_metadata_when_compiling_then_rules_report 'SELECT order_id FROM __ref("commerce__mart__stg_orders")\n', encoding="utf-8", ) - published_dir: Path = tmp_path / "models" / "commerce" / "mart" - published_dir.mkdir() + published_dir: Path = tmp_path / "sql" / "models" / "commerce" / "mart" + published_dir.mkdir(parents=True) (published_dir / "commerce__mart__stg_orders.sql").write_text( 'MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8" ) @@ -315,8 +315,8 @@ def test_given_exact_internal_edge_exception_when_compiling_then_live_edge_passe 'reason = "Tracked cleanup"\n' ) project_file.write_text(base_config + live_exception, encoding="utf-8") - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "commerce__stg__orders.sql").write_text( 'MODEL (description "Test model commerce__stg__orders.");\nSELECT order_id FROM __ref("commerce__int_enriched__orders")\n', encoding="utf-8", @@ -422,8 +422,8 @@ def test_given_numeric_range_or_value_list_when_compiling_then_literal_decisions 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQBRDECLARATION102"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (\n" ' description "Orders",\n' + test_case.constants + ");\n\n" @@ -457,8 +457,8 @@ def test_given_constant_backed_decision_and_numeric_alias_when_compiling_then_ru 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQBRDECLARATION102"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Test model orders.", constants (_large_batch 7), @@ -646,8 +646,8 @@ def test_given_enforced_contract_when_compiling_explicit_output_rule_then_enforc 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQBRCONTRACT105"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (description 'Test model orders.',\n" " contract enforced,\n" @@ -692,8 +692,8 @@ def test_given_proven_dynamic_pivot_when_compiling_contract_rules_then_wildcard_ 'contract = "enforced"\n', encoding="utf-8", ) - models_dir: Path = tmp_path / "models" - models_dir.mkdir() + models_dir: Path = tmp_path / "sql" / "models" + models_dir.mkdir(parents=True) (models_dir / "stg_order_amounts.sql").write_text( "MODEL (description 'Test model stg_order_amounts.', database analytics, schema analytics, columns (customer_id (type INTEGER), " "category (type VARCHAR), " @@ -782,8 +782,8 @@ def test_given_contract_rules_when_compiling_then_contract_is_enforced_typed_and '[defaults]\ncontract = "enforced"\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (description 'Test model orders.',\n" f" columns ({test_case.columns_sql}),\n" @@ -817,8 +817,8 @@ def test_given_selected_sql_rule_when_compiling_then_authored_diagnostic_blocks_ 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN004"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\nSELECT order_id FROM orders LIMIT 1\n', encoding="utf-8", @@ -839,7 +839,7 @@ def test_given_selected_sql_rule_when_compiling_then_authored_diagnostic_blocks_ diagnostics: object = first["diagnostics"] assert isinstance(diagnostics, list) assert diagnostics[0]["code"] == test_case.expected_code - assert diagnostics[0]["path"] == "models/orders.sql" + assert diagnostics[0]["path"] == "sql/models/orders.sql" assert second["compile_timings"]["rule_cache_hits"] == 1 assert third_exit == 0 assert third["compile_timings"]["rule_cache_misses"] == 1 @@ -861,8 +861,8 @@ def test_given_sql_rule_cache_from_another_native_build_when_compiling_then_rule f'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["{test_case.expected_code}"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\nSELECT order_id FROM orders LIMIT 1\n', encoding="utf-8", @@ -905,8 +905,8 @@ def test_given_cached_sql_test_rules_when_test_or_macro_changes_then_findings_ar f'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["{test_case.expected_code}"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") tests_dir: Path = tmp_path / "tests" / "unit" macro: Path = tests_dir / "_macros" / "python" / "row_limit.py" @@ -956,8 +956,8 @@ def test_given_warm_scoped_macro_sql_test_when_compiling_then_rules_reuse_compil f'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["{test_case.expected_code}"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") tests_dir: Path = tmp_path / "tests" / "unit" macro: Path = tests_dir / "_macros" / "python" / "row_limit.py" @@ -995,8 +995,8 @@ def test_given_cold_scoped_macro_sql_test_when_compiling_then_early_lint_uses_pr f'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["{test_case.expected_code}"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") tests_dir: Path = tmp_path / "tests" / "unit" macro: Path = tests_dir / "_macros" / "python" / "row_limit.py" @@ -1041,8 +1041,8 @@ def test_given_cold_non_model_sql_finding_when_compiling_twice_then_warm_finding f'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["{test_case.expected_code}"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") test_file: Path = tmp_path / "tests" / "unit" / "test_orders.sql" test_file.parent.mkdir(parents=True) @@ -1130,8 +1130,8 @@ def test_given_graph_error_when_compiling_then_early_lint_is_stopped_instead_of_ 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN005"]\n', encoding="utf-8", ) - models_dir: Path = tmp_path / "models" - models_dir.mkdir() + models_dir: Path = tmp_path / "sql" / "models" + models_dir.mkdir(parents=True) (models_dir / "orders.sql").write_text( 'MODEL (description "Orders");\nSELECT @py.slow_total("orders") AS order_id\n', encoding="utf-8", @@ -1142,9 +1142,9 @@ def test_given_graph_error_when_compiling_then_early_lint_is_stopped_instead_of_ 'SELECT order_id, missing_column FROM __ref("orders")\n', encoding="utf-8", ) - macros_dir: Path = tmp_path / "macros" / "python" + macros_dir: Path = tmp_path / "sql" / "macros" / "python" macros_dir.mkdir(parents=True) - (tmp_path / "hooks").mkdir() + (tmp_path / "sql" / "hooks").mkdir(parents=True) (macros_dir / "slow_total.py").write_text( "import orders_lint_probe\n\n\n" "def slow_total(name: str) -> str:\n" @@ -1153,7 +1153,7 @@ def test_given_graph_error_when_compiling_then_early_lint_is_stopped_instead_of_ encoding="utf-8", ) for index in range(_EARLY_LINT_SLOW_HOOKS): - (tmp_path / "hooks" / f"total_{index:02d}.sql").write_text( + (tmp_path / "sql" / "hooks" / f"total_{index:02d}.sql").write_text( f'SELECT @py.slow_total("total_{index:02d}") AS order_total\n', encoding="utf-8" ) expanded: list[str] = [] @@ -1193,8 +1193,8 @@ def test_given_sql_and_custom_rules_when_compiling_twice_then_custom_host_runs_o "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n", encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") test_file: Path = tmp_path / "tests" / "unit" / "test_orders.sql" test_file.parent.mkdir(parents=True) @@ -1205,14 +1205,14 @@ def test_given_sql_and_custom_rules_when_compiling_twice_then_custom_host_runs_o encoding="utf-8", ) rule_file: Path = tmp_path / "rules" / "architecture.py" - rule_file.parent.mkdir() + rule_file.parent.mkdir(parents=True) rule_file.write_text( """from sqlbuild.rules import Finding, Model, RuleContext, rule @rule( code="XSQBRARCH001", message="Final models must use the final directory", - remediation="Move this model beneath models/final/.", + remediation="Move this model beneath sql/models/final/.", ) def final_directory(*, model: Model, ctx: RuleContext) -> list[Finding]: return [] if "final" in model.path.parts else [ctx.finding(subject=model)] @@ -1228,7 +1228,7 @@ def final_directory(*, model: Model, ctx: RuleContext) -> list[Finding]: assert len(hosts.launches()) == 1 assert warm == cold assert { - f"models/orders.sql:{test_case.expected_code}", + f"sql/models/orders.sql:{test_case.expected_code}", "tests/unit/test_orders.sql:SQLCLEAN004", } <= cold @@ -1239,13 +1239,13 @@ def final_directory(*, model: Model, ctx: RuleContext) -> list[Finding]: ProjectRuleScratchStateTestCase( description="one host runs the project rules in order", hosts=1, - expected_findings=(("XSQBRSCR002", "models/customers.sql"),), + expected_findings=(("XSQBRSCR002", "sql/models/customers.sql"),), expected_launches=1, ), ProjectRuleScratchStateTestCase( description="split project rules rerun in one host after the scratch list fills", hosts=2, - expected_findings=(("XSQBRSCR002", "models/customers.sql"),), + expected_findings=(("XSQBRSCR002", "sql/models/customers.sql"),), expected_launches=3, ), ], @@ -1287,21 +1287,21 @@ def test_given_custom_rules_split_across_hosts_when_compiling_then_output_matche ) for index in range(test_case.model_count): folder: str = ("final", "staging", "staging")[index % 3] - model: Path = tmp_path / "models" / folder / f"orders_{index:02d}.sql" + model: Path = tmp_path / "sql" / "models" / folder / f"orders_{index:02d}.sql" model.parent.mkdir(parents=True, exist_ok=True) model.write_text( f'MODEL (description "Orders {index}");\nSELECT {index} AS order_id\n', encoding="utf-8", ) rule_file: Path = tmp_path / "rules" / "architecture.py" - rule_file.parent.mkdir() + rule_file.parent.mkdir(parents=True) rule_file.write_text( """from sqlbuild.rules import Finding, Model, RuleContext, rule @rule( code="XSQBRARCH001", message="Final models must use the final directory", - remediation="Move this model beneath models/final/.", + remediation="Move this model beneath sql/models/final/.", ) def final_directory(*, model: Model, ctx: RuleContext) -> list[Finding]: return [] if "final" in model.path.parts else [ctx.finding(subject=model)] @@ -1318,7 +1318,7 @@ def compile_payload() -> dict[str, Any]: single_hosts: CustomHostObserver = observe_hosts(monkeypatch=monkeypatch, cores=1) single: dict[str, Any] = compile_payload() rules_bulk_cache_path(project_dir=tmp_path, file_name="custom-rules.json").parent.parent.rename( - tmp_path / "single-rules-cache" + tmp_path / "target" / "single-rules-cache" ) split_hosts: CustomHostObserver = observe_hosts(monkeypatch=monkeypatch, cores=test_case.hosts) split: dict[str, Any] = compile_payload() @@ -1334,7 +1334,9 @@ def compile_payload() -> dict[str, Any]: assert len(split["diagnostics"]) == test_case.model_count - test_case.model_count // 3 assert warm["diagnostics"] == single["diagnostics"] assert warm["compile_timings"]["rule_cache_hits"] >= test_case.model_count - assert (tmp_path / "single-rules-cache" / "bulk" / "custom-rules.json").read_bytes() == ( + assert ( + tmp_path / "target" / "single-rules-cache" / "bulk" / "custom-rules.json" + ).read_bytes() == ( rules_bulk_cache_path(project_dir=tmp_path, file_name="custom-rules.json").read_bytes() ) @@ -1402,15 +1404,15 @@ def test_given_busy_split_hosts_when_compile_is_interrupted_then_hosts_stop_and_ monkeypatch: pytest.MonkeyPatch, ) -> None: project_dir: Path = tmp_path / "orders" - project_dir.mkdir() + project_dir.mkdir(parents=True) started: Path = tmp_path / "started" - started.mkdir() + started.mkdir(parents=True) write_custom_host_project( project_dir=project_dir, model_count=test_case.model_count, rule_body=( "from pathlib import Path\n" - f"(Path({str(started)!r}) / model.name).mkdir()\n" + f"(Path({str(started)!r}) / model.name).mkdir(parents=True)\n" "total = 0\nfor index in range(10_000_000):\n total += index\nreturn []" ), ) @@ -1447,18 +1449,18 @@ def test_given_typed_custom_rule_when_compiling_then_same_rule_is_enforced_and_c "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n", encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") rule_file: Path = tmp_path / "rules" / "architecture.py" - rule_file.parent.mkdir() + rule_file.parent.mkdir(parents=True) rule_file.write_text( """from sqlbuild.rules import Finding, Model, RuleContext, rule @rule( code="XSQBRARCH001", message="Final models must use the final directory", - remediation="Move this model beneath models/final/.", + remediation="Move this model beneath sql/models/final/.", ) def final_directory(*, model: Model, ctx: RuleContext) -> list[Finding]: return [] if "final" in model.path.parts else [ctx.finding(subject=model)] @@ -1488,7 +1490,7 @@ def final_directory(*, model: Model, ctx: RuleContext) -> list[Finding]: assert cold["compile_timings"]["rule_cache_hits"] == 0 assert warm["compile_timings"]["rule_cache_hits"] >= 1 assert ( - (tmp_path / "target" / "compiled-failed" / "models" / "orders.sql") + (tmp_path / "target" / "compiled-failed" / "sql" / "models" / "orders.sql") .read_text(encoding="utf-8") .startswith("-- sqb: compile failed for this model; not buildable\n-- XSQBRARCH001 at ") ) @@ -1509,8 +1511,8 @@ def test_given_project_when_running_focused_rule_family_then_only_that_family_ru (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\nSELECT order_id FROM orders LIMIT 1\n', encoding="utf-8", @@ -1547,8 +1549,8 @@ def test_given_inline_query_relation_when_running_readability_rule_then_finding_ (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Orders"); WITH actual_orders AS ( @@ -1596,8 +1598,8 @@ def test_given_scalar_query_with_derived_relation_when_running_readability_rule_ (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "order_summary.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "order_summary.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Order summary"); SELECT ( @@ -1641,7 +1643,7 @@ def test_given_sql_function_argument_when_running_qualification_rule_then_argume (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - function: Path = tmp_path / "functions" / "sql" / "orders_by_date.sql" + function: Path = tmp_path / "sql" / "functions" / "sql" / "orders_by_date.sql" function.parent.mkdir(parents=True) function.write_text( """FUNCTION (description "Test function orders_by_date.", @@ -1687,7 +1689,7 @@ def test_given_table_function_argument_when_running_alias_rule_then_left_alias_i (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - function: Path = tmp_path / "functions" / "sql" / "expand_order.sql" + function: Path = tmp_path / "sql" / "functions" / "sql" / "expand_order.sql" function.parent.mkdir(parents=True) function.write_text( """FUNCTION (description "Test function expand_order.", @@ -1699,8 +1701,8 @@ def test_given_table_function_argument_when_running_alias_rule_then_left_alias_i """, encoding="utf-8", ) - model: Path = tmp_path / "models" / "expanded_orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "expanded_orders.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Expanded orders"); SELECT expanded.order_id @@ -1783,8 +1785,8 @@ def test_given_implicit_table_alias_when_running_alias_rule_then_usage_decides_f (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( 'MODEL (description "Orders");\nSELECT 1 AS order_id, 2 AS customer_id\n', encoding="utf-8", @@ -1804,7 +1806,7 @@ def test_given_implicit_table_alias_when_running_alias_rule_then_usage_decides_f assert tuple((finding["line"], finding["column"]) for finding in findings) == ( test_case.expected_locations ) - assert {finding["path"] for finding in findings} <= {"models/order_customers.sql"} + assert {finding["path"] for finding in findings} <= {"sql/models/order_customers.sql"} @pytest.mark.parametrize( @@ -1821,8 +1823,8 @@ def test_given_ceremonial_sql_test_when_compiling_with_rule_035_then_project_is_ 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN035"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Orders"); WITH final AS (SELECT 1 AS order_id) @@ -1862,8 +1864,8 @@ def test_given_keyword_named_columns_when_running_terminal_rule_then_projection_ (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Orders with contextual column names"); WITH final AS ( @@ -1922,8 +1924,8 @@ def test_given_assertion_expected_dependency_when_compiling_then_compiler_reject (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") test: Path = tmp_path / "tests" / "unit" / "test_orders.sql" test.parent.mkdir(parents=True) @@ -1963,10 +1965,10 @@ def test_given_seed_and_function_references_when_running_source_rule_then_they_a 'name = "orders"\nadapter = "duckdb"\n\n[rules]\napproved_source_tokens = ["partner"]\n', encoding="utf-8", ) - seed: Path = tmp_path / "seeds" / "order_statuses.csv" - seed.parent.mkdir() + seed: Path = tmp_path / "sql" / "seeds" / "order_statuses.csv" + seed.parent.mkdir(parents=True) seed.write_text("status\nopen\n", encoding="utf-8") - (tmp_path / "seeds" / "schema.yml").write_text( + (tmp_path / "sql" / "seeds" / "schema.yml").write_text( """seeds: - name: order_statuses description: Supported order statuses. @@ -1976,7 +1978,7 @@ def test_given_seed_and_function_references_when_running_source_rule_then_they_a """, encoding="utf-8", ) - function: Path = tmp_path / "functions" / "sql" / "normalize_quantity.sql" + function: Path = tmp_path / "sql" / "functions" / "sql" / "normalize_quantity.sql" function.parent.mkdir(parents=True) function.write_text( """FUNCTION (description "Test function normalize_quantity.", @@ -1988,8 +1990,8 @@ def test_given_seed_and_function_references_when_running_source_rule_then_they_a """, encoding="utf-8", ) - model: Path = tmp_path / "models" / "sales__stg__orders__partner.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "sales__stg__orders__partner.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Partner orders"); SELECT __udf("normalize_quantity")(1) AS quantity @@ -2033,13 +2035,13 @@ def test_given_dependency_import_star_when_running_output_shape_rule_then_import (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - staging: Path = tmp_path / "models" / "stg_orders.sql" - staging.parent.mkdir() + staging: Path = tmp_path / "sql" / "models" / "stg_orders.sql" + staging.parent.mkdir(parents=True) staging.write_text( 'MODEL (description "Staged orders");\nSELECT 1 AS order_id\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" + model: Path = tmp_path / "sql" / "models" / "orders.sql" model.write_text( """MODEL (description "Orders"); WITH imported_orders AS ( @@ -2085,8 +2087,8 @@ def test_given_invocation_dependent_shapes_when_running_output_shape_rule_then_s (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "order_totals.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "order_totals.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL ( description "Dynamic order totals", @@ -2101,7 +2103,7 @@ def test_given_invocation_dependent_shapes_when_running_output_shape_rule_then_s """, encoding="utf-8", ) - audit: Path = tmp_path / "audits" / "generic" / "recent_orders.sql" + audit: Path = tmp_path / "sql" / "audits" / "generic" / "recent_orders.sql" audit.parent.mkdir(parents=True) audit.write_text( """AUDIT (); @@ -2144,13 +2146,13 @@ def test_given_commented_dependency_call_when_running_import_rule_then_comment_i (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - staging: Path = tmp_path / "models" / "stg_orders.sql" - staging.parent.mkdir() + staging: Path = tmp_path / "sql" / "models" / "stg_orders.sql" + staging.parent.mkdir(parents=True) staging.write_text( 'MODEL (description "Staged orders");\nSELECT 1 AS order_id\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" + model: Path = tmp_path / "sql" / "models" / "orders.sql" model.write_text( """MODEL (description "Orders"); WITH imported_orders AS ( @@ -2204,14 +2206,14 @@ def test_given_bigquery_quoted_comment_marker_when_running_import_rule_then_repo (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "bigquery"\n', encoding="utf-8" ) - staging: Path = tmp_path / "models" / "stg_orders.sql" - staging.parent.mkdir() + staging: Path = tmp_path / "sql" / "models" / "stg_orders.sql" + staging.parent.mkdir(parents=True) staging.write_text( 'MODEL (description "Staged orders", database warehouse, schema analytics);\n' "SELECT 1 AS order_id\n", encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" + model: Path = tmp_path / "sql" / "models" / "orders.sql" model.write_text( """MODEL (description "Orders", database warehouse, schema analytics); WITH imported_orders AS ( @@ -2263,18 +2265,18 @@ def test_given_postgres_nested_comment_when_running_import_rule_then_comment_is_ (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "postgres"\n', encoding="utf-8" ) - staging: Path = tmp_path / "models" / "stg_orders.sql" - staging.parent.mkdir() + staging: Path = tmp_path / "sql" / "models" / "stg_orders.sql" + staging.parent.mkdir(parents=True) staging.write_text( 'MODEL (description "Staged orders", schema analytics);\nSELECT 1 AS order_id\n', encoding="utf-8", ) - retired: Path = tmp_path / "models" / "retired_orders.sql" + retired: Path = tmp_path / "sql" / "models" / "retired_orders.sql" retired.write_text( 'MODEL (description "Retired orders", schema analytics);\nSELECT 1 AS order_id\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" + model: Path = tmp_path / "sql" / "models" / "orders.sql" model.write_text( """MODEL (description "Orders", schema analytics); WITH imported_orders AS ( @@ -2321,8 +2323,8 @@ def test_given_cross_join_used_by_filter_when_running_unused_join_rule_then_no_f (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "recent_orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "recent_orders.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Recent orders"); SELECT orders.order_id @@ -2363,8 +2365,8 @@ def test_given_ceremonial_test_select_when_running_alias_rule_then_control_proje (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") test: Path = tmp_path / "tests" / "unit" / "orders_test.sql" test.parent.mkdir(parents=True) @@ -2408,8 +2410,8 @@ def test_given_direct_ceremonial_select_when_running_terminal_rule_then_test_is_ (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") test: Path = tmp_path / "tests" / "unit" / "orders_test.sql" test.parent.mkdir(parents=True) @@ -2449,8 +2451,8 @@ def test_given_prior_cte_when_scalar_subquery_is_aliased_then_inner_aggregate_is (tmp_path / "sqlbuild_project.toml").write_text( 'name = "support"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "ticket_totals.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "ticket_totals.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Support ticket totals"); WITH products_used AS ( @@ -2497,8 +2499,8 @@ def test_given_cast_and_relation_aliases_when_running_self_alias_rule_then_no_fi (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( """MODEL (description "Orders"); SELECT CAST(orders.order_id::INTEGER AS INTEGER) AS order_id @@ -2542,8 +2544,8 @@ def test_given_graph_scoped_rule_ignore_when_running_rules_then_only_matched_res 'reason = "Reviewed upstream interface boundary"\n', encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "base_orders.sql").write_text( 'MODEL (description "Base orders");\nSELECT 1 AS order_id\n', encoding="utf-8", @@ -2573,7 +2575,7 @@ def test_given_graph_scoped_rule_ignore_when_running_rules_then_only_matched_res payload: dict[str, object] = json.loads(captured.out) findings: list[dict[str, object]] = cast(list[dict[str, object]], payload["findings"]) finding_paths: list[object] = [finding.get("path") for finding in findings] - assert finding_paths == ["models/customer_orders.sql"] + assert finding_paths == ["sql/models/customer_orders.sql"] @pytest.mark.parametrize( @@ -2595,11 +2597,11 @@ def test_given_default_off_custom_rule_when_running_exact_and_prefix_then_both_s "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n", encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") rule_file: Path = tmp_path / "rules" / "architecture.py" - rule_file.parent.mkdir() + rule_file.parent.mkdir(parents=True) rule_file.write_text( """from sqlbuild.rules import Finding, Model, RuleContext, rule @@ -2636,11 +2638,11 @@ def test_given_sql_rule_exception_when_compiling_then_unified_suppression_is_app 'name = "orders"\nadapter = "duckdb"\n\n' '[rules]\nselect = ["SQLCLEAN004"]\n\n' '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\n' - 'path = "models/orders.sql"\nreason = "The fixture intentionally selects one row."\n', + 'path = "sql/models/orders.sql"\nreason = "The fixture intentionally selects one row."\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\nSELECT order_id FROM orders LIMIT 1\n', encoding="utf-8", @@ -2669,13 +2671,13 @@ def test_given_custom_rule_module_constant_edit_when_compiling_then_cached_resul "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n", encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", encoding="utf-8" ) rule_file: Path = tmp_path / "rules" / "architecture.py" - rule_file.parent.mkdir() + rule_file.parent.mkdir(parents=True) rule_source: str = """from sqlbuild.rules import Finding, Model, RuleContext, rule FORBIDDEN, UNUSED = ("orders", "unused") @@ -2720,8 +2722,8 @@ def test_given_focused_project_rule_result_when_compiling_full_project_then_subs "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n", encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", encoding="utf-8" ) @@ -2729,7 +2731,7 @@ def test_given_focused_project_rule_result_when_compiling_full_project_then_subs "MODEL (description 'Test model customers.');\nSELECT 1 AS customer_id\n", encoding="utf-8" ) rule_file: Path = tmp_path / "rules" / "architecture.py" - rule_file.parent.mkdir() + rule_file.parent.mkdir(parents=True) rule_file.write_text( """from sqlbuild.rules import Finding, Project, RuleContext, rule @@ -2767,15 +2769,15 @@ def test_given_non_model_sql_violation_when_compiling_then_compile_is_authoritat 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN004"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", encoding="utf-8" ) - (tmp_path / "models" / "customers.sql").write_text( + (tmp_path / "sql" / "models" / "customers.sql").write_text( "MODEL (description 'Test model customers.');\nSELECT 1 AS order_id\n", encoding="utf-8" ) - audit: Path = tmp_path / "audits" / "singular" / "order_sample.sql" + audit: Path = tmp_path / "sql" / "audits" / "singular" / "order_sample.sql" audit.parent.mkdir(parents=True) audit.write_text( 'AUDIT ();\nSELECT * FROM __ref("orders") JOIN __ref("customers") USING (order_id) LIMIT 1\n', @@ -2787,7 +2789,7 @@ def test_given_non_model_sql_violation_when_compiling_then_compile_is_authoritat assert exit_code == test_case.expected_exit_code assert payload["diagnostics"][0]["code"] == test_case.expected_code - assert payload["diagnostics"][0]["path"] == "audits/singular/order_sample.sql" + assert payload["diagnostics"][0]["path"] == "sql/audits/singular/order_sample.sql" @pytest.mark.parametrize( @@ -2802,12 +2804,12 @@ def test_given_exception_for_other_model_when_compiling_selection_then_exception ) -> None: (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN004"]\n\n' - '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\npath = "models/customers.sql"\n' + '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\npath = "sql/models/customers.sql"\n' 'reason = "The fixture intentionally selects one row."\n', encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", encoding="utf-8" ) @@ -2840,8 +2842,8 @@ def test_given_typed_unselected_model_when_planning_selection_then_rules_use_sel '[rules]\nselect = ["SQBRCONTRACT105"]\n', encoding="utf-8", ) - sources: Path = tmp_path / "sources" - sources.mkdir() + sources: Path = tmp_path / "sql" / "sources" + sources.mkdir(parents=True) (sources / "customers.yml").write_text( """sources: - name: raw_customers @@ -2854,8 +2856,8 @@ def test_given_typed_unselected_model_when_planning_selection_then_rules_use_sel """, encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( "MODEL (description 'Test model orders.', contract enforced, columns (order_id (type INTEGER)));\n" "SELECT CAST(1 AS INTEGER) AS order_id\n", @@ -2902,6 +2904,7 @@ def test_given_subject_before_layer_when_running_folder_rule_then_canonical_move ) model: Path = ( tmp_path + / "sql" / "models" / "commerce" / "intermediate" @@ -2933,7 +2936,7 @@ def test_given_subject_before_layer_when_running_folder_rule_then_canonical_move '"intermediate/clean" contiguous' ] assert [finding["remediation"] for finding in findings] == [ - 'Move the model to "models/commerce/intermediate/clean/payments/' + 'Move the model to "sql/models/commerce/intermediate/clean/payments/' 'commerce__int_clean__orders.sql"; preserve subject folders outside ' '"intermediate/clean". Use rules.layout with SQBRPROJECT201-204 to enforce ' "domain and subdomain ordering." @@ -2956,13 +2959,13 @@ def test_given_relative_project_path_when_compiling_twice_then_sql_finding_remai monkeypatch: pytest.MonkeyPatch, ) -> None: project_dir: Path = tmp_path / "project" - project_dir.mkdir() + project_dir.mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN004"]\n', encoding="utf-8", ) - model: Path = project_dir / "models" / "orders.sql" - model.parent.mkdir() + model: Path = project_dir / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (description 'Test model orders.');\nSELECT order_id FROM orders LIMIT 1\n", encoding="utf-8", @@ -2993,8 +2996,8 @@ def test_given_inline_directive_without_finding_when_compiling_then_directive_is 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQLCLEAN004"]\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (description 'Test model orders.');\n-- sqb: ignore SQLCLEAN004 because this fixture checks stale directives\n" "SELECT 1 AS order_id\n", @@ -3023,13 +3026,13 @@ def test_given_unselected_custom_rule_options_when_compiling_then_configuration_ '[rules.rule_options.XSQBRARCH001]\nrequired_prefix = "order"\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", encoding="utf-8" ) rule_file: Path = tmp_path / "rules" / "architecture.py" - rule_file.parent.mkdir() + rule_file.parent.mkdir(parents=True) rule_file.write_text( """from sqlbuild.rules import Finding, Model, RuleContext, RuleOption, rule @@ -3062,41 +3065,41 @@ def required_prefix(*, model: Model, ctx: RuleContext) -> list[Finding]: EmptyRuleSelectionTestCase( "valid exception for an unevaluated rule compiles", "[[rules.rule_exceptions]]\n" - 'rule = "SQBRCONTRACT101"\npath = "models/orders.sql"\nreason = "Legacy."\n', + 'rule = "SQBRCONTRACT101"\npath = "sql/models/orders.sql"\nreason = "Legacy."\n', 0, (), ), EmptyRuleSelectionTestCase( "unknown exception rule is rejected", - '[[rules.rule_exceptions]]\nrule = "SQBRNOPE999"\npath = "models/orders.sql"\n' + '[[rules.rule_exceptions]]\nrule = "SQBRNOPE999"\npath = "sql/models/orders.sql"\n' 'reason = "Legacy."\n', 1, ("rule exceptions target unknown rules: SQBRNOPE999",), ), EmptyRuleSelectionTestCase( "missing exception path is rejected", - '[[rules.rule_exceptions]]\nrule = "SQBRCONTRACT101"\npath = "models/missing.sql"\n' + '[[rules.rule_exceptions]]\nrule = "SQBRCONTRACT101"\npath = "sql/models/missing.sql"\n' 'reason = "Legacy."\n', 1, - ("rule exception path does not exist: models/missing.sql",), + ("rule exception path does not exist: sql/models/missing.sql",), ), EmptyRuleSelectionTestCase( "ignore selector matching no rule is rejected", - '[[rules.rule_ignores]]\nrules = ["SQBRZZZ"]\npaths = ["models/orders.sql"]\n' + '[[rules.rule_ignores]]\nrules = ["SQBRZZZ"]\npaths = ["sql/models/orders.sql"]\n' 'reason = "Legacy."\n', 1, ("rule-ignore selector matches no rules: SQBRZZZ",), ), EmptyRuleSelectionTestCase( "missing literal ignore path is rejected", - '[[rules.rule_ignores]]\nrules = ["SQLCLEAN"]\npaths = ["models/orders.sql", "models/gone.sql"]\n' + '[[rules.rule_ignores]]\nrules = ["SQLCLEAN"]\npaths = ["sql/models/orders.sql", "sql/models/gone.sql"]\n' 'reason = "Legacy."\n', 1, - ("rule ignore path does not exist: models/gone.sql",), + ("rule ignore path does not exist: sql/models/gone.sql",), ), EmptyRuleSelectionTestCase( "ignore paths naming a folder or a glob that matches nothing compile", - '[[rules.rule_ignores]]\nrules = ["SQLCLEAN"]\npaths = ["models", "models/legacy/**"]\n' + '[[rules.rule_ignores]]\nrules = ["SQLCLEAN"]\npaths = ["sql/models", "sql/models/legacy/**"]\n' 'reason = "Legacy."\n', 0, (), @@ -3119,8 +3122,8 @@ def test_given_empty_rule_selection_when_compiling_then_only_configuration_is_va f'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = []\n\n{test_case.configuration}', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id\n", encoding="utf-8" ) @@ -3171,8 +3174,8 @@ def test_given_sql_rule_cache_when_inputs_change_then_only_unchanged_runs_hit( tmp_path: Path, capsys: pytest.CaptureFixture[str], ) -> None: - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) observed: list[tuple[int, int]] = [] for project_toml, model_sql in test_case.steps: (tmp_path / "sqlbuild_project.toml").write_text(project_toml, encoding="utf-8") @@ -3213,10 +3216,10 @@ def test_given_custom_rule_cache_when_inputs_change_then_only_unchanged_runs_hit capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_CUSTOM_CACHE_TOML, encoding="utf-8") - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) rule_file: Path = tmp_path / "rules" / "layout.py" - rule_file.parent.mkdir() + rule_file.parent.mkdir(parents=True) observed: list[tuple[int, int]] = [] for rule_source, model_sql in test_case.steps: rule_file.write_text(rule_source, encoding="utf-8") @@ -3244,15 +3247,15 @@ def test_given_custom_rule_cache_when_inputs_change_then_only_unchanged_runs_hit "2|None|order_totals,stg_orders|raw_orders|regions||test_order_totals|" "not_null,accepted_values,accepted_values|1|3|order_status|minimum_amount|1|1|" "order_totals", - "order_totals|models/marts/order_totals.sql|table|137|79|stg_orders|||" + "order_totals|sql/models/marts/order_totals.sql|table|137|79|stg_orders|||" "order_id:INTEGER:non_null;doubled_amount:DOUBLE:unknown|order_id,doubled_amount|" "False||test_order_totals|", - "stg_orders|models/staging/stg_orders.sql|None|417|109||order_totals|" + "stg_orders|sql/models/staging/stg_orders.sql|None|417|109||order_totals|" "order_id:INTEGER:False:Order key:not_null:[]:None/accepted_values:" - "[('values', [1, 2])]:warn:models/staging/stg_orders.sql:2;" - "amount:DOUBLE:None:None::models/staging/stg_orders.sql:4;" + "[('values', [1, 2])]:warn:sql/models/staging/stg_orders.sql:2;" + "amount:DOUBLE:None:None::sql/models/staging/stg_orders.sql:4;" "status:VARCHAR:None:None:accepted_values:[('values', ('PAID', 'OPEN'))]:None:" - "models/staging/stg_orders.sql:5|" + "sql/models/staging/stg_orders.sql:5|" "order_id:INTEGER:unknown;amount:DOUBLE:unknown;status:VARCHAR:non_null|" "order_id,amount,status|True|||not_null,accepted_values,accepted_values", ), @@ -3303,7 +3306,7 @@ def test_given_rules_reading_every_fact_when_compiling_then_values_and_cache_reu expected_exit_code=1, expected_messages=( "invalid rules lifecycle: custom host failed: rule XSQBRHOST001 failed for " - "models/orders_001.sql: cannot inspect order_id", + "sql/models/orders_001.sql: cannot inspect order_id", ), ), CustomHostOutcomeTestCase( @@ -3376,12 +3379,14 @@ def test_given_star_in_set_operation_branches_when_compiling_then_each_branch_is 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQBRMODEL102"]\n', encoding="utf-8", ) - (tmp_path / "models").mkdir() - (tmp_path / "models" / "orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql" / "models" / "orders.sql").write_text( "MODEL (description 'Test model orders.', materialized view);\nSELECT 1 AS order_id\n", encoding="utf-8", ) - (tmp_path / "models" / "order_ids.sql").write_text(test_case.model_sql, encoding="utf-8") + (tmp_path / "sql" / "models" / "order_ids.sql").write_text( + test_case.model_sql, encoding="utf-8" + ) exit_code: int = main(["--project-dir", str(tmp_path), "compile", "--json", "--no-cache"]) result: dict[str, object] = json.loads(capsys.readouterr().out) @@ -3417,7 +3422,7 @@ def test_given_star_in_set_operation_branches_when_compiling_then_each_branch_is fixture="violations", rules_toml=( 'select = ["SQBR"]\n\n[[rules.rule_ignores]]\nrules = ["SQBR"]\n' - 'paths = ["models/orders.sql"]\nreason = "Only Python findings matter here."\n' + 'paths = ["sql/models/orders.sql"]\nreason = "Only Python findings matter here."\n' ), expected_exit_code=0, expected_findings=(), @@ -3427,7 +3432,7 @@ def test_given_star_in_set_operation_branches_when_compiling_then_each_branch_is fixture="violations", rules_toml=( 'select = ["SQBRPYTHON101"]\n\n[[rules.rule_exceptions]]\n' - 'rule = "SQBRPYTHON101"\npath = "hooks/python/alert.py"\n' + 'rule = "SQBRPYTHON101"\npath = "sql/hooks/python/alert.py"\n' 'reason = "The alert hook keeps its documented signature."\n' ), expected_exit_code=0, @@ -3438,12 +3443,12 @@ def test_given_star_in_set_operation_branches_when_compiling_then_each_branch_is fixture="violations", rules_toml=( 'select = ["SQBRPYTHON101"]\n\n[[rules.rule_exceptions]]\n' - 'rule = "SQBRPYTHON101"\npath = "python/report.py"\nreason = "Legacy."\n' + 'rule = "SQBRPYTHON101"\npath = "python/nodes/report.py"\nreason = "Legacy."\n' ), expected_exit_code=1, expected_findings=(("C000", None, None, None),), expected_text=( - "stale rule exception suppresses no finding: SQBRPYTHON101 at python/report.py" + "stale rule exception suppresses no finding: SQBRPYTHON101 at python/nodes/report.py" ), ), PythonRulesIntegrationTestCase( @@ -3452,7 +3457,7 @@ def test_given_star_in_set_operation_branches_when_compiling_then_each_branch_is rules_toml=( 'select = ["SQBRPYTHON022"]\n\n[rules.rule_options.SQBRPYTHON022]\n' "approved_loader_boundaries = " - '["python.inventory.restock._helpers.thresholds.load_thresholds"]\n' + '["python.nodes.inventory.restock._helpers.thresholds.load_thresholds"]\n' ), expected_exit_code=0, expected_findings=(), @@ -3462,7 +3467,7 @@ def test_given_star_in_set_operation_branches_when_compiling_then_each_branch_is fixture="violations", rules_toml=( 'select = ["SQBRPYTHON022"]\n\n[rules.rule_options.SQBRPYTHON022]\n' - 'approved_loader_boundaries = ["python.inventory.*"]\n' + 'approved_loader_boundaries = ["python.nodes.inventory.*"]\n' ), expected_exit_code=1, expected_findings=(("C000", None, None, None),), @@ -3476,7 +3481,7 @@ def test_given_star_in_set_operation_branches_when_compiling_then_each_branch_is "[rules.rule_options.SQBRPYTHON504]\nmax_arguments = 1\n" ), expected_exit_code=1, - expected_findings=(("SQBRPYTHON504", "hooks/python/alert.py", 4, 1),), + expected_findings=(("SQBRPYTHON504", "sql/hooks/python/alert.py", 4, 1),), expected_text="function has 2 parameters", ), ], @@ -3726,7 +3731,7 @@ def test_given_orchestration_selections_when_compiling_then_named_selector_limit PerformanceRulesIntegrationTestCase( description="a second reader ends the published-view exemption", extra_models={ - "models/order_line_counts.sql": ( + "sql/models/order_line_counts.sql": ( 'MODEL (description "Lines per order.");\n' "SELECT order_id, COUNT(*) AS line_count\n" 'FROM __ref("shop__mart__order_lines")\nGROUP BY order_id\n' @@ -3734,7 +3739,7 @@ def test_given_orchestration_selections_when_compiling_then_named_selector_limit }, expected_findings=( *_PERFORMANCE_FINDINGS, - ("SQBRPERFORMANCE102", "models/shop__mart__order_lines.sql", 11, 3), + ("SQBRPERFORMANCE102", "sql/models/shop__mart__order_lines.sql", 11, 3), ), ), ], diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_rules_concurrent.py b/tests/integration/src/sqlbuild/cli/commands/main/test_rules_concurrent.py index 3d78bd8bce..f1e2deee5e 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_rules_concurrent.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_rules_concurrent.py @@ -29,19 +29,19 @@ def test_given_sql_and_custom_exceptions_when_compiling_cold_and_warm_then_both_ '[rules]\nselect = ["SQLCLEAN004", "XSQBRARCH001"]\n' "[rules.thresholds]\nmin_custom_rule_test_cases = 0\n" '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\n' - 'path = "models/orders.sql"\nreason = "A single synthetic row is intentional."\n' + 'path = "sql/models/orders.sql"\nreason = "A single synthetic row is intentional."\n' '[[rules.rule_exceptions]]\nrule = "XSQBRARCH001"\n' - 'path = "models/orders.sql"\nreason = "The synthetic model name is intentional."\n' + 'path = "sql/models/orders.sql"\nreason = "The synthetic model name is intentional."\n' ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( "MODEL (description 'Test model orders.');\n" "WITH source AS (SELECT 1 AS order_id UNION ALL SELECT 2 AS order_id)\n" "SELECT s.order_id FROM source AS s LIMIT 1\n" ) rules: Path = tmp_path / "rules" - rules.mkdir() + rules.mkdir(parents=True) (rules / "architecture.py").write_text( "from sqlbuild.rules import Finding, Model, RuleContext, rule\n\n" '@rule(code="XSQBRARCH001", message="Review model name", remediation="Rename the model.")\n' diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py b/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py index f01a5e50df..ec8296130d 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py @@ -209,9 +209,9 @@ def test_given_a_seed_run_when_it_loads_then_it_records_its_start_and_end( capsys: pytest.CaptureFixture[str], ) -> None: write_run_record_project(project_dir=tmp_path, settings="") - (tmp_path / "seeds").mkdir() - (tmp_path / "seeds" / "regions.csv").write_text("region_id\n1\n", encoding="utf-8") - (tmp_path / "seeds" / "regions.yml").write_text( + (tmp_path / "sql" / "seeds").mkdir(parents=True) + (tmp_path / "sql" / "seeds" / "regions.csv").write_text("region_id\n1\n", encoding="utf-8") + (tmp_path / "sql" / "seeds" / "regions.yml").write_text( "seeds:\n - name: regions\n description: Regions.\n columns:\n" " - name: region_id\n type: INTEGER\n", encoding="utf-8", diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_sql_readability.py b/tests/integration/src/sqlbuild/cli/commands/main/test_sql_readability.py index 6f39f592e9..26a612b0f6 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_sql_readability.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_sql_readability.py @@ -63,8 +63,8 @@ def test_given_join_predicate_when_compiling_and_running_rules_then_expression_p test_case: SqlReadabilityTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_CONFIG) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\n' "WITH customers AS (SELECT 1 AS order_id, 'success' AS status),\n" @@ -184,8 +184,8 @@ def test_given_cte_names_when_compiling_and_running_rules_then_final_name_policy test_case: SqlReadabilityTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_CONFIG) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text(f'MODEL (description "Orders");\n{test_case.sql}\n') assert main(["--project-dir", str(tmp_path), "compile", "--no-cache"]) == 0 capsys.readouterr() @@ -209,8 +209,8 @@ def test_given_family_selection_when_compiling_then_new_rules_are_enforced( (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = ["{test_case.sql}"]\n' ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\n' "WITH customers AS (SELECT 1 AS order_id), " @@ -246,8 +246,8 @@ def test_given_lateral_join_when_running_expression_rule_then_literals_pass_and_ test_case: SqlReadabilityTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "snowflake"\n') - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders", database warehouse, schema analytics);\n' "SELECT o.order_id FROM raw_orders AS o LEFT JOIN LATERAL FLATTEN(input => o.items) AS f " diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_target_retention_views.py b/tests/integration/src/sqlbuild/cli/commands/main/test_target_retention_views.py index be49be4ce0..b7f12ea73c 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_target_retention_views.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_target_retention_views.py @@ -41,13 +41,13 @@ def test_given_target_retention_default_when_compiling_views_then_only_explicit_ tmp_path: Path, capsys: pytest.CaptureFixture[str], ) -> None: - (tmp_path / "models").mkdir() + (tmp_path / "sql" / "models").mkdir(parents=True) (tmp_path / "sqlbuild_project.toml").write_text(_PROJECT_TOML, encoding="utf-8") - (tmp_path / "models" / "orders.sql").write_text( + (tmp_path / "sql" / "models" / "orders.sql").write_text( "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id\n", encoding="utf-8", ) - (tmp_path / "models" / "order_view.sql").write_text( + (tmp_path / "sql" / "models" / "order_view.sql").write_text( f'{test_case.view_header}\n\nSELECT order_id FROM __ref("orders")\n', encoding="utf-8" ) diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_unicode_lint.py b/tests/integration/src/sqlbuild/cli/commands/main/test_unicode_lint.py index 16d3aeb446..bfba6bd0ff 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_unicode_lint.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_unicode_lint.py @@ -90,8 +90,8 @@ def test_given_unicode_before_sql_when_running_rules_then_findings_have_characte test_case: UnicodeRuleLocationTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) contents: str = 'MODEL (description "Orders");\n' + test_case.sql + "\n" model.write_text(contents, encoding="utf-8") native_payload: dict[str, Any] = json.loads( @@ -126,7 +126,7 @@ def test_given_unicode_before_sql_when_running_rules_then_findings_have_characte (finding["line"], finding["column"]) for finding in payload["findings"] ] == expected_locations assert all(finding["code"] == test_case.rule_code for finding in payload["findings"]) - assert all(finding["path"] == "models/orders.sql" for finding in payload["findings"]) + assert all(finding["path"] == "sql/models/orders.sql" for finding in payload["findings"]) if __name__ == "__main__": diff --git a/tests/integration/src/sqlbuild/cli/entry/helpers.py b/tests/integration/src/sqlbuild/cli/entry/helpers.py index b510600905..6c44ade0a4 100644 --- a/tests/integration/src/sqlbuild/cli/entry/helpers.py +++ b/tests/integration/src/sqlbuild/cli/entry/helpers.py @@ -33,7 +33,7 @@ 'connection = "local"\n' 'schema = "dev"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n description "One row per order",\n materialized table,\n);\n\n' "SELECT 1 AS order_id, CAST('2026-04-01' AS DATE) AS ordered_on\n" ), @@ -130,7 +130,7 @@ def write_linked_project(project_dir: Path) -> Path: """Put the model behind a file link to an external input.""" project: Path = write_project(project_dir) - model: Path = project / "models" / "orders.sql" + model: Path = project / "sql" / "models" / "orders.sql" target: Path = project.parent / "linked_orders.sql" _ = model.replace(target) model.symlink_to(target) @@ -140,7 +140,7 @@ def write_linked_project(project_dir: Path) -> Path: def rewrite_model_preserving_mtime(project_dir: Path) -> None: """Change equal-length SQL bytes, including through a link, without changing mtime.""" - model: Path = project_dir / "models" / "orders.sql" + model: Path = project_dir / "sql" / "models" / "orders.sql" original: os.stat_result = model.stat() _ = model.write_text(model.read_text().replace("1 AS order_id", "2 AS order_id")) os.utime(model, ns=(original.st_atime_ns, original.st_mtime_ns)) @@ -189,8 +189,8 @@ def startup_install(directory: Path) -> tuple[Path, Path, Path]: ) old: Path = directory.parent / "old_helpers" new: Path = directory.parent / "new_helpers" - old.mkdir() - new.mkdir() + old.mkdir(parents=True) + new.mkdir(parents=True) _ = (old / "catalog_helper.py").write_text("SQL = '1'\n", encoding="utf-8") _ = (new / "catalog_helper.py").write_text("SQL = '2'\n", encoding="utf-8") startup: Path = site_packages / "catalog.pth" @@ -284,7 +284,7 @@ def prepare_custom_rules(directory: Path) -> None: """Write the project with a custom rules directory.""" _ = write_project(directory) - (directory / "rules").mkdir() + (directory / "rules").mkdir(parents=True) def prepare_removed_allow_exceptions(directory: Path) -> None: @@ -349,13 +349,13 @@ def write_janitor_project(project_dir: Path, *, extra_toml: str) -> Path: """Write a DuckDB project with one model, janitor left disabled, and extra settings.""" project_dir.mkdir(parents=True, exist_ok=True) - (project_dir / "models").mkdir(exist_ok=True) + (project_dir / "sql" / "models").mkdir(parents=True, exist_ok=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders_shop"\nadapter = "duckdb"\n\n[connection]\n' f'database = "orders.duckdb"\n{extra_toml}', encoding="utf-8", ) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( "MODEL (description 'Orders.');\n\nSELECT 1 AS order_id\n", encoding="utf-8" ) return project_dir diff --git a/tests/integration/src/sqlbuild/cli/entry/test_native_launcher.py b/tests/integration/src/sqlbuild/cli/entry/test_native_launcher.py index 6f20b1ca24..a1d9ead36a 100644 --- a/tests/integration/src/sqlbuild/cli/entry/test_native_launcher.py +++ b/tests/integration/src/sqlbuild/cli/entry/test_native_launcher.py @@ -147,7 +147,7 @@ def test_given_edited_model_when_compiling_through_sqb_then_python_recompiles_th ) -> None: project_dir: Path = write_project(tmp_path / "project") _ = run(NATIVE_SQB, args=test_case.args, cwd=project_dir) - model: Path = project_dir / "models" / "orders.sql" + model: Path = project_dir / "sql" / "models" / "orders.sql" _ = model.write_text( model.read_text(encoding="utf-8").replace(test_case.old_text, test_case.new_text), encoding="utf-8", @@ -208,7 +208,7 @@ def test_given_unchanged_project_when_sqb_serves_the_hit_then_python_never_start after_first: int = python_starts(marker) served: LauncherRun = run(program, args=test_case.args, cwd=project_dir) after_served: int = python_starts(marker) - model: Path = project_dir / "models" / "orders.sql" + model: Path = project_dir / "sql" / "models" / "orders.sql" _ = model.write_text( model.read_text(encoding="utf-8").replace("1 AS order_id", "2 AS order_id"), encoding="utf-8", @@ -290,12 +290,12 @@ def test_given_cached_compile_when_startup_search_path_changes_then_new_helper_i ) -> None: program, startup, new_helpers = startup_install(tmp_path / "environment") project_dir: Path = write_project(tmp_path / "project") - (project_dir / "models" / "_macros" / "python").mkdir(parents=True) - _ = (project_dir / "models" / "_macros" / "python" / "orders.py").write_text( + (project_dir / "sql" / "models" / "_macros" / "python").mkdir(parents=True) + _ = (project_dir / "sql" / "models" / "_macros" / "python" / "orders.py").write_text( 'import catalog_helper\n\ndef order_value() -> str:\n """The order value."""\n return catalog_helper.SQL\n', encoding="utf-8", ) - model: Path = project_dir / "models" / "orders.sql" + model: Path = project_dir / "sql" / "models" / "orders.sql" _ = model.write_text( model.read_text().replace("1 AS order_id", "@py.order_value() AS order_id") ) @@ -311,5 +311,5 @@ def test_given_cached_compile_when_startup_search_path_changes_then_new_helper_i assert compile_timings(edited[1])["project_reuse_misses"] == test_case.expected_misses assert ( test_case.expected_fragment - in (project_dir / "target" / "compiled" / "models" / "orders.sql").read_text() + in (project_dir / "target" / "compiled" / "sql" / "models" / "orders.sql").read_text() ) diff --git a/tests/integration/src/sqlbuild/cli/recall/helpers.py b/tests/integration/src/sqlbuild/cli/recall/helpers.py index c54a3e1ef8..8f4b91c49e 100644 --- a/tests/integration/src/sqlbuild/cli/recall/helpers.py +++ b/tests/integration/src/sqlbuild/cli/recall/helpers.py @@ -18,6 +18,8 @@ from pathlib import Path from typing import Any +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files + PYTHON_CLI: Path = Path(sys.executable).with_name("sqlbuild-python") NATIVE_SQB: Path = Path(sys.executable).with_name("sqb") EMITTED_STDOUT: bytes = b"binary \x00\xff\xfe chunk\n" @@ -103,8 +105,8 @@ def write_project(project_dir: Path, *, extra_toml: str = "", targets: int = 1) ) files: dict[str, str] = { "sqlbuild_project.toml": toml, - "models/orders.sql": ORDERS_MODEL, - "python/tasks/emit.py": EMIT_TASK, + "sql/models/orders.sql": ORDERS_MODEL, + **node_module_files("python/nodes/tasks/emit.py", EMIT_TASK), } for relative, contents in files.items(): path: Path = project_dir / relative @@ -200,7 +202,7 @@ def build_with_read_only_logs( """Two builds while the project's `logs` directory cannot be written.""" logs: Path = project_dir / "logs" - logs.mkdir() + logs.mkdir(parents=True) logs.chmod(stat.S_IRUSR | stat.S_IXUSR) try: return run(project_dir, "build"), run(project_dir, "build") @@ -263,7 +265,7 @@ def killed_during_discovery( def write_slow_import_sink(project_dir: Path) -> Path: """Add a sink module whose import sleeps for `ORDERS_IMPORT_SECONDS`, slowing discovery.""" - sink: Path = project_dir / "sinks" / "slow_import.py" + sink: Path = project_dir / "python" / "event_sinks" / "slow_import.py" sink.parent.mkdir(parents=True, exist_ok=True) _ = sink.write_text( "import os\nimport sys\nimport time\n\n" @@ -503,20 +505,20 @@ def simultaneous_builds(project_dir: Path, targets: tuple[str, ...]) -> list[int RECALL_SINK_IMPORTS: str = ( "from pathlib import Path\n\n" "from sqlbuild.recall import RecallWriter\n" - "from sqlbuild.sinks import (\n" - " CommandOutputRecord, LifecycleEvent, command_output_sink, lifecycle_event_sink,\n" + "from sqlbuild.event_sinks import (\n" + " CommandOutputRecord, LifecycleEvent, command_output_event_sink, lifecycle_event_sink,\n" ")\n\n" ) EVENT_LOG_SINK: str = ( "@lifecycle_event_sink\n" "def event_log(event: LifecycleEvent) -> None:\n" - " with (Path(__file__).parents[1] / 'events.log').open('a') as log:\n" + " with (Path(__file__).parents[2] / '.events.log').open('a') as log:\n" " log.write(event.event_type + '\\n')\n" ) OUTPUT_LOG_SINK: str = ( - "@command_output_sink\n" + "@command_output_event_sink\n" "def output_log(record: CommandOutputRecord) -> None:\n" - " with (Path(__file__).parents[1] / 'output.log').open('a') as log:\n" + " with (Path(__file__).parents[2] / '.output.log').open('a') as log:\n" " log.write(record.message)\n" ) SLOW_LIFECYCLE_SINK: str = ( @@ -531,7 +533,7 @@ def simultaneous_builds(project_dir: Path, targets: tuple[str, ...]) -> list[int "@lifecycle_event_sink\n" "def recall_events(event: LifecycleEvent, writer: RecallWriter) -> None:\n" " raise RuntimeError('lifecycle sink failed')\n\n" - "@command_output_sink\n" + "@command_output_event_sink\n" "def recall_output(record: CommandOutputRecord, writer: RecallWriter) -> None:\n" " raise RuntimeError('output sink failed')\n" ) @@ -553,7 +555,7 @@ def rewriting_output_sink(replaced: tuple[bytes, bytes]) -> str: old, new = replaced return ( - "@command_output_sink\n" + "@command_output_event_sink\n" "def recall_output(record: CommandOutputRecord, writer: RecallWriter) -> None:\n" f" data = record.data.replace({old!r}, {new!r})\n" " writer.publish_command_output(record.replace(data=data))\n" @@ -561,10 +563,10 @@ def rewriting_output_sink(replaced: tuple[bytes, bytes]) -> str: def write_sinks(project_dir: Path, sinks: dict[str, str]) -> Path: - """Add `sinks/.py` modules holding the given sink definitions.""" + """Add `python/event_sinks/.py` modules holding the given sink definitions.""" for name, source in sinks.items(): - path: Path = project_dir / "sinks" / f"{name}.py" + path: Path = project_dir / "python" / "event_sinks" / f"{name}.py" path.parent.mkdir(parents=True, exist_ok=True) _ = path.write_text(RECALL_SINK_IMPORTS + source, encoding="utf-8") return project_dir @@ -574,7 +576,7 @@ def logged_event_types(project_dir: Path, dropped_prefix: str) -> tuple[list[str """The sorted event types `event_log` wrote, then those not starting with `dropped_prefix`.""" logged: list[str] = sorted( - (project_dir / "events.log").read_text(encoding="utf-8").splitlines() + (project_dir / ".events.log").read_text(encoding="utf-8").splitlines() ) dropped: operator.methodcaller = operator.methodcaller("startswith", dropped_prefix) return logged, list(itertools.filterfalse(dropped, logged)) diff --git a/tests/integration/src/sqlbuild/cli/recall/test_recall_cli.py b/tests/integration/src/sqlbuild/cli/recall/test_recall_cli.py index de785bec9c..431337d457 100644 --- a/tests/integration/src/sqlbuild/cli/recall/test_recall_cli.py +++ b/tests/integration/src/sqlbuild/cli/recall/test_recall_cli.py @@ -211,14 +211,14 @@ def test_given_project_sinks_when_reading_recall_then_no_sink_runs_and_no_comput project_dir: Path = write_project(tmp_path / "orders_shop") _ = write_sinks(project_dir, {"output_log": OUTPUT_LOG_SINK}) assert run(project_dir, "build").returncode == 0 - (project_dir / "output.log").unlink() + (project_dir / ".output.log").unlink() logs_before: set[Path] = set((project_dir / "logs").glob("*/*")) read: subprocess.CompletedProcess[bytes] = run(project_dir, *test_case.args) assert read.returncode == 0, read.stderr.decode(errors="replace") assert read.stdout - assert (project_dir / "output.log").exists() is test_case.expected_sink_log + assert (project_dir / ".output.log").exists() is test_case.expected_sink_log assert set((project_dir / "logs").glob("*/*")) == logs_before diff --git a/tests/integration/src/sqlbuild/cli/recall/test_recall_invocation_facts.py b/tests/integration/src/sqlbuild/cli/recall/test_recall_invocation_facts.py index 518a44557e..56d5d77c38 100644 --- a/tests/integration/src/sqlbuild/cli/recall/test_recall_invocation_facts.py +++ b/tests/integration/src/sqlbuild/cli/recall/test_recall_invocation_facts.py @@ -84,7 +84,9 @@ def test_given_an_orchestrated_build_when_running_the_documented_queries_then_th test_case: DocumentedQueryTestCase, tmp_path: Path ) -> None: project_dir: Path = write_project(tmp_path / "orders_shop", extra_toml=WARNING_AUDITS) - _ = (project_dir / "models" / "customers.sql").write_text(CUSTOMERS_MODEL, encoding="utf-8") + _ = (project_dir / "sql" / "models" / "customers.sql").write_text( + CUSTOMERS_MODEL, encoding="utf-8" + ) built: subprocess.CompletedProcess[bytes] = run( project_dir, "build", SQLBUILD_INVOCATION_CONTEXT_JSON=ORCHESTRATED_CONTEXT ) diff --git a/tests/integration/src/sqlbuild/cli/recall/test_recall_replacement_sinks.py b/tests/integration/src/sqlbuild/cli/recall/test_recall_replacement_sinks.py index 97748f5ff0..eca938c32e 100644 --- a/tests/integration/src/sqlbuild/cli/recall/test_recall_replacement_sinks.py +++ b/tests/integration/src/sqlbuild/cli/recall/test_recall_replacement_sinks.py @@ -215,7 +215,7 @@ def test_given_a_lifecycle_sink_slower_than_the_budget_when_building_then_nothin ) elapsed: float = time.monotonic() - started - logged: list[str] = (project_dir / "events.log").read_text(encoding="utf-8").splitlines() + logged: list[str] = (project_dir / ".events.log").read_text(encoding="utf-8").splitlines() assert built.returncode == 0, built.stderr assert elapsed < test_case.expected_max_seconds assert logged[-1] == "invocation_completed" diff --git a/tests/integration/src/sqlbuild/cli/recall/test_recall_run_facts.py b/tests/integration/src/sqlbuild/cli/recall/test_recall_run_facts.py index 0cfcd34df3..7b11bc1540 100644 --- a/tests/integration/src/sqlbuild/cli/recall/test_recall_run_facts.py +++ b/tests/integration/src/sqlbuild/cli/recall/test_recall_run_facts.py @@ -74,6 +74,12 @@ def test_given_selectors_when_building_then_the_effective_selection_is_recorded( test_case: RecordedSelectionTestCase, tmp_path: Path ) -> None: project_dir: Path = write_project(tmp_path / "orders_shop") + project_file: Path = project_dir / "sqlbuild_project.toml" + # A selector file at the top level is outside the project layout unless the project lists it. + _ = project_file.write_text( + 'extra_paths = ["nightly.txt"]\n' + project_file.read_text(encoding="utf-8"), + encoding="utf-8", + ) _ = (project_dir / "nightly.txt").write_text(test_case.selector_file, encoding="utf-8") built: subprocess.CompletedProcess[bytes] = run(project_dir, "build", *test_case.args) @@ -148,7 +154,9 @@ def test_given_sigterm_when_a_build_is_stopped_then_it_is_recorded_cancelled_wit test_case: TerminatedCommandTestCase, tmp_path: Path ) -> None: project_dir: Path = write_slow_import_sink(write_project(tmp_path / "orders_shop")) - _ = (project_dir / "models" / "orders.sql").write_text(test_case.orders_model, encoding="utf-8") + _ = (project_dir / "sql" / "models" / "orders.sql").write_text( + test_case.orders_model, encoding="utf-8" + ) terminated: subprocess.CompletedProcess[bytes] = terminated_build( project_dir, @@ -227,7 +235,7 @@ def test_given_a_failed_statement_when_recalled_then_its_sql_is_readable( test_case: FailedStatementSqlTestCase, tmp_path: Path ) -> None: project_dir: Path = write_project(tmp_path / "orders_shop") - _ = (project_dir / "models" / "orders.sql").write_text( + _ = (project_dir / "sql" / "models" / "orders.sql").write_text( f'MODEL (\n description "One row per order",\n materialized table,\n);\n\n' f"{test_case.model_sql}\n", encoding="utf-8", @@ -292,7 +300,7 @@ def test_given_a_failing_audit_when_recalled_then_its_evidence_follows_the_setti test_case: AuditEvidenceTestCase, tmp_path: Path ) -> None: project_dir: Path = write_project(tmp_path / "orders_shop", extra_toml=test_case.recall_toml) - _ = (project_dir / "models" / "customers.sql").write_text( + _ = (project_dir / "sql" / "models" / "customers.sql").write_text( CUSTOMERS_MODEL.replace("severity warn", f"severity {test_case.severity}"), encoding="utf-8", ) @@ -350,7 +358,7 @@ def test_given_cost_attribution_when_a_build_ends_then_the_invocation_records_ho toml.read_text(encoding="utf-8").replace('"duckdb"', '"duckdb_costed"', 1), encoding="utf-8", ) - adapter: Path = project_dir / "adapters" / "warehouse" / "duckdb_costed.py" + adapter: Path = project_dir / "python" / "adapters" / "warehouse" / "duckdb_costed.py" adapter.parent.mkdir(parents=True) _ = adapter.write_text(COSTED_ADAPTER.format(collected=test_case.collected), encoding="utf-8") diff --git a/tests/integration/src/sqlbuild/cli/recall/test_third_party_logs.py b/tests/integration/src/sqlbuild/cli/recall/test_third_party_logs.py index 7aeb3813a8..302d0ecc2b 100644 --- a/tests/integration/src/sqlbuild/cli/recall/test_third_party_logs.py +++ b/tests/integration/src/sqlbuild/cli/recall/test_third_party_logs.py @@ -79,12 +79,12 @@ def test_given_project_and_library_logs_during_build_when_running_then_only_libr test_case: ThirdPartyLogTestCase, tmp_path: Path ) -> None: project_dir: Path = write_project(tmp_path / "orders_shop") - (project_dir / "models" / "orders.sql").write_text(ORDERS_MODEL, encoding="utf-8") - hook_path: Path = project_dir / "hooks" / "python" / "sync.py" + (project_dir / "sql" / "models" / "orders.sql").write_text(ORDERS_MODEL, encoding="utf-8") + hook_path: Path = project_dir / "sql" / "hooks" / "python" / "sync.py" hook_path.parent.mkdir(parents=True) hook_path.write_text(PROJECT_HOOK, encoding="utf-8") library_dir: Path = tmp_path / "installed" - library_dir.mkdir() + library_dir.mkdir(parents=True) (library_dir / "vendor_client.py").write_text(VENDOR_MODULE, encoding="utf-8") built: subprocess.CompletedProcess[bytes] = run( diff --git a/tests/integration/src/sqlbuild/compiler/analysis_session/helpers.py b/tests/integration/src/sqlbuild/compiler/analysis_session/helpers.py index cf1b1d3076..9429bda6d4 100644 --- a/tests/integration/src/sqlbuild/compiler/analysis_session/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/analysis_session/helpers.py @@ -205,19 +205,19 @@ ), } ADAPTER_RULE_MODELS: dict[str, str] = { - f"models/adapter_rules/{name}.sql": ( + f"sql/models/adapter_rules/{name}.sql": ( f'MODEL (\n description "Adapter rule model {name}",\n{header});\n\n{sql}\n' ) for name, (header, sql) in _ADAPTER_RULE_SQL.items() } _CONTRACT_CTE_MODELS: dict[str, str] = { - "models/marts/payments_by_customer.sql": ( + "sql/models/marts/payments_by_customer.sql": ( 'MODEL (\n description "Payments passed through a CTE",\n contract enforced,\n' " columns (customer_id (type INTEGER), region (type VARCHAR)),\n);\n\n" 'WITH base AS (SELECT customer_id, region FROM __source("raw_payments"))\n' "SELECT customer_id, region FROM base\n" ), - "models/marts/payment_totals.sql": ( + "sql/models/marts/payment_totals.sql": ( 'MODEL (\n description "Payment totals aggregated in a CTE",\n contract enforced,\n' " columns (total_amount (type DECIMAL(38, 2)), region (type VARCHAR)),\n);\n\n" "WITH base AS (\n SELECT SUM(amount) AS total_amount, region\n" @@ -254,10 +254,10 @@ def _pivot_files( """A typed pivot every passthrough reads, and the drawn pivot shapes in one dialect's PIVOT.""" return { - "models/marts/status_amounts.sql": typed_pivot, - "models/marts/status_passthrough.sql": _TYPED_PIVOT_PASSTHROUGH, + "sql/models/marts/status_amounts.sql": typed_pivot, + "sql/models/marts/status_passthrough.sql": _TYPED_PIVOT_PASSTHROUGH, **{ - f"models/marts/pivot_{index}.sql": ( + f"sql/models/marts/pivot_{index}.sql": ( _PIVOT_HEADER.format(pivot=pivot, value=value, aggregate=aggregates[aggregate]) + bodies[shape].format(aggregate=aggregates[aggregate]) + "\n" @@ -477,10 +477,10 @@ def pivot_project_files() -> dict[str, str]: return { "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": _SOURCES, - "models/marts/status_amounts.sql": _TYPED_PIVOT, - "models/marts/status_passthrough.sql": _TYPED_PIVOT_PASSTHROUGH, - "models/staging/orders_list.sql": ( + "sql/sources/raw.yml": _SOURCES, + "sql/models/marts/status_amounts.sql": _TYPED_PIVOT, + "sql/models/marts/status_passthrough.sql": _TYPED_PIVOT_PASSTHROUGH, + "sql/models/staging/orders_list.sql": ( 'MODEL (description "Order ids");\n\nSELECT order_id FROM __source("raw_orders")\n' ), } @@ -515,7 +515,7 @@ def generated_analysis_files( named: str = dialect or "" files: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": _SOURCES, + "sql/sources/raw.yml": _SOURCES, **_pivot_models(rng, named), **_CONTRACT_CTE_MODELS, } @@ -528,7 +528,7 @@ def generated_analysis_files( template: _Template = templates[index % len(templates)] header, sql, columns = template(rng, rng.sample(relations, k=2)) name: str = f"orders_model_{index}" - files[f"models/layer_{index % 3}/{name}.sql"] = ( + files[f"sql/models/layer_{index % 3}/{name}.sql"] = ( f'MODEL (\n description "Generated orders model {index}",\n{header});\n\n{sql}\n' ) relations.append((f'__ref("{name}")', columns)) @@ -541,14 +541,14 @@ def shared_analysis_files( """Equal regional models and rollups, missing-column readers and one unshared summary.""" regional: dict[str, str] = { - f"models/staging/orders_{region}.sql": ( + f"sql/models/staging/orders_{region}.sql": ( f'MODEL (description "Orders in {region}");\n\n' 'SELECT order_id, customer_id, amount FROM __source("raw_orders")\n' ) for region in regions } rollups: dict[str, str] = { - f"models/marts/totals_{region}.sql": ( + f"sql/models/marts/totals_{region}.sql": ( f'MODEL (description "Customer totals in {region}");\n\n' "SELECT customer_id, SUM(amount) AS total_amount\n" f'FROM __ref("orders_{region}")\nGROUP BY customer_id\n' @@ -556,7 +556,7 @@ def shared_analysis_files( for region in regions } inexact: dict[str, str] = { - f"models/marts/missing_{region}.sql": ( + f"sql/models/marts/missing_{region}.sql": ( f'MODEL (description "Orders in {region} with an unknown column");\n\n' f'SELECT customer_id, missing_column FROM __ref("orders_{region}")\n' ) @@ -564,11 +564,11 @@ def shared_analysis_files( } return { "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": _SOURCES, + "sql/sources/raw.yml": _SOURCES, **regional, **rollups, **inexact, - "models/marts/orders_summary.sql": ( + "sql/models/marts/orders_summary.sql": ( 'MODEL (description "Order count");\n\n' f'SELECT COUNT(*) AS order_count FROM __ref("orders_{regions[0]}")\n' ), @@ -931,8 +931,8 @@ def write_shared_query_project( _ = (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n', encoding="utf-8" ) - model_dir: Path = project_dir / "models" - model_dir.mkdir() + model_dir: Path = project_dir / "sql" / "models" + model_dir.mkdir(parents=True) for name, sql in {"orders": upstream_sql, "customers": upstream_sql, **models}.items(): _ = (model_dir / f"{name}.sql").write_text(sql, encoding="utf-8") diff --git a/tests/integration/src/sqlbuild/compiler/analysis_session/test_native_model_analysis.py b/tests/integration/src/sqlbuild/compiler/analysis_session/test_native_model_analysis.py index 0d7312db2f..d23ffea4c2 100644 --- a/tests/integration/src/sqlbuild/compiler/analysis_session/test_native_model_analysis.py +++ b/tests/integration/src/sqlbuild/compiler/analysis_session/test_native_model_analysis.py @@ -87,48 +87,48 @@ ) _CYCLIC_PROJECT: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders_cycle"\nadapter = "duckdb"\n', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n columns:\n" " - name: order_id\n type: INTEGER\n" " - name: amount\n type: DOUBLE\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders");\n\nSELECT o.order_id, o.amount, r.refund\n' 'FROM __source("raw_orders") AS o\n' 'LEFT JOIN __ref("returns") AS r ON r.order_id = o.order_id\n' ), - "models/returns.sql": ( + "sql/models/returns.sql": ( 'MODEL (description "Returns");\n\n' 'SELECT order_id, amount * -1 AS refund FROM __ref("orders")\n' ), - "models/order_summary.sql": ( + "sql/models/order_summary.sql": ( 'MODEL (description "Summary");\n\nSELECT * FROM __ref("returns")\n' ), - "models/order_audit.sql": ( + "sql/models/order_audit.sql": ( 'MODEL (description "Audit");\n\n' 'SELECT order_id, missing_column FROM __ref("order_audit")\n' ), } _ORDERS_PROJECT: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders_cycle"\nadapter = "duckdb"\n', - "models/orders.sql": 'MODEL (description "Orders");\n\nSELECT order_id FROM __ref("returns")\n', - "models/returns.sql": 'MODEL (description "Returns");\n\nSELECT order_id FROM __ref("orders")\n', + "sql/models/orders.sql": 'MODEL (description "Orders");\n\nSELECT order_id FROM __ref("returns")\n', + "sql/models/returns.sql": 'MODEL (description "Returns");\n\nSELECT order_id FROM __ref("orders")\n', } _DECLARED_SOURCE_PROJECT: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders_sources"\nadapter = "duckdb"\n', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n columns:\n" " - name: order_id\n type: INTEGER\n" " - name: amount\n type: DOUBLE\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders");\n\n' 'SELECT order_id, amount * -1 AS refund FROM __source("raw_orders")\n' ), } _EXPRESSION_SOURCE_PROJECT: dict[str, str] = _DECLARED_SOURCE_PROJECT | { - "sources/raw.yml": _DECLARED_SOURCE_PROJECT["sources/raw.yml"].replace( + "sql/sources/raw.yml": _DECLARED_SOURCE_PROJECT["sql/sources/raw.yml"].replace( " columns:\n", " expression: >-\n (SELECT 1 AS order_id, CAST(5 AS DOUBLE) AS amount)\n" " columns:\n", @@ -137,11 +137,11 @@ _MIXED_CASE_SOURCE_PROJECT: dict[str, str] = { "sqlbuild_project.toml": 'name = "customers"\nadapter = "duckdb"\n', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Raw customers.\n" " expression: >-\n (SELECT 10 AS customer_id, 'Ada' AS Customer_Name)\n" ), - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (description "Customers");\n\nSELECT * FROM __source("raw_customers")\n' ), } @@ -567,10 +567,10 @@ def test_given_pending_postgres_expression_source_when_analysing_then_star_lists files=_CYCLIC_PROJECT, expected_exit_code=1, expected_compiled=( - "models/order_audit.sql", - "models/order_summary.sql", - "models/orders.sql", - "models/returns.sql", + "sql/models/order_audit.sql", + "sql/models/order_summary.sql", + "sql/models/orders.sql", + "sql/models/returns.sql", ), ) ], diff --git a/tests/integration/src/sqlbuild/compiler/analysis_session/test_native_query_columns.py b/tests/integration/src/sqlbuild/compiler/analysis_session/test_native_query_columns.py index 9485a7ce0a..188e1816f0 100644 --- a/tests/integration/src/sqlbuild/compiler/analysis_session/test_native_query_columns.py +++ b/tests/integration/src/sqlbuild/compiler/analysis_session/test_native_query_columns.py @@ -54,7 +54,7 @@ def test_given_unprojectable_model_when_compiling_then_parsed_tree_columns_are_k project_dir=tmp_path, files={ "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": _HEADER + test_case.query_sql, + "sql/models/orders.sql": _HEADER + test_case.query_sql, }, ) model: CompiledModelView = project.models[0] @@ -83,7 +83,7 @@ def test_given_unprojectable_model_when_compiling_then_parsed_tree_columns_are_k returns="table (id INTEGER, label VARCHAR)", body_sql="SELECT x AS id", expected_error=( - "SQL table function functions/sql/table_fn__orders.sql declares 2 return " + "SQL table function sql/functions/sql/table_fn__orders.sql declares 2 return " "columns but its query produces 1" ), ), @@ -95,7 +95,7 @@ def test_given_table_function_when_compiling_then_body_columns_match_declaration ) -> None: files: dict[str, str] = { "sqlbuild_project.toml": _PROJECT, - "functions/sql/table_fn__orders.sql": ( + "sql/functions/sql/table_fn__orders.sql": ( "FUNCTION (description 'Test function.', arguments (x INTEGER), " f"returns {test_case.returns}); {test_case.body_sql}" ), diff --git a/tests/integration/src/sqlbuild/compiler/compile/helpers.py b/tests/integration/src/sqlbuild/compiler/compile/helpers.py index 79dd68d079..5162004979 100644 --- a/tests/integration/src/sqlbuild/compiler/compile/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compile/helpers.py @@ -50,7 +50,7 @@ "-- @py.m(1)\n", "/* @py.n() */", "$$@py.m()$$", "`@py.m()`", "@@v", "@", " ", "\n", "\u3000", "é", "'", "(", ")", "SELECT ", ", ", "\"q\"", "@py.sur()", ) # fmt: skip -_DIFFERENTIAL_FILE: Path = Path("models/orders_summary.sql") +_DIFFERENTIAL_FILE: Path = Path("sql/models/orders_summary.sql") MACRO_BRIDGE_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": ( @@ -68,7 +68,7 @@ "[scopes]\n" "enforce_placement = false\n" ), - "macros/python/common.py": ( + "sql/macros/python/common.py": ( '"""Shared macros for the bridge demo."""\n\n' "import os\n\n\n" "def cents(column: str) -> str:\n" @@ -109,25 +109,29 @@ ' log.write(column + "\\n")\n' " return column\n" ), - "enums/order_status.sql": ( + "sql/enums/order_status.sql": ( 'ENUM (\n name order_status,\n members (PLACED "placed", SHIPPED "shipped"),\n);\n' ), - "models/north/_sqlbuild/_macros/python/fmt.py": ( + "sql/models/north/_sqlbuild/_macros/python/fmt.py": ( 'def fmt(value: str) -> str:\n """Label a value."""\n return f"\'north:{value}\'"\n' ), - "constants/base_rate.sql": "CONSTANT (name base_rate, value 1);\n", - "models/north/_sqlbuild/_constants/north_rate.sql": "CONSTANT (name north_rate, value 10);\n", - "models/south/_sqlbuild/_constants/south_rate.sql": "CONSTANT (name south_rate, value 20);\n", - "models/shared/customers.sql": ( + "sql/constants/base_rate.sql": "CONSTANT (name base_rate, value 1);\n", + "sql/models/north/_sqlbuild/_constants/north_rate.sql": ( + "CONSTANT (name north_rate, value 10);\n" + ), + "sql/models/south/_sqlbuild/_constants/south_rate.sql": ( + "CONSTANT (name south_rate, value 20);\n" + ), + "sql/models/shared/customers.sql": ( "MODEL (description \"Customers\");\n\nSELECT 1 AS id, 2 AS amount, 'north' AS region\n" ), - "models/shared/orders_source.sql": ( + "sql/models/shared/orders_source.sql": ( 'MODEL (description "Orders source");\n\nSELECT 1 AS id, 3 AS amount\n' ), - "hooks/sql/stamp.sql": ( + "sql/hooks/sql/stamp.sql": ( "HOOK (description \"Stamp a value\");\n\nSELECT @py.cents('2') AS stamped\n" ), - "functions/sql/udf__cents_of.sql": ( + "sql/functions/sql/udf__cents_of.sql": ( "FUNCTION (\n" ' description "Convert a value to cents",\n' " arguments (v INTEGER),\n" @@ -135,10 +139,10 @@ ");\n\n" '@py.cents("v")\n' ), - "audits/generic/positive_cents.sql": ( + "sql/audits/generic/positive_cents.sql": ( 'AUDIT ();\n\nSELECT *\nFROM __ref("@model")\nWHERE @py.cents("amount") < 0\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw__payments\n" " description: Payments\n" @@ -197,19 +201,19 @@ def _region_model(*, description: str, hooks: str, ref_tags: str, label: str) -> ) MACRO_BRIDGE_PROJECT_FILES.update( { - "models/north/orders_north.sql": _region_model( + "sql/models/north/orders_north.sql": _region_model( description="North orders", hooks=_NORTH_HOOKS, ref_tags=_NORTH_REF_TAGS, label='@py.fmt("x")', ), - "models/north/orders_north_copy.sql": _region_model( + "sql/models/north/orders_north_copy.sql": _region_model( description="North orders copy", hooks=_NORTH_HOOKS, ref_tags=_NORTH_REF_TAGS, label='@py.fmt("x")', ), - "models/south/orders_south.sql": _region_model( + "sql/models/south/orders_south.sql": _region_model( description="South orders", hooks="", ref_tags=_SOUTH_REF_TAGS, label="'south'" ), } @@ -295,7 +299,7 @@ def _generated() -> str: def _loaded_macro(*, name: str, function: Callable[..., object]) -> LoadedMacro: - path: Path = Path(f"macros/python/{name}.py") + path: Path = Path(f"sql/macros/python/{name}.py") return LoadedMacro( name=name, file_path=path, relative_path=path, raw_source="", function=function ) @@ -428,13 +432,13 @@ def generated_failing_macro_project(*, rng: random.Random) -> dict[str, str]: models: dict[str, str] = dict( _generated_model(rng=rng, model=model) for model in range(rng.randint(2, 6)) ) - cyclic: dict[str, str] = {True: {"macros/python/cyclic.py": _CYCLIC_MACROS}, False: {}}[ + cyclic: dict[str, str] = {True: {"sql/macros/python/cyclic.py": _CYCLIC_MACROS}, False: {}}[ rng.choice(_CYCLE_CHANCE) ] return { "sqlbuild_project.toml": MACRO_BRIDGE_PROJECT_FILES["sqlbuild_project.toml"], - "macros/python/common.py": _FAILING_MACROS, - "models/marts/_sqlbuild/macros/python/local.py": _LOCAL_MACROS, + "sql/macros/python/common.py": _FAILING_MACROS, + "sql/models/marts/_sqlbuild/macros/python/local.py": _LOCAL_MACROS, **cyclic, **models, } @@ -446,7 +450,7 @@ def _generated_model(*, rng: random.Random, model: int) -> tuple[str, str]: for call in range(rng.randint(1, 3)) ] return ( - f"models/{rng.choice(_MODEL_FOLDERS)}/m{model}.sql", + f"sql/models/{rng.choice(_MODEL_FOLDERS)}/m{model}.sql", f'MODEL (description "Generated {model}");\n\nSELECT {", ".join(calls)}\n', ) diff --git a/tests/integration/src/sqlbuild/compiler/compile/native_model_config/helpers.py b/tests/integration/src/sqlbuild/compiler/compile/native_model_config/helpers.py index 94cd47b87d..33850a5f1a 100644 --- a/tests/integration/src/sqlbuild/compiler/compile/native_model_config/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compile/native_model_config/helpers.py @@ -48,7 +48,7 @@ def validation_outcome(*, values: dict[str, object]) -> object: request: ModelValidationRequest = ModelValidationRequest( model_file=DiscoveredSqlModelFile( file_path=Path("/project/models/marts/orders_daily.sql"), - relative_path=Path("models/marts/orders_daily.sql"), + relative_path=Path("sql/models/marts/orders_daily.sql"), contents="", header_values={}, header_column_locations={}, diff --git a/tests/integration/src/sqlbuild/compiler/compile/test_native_macro_bridge.py b/tests/integration/src/sqlbuild/compiler/compile/test_native_macro_bridge.py index b016a58815..0b61a01cd0 100644 --- a/tests/integration/src/sqlbuild/compiler/compile/test_native_macro_bridge.py +++ b/tests/integration/src/sqlbuild/compiler/compile/test_native_macro_bridge.py @@ -39,7 +39,7 @@ _FAILURE_BASE_FILES: dict[str, str] = { "sqlbuild_project.toml": MACRO_BRIDGE_PROJECT_FILES["sqlbuild_project.toml"], - "macros/python/common.py": ( + "sql/macros/python/common.py": ( "def cents(column: str) -> str:\n" ' """Convert an amount to cents."""\n' ' return f"{column} * 100"\n\n\n' @@ -50,7 +50,7 @@ ' """Return a value that is not SQL."""\n' " return 1\n" ), - "models/a_first.sql": ( + "sql/models/a_first.sql": ( 'MODEL (description "First");\n\nSELECT @py.cents("amount") AS amount_cents\n' ), } @@ -120,7 +120,7 @@ def test_given_repeated_macro_calls_when_rendering_natively_then_each_call_class description="macro raises in a later model", files={ **_FAILURE_BASE_FILES, - "models/b_second.sql": ( + "sql/models/b_second.sql": ( 'MODEL (description "Second");\n\nSELECT @py.explode("amount") AS bogus\n' ), }, @@ -130,7 +130,7 @@ def test_given_repeated_macro_calls_when_rendering_natively_then_each_call_class description="unknown macro after a successful call", files={ **_FAILURE_BASE_FILES, - "models/b_second.sql": ( + "sql/models/b_second.sql": ( 'MODEL (description "Second");\n\n' 'SELECT @py.cents("amount") AS a, @py.nope("amount") AS b\n' ), @@ -141,7 +141,7 @@ def test_given_repeated_macro_calls_when_rendering_natively_then_each_call_class description="macro returns a value that is not SQL", files={ **_FAILURE_BASE_FILES, - "models/b_second.sql": ( + "sql/models/b_second.sql": ( 'MODEL (description "Second");\n\nSELECT @py.number("amount") AS b\n' ), }, @@ -151,7 +151,7 @@ def test_given_repeated_macro_calls_when_rendering_natively_then_each_call_class description="malformed call after a successful call", files={ **_FAILURE_BASE_FILES, - "models/b_second.sql": ( + "sql/models/b_second.sql": ( 'MODEL (description "Second");\n\n' 'SELECT @py.cents("amount") AS a, @py.cents x("amount") AS b\n' ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/header_contract.json b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/header_contract.json index 781f00856b..a1f0b75286 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/header_contract.json +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/header_contract.json @@ -1,11 +1,11 @@ { "diagnostics": [ - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'category_amounts' has no description\", resource_type=, resource_name='category_amounts', column_name=None, path=PosixPath('models/category_amounts.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/category_amounts.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'category_amounts\\', add this to the MODEL header in models/category_amounts.sql:\\n MODEL (\\n description \"What one row of category_amounts represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'order_amounts' has no description\", resource_type=, resource_name='order_amounts', column_name=None, path=PosixPath('models/order_amounts.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/order_amounts.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'order_amounts\\', add this to the MODEL header in models/order_amounts.sql:\\n MODEL (\\n description \"What one row of order_amounts represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'order_statuses' has no description\", resource_type=, resource_name='order_statuses', column_name=None, path=PosixPath('models/order_statuses.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/order_statuses.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'order_statuses\\', add this to the MODEL header in models/order_statuses.sql:\\n MODEL (\\n description \"What one row of order_statuses represents\",\\n ...\\n );', notes=(), affected_rules=())" + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'category_amounts' has no description\", resource_type=, resource_name='category_amounts', column_name=None, path=PosixPath('sql/models/category_amounts.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/category_amounts.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'category_amounts\\', add this to the MODEL header in sql/models/category_amounts.sql:\\n MODEL (\\n description \"What one row of category_amounts represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'order_amounts' has no description\", resource_type=, resource_name='order_amounts', column_name=None, path=PosixPath('sql/models/order_amounts.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/order_amounts.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'order_amounts\\', add this to the MODEL header in sql/models/order_amounts.sql:\\n MODEL (\\n description \"What one row of order_amounts represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'order_statuses' has no description\", resource_type=, resource_name='order_statuses', column_name=None, path=PosixPath('sql/models/order_statuses.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/order_statuses.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'order_statuses\\', add this to the MODEL header in sql/models/order_statuses.sql:\\n MODEL (\\n description \"What one row of order_statuses represents\",\\n ...\\n );', notes=(), affected_rules=())" ], "models": { - "models/category_amounts.sql": { + "sql/models/category_amounts.sql": { "config": "CompileModelConfig(values={}, model_header_keys=('columns', 'dynamic_columns'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -18,11 +18,11 @@ "query_sql": "'PIVOT __ref(\"order_amounts\") ON category USING MAX(amount)'", "references": "(CompileSqlReference(ref_kind=, ref_name='order_amounts', ref_package=None, call_argument_count=None, call_partitioned=False),)", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='category_amounts', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='customer_id', type='INTEGER', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('models/category_amounts.sql'), line=2, column=12, end_line=2, end_column=23), migrate_from=None),), dynamic_columns=(SchemaDynamicColumnFamily(name='category_amounts', pivot_column='category', value_column='amount', aggregate='MAX', type='INTEGER', name_pattern='^[a-z]+$'),), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='category_amounts', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='customer_id', type='INTEGER', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('sql/models/category_amounts.sql'), line=2, column=12, end_line=2, end_column=23), migrate_from=None),), dynamic_columns=(SchemaDynamicColumnFamily(name='category_amounts', pivot_column='category', value_column='amount', aggregate='MAX', type='INTEGER', name_pattern='^[a-z]+$'),), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='PIVOT __ref(\"order_amounts\") ON category USING MAX(amount)', expanded_sql='PIVOT __ref(\"order_amounts\") ON category USING MAX(amount)', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/order_amounts.sql": { + "sql/models/order_amounts.sql": { "config": "CompileModelConfig(values={}, model_header_keys=('columns',), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -35,15 +35,15 @@ "query_sql": "\"SELECT 1 AS customer_id, 'books' AS category, 2 AS amount\"", "references": "()", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='order_amounts', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='customer_id', type='INTEGER', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('models/order_amounts.sql'), line=1, column=17, end_line=1, end_column=28), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='order_amounts', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='customer_id', type='INTEGER', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('sql/models/order_amounts.sql'), line=1, column=17, end_line=1, end_column=28), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql=\"SELECT 1 AS customer_id, 'books' AS category, 2 AS amount\", expanded_sql=\"SELECT 1 AS customer_id, 'books' AS category, 2 AS amount\", passes=((), ()))", "sql_validation_enabled": "True" }, - "models/order_statuses.sql": { + "sql/models/order_statuses.sql": { "config": "CompileModelConfig(values={'contract': 'enforced'}, model_header_keys=('audit_factories', 'columns', 'contract'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "(UsageRecord(consumer=ResourceIdentity(kind=, name='order_statuses'), declaration=DeclarationIdentity(kind=, name='order_status', owner=None), kind=, through=None, enum_member='PLACED'), UsageRecord(consumer=ResourceIdentity(kind=, name='order_statuses'), declaration=DeclarationIdentity(kind=, name='order_status', owner=None), kind=, through=None, enum_member=None))", - "enum_columns": "{'status': EnumDeclaration(name='order_status', members=(EnumMember(name='PLACED', value='PLACED'), EnumMember(name='SHIPPED', value='SHIPPED')), scalar_type='VARCHAR', relative_path=PosixPath('enums/status.sql'), model_name=None)}", + "enum_columns": "{'status': EnumDeclaration(name='order_status', members=(EnumMember(name='PLACED', value='PLACED'), EnumMember(name='SHIPPED', value='SHIPPED')), scalar_type='VARCHAR', relative_path=PosixPath('sql/enums/status.sql'), model_name=None)}", "enum_declarations": "()", "lint_expansion": "CompiledSqlExpansion(authored_sql='SELECT @enum(\"order_status\").PLACED AS status, 3 AS total', expanded_sql=\"SELECT 'PLACED' AS status, 3 AS total\", passes=((), (ExpansionSpan(source_start=7, source_end=35, output_start=7, output_end=15),), ()))", "macro_deps": "()", @@ -52,7 +52,7 @@ "query_sql": "\"SELECT 'PLACED' AS status, 3 AS total\"", "references": "()", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='order_statuses', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='status', type='VARCHAR', nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='accepted_values', arguments={'values': ('PLACED', 'SHIPPED')}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('models/order_statuses.sql'), line=3, column=12, end_line=3, end_column=18), migrate_from=None), SchemaColumn(name='total', type='INTEGER', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('models/order_statuses.sql'), line=3, column=59, end_line=3, end_column=64), migrate_from=None)), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'total > 0'}, name='positive_total', description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", + "schema_entry": "SchemaModelEntry(name='order_statuses', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='status', type='VARCHAR', nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='accepted_values', arguments={'values': ('PLACED', 'SHIPPED')}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('sql/models/order_statuses.sql'), line=3, column=12, end_line=3, end_column=18), migrate_from=None), SchemaColumn(name='total', type='INTEGER', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('sql/models/order_statuses.sql'), line=3, column=59, end_line=3, end_column=64), migrate_from=None)), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'total > 0'}, name='positive_total', description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT @enum(\"order_status\").PLACED AS status, 3 AS total', expanded_sql=\"SELECT 'PLACED' AS status, 3 AS total\", passes=((ExpansionSpan(source_start=7, source_end=35, output_start=7, output_end=15),), ()))", "sql_validation_enabled": "True" } diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/model_schema.json b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/model_schema.json index a3d8b6491a..18508d7a7f 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/model_schema.json +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/model_schema.json @@ -1,13 +1,13 @@ { "diagnostics": [ - "CompilerDiagnostic(phase=, severity=, code='S006', message=\"Schema 'marts_shape' is not visible from 'models/staging/hidden.sql'. It is defined at models/marts/_sqlbuild/schemas/local.sql with inherited scope owned by 'models/marts'\", resource_type=, resource_name='hidden', column_name=None, path=PosixPath('models/staging/hidden.sql'), line=None, column=None, location=None, related_locations=(), help=\"move 'models/marts/_sqlbuild/schemas/local.sql' to a schemas/ role owned by 'models/staging' or one of its parent folders, or to the project-wide schemas/ when consumers span resource trees\", notes=(), affected_rules=())" + "CompilerDiagnostic(phase=, severity=, code='S006', message=\"Schema 'marts_shape' is not visible from 'sql/models/staging/hidden.sql'. It is defined at sql/models/marts/_sqlbuild/schemas/local.sql with inherited scope owned by 'sql/models/marts'\", resource_type=, resource_name='hidden', column_name=None, path=PosixPath('sql/models/staging/hidden.sql'), line=None, column=None, location=None, related_locations=(), help=\"move 'sql/models/marts/_sqlbuild/schemas/local.sql' to a schemas/ role owned by 'sql/models/staging' or one of its parent folders, or to the project-wide sql/schemas/ when consumers span resource trees\", notes=(), affected_rules=())" ], "models": { - "models/orders.sql": { + "sql/models/orders.sql": { "config": "CompileModelConfig(values={'contract': 'enforced'}, model_header_keys=('columns', 'contract', 'model_schema'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "(UsageRecord(consumer=ResourceIdentity(kind=, name='orders'), declaration=DeclarationIdentity(kind=, name='order_status', owner=None), kind=, through=None, enum_member=None), UsageRecord(consumer=ResourceIdentity(kind=, name='orders'), declaration=DeclarationIdentity(kind=, name='order_shape', owner=None), kind=, through=None, enum_member=None))", - "enum_columns": "{'status': EnumDeclaration(name='order_status', members=(EnumMember(name='PLACED', value='PLACED'), EnumMember(name='SHIPPED', value='SHIPPED')), scalar_type='VARCHAR', relative_path=PosixPath('enums/status.sql'), model_name=None)}", + "enum_columns": "{'status': EnumDeclaration(name='order_status', members=(EnumMember(name='PLACED', value='PLACED'), EnumMember(name='SHIPPED', value='SHIPPED')), scalar_type='VARCHAR', relative_path=PosixPath('sql/enums/status.sql'), model_name=None)}", "enum_declarations": "()", "lint_expansion": "CompiledSqlExpansion(authored_sql=\"SELECT 1 AS order_id, 'PLACED' AS status, 'x' AS note\", expanded_sql=\"SELECT 1 AS order_id, 'PLACED' AS status, 'x' AS note\", passes=((), (), ()))", "macro_deps": "()", @@ -16,11 +16,11 @@ "query_sql": "\"SELECT 1 AS order_id, 'PLACED' AS status, 'x' AS note\"", "references": "()", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='orders', model_schema='order_shape', description='Order shape.', type_enforcement=True, meta={}, columns=(SchemaColumn(name='order_id', type='INTEGER', nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('schemas/orders.sql'), line=4, column=12, end_line=4, end_column=20), migrate_from=None), SchemaColumn(name='status', type='VARCHAR', nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='accepted_values', arguments={'values': ('PLACED', 'SHIPPED')}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('schemas/orders.sql'), line=4, column=53, end_line=4, end_column=59), migrate_from=None), SchemaColumn(name='note', type='VARCHAR', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('models/orders.sql'), line=4, column=40, end_line=4, end_column=44), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='orders', model_schema='order_shape', description='Order shape.', type_enforcement=True, meta={}, columns=(SchemaColumn(name='order_id', type='INTEGER', nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/schemas/orders.sql'), line=4, column=12, end_line=4, end_column=20), migrate_from=None), SchemaColumn(name='status', type='VARCHAR', nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='accepted_values', arguments={'values': ('PLACED', 'SHIPPED')}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/schemas/orders.sql'), line=4, column=53, end_line=4, end_column=59), migrate_from=None), SchemaColumn(name='note', type='VARCHAR', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('sql/models/orders.sql'), line=4, column=40, end_line=4, end_column=44), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql=\"SELECT 1 AS order_id, 'PLACED' AS status, 'x' AS note\", expanded_sql=\"SELECT 1 AS order_id, 'PLACED' AS status, 'x' AS note\", passes=((), ()))", "sql_validation_enabled": "True" }, - "models/staging/hidden.sql": { + "sql/models/staging/hidden.sql": { "config": "CompileModelConfig(values={}, model_header_keys=('description', 'model_schema'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "(UsageRecord(consumer=ResourceIdentity(kind=, name='hidden'), declaration=DeclarationIdentity(kind=, name='marts_shape', owner=None), kind=, through=None, enum_member=None),)", @@ -33,7 +33,7 @@ "query_sql": "'SELECT 1 AS order_id'", "references": "()", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='hidden', model_schema='marts_shape', description='Out of reach.', type_enforcement=True, meta={}, columns=(SchemaColumn(name='order_id', type='INTEGER', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('models/marts/_sqlbuild/schemas/local.sql'), line=3, column=12, end_line=3, end_column=20), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='hidden', model_schema='marts_shape', description='Out of reach.', type_enforcement=True, meta={}, columns=(SchemaColumn(name='order_id', type='INTEGER', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('sql/models/marts/_sqlbuild/schemas/local.sql'), line=3, column=12, end_line=3, end_column=20), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT 1 AS order_id', expanded_sql='SELECT 1 AS order_id', passes=((), ()))", "sql_validation_enabled": "True" } diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/opt_out.json b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/opt_out.json index 793b802804..aa891a8cc2 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/opt_out.json +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/opt_out.json @@ -1,14 +1,14 @@ { "diagnostics": [ - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'header_opt_out' has no description\", resource_type=, resource_name='header_opt_out', column_name=None, path=PosixPath('models/header_opt_out.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/header_opt_out.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'header_opt_out\\', add this to the MODEL header in models/header_opt_out.sql:\\n MODEL (\\n description \"What one row of header_opt_out represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'invalid_call' has no description\", resource_type=, resource_name='invalid_call', column_name=None, path=PosixPath('models/invalid_call.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/invalid_call.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'invalid_call\\', add this to the MODEL header in models/invalid_call.sql:\\n MODEL (\\n description \"What one row of invalid_call represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'path_opt_out' has no description\", resource_type=, resource_name='path_opt_out', column_name=None, path=PosixPath('models/legacy/path_opt_out.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/legacy/path_opt_out.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'path_opt_out\\', add this to the MODEL header in models/legacy/path_opt_out.sql:\\n MODEL (\\n description \"What one row of path_opt_out represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'unparsed' has no description\", resource_type=, resource_name='unparsed', column_name=None, path=PosixPath('models/unparsed.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/unparsed.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'unparsed\\', add this to the MODEL header in models/unparsed.sql:\\n MODEL (\\n description \"What one row of unparsed represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P012', message='__ref(order_name) is not a valid __ref() call', resource_type=, resource_name='invalid_call', column_name=None, path=PosixPath('models/invalid_call.sql'), line=2, column=15, location=SourceLocation(path=PosixPath('models/invalid_call.sql'), line=2, column=15, end_line=2, end_column=32), related_locations=(), help='__ref() takes exactly one double-quoted name, with no comments or extra spaces inside the parentheses: __ref(\"order_name\")', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P012', message=\"__table_fn('customer_orders') is not a valid __table_fn() call\", resource_type=, resource_name='invalid_call', column_name=None, path=PosixPath('models/invalid_call.sql'), line=3, column=12, location=SourceLocation(path=PosixPath('models/invalid_call.sql'), line=3, column=12, end_line=3, end_column=41), related_locations=(), help='__table_fn() takes exactly one double-quoted name, with no comments or extra spaces inside the parentheses: __table_fn(\"customer_orders\")(...)', notes=(), affected_rules=())" + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'header_opt_out' has no description\", resource_type=, resource_name='header_opt_out', column_name=None, path=PosixPath('sql/models/header_opt_out.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/header_opt_out.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'header_opt_out\\', add this to the MODEL header in sql/models/header_opt_out.sql:\\n MODEL (\\n description \"What one row of header_opt_out represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'invalid_call' has no description\", resource_type=, resource_name='invalid_call', column_name=None, path=PosixPath('sql/models/invalid_call.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/invalid_call.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'invalid_call\\', add this to the MODEL header in sql/models/invalid_call.sql:\\n MODEL (\\n description \"What one row of invalid_call represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'path_opt_out' has no description\", resource_type=, resource_name='path_opt_out', column_name=None, path=PosixPath('sql/models/legacy/path_opt_out.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/legacy/path_opt_out.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'path_opt_out\\', add this to the MODEL header in sql/models/legacy/path_opt_out.sql:\\n MODEL (\\n description \"What one row of path_opt_out represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'unparsed' has no description\", resource_type=, resource_name='unparsed', column_name=None, path=PosixPath('sql/models/unparsed.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/unparsed.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'unparsed\\', add this to the MODEL header in sql/models/unparsed.sql:\\n MODEL (\\n description \"What one row of unparsed represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P012', message='__ref(order_name) is not a valid __ref() call', resource_type=, resource_name='invalid_call', column_name=None, path=PosixPath('sql/models/invalid_call.sql'), line=2, column=15, location=SourceLocation(path=PosixPath('sql/models/invalid_call.sql'), line=2, column=15, end_line=2, end_column=32), related_locations=(), help='__ref() takes exactly one double-quoted name, with no comments or extra spaces inside the parentheses: __ref(\"order_name\")', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P012', message=\"__table_fn('customer_orders') is not a valid __table_fn() call\", resource_type=, resource_name='invalid_call', column_name=None, path=PosixPath('sql/models/invalid_call.sql'), line=3, column=12, location=SourceLocation(path=PosixPath('sql/models/invalid_call.sql'), line=3, column=12, end_line=3, end_column=41), related_locations=(), help='__table_fn() takes exactly one double-quoted name, with no comments or extra spaces inside the parentheses: __table_fn(\"customer_orders\")(...)', notes=(), affected_rules=())" ], "models": { - "models/header_opt_out.sql": { + "sql/models/header_opt_out.sql": { "config": "CompileModelConfig(values={'sql_analysis': False}, model_header_keys=('sql_analysis',), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -20,12 +20,12 @@ "macro_usages": "()", "query_sql": "'SELECT 1 AS order_id'", "references": "()", - "rejected_sql_analysis_opt_out": "SourceLocation(path=PosixPath('models/header_opt_out.sql'), line=2, column=3, end_line=None, end_column=None)", + "rejected_sql_analysis_opt_out": "SourceLocation(path=PosixPath('sql/models/header_opt_out.sql'), line=2, column=3, end_line=None, end_column=None)", "schema_entry": "None", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT 1 AS order_id', expanded_sql='SELECT 1 AS order_id', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/invalid_call.sql": { + "sql/models/invalid_call.sql": { "config": "CompileModelConfig(values={}, model_header_keys=(), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -42,7 +42,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql=\"SELECT * FROM __ref(order_name)\\nCROSS JOIN __table_fn('customer_orders')\", expanded_sql=\"SELECT * FROM __ref(order_name)\\nCROSS JOIN __table_fn('customer_orders')\", passes=((), ()))", "sql_validation_enabled": "False" }, - "models/legacy/path_opt_out.sql": { + "sql/models/legacy/path_opt_out.sql": { "config": "CompileModelConfig(values={'sql_analysis': False}, model_header_keys=(), matched_path_default='legacy', logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -59,7 +59,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT 1 AS order_id', expanded_sql='SELECT 1 AS order_id', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/unparsed.sql": { + "sql/models/unparsed.sql": { "config": "CompileModelConfig(values={'sql_analysis': False}, model_header_keys=('sql_analysis',), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/parity.json b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/parity.json index d847394db3..9e44f97526 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/parity.json +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/parity.json @@ -1,13 +1,13 @@ { "diagnostics": [ - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'described_columns' has no description\", resource_type=, resource_name='described_columns', column_name=None, path=PosixPath('models/marts/described_columns.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/marts/described_columns.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'described_columns\\', add this to the MODEL header in models/marts/described_columns.sql:\\n MODEL (\\n description \"What one row of described_columns represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'migrated' has no description\", resource_type=, resource_name='migrated', column_name=None, path=PosixPath('models/marts/migrated.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/marts/migrated.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'migrated\\', add this to the MODEL header in models/marts/migrated.sql:\\n MODEL (\\n description \"What one row of migrated represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'opted_out' has no description\", resource_type=, resource_name='opted_out', column_name=None, path=PosixPath('models/marts/opted_out.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/marts/opted_out.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'opted_out\\', add this to the MODEL header in models/marts/opted_out.sql:\\n MODEL (\\n description \"What one row of opted_out represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'statuses' has no description\", resource_type=, resource_name='statuses', column_name=None, path=PosixPath('models/marts/statuses.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/marts/statuses.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'statuses\\', add this to the MODEL header in models/marts/statuses.sql:\\n MODEL (\\n description \"What one row of statuses represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'stg_payments' has no description\", resource_type=, resource_name='stg_payments', column_name=None, path=PosixPath('models/staging/stg_payments.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/staging/stg_payments.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'stg_payments\\', add this to the MODEL header in models/staging/stg_payments.sql:\\n MODEL (\\n description \"What one row of stg_payments represents\",\\n ...\\n );', notes=(), affected_rules=())" + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'described_columns' has no description\", resource_type=, resource_name='described_columns', column_name=None, path=PosixPath('sql/models/marts/described_columns.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/marts/described_columns.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'described_columns\\', add this to the MODEL header in sql/models/marts/described_columns.sql:\\n MODEL (\\n description \"What one row of described_columns represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'migrated' has no description\", resource_type=, resource_name='migrated', column_name=None, path=PosixPath('sql/models/marts/migrated.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/marts/migrated.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'migrated\\', add this to the MODEL header in sql/models/marts/migrated.sql:\\n MODEL (\\n description \"What one row of migrated represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'opted_out' has no description\", resource_type=, resource_name='opted_out', column_name=None, path=PosixPath('sql/models/marts/opted_out.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/marts/opted_out.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'opted_out\\', add this to the MODEL header in sql/models/marts/opted_out.sql:\\n MODEL (\\n description \"What one row of opted_out represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'statuses' has no description\", resource_type=, resource_name='statuses', column_name=None, path=PosixPath('sql/models/marts/statuses.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/marts/statuses.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'statuses\\', add this to the MODEL header in sql/models/marts/statuses.sql:\\n MODEL (\\n description \"What one row of statuses represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'stg_payments' has no description\", resource_type=, resource_name='stg_payments', column_name=None, path=PosixPath('sql/models/staging/stg_payments.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/staging/stg_payments.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'stg_payments\\', add this to the MODEL header in sql/models/staging/stg_payments.sql:\\n MODEL (\\n description \"What one row of stg_payments represents\",\\n ...\\n );', notes=(), affected_rules=())" ], "models": { - "models/marts/described_columns.sql": { + "sql/models/marts/described_columns.sql": { "config": "CompileModelConfig(values={'materialized': 'table'}, model_header_keys=('columns',), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -20,11 +20,11 @@ "query_sql": "\"SELECT 1 AS order_id, 'x' AS note\"", "references": "()", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='described_columns', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='order_id', type='INTEGER', nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('models/marts/described_columns.sql'), line=2, column=12, end_line=2, end_column=20), migrate_from=None), SchemaColumn(name='note', type=None, nullable=None, description='Free text.', meta={}, audits=(), location=SourceLocation(path=PosixPath('models/marts/described_columns.sql'), line=2, column=80, end_line=2, end_column=84), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='described_columns', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='order_id', type='INTEGER', nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('sql/models/marts/described_columns.sql'), line=2, column=12, end_line=2, end_column=20), migrate_from=None), SchemaColumn(name='note', type=None, nullable=None, description='Free text.', meta={}, audits=(), location=SourceLocation(path=PosixPath('sql/models/marts/described_columns.sql'), line=2, column=80, end_line=2, end_column=84), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql=\"SELECT 1 AS order_id, 'x' AS note\", expanded_sql=\"SELECT 1 AS order_id, 'x' AS note\", passes=((), ()))", "sql_validation_enabled": "True" }, - "models/marts/hooked.sql": { + "sql/models/marts/hooked.sql": { "config": "CompileModelConfig(values={'materialized': 'table', 'pre_hooks': [SqlHookEntry(statement='SELECT eu AS region', name=None, relative_path=None, definition_sql=None, kwargs=None, description=None, reads=())], 'post_hooks': [SqlHookEntry(statement='SELECT 2 * 100 AS cents', name=None, relative_path=None, definition_sql=None, kwargs=None, description=None, reads=())]}, model_header_keys=('description', 'post_hooks', 'pre_hooks'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "(UsageRecord(consumer=ResourceIdentity(kind=, name='hooked'), declaration=DeclarationIdentity(kind=, name='cents', owner=None), kind=, through=None, enum_member=None),)", @@ -41,7 +41,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT 1 AS order_id', expanded_sql='SELECT 1 AS order_id', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/marts/migrated.sql": { + "sql/models/marts/migrated.sql": { "config": "CompileModelConfig(values={'materialized': 'incremental', 'incremental_strategy': 'append'}, model_header_keys=('columns', 'incremental_strategy', 'materialized'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -54,11 +54,11 @@ "query_sql": "'SELECT 1 AS order_id'", "references": "()", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='migrated', model_schema=None, description=None, type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_id', type=None, nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('models/marts/migrated.sql'), line=1, column=72, end_line=1, end_column=80), migrate_from='id'),), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='migrated', model_schema=None, description=None, type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_id', type=None, nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('sql/models/marts/migrated.sql'), line=1, column=72, end_line=1, end_column=80), migrate_from='id'),), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT 1 AS order_id', expanded_sql='SELECT 1 AS order_id', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/marts/opted_out.sql": { + "sql/models/marts/opted_out.sql": { "config": "CompileModelConfig(values={'materialized': 'table', 'sql_analysis': False}, model_header_keys=('sql_analysis',), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -75,7 +75,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT 1 AS order_id', expanded_sql='SELECT 1 AS order_id', passes=((), ()))", "sql_validation_enabled": "False" }, - "models/marts/orders.sql": { + "sql/models/marts/orders.sql": { "config": "CompileModelConfig(values={'materialized': 'incremental', 'incremental_strategy': 'append', 'cursor': 'order_id', 'cursor_type': 'integer'}, model_header_keys=('cursor', 'cursor_type', 'description', 'incremental_strategy', 'materialized'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -92,7 +92,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT order_id FROM __ref(\"stg_orders\")\\nWHERE order_id >= __cursor_start()', expanded_sql='SELECT order_id FROM __ref(\"stg_orders\")\\nWHERE order_id >= __cursor_start()', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/marts/priced.sql": { + "sql/models/marts/priced.sql": { "config": "CompileModelConfig(values={'materialized': 'table'}, model_header_keys=('columns',), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -109,7 +109,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT @py.cents(\\'3\\') AS cents, order_id FROM __ref(\"stg_orders\")', expanded_sql='SELECT 3 * 100 AS cents, order_id FROM __ref(\"stg_orders\")', passes=((), (ExpansionSpan(source_start=7, source_end=21, output_start=7, output_end=14),)))", "sql_validation_enabled": "True" }, - "models/marts/statuses.sql": { + "sql/models/marts/statuses.sql": { "config": "CompileModelConfig(values={'materialized': 'table'}, model_header_keys=('columns',), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "(UsageRecord(consumer=ResourceIdentity(kind=, name='statuses'), declaration=DeclarationIdentity(kind=, name='order_status', owner=None), kind=, through=None, enum_member='PLACED'), UsageRecord(consumer=ResourceIdentity(kind=, name='statuses'), declaration=DeclarationIdentity(kind=, name='order_cap', owner=None), kind=, through=None, enum_member=None), UsageRecord(consumer=ResourceIdentity(kind=, name='statuses'), declaration=DeclarationIdentity(kind=, name='held_codes', owner=None), kind=, through=None, enum_member=None))", @@ -122,11 +122,11 @@ "query_sql": "\"SELECT 'PLACED' AS status, 3 AS cap\\nWHERE 30 NOT IN (30, 31)\"", "references": "()", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='statuses', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='status', type='VARCHAR', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('models/marts/statuses.sql'), line=1, column=17, end_line=1, end_column=23), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='statuses', model_schema=None, description=None, type_enforcement=True, meta={}, columns=(SchemaColumn(name='status', type='VARCHAR', nullable=None, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('sql/models/marts/statuses.sql'), line=1, column=17, end_line=1, end_column=23), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT @enum(\"order_status\").PLACED AS status, @const(\"order_cap\") AS cap\\nWHERE 30 NOT IN @const(\"held_codes\")', expanded_sql=\"SELECT 'PLACED' AS status, 3 AS cap\\nWHERE 30 NOT IN (30, 31)\", passes=((ExpansionSpan(source_start=7, source_end=35, output_start=7, output_end=15), ExpansionSpan(source_start=47, source_end=66, output_start=27, output_end=28), ExpansionSpan(source_start=90, source_end=110, output_start=52, output_end=60)), ()))", "sql_validation_enabled": "True" }, - "models/staging/stg_orders.sql": { + "sql/models/staging/stg_orders.sql": { "config": "CompileModelConfig(values={'materialized': 'view', 'tags': ['staged', 'daily']}, model_header_keys=('description', 'tags'), matched_path_default='staging', logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -143,7 +143,7 @@ "sql_expansion": "None", "sql_validation_enabled": "True" }, - "models/staging/stg_payments.sql": { + "sql/models/staging/stg_payments.sql": { "config": "CompileModelConfig(values={'materialized': 'view', 'tags': ['staged', 'payments']}, model_header_keys=('tags',), matched_path_default='staging', logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/python_hooks.json b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/python_hooks.json index 93c2e47e1e..aeb8fb840e 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/python_hooks.json +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/python_hooks.json @@ -1,12 +1,12 @@ { "diagnostics": [ - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'summary' has no description\", resource_type=, resource_name='summary', column_name=None, path=PosixPath('models/marts/summary.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/marts/summary.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'summary\\', add this to the MODEL header in models/marts/summary.sql:\\n MODEL (\\n description \"What one row of summary represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'orders' has no description\", resource_type=, resource_name='orders', column_name=None, path=PosixPath('models/orders.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/orders.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'orders\\', add this to the MODEL header in models/orders.sql:\\n MODEL (\\n description \"What one row of orders represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'hidden' has no description\", resource_type=, resource_name='hidden', column_name=None, path=PosixPath('models/staging/hidden.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/staging/hidden.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'hidden\\', add this to the MODEL header in models/staging/hidden.sql:\\n MODEL (\\n description \"What one row of hidden represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='S006', message=\"Python hook 'refresh' is not visible from 'models/staging/hidden.sql'. It is defined at models/marts/_sqlbuild/hooks/python/local.py with inherited scope owned by 'models/marts'\", resource_type=, resource_name='hidden', column_name=None, path=PosixPath('models/staging/hidden.sql'), line=None, column=None, location=None, related_locations=(), help=\"move 'models/marts/_sqlbuild/hooks/python/local.py' to a hooks/python/ role owned by 'models/staging' or one of its parent folders, or to the project-wide hooks/python/ when consumers span resource trees\", notes=(), affected_rules=())" + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'summary' has no description\", resource_type=, resource_name='summary', column_name=None, path=PosixPath('sql/models/marts/summary.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/marts/summary.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'summary\\', add this to the MODEL header in sql/models/marts/summary.sql:\\n MODEL (\\n description \"What one row of summary represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'orders' has no description\", resource_type=, resource_name='orders', column_name=None, path=PosixPath('sql/models/orders.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/orders.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'orders\\', add this to the MODEL header in sql/models/orders.sql:\\n MODEL (\\n description \"What one row of orders represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'hidden' has no description\", resource_type=, resource_name='hidden', column_name=None, path=PosixPath('sql/models/staging/hidden.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/staging/hidden.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'hidden\\', add this to the MODEL header in sql/models/staging/hidden.sql:\\n MODEL (\\n description \"What one row of hidden represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='S006', message=\"Python hook 'refresh' is not visible from 'sql/models/staging/hidden.sql'. It is defined at sql/models/marts/_sqlbuild/hooks/python/local.py with inherited scope owned by 'sql/models/marts'\", resource_type=, resource_name='hidden', column_name=None, path=PosixPath('sql/models/staging/hidden.sql'), line=None, column=None, location=None, related_locations=(), help=\"move 'sql/models/marts/_sqlbuild/hooks/python/local.py' to a hooks/python/ role owned by 'sql/models/staging' or one of its parent folders, or to the project-wide sql/hooks/python/ when consumers span resource trees\", notes=(), affected_rules=())" ], "models": { - "models/marts/summary.sql": { + "sql/models/marts/summary.sql": { "config": "CompileModelConfig(values={'post_hooks': [PythonHookEntry(name='refresh', kwargs={}), PythonHookEntry(name='flexible', kwargs={})]}, model_header_keys=('post_hooks',), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "(UsageRecord(consumer=ResourceIdentity(kind=, name='summary'), declaration=DeclarationIdentity(kind=, name='refresh', owner=None), kind=, through=None, enum_member=None), UsageRecord(consumer=ResourceIdentity(kind=, name='summary'), declaration=DeclarationIdentity(kind=, name='flexible', owner=None), kind=, through=None, enum_member=None))", @@ -23,7 +23,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT 1 AS order_id', expanded_sql='SELECT 1 AS order_id', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/orders.sql": { + "sql/models/orders.sql": { "config": "CompileModelConfig(values={'pre_hooks': [PythonHookEntry(name='notify', kwargs={'channel': 'ops'})], 'post_hooks': [PythonHookEntry(name='flexible', kwargs={'any': 1}), PythonHookEntry(name='notify', kwargs={'channel': 'c', 'level': 'x'})]}, model_header_keys=('post_hooks', 'pre_hooks'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "(UsageRecord(consumer=ResourceIdentity(kind=, name='orders'), declaration=DeclarationIdentity(kind=, name='flexible', owner=None), kind=, through=None, enum_member=None), UsageRecord(consumer=ResourceIdentity(kind=, name='orders'), declaration=DeclarationIdentity(kind=, name='notify', owner=None), kind=, through=None, enum_member=None))", @@ -40,7 +40,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT 1 AS order_id', expanded_sql='SELECT 1 AS order_id', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/staging/hidden.sql": { + "sql/models/staging/hidden.sql": { "config": "CompileModelConfig(values={'post_hooks': [PythonHookEntry(name='refresh', kwargs={})]}, model_header_keys=('post_hooks',), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "(UsageRecord(consumer=ResourceIdentity(kind=, name='hidden'), declaration=DeclarationIdentity(kind=, name='refresh', owner=None), kind=, through=None, enum_member=None),)", diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/sql_hooks.json b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/sql_hooks.json index 6a2315741c..f966435492 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/sql_hooks.json +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/sql_hooks.json @@ -1,11 +1,11 @@ { "diagnostics": [ - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'loaded' has no description\", resource_type=, resource_name='loaded', column_name=None, path=PosixPath('models/marts/loaded.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/marts/loaded.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'loaded\\', add this to the MODEL header in models/marts/loaded.sql:\\n MODEL (\\n description \"What one row of loaded represents\",\\n ...\\n );', notes=(), affected_rules=())", - "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'stg_orders' has no description\", resource_type=, resource_name='stg_orders', column_name=None, path=PosixPath('models/staging/stg_orders.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('models/staging/stg_orders.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'stg_orders\\', add this to the MODEL header in models/staging/stg_orders.sql:\\n MODEL (\\n description \"What one row of stg_orders represents\",\\n ...\\n );', notes=(), affected_rules=())" + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'loaded' has no description\", resource_type=, resource_name='loaded', column_name=None, path=PosixPath('sql/models/marts/loaded.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/marts/loaded.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'loaded\\', add this to the MODEL header in sql/models/marts/loaded.sql:\\n MODEL (\\n description \"What one row of loaded represents\",\\n ...\\n );', notes=(), affected_rules=())", + "CompilerDiagnostic(phase=, severity=, code='P010', message=\"model 'stg_orders' has no description\", resource_type=, resource_name='stg_orders', column_name=None, path=PosixPath('sql/models/staging/stg_orders.sql'), line=1, column=1, location=SourceLocation(path=PosixPath('sql/models/staging/stg_orders.sql'), line=1, column=1, end_line=None, end_column=None), related_locations=(), help='to describe model \\'stg_orders\\', add this to the MODEL header in sql/models/staging/stg_orders.sql:\\n MODEL (\\n description \"What one row of stg_orders represents\",\\n ...\\n );', notes=(), affected_rules=())" ], "models": { - "models/marts/loaded.sql": { - "config": "CompileModelConfig(values={'schema': 'analytics', 'pre_hooks': [SqlHookEntry(statement=\"INSERT INTO audit.read_grants SELECT 'analytics.loaded', grantee\\nFROM unnest(['reader', 'writer']) AS granted(grantee)\", name='grant_read', relative_path=PosixPath('hooks/sql/grant_read.sql'), definition_sql=\"INSERT INTO audit.read_grants SELECT '@@CTX:destination.qualified', grantee\\nFROM unnest([@'role']) AS granted(grantee)\", kwargs={'role': ['reader', 'writer']}, description='Grant read access.', reads=())], 'post_hooks': [SqlHookEntry(statement='INSERT INTO audit.loads SELECT \\'PLACED\\', 3, 5 * 100, \\'eu\\' FROM __ref(\"stg_orders\")', name='log_load', relative_path=PosixPath('hooks/sql/log_load.sql'), definition_sql='INSERT INTO @target SELECT @enum(\"order_status\").PLACED, @const(\"order_cap\"), @py.cents(@amount), \\'@@region\\' FROM __ref(\"stg_orders\")', kwargs={'target': 'audit.loads', 'amount': 5}, description='Log a load.', reads=(SqlResourceRef(kind=, name='stg_orders'),)), SqlHookEntry(statement='SELECT 3 FROM __ref(\"stg_orders\")', name=None, relative_path=None, definition_sql=None, kwargs=None, description=None, reads=(SqlResourceRef(kind=, name='stg_orders'),))]}, model_header_keys=('post_hooks', 'pre_hooks', 'schema'), matched_path_default=None, logical_schema='analytics', layer_schema='analytics', logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", + "sql/models/marts/loaded.sql": { + "config": "CompileModelConfig(values={'schema': 'analytics', 'pre_hooks': [SqlHookEntry(statement=\"INSERT INTO audit.read_grants SELECT 'analytics.loaded', grantee\\nFROM unnest(['reader', 'writer']) AS granted(grantee)\", name='grant_read', relative_path=PosixPath('sql/hooks/sql/grant_read.sql'), definition_sql=\"INSERT INTO audit.read_grants SELECT '@@CTX:destination.qualified', grantee\\nFROM unnest([@'role']) AS granted(grantee)\", kwargs={'role': ['reader', 'writer']}, description='Grant read access.', reads=())], 'post_hooks': [SqlHookEntry(statement='INSERT INTO audit.loads SELECT \\'PLACED\\', 3, 5 * 100, \\'eu\\' FROM __ref(\"stg_orders\")', name='log_load', relative_path=PosixPath('sql/hooks/sql/log_load.sql'), definition_sql='INSERT INTO @target SELECT @enum(\"order_status\").PLACED, @const(\"order_cap\"), @py.cents(@amount), \\'@@region\\' FROM __ref(\"stg_orders\")', kwargs={'target': 'audit.loads', 'amount': 5}, description='Log a load.', reads=(SqlResourceRef(kind=, name='stg_orders'),)), SqlHookEntry(statement='SELECT 3 FROM __ref(\"stg_orders\")', name=None, relative_path=None, definition_sql=None, kwargs=None, description=None, reads=(SqlResourceRef(kind=, name='stg_orders'),))]}, model_header_keys=('post_hooks', 'pre_hooks', 'schema'), matched_path_default=None, logical_schema='analytics', layer_schema='analytics', logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "(UsageRecord(consumer=ResourceIdentity(kind=, name='loaded'), declaration=DeclarationIdentity(kind=, name='grant_read', owner=None), kind=, through=None, enum_member=None), UsageRecord(consumer=ResourceIdentity(kind=, name='loaded'), declaration=DeclarationIdentity(kind=, name='log_load', owner=None), kind=, through=None, enum_member=None), UsageRecord(consumer=DeclarationIdentity(kind=, name='log_load', owner=None), declaration=DeclarationIdentity(kind=, name='order_status', owner=None), kind=, through=None, enum_member='PLACED'), UsageRecord(consumer=DeclarationIdentity(kind=, name='log_load', owner=None), declaration=DeclarationIdentity(kind=, name='order_cap', owner=None), kind=, through=None, enum_member=None), UsageRecord(consumer=DeclarationIdentity(kind=, name='log_load', owner=None), declaration=DeclarationIdentity(kind=, name='cents', owner=None), kind=, through=None, enum_member=None), UsageRecord(consumer=ResourceIdentity(kind=, name='loaded'), declaration=DeclarationIdentity(kind=, name='order_cap', owner=None), kind=, through=None, enum_member=None))", "enum_columns": "{}", @@ -21,7 +21,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT order_id FROM __ref(\"stg_orders\")', expanded_sql='SELECT order_id FROM __ref(\"stg_orders\")', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/staging/stg_orders.sql": { + "sql/models/staging/stg_orders.sql": { "config": "CompileModelConfig(values={}, model_header_keys=(), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/waffle_shop.json b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/waffle_shop.json index be6dcf27d9..64a6ad71c0 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/expected/waffle_shop.json +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/expected/waffle_shop.json @@ -1,7 +1,7 @@ { "diagnostics": [], "models": { - "models/intermediate/customer_status_snapshot.sql": { + "sql/models/intermediate/customer_status_snapshot.sql": { "config": "CompileModelConfig(values={'materialized': 'incremental', 'incremental_strategy': 'merge', 'unique_key': ['customer_id'], 'cursor': 'last_ordered_at', 'cursor_type': 'timestamp', 'cursor_grain': 'second', 'cursor_inputs': {'fact_orders': 'ordered_at'}, 'replay_on_change': 'full', 'on_schema_change': 'sync_all_columns', 'tags': ['intermediate', 'acceptance']}, model_header_keys=('columns', 'cursor', 'cursor_grain', 'cursor_inputs', 'cursor_type', 'description', 'incremental_strategy', 'materialized', 'on_schema_change', 'replay_on_change', 'tags', 'unique_key'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -14,11 +14,11 @@ "query_sql": "'SELECT\\n customer_id,\\n MAX(ordered_at) AS last_ordered_at,\\n MAX(order_status) AS latest_order_status,\\n COUNT(*) AS total_orders,\\n SUM(line_total_cents) AS total_revenue_cents\\nFROM __ref(\"fact_orders\")\\nGROUP BY customer_id'", "references": "(CompileSqlReference(ref_kind=, ref_name='fact_orders', ref_package=None, call_argument_count=None, call_partitioned=False),)", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='customer_status_snapshot', model_schema=None, description='Merge-based customer snapshot with timestamp cursor and explicit backfill policies.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='customer_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('models/intermediate/customer_status_snapshot.sql'), line=16, column=5, end_line=16, end_column=16), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='customer_status_snapshot', model_schema=None, description='Merge-based customer snapshot with timestamp cursor and explicit backfill policies.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='customer_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('sql/models/intermediate/customer_status_snapshot.sql'), line=16, column=5, end_line=16, end_column=16), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n customer_id,\\n MAX(ordered_at) AS last_ordered_at,\\n MAX(order_status) AS latest_order_status,\\n COUNT(*) AS total_orders,\\n SUM(line_total_cents) AS total_revenue_cents\\nFROM __ref(\"fact_orders\")\\nGROUP BY customer_id', expanded_sql='SELECT\\n customer_id,\\n MAX(ordered_at) AS last_ordered_at,\\n MAX(order_status) AS latest_order_status,\\n COUNT(*) AS total_orders,\\n SUM(line_total_cents) AS total_revenue_cents\\nFROM __ref(\"fact_orders\")\\nGROUP BY customer_id', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/intermediate/order_status_index.sql": { + "sql/models/intermediate/order_status_index.sql": { "config": "CompileModelConfig(values={'materialized': 'incremental', 'incremental_strategy': 'delete_insert', 'cursor': 'order_id', 'cursor_type': 'integer', 'on_schema_change': 'append_new_columns', 'replay_on_change': 'bounded-7d', 'tags': ['intermediate', 'acceptance']}, model_header_keys=('columns', 'cursor', 'cursor_type', 'description', 'incremental_strategy', 'materialized', 'on_schema_change', 'replay_on_change', 'tags'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -31,11 +31,11 @@ "query_sql": "'SELECT\\n order_id,\\n customer_id,\\n order_status,\\n ordered_at,\\n line_total_cents\\nFROM __ref(\"fact_orders\")'", "references": "(CompileSqlReference(ref_kind=, ref_name='fact_orders', ref_package=None, call_argument_count=None, call_partitioned=False),)", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='order_status_index', model_schema=None, description='Integer-cursor incremental projection over fact orders.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('models/intermediate/order_status_index.sql'), line=11, column=5, end_line=11, end_column=13), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='order_status_index', model_schema=None, description='Integer-cursor incremental projection over fact orders.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('sql/models/intermediate/order_status_index.sql'), line=11, column=5, end_line=11, end_column=13), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n order_id,\\n customer_id,\\n order_status,\\n ordered_at,\\n line_total_cents\\nFROM __ref(\"fact_orders\")', expanded_sql='SELECT\\n order_id,\\n customer_id,\\n order_status,\\n ordered_at,\\n line_total_cents\\nFROM __ref(\"fact_orders\")', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/marts/daily_activity_rollup.sql": { + "sql/models/marts/daily_activity_rollup.sql": { "config": "CompileModelConfig(values={'materialized': 'incremental', 'incremental_strategy': 'delete_insert', 'cursor': 'activity_day', 'cursor_type': 'timestamp', 'cursor_grain': 'day', 'microbatch_strategy': 'watermark', 'cursor_watermark_mode': 'all', 'cursor_inputs': {'hourly_order_activity': {'column': 'activity_hour', 'roles': ['filter', 'watermark']}}, 'incremental_mode': 'microbatch', 'batch_size': '2d', 'replay_on_change': 'bounded-14d', 'tags': ['marts', 'acceptance']}, model_header_keys=('audits', 'batch_size', 'columns', 'cursor', 'cursor_grain', 'cursor_inputs', 'cursor_type', 'cursor_watermark_mode', 'description', 'incremental_mode', 'incremental_strategy', 'materialized', 'microbatch_strategy', 'replay_on_change', 'tags'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -48,11 +48,11 @@ "query_sql": "'SELECT\\n DATE_TRUNC(\\'day\\', activity_hour) AS activity_day,\\n SUM(orders_placed) AS orders_placed,\\n SUM(waffles_ordered) AS waffles_ordered,\\n SUM(revenue_cents) AS revenue_cents\\nFROM __ref(\"hourly_order_activity\")\\nGROUP BY DATE_TRUNC(\\'day\\', activity_hour)'", "references": "(CompileSqlReference(ref_kind=, ref_name='hourly_order_activity', ref_package=None, call_argument_count=None, call_partitioned=False),)", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='daily_activity_rollup', model_schema=None, description='Downstream daily microbatch rollup with a wider batch size than its hourly upstream.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='activity_day', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('models/marts/daily_activity_rollup.sql'), line=18, column=5, end_line=18, end_column=17), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'orders_placed >= 0'}, name='daily_orders_placed_is_non_negative', description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", + "schema_entry": "SchemaModelEntry(name='daily_activity_rollup', model_schema=None, description='Downstream daily microbatch rollup with a wider batch size than its hourly upstream.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='activity_day', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/models/marts/daily_activity_rollup.sql'), line=18, column=5, end_line=18, end_column=17), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'orders_placed >= 0'}, name='daily_orders_placed_is_non_negative', description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n @py.timestamp_trunc(\\'day\\', \\'activity_hour\\') AS activity_day,\\n SUM(orders_placed) AS orders_placed,\\n SUM(waffles_ordered) AS waffles_ordered,\\n SUM(revenue_cents) AS revenue_cents\\nFROM __ref(\"hourly_order_activity\")\\nGROUP BY @py.timestamp_trunc(\\'day\\', \\'activity_hour\\')', expanded_sql='SELECT\\n DATE_TRUNC(\\'day\\', activity_hour) AS activity_day,\\n SUM(orders_placed) AS orders_placed,\\n SUM(waffles_ordered) AS waffles_ordered,\\n SUM(revenue_cents) AS revenue_cents\\nFROM __ref(\"hourly_order_activity\")\\nGROUP BY DATE_TRUNC(\\'day\\', activity_hour)', passes=((), (ExpansionSpan(source_start=9, source_end=52, output_start=9, output_end=41), ExpansionSpan(source_start=235, source_end=278, output_start=224, output_end=256))))", "sql_validation_enabled": "True" }, - "models/marts/daily_order_partitioned.sql": { + "sql/models/marts/daily_order_partitioned.sql": { "config": "CompileModelConfig(values={'materialized': 'partition_tracked', 'tags': ['marts'], 'placeholders': {'partition_start': \"'2026-04-01'\", 'partition_end': \"'2026-04-05'\"}, 'config': {'tracking_table': 'partition_state', 'partition_column': 'order_date', 'date_range_start': '2026-04-01', 'date_range_end': '2026-04-05'}}, model_header_keys=('audits', 'columns', 'config', 'description', 'materialized', 'placeholders', 'tags'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -65,11 +65,11 @@ "query_sql": "'SELECT\\n CAST(o.ordered_at AS DATE) AS order_date,\\n COUNT(DISTINCT o.order_id) AS order_count,\\n SUM(o.quantity) AS waffles_ordered,\\n COUNT(DISTINCT o.customer_id) AS unique_customers\\nFROM __ref(\"stg_orders\") o\\nWHERE CAST(o.ordered_at AS DATE) >= CAST(@@@partition_start AS DATE)\\n AND CAST(o.ordered_at AS DATE) < CAST(@@@partition_end AS DATE)\\nGROUP BY CAST(o.ordered_at AS DATE)'", "references": "(CompileSqlReference(ref_kind=, ref_name='stg_orders', ref_package=None, call_argument_count=None, call_partitioned=False),)", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='daily_order_partitioned', model_schema=None, description='Partition-tracked daily order summary using custom materialization.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_date', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('models/marts/daily_order_partitioned.sql'), line=16, column=5, end_line=16, end_column=15), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'waffles_ordered > 0'}, name='waffles_ordered_is_positive', description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", + "schema_entry": "SchemaModelEntry(name='daily_order_partitioned', model_schema=None, description='Partition-tracked daily order summary using custom materialization.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_date', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/models/marts/daily_order_partitioned.sql'), line=16, column=5, end_line=16, end_column=15), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'waffles_ordered > 0'}, name='waffles_ordered_is_positive', description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n CAST(o.ordered_at AS DATE) AS order_date,\\n COUNT(DISTINCT o.order_id) AS order_count,\\n SUM(o.quantity) AS waffles_ordered,\\n COUNT(DISTINCT o.customer_id) AS unique_customers\\nFROM __ref(\"stg_orders\") o\\nWHERE CAST(o.ordered_at AS DATE) >= CAST(@@@partition_start AS DATE)\\n AND CAST(o.ordered_at AS DATE) < CAST(@@@partition_end AS DATE)\\nGROUP BY CAST(o.ordered_at AS DATE)', expanded_sql='SELECT\\n CAST(o.ordered_at AS DATE) AS order_date,\\n COUNT(DISTINCT o.order_id) AS order_count,\\n SUM(o.quantity) AS waffles_ordered,\\n COUNT(DISTINCT o.customer_id) AS unique_customers\\nFROM __ref(\"stg_orders\") o\\nWHERE CAST(o.ordered_at AS DATE) >= CAST(@@@partition_start AS DATE)\\n AND CAST(o.ordered_at AS DATE) < CAST(@@@partition_end AS DATE)\\nGROUP BY CAST(o.ordered_at AS DATE)', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/marts/daily_revenue.sql": { + "sql/models/marts/daily_revenue.sql": { "config": "CompileModelConfig(values={'materialized': 'table', 'tags': ['marts']}, model_header_keys=('audits', 'columns', 'description', 'materialized', 'tags'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -82,11 +82,11 @@ "query_sql": "'SELECT\\n CAST(o.ordered_at AS DATE) AS revenue_date,\\n COUNT(DISTINCT o.order_id) AS order_count,\\n SUM(o.quantity) AS waffles_sold,\\n SUM(p.amount_cents) AS total_revenue_cents,\\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\\nFROM __ref(\"stg_orders\") o\\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = \\'success\\'\\nGROUP BY CAST(o.ordered_at AS DATE)'", "references": "(CompileSqlReference(ref_kind=, ref_name='stg_orders', ref_package=None, call_argument_count=None, call_partitioned=False), CompileSqlReference(ref_kind=, ref_name='stg_payments', ref_package=None, call_argument_count=None, call_partitioned=False))", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='daily_revenue', model_schema=None, description='Daily revenue aggregation.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='revenue_date', type=None, nullable=False, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('models/marts/daily_revenue.sql'), line=12, column=5, end_line=12, end_column=17), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'total_revenue_cents >= 0'}, name='revenue_is_non_negative', description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", + "schema_entry": "SchemaModelEntry(name='daily_revenue', model_schema=None, description='Daily revenue aggregation.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='revenue_date', type=None, nullable=False, description=None, meta={}, audits=(), location=SourceLocation(path=PosixPath('sql/models/marts/daily_revenue.sql'), line=12, column=5, end_line=12, end_column=17), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'total_revenue_cents >= 0'}, name='revenue_is_non_negative', description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n CAST(o.ordered_at AS DATE) AS revenue_date,\\n COUNT(DISTINCT o.order_id) AS order_count,\\n SUM(o.quantity) AS waffles_sold,\\n SUM(p.amount_cents) AS total_revenue_cents,\\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\\nFROM __ref(\"stg_orders\") o\\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = \\'success\\'\\nGROUP BY CAST(o.ordered_at AS DATE)', expanded_sql='SELECT\\n CAST(o.ordered_at AS DATE) AS revenue_date,\\n COUNT(DISTINCT o.order_id) AS order_count,\\n SUM(o.quantity) AS waffles_sold,\\n SUM(p.amount_cents) AS total_revenue_cents,\\n SUM(p.amount_cents) / COUNT(DISTINCT o.order_id) AS avg_order_value_cents\\nFROM __ref(\"stg_orders\") o\\nINNER JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = \\'success\\'\\nGROUP BY CAST(o.ordered_at AS DATE)', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/marts/dim_customers.sql": { + "sql/models/marts/dim_customers.sql": { "config": "CompileModelConfig(values={'materialized': 'table', 'tags': ['marts']}, model_header_keys=('columns', 'description', 'materialized', 'tags'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -99,11 +99,11 @@ "query_sql": "'SELECT\\n c.customer_id,\\n c.first_name,\\n c.last_name,\\n c.email,\\n c.created_at AS customer_since,\\n COUNT(DISTINCT o.order_id) AS lifetime_orders,\\n COALESCE(SUM(p.amount_cents), 0) AS lifetime_spend_cents\\nFROM __ref(\"stg_customers\") c\\nLEFT JOIN __ref(\"stg_orders\") o ON c.customer_id = o.customer_id\\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = \\'success\\'\\nGROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.created_at'", "references": "(CompileSqlReference(ref_kind=, ref_name='stg_customers', ref_package=None, call_argument_count=None, call_partitioned=False), CompileSqlReference(ref_kind=, ref_name='stg_orders', ref_package=None, call_argument_count=None, call_partitioned=False), CompileSqlReference(ref_kind=, ref_name='stg_payments', ref_package=None, call_argument_count=None, call_partitioned=False))", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='dim_customers', model_schema=None, description='Customer dimension with lifetime metrics.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='customer_id', type=None, nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('models/marts/dim_customers.sql'), line=6, column=5, end_line=6, end_column=16), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='dim_customers', model_schema=None, description='Customer dimension with lifetime metrics.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='customer_id', type=None, nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('sql/models/marts/dim_customers.sql'), line=6, column=5, end_line=6, end_column=16), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n c.customer_id,\\n c.first_name,\\n c.last_name,\\n c.email,\\n c.created_at AS customer_since,\\n COUNT(DISTINCT o.order_id) AS lifetime_orders,\\n COALESCE(SUM(p.amount_cents), 0) AS lifetime_spend_cents\\nFROM __ref(\"stg_customers\") c\\nLEFT JOIN __ref(\"stg_orders\") o ON c.customer_id = o.customer_id\\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = \\'success\\'\\nGROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.created_at', expanded_sql='SELECT\\n c.customer_id,\\n c.first_name,\\n c.last_name,\\n c.email,\\n c.created_at AS customer_since,\\n COUNT(DISTINCT o.order_id) AS lifetime_orders,\\n COALESCE(SUM(p.amount_cents), 0) AS lifetime_spend_cents\\nFROM __ref(\"stg_customers\") c\\nLEFT JOIN __ref(\"stg_orders\") o ON c.customer_id = o.customer_id\\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id AND p.payment_status = \\'success\\'\\nGROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.created_at', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/marts/fact_orders.sql": { + "sql/models/marts/fact_orders.sql": { "config": "CompileModelConfig(values={'materialized': 'table', 'tags': ['marts']}, model_header_keys=('columns', 'description', 'materialized', 'tags'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -116,11 +116,11 @@ "query_sql": "'SELECT\\n o.order_id,\\n o.customer_id,\\n o.waffle_type_id,\\n w.waffle_name,\\n w.category AS waffle_category,\\n o.quantity,\\n w.price_cents * o.quantity AS line_total_cents,\\n o.ordered_at,\\n o.status AS order_status,\\n __udf(\"is_completed_order\")(o.status) AS is_completed_order,\\n __udf(\"is_completed_order_py\")(o.status) AS is_completed_order_py,\\n p.payment_method,\\n p.payment_status,\\n p.amount_cents AS payment_amount_cents\\nFROM __ref(\"stg_orders\") o\\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id'", "references": "(CompileSqlReference(ref_kind=, ref_name='is_completed_order', ref_package=None, call_argument_count=None, call_partitioned=False), CompileSqlReference(ref_kind=, ref_name='is_completed_order_py', ref_package=None, call_argument_count=None, call_partitioned=False), CompileSqlReference(ref_kind=, ref_name='stg_orders', ref_package=None, call_argument_count=None, call_partitioned=False), CompileSqlReference(ref_kind=, ref_name='waffle_types', ref_package=None, call_argument_count=None, call_partitioned=False), CompileSqlReference(ref_kind=, ref_name='stg_payments', ref_package=None, call_argument_count=None, call_partitioned=False))", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='fact_orders', model_schema=None, description='Order fact table with waffle and payment details.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_id', type=None, nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('models/marts/fact_orders.sql'), line=6, column=5, end_line=6, end_column=13), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='fact_orders', model_schema=None, description='Order fact table with waffle and payment details.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_id', type=None, nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/models/marts/fact_orders.sql'), line=6, column=5, end_line=6, end_column=13), migrate_from=None),), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n o.order_id,\\n o.customer_id,\\n o.waffle_type_id,\\n w.waffle_name,\\n w.category AS waffle_category,\\n o.quantity,\\n @py.line_total_cents(\"w.price_cents\", \"o.quantity\") AS line_total_cents,\\n o.ordered_at,\\n o.status AS order_status,\\n __udf(\"is_completed_order\")(o.status) AS is_completed_order,\\n __udf(\"is_completed_order_py\")(o.status) AS is_completed_order_py,\\n p.payment_method,\\n p.payment_status,\\n p.amount_cents AS payment_amount_cents\\nFROM __ref(\"stg_orders\") o\\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id', expanded_sql='SELECT\\n o.order_id,\\n o.customer_id,\\n o.waffle_type_id,\\n w.waffle_name,\\n w.category AS waffle_category,\\n o.quantity,\\n w.price_cents * o.quantity AS line_total_cents,\\n o.ordered_at,\\n o.status AS order_status,\\n __udf(\"is_completed_order\")(o.status) AS is_completed_order,\\n __udf(\"is_completed_order_py\")(o.status) AS is_completed_order_py,\\n p.payment_method,\\n p.payment_status,\\n p.amount_cents AS payment_amount_cents\\nFROM __ref(\"stg_orders\") o\\nLEFT JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id', passes=((), (ExpansionSpan(source_start=124, source_end=175, output_start=124, output_end=150),)))", "sql_validation_enabled": "True" }, - "models/marts/hourly_activity_with_daily_context.sql": { + "sql/models/marts/hourly_activity_with_daily_context.sql": { "config": "CompileModelConfig(values={'materialized': 'incremental', 'incremental_strategy': 'delete_insert', 'cursor': 'activity_hour', 'cursor_type': 'timestamp', 'cursor_grain': 'hour', 'microbatch_strategy': 'watermark', 'cursor_watermark_mode': 'all', 'cursor_inputs': {'daily_activity_rollup': {'column': 'activity_day', 'roles': ['filter', 'watermark']}}, 'incremental_mode': 'microbatch', 'batch_size': '6h', 'tags': ['marts', 'acceptance']}, model_header_keys=('audits', 'batch_size', 'columns', 'cursor', 'cursor_grain', 'cursor_inputs', 'cursor_type', 'cursor_watermark_mode', 'description', 'incremental_mode', 'incremental_strategy', 'materialized', 'microbatch_strategy', 'tags'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -133,11 +133,11 @@ "query_sql": "'SELECT\\n h.activity_hour,\\n h.orders_placed,\\n d.orders_placed AS day_orders_placed,\\n h.waffles_ordered,\\n h.revenue_cents\\nFROM __ref(\"hourly_order_activity\") h\\nINNER JOIN __ref(\"daily_activity_rollup\") d\\n ON DATE_TRUNC(\\'day\\', h.activity_hour) = d.activity_day'", "references": "(CompileSqlReference(ref_kind=, ref_name='hourly_order_activity', ref_package=None, call_argument_count=None, call_partitioned=False), CompileSqlReference(ref_kind=, ref_name='daily_activity_rollup', ref_package=None, call_argument_count=None, call_partitioned=False))", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='hourly_activity_with_daily_context', model_schema=None, description='Hourly downstream microbatch model that depends on a coarser-grain daily upstream.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='activity_hour', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('models/marts/hourly_activity_with_daily_context.sql'), line=17, column=5, end_line=17, end_column=18), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'day_orders_placed >= orders_placed'}, name='day_orders_cover_hourly_orders', description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", + "schema_entry": "SchemaModelEntry(name='hourly_activity_with_daily_context', model_schema=None, description='Hourly downstream microbatch model that depends on a coarser-grain daily upstream.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='activity_hour', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/models/marts/hourly_activity_with_daily_context.sql'), line=17, column=5, end_line=17, end_column=18), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'day_orders_placed >= orders_placed'}, name='day_orders_cover_hourly_orders', description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n h.activity_hour,\\n h.orders_placed,\\n d.orders_placed AS day_orders_placed,\\n h.waffles_ordered,\\n h.revenue_cents\\nFROM __ref(\"hourly_order_activity\") h\\nINNER JOIN __ref(\"daily_activity_rollup\") d\\n ON @py.timestamp_trunc(\\'day\\', \\'h.activity_hour\\') = d.activity_day', expanded_sql='SELECT\\n h.activity_hour,\\n h.orders_placed,\\n d.orders_placed AS day_orders_placed,\\n h.waffles_ordered,\\n h.revenue_cents\\nFROM __ref(\"hourly_order_activity\") h\\nINNER JOIN __ref(\"daily_activity_rollup\") d\\n ON DATE_TRUNC(\\'day\\', h.activity_hour) = d.activity_day', passes=((), (ExpansionSpan(source_start=211, source_end=256, output_start=211, output_end=245),)))", "sql_validation_enabled": "True" }, - "models/marts/hourly_order_activity.sql": { + "sql/models/marts/hourly_order_activity.sql": { "config": "CompileModelConfig(values={'materialized': 'incremental', 'incremental_strategy': 'delete_insert', 'cursor': 'activity_hour', 'cursor_type': 'timestamp', 'cursor_grain': 'hour', 'microbatch_strategy': 'watermark', 'cursor_watermark_mode': 'all', 'cursor_inputs': {'fact_orders': {'column': 'ordered_at', 'roles': ['filter', 'watermark']}}, 'incremental_mode': 'microbatch', 'batch_size': '1d', 'tags': ['marts']}, model_header_keys=('audits', 'batch_size', 'columns', 'cursor', 'cursor_grain', 'cursor_inputs', 'cursor_type', 'cursor_watermark_mode', 'description', 'incremental_mode', 'incremental_strategy', 'materialized', 'microbatch_strategy', 'tags'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -150,11 +150,11 @@ "query_sql": "'SELECT\\n DATE_TRUNC(\\'hour\\', o.ordered_at) AS activity_hour,\\n COUNT(*) AS orders_placed,\\n SUM(o.quantity) AS waffles_ordered,\\n SUM(o.line_total_cents) AS revenue_cents\\nFROM __ref(\"fact_orders\") o\\nGROUP BY DATE_TRUNC(\\'hour\\', o.ordered_at)'", "references": "(CompileSqlReference(ref_kind=, ref_name='fact_orders', ref_package=None, call_argument_count=None, call_partitioned=False),)", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='hourly_order_activity', model_schema=None, description='Hourly order activity aggregated via microbatch incremental.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='activity_hour', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('models/marts/hourly_order_activity.sql'), line=17, column=5, end_line=17, end_column=18), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'orders_placed >= 0'}, name='orders_placed_is_non_negative', description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", + "schema_entry": "SchemaModelEntry(name='hourly_order_activity', model_schema=None, description='Hourly order activity aggregated via microbatch incremental.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='activity_hour', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/models/marts/hourly_order_activity.sql'), line=17, column=5, end_line=17, end_column=18), migrate_from=None),), dynamic_columns=(), audits=(SchemaAuditInstance(definition_name='expression_is_true', arguments={'expression': 'orders_placed >= 0'}, name='orders_placed_is_non_negative', description=None, severity=None, run_scope='delta_and_final', always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n @py.timestamp_trunc(\\'hour\\', \\'o.ordered_at\\') AS activity_hour,\\n COUNT(*) AS orders_placed,\\n SUM(o.quantity) AS waffles_ordered,\\n SUM(o.line_total_cents) AS revenue_cents\\nFROM __ref(\"fact_orders\") o\\nGROUP BY @py.timestamp_trunc(\\'hour\\', \\'o.ordered_at\\')', expanded_sql='SELECT\\n DATE_TRUNC(\\'hour\\', o.ordered_at) AS activity_hour,\\n COUNT(*) AS orders_placed,\\n SUM(o.quantity) AS waffles_ordered,\\n SUM(o.line_total_cents) AS revenue_cents\\nFROM __ref(\"fact_orders\") o\\nGROUP BY DATE_TRUNC(\\'hour\\', o.ordered_at)', passes=((), (ExpansionSpan(source_start=9, source_end=52, output_start=9, output_end=41), ExpansionSpan(source_start=218, source_end=261, output_start=207, output_end=239))))", "sql_validation_enabled": "True" }, - "models/marts/scenario_order_prices.sql": { + "sql/models/marts/scenario_order_prices.sql": { "config": "CompileModelConfig(values={'materialized': 'table', 'tags': ['marts', 'scenario']}, model_header_keys=('description', 'materialized', 'tags'), matched_path_default=None, logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -171,7 +171,7 @@ "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n o.order_id,\\n o.quantity,\\n w.waffle_name,\\n w.price_cents,\\n w.price_cents * o.quantity AS line_total_cents,\\n p.amount_cents AS payment_amount_cents\\nFROM __ref(\"stg_orders\") o\\nINNER JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id', expanded_sql='SELECT\\n o.order_id,\\n o.quantity,\\n w.waffle_name,\\n w.price_cents,\\n w.price_cents * o.quantity AS line_total_cents,\\n p.amount_cents AS payment_amount_cents\\nFROM __ref(\"stg_orders\") o\\nINNER JOIN __seed(\"waffle_types\") w ON o.waffle_type_id = w.waffle_type_id\\nLEFT JOIN __ref(\"stg_payments\") p ON o.order_id = p.order_id', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/staging/stg_customers.sql": { + "sql/models/staging/stg_customers.sql": { "config": "CompileModelConfig(values={'materialized': 'view', 'tags': ['staging']}, model_header_keys=('columns', 'description', 'materialized', 'tags'), matched_path_default='staging', logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -184,11 +184,11 @@ "query_sql": "'SELECT\\n id AS customer_id,\\n first_name,\\n last_name,\\n email,\\n created_at\\nFROM __source(\"raw_customers\")'", "references": "(CompileSqlReference(ref_kind=, ref_name='raw_customers', ref_package=None, call_argument_count=None, call_partitioned=False),)", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='stg_customers', model_schema=None, description='Cleaned customer records.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='customer_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('models/staging/stg_customers.sql'), line=6, column=5, end_line=6, end_column=16), migrate_from=None), SchemaColumn(name='email', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('models/staging/stg_customers.sql'), line=7, column=5, end_line=7, end_column=10), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='stg_customers', model_schema=None, description='Cleaned customer records.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='customer_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('sql/models/staging/stg_customers.sql'), line=6, column=5, end_line=6, end_column=16), migrate_from=None), SchemaColumn(name='email', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/models/staging/stg_customers.sql'), line=7, column=5, end_line=7, end_column=10), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n id AS customer_id,\\n first_name,\\n last_name,\\n email,\\n created_at\\nFROM __source(\"raw_customers\")', expanded_sql='SELECT\\n id AS customer_id,\\n first_name,\\n last_name,\\n email,\\n created_at\\nFROM __source(\"raw_customers\")', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/staging/stg_orders.sql": { + "sql/models/staging/stg_orders.sql": { "config": "CompileModelConfig(values={'materialized': 'view', 'tags': ['staging']}, model_header_keys=('columns', 'description', 'materialized', 'tags'), matched_path_default='staging', logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -201,11 +201,11 @@ "query_sql": "'SELECT\\n id AS order_id,\\n customer_id,\\n waffle_type_id,\\n quantity,\\n ordered_at,\\n status\\nFROM __source(\"raw_orders\")'", "references": "(CompileSqlReference(ref_kind=, ref_name='raw_orders', ref_package=None, call_argument_count=None, call_partitioned=False),)", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='stg_orders', model_schema=None, description='Cleaned order records.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_id', type=None, nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('models/staging/stg_orders.sql'), line=6, column=5, end_line=6, end_column=13), migrate_from=None), SchemaColumn(name='customer_id', type=None, nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('models/staging/stg_orders.sql'), line=7, column=5, end_line=7, end_column=16), migrate_from=None), SchemaColumn(name='waffle_type_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='relationships', arguments={'to': '__seed(\"waffle_types\")', 'field': 'waffle_type_id'}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('models/staging/stg_orders.sql'), line=8, column=5, end_line=8, end_column=19), migrate_from=None), SchemaColumn(name='status', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='accepted_values', arguments={'values': ['placed', 'preparing', 'ready', 'completed', 'cancelled']}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('models/staging/stg_orders.sql'), line=11, column=5, end_line=11, end_column=11), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='stg_orders', model_schema=None, description='Cleaned order records.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='order_id', type=None, nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('sql/models/staging/stg_orders.sql'), line=6, column=5, end_line=6, end_column=13), migrate_from=None), SchemaColumn(name='customer_id', type=None, nullable=False, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/models/staging/stg_orders.sql'), line=7, column=5, end_line=7, end_column=16), migrate_from=None), SchemaColumn(name='waffle_type_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='relationships', arguments={'to': '__seed(\"waffle_types\")', 'field': 'waffle_type_id'}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/models/staging/stg_orders.sql'), line=8, column=5, end_line=8, end_column=19), migrate_from=None), SchemaColumn(name='status', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='accepted_values', arguments={'values': ['placed', 'preparing', 'ready', 'completed', 'cancelled']}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None),), location=SourceLocation(path=PosixPath('sql/models/staging/stg_orders.sql'), line=11, column=5, end_line=11, end_column=11), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n id AS order_id,\\n customer_id,\\n waffle_type_id,\\n quantity,\\n ordered_at,\\n status\\nFROM __source(\"raw_orders\")', expanded_sql='SELECT\\n id AS order_id,\\n customer_id,\\n waffle_type_id,\\n quantity,\\n ordered_at,\\n status\\nFROM __source(\"raw_orders\")', passes=((), ()))", "sql_validation_enabled": "True" }, - "models/staging/stg_payments.sql": { + "sql/models/staging/stg_payments.sql": { "config": "CompileModelConfig(values={'materialized': 'view', 'tags': ['staging']}, model_header_keys=('columns', 'description', 'materialized', 'tags'), matched_path_default='staging', logical_schema=None, layer_schema=None, logical_database=None, time_travel_retention=ResolvedTimeTravelRetention(desired_days=None, unmanaged=True, source=None), table_type=ResolvedTableType(value=, source=, declared=False))", "constant_declarations": "()", "declaration_usages": "()", @@ -218,7 +218,7 @@ "query_sql": "'SELECT\\n id AS payment_id,\\n order_id,\\n amount_cents,\\n payment_method,\\n paid_at,\\n status AS payment_status\\nFROM __source(\"raw_payments\")'", "references": "(CompileSqlReference(ref_kind=, ref_name='raw_payments', ref_package=None, call_argument_count=None, call_partitioned=False),)", "rejected_sql_analysis_opt_out": "None", - "schema_entry": "SchemaModelEntry(name='stg_payments', model_schema=None, description='Cleaned payment records.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='payment_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('models/staging/stg_payments.sql'), line=6, column=5, end_line=6, end_column=15), migrate_from=None), SchemaColumn(name='order_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='relationships', arguments={'to': '__source(\"raw_orders\")', 'field': 'id'}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('models/staging/stg_payments.sql'), line=7, column=5, end_line=7, end_column=13), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", + "schema_entry": "SchemaModelEntry(name='stg_payments', model_schema=None, description='Cleaned payment records.', type_enforcement=None, meta={}, columns=(SchemaColumn(name='payment_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='unique', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('sql/models/staging/stg_payments.sql'), line=6, column=5, end_line=6, end_column=15), migrate_from=None), SchemaColumn(name='order_id', type=None, nullable=None, description=None, meta={}, audits=(SchemaAuditInstance(definition_name='not_null', arguments={}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None), SchemaAuditInstance(definition_name='relationships', arguments={'to': '__source(\"raw_orders\")', 'field': 'id'}, name=None, description=None, severity=None, run_scope=None, always_run=False, thresholds=None, minimum_samples=None, evidence_limit=None, meta=None)), location=SourceLocation(path=PosixPath('sql/models/staging/stg_payments.sql'), line=7, column=5, end_line=7, end_column=13), migrate_from=None)), dynamic_columns=(), audits=(), tags=())", "sql_expansion": "CompiledSqlExpansion(authored_sql='SELECT\\n id AS payment_id,\\n order_id,\\n amount_cents,\\n payment_method,\\n paid_at,\\n status AS payment_status\\nFROM __source(\"raw_payments\")', expanded_sql='SELECT\\n id AS payment_id,\\n order_id,\\n amount_cents,\\n payment_method,\\n paid_at,\\n status AS payment_status\\nFROM __source(\"raw_payments\")', passes=((), ()))", "sql_validation_enabled": "True" } diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/helpers.py b/tests/integration/src/sqlbuild/compiler/compiled_project/helpers.py index 5454370e9e..1619a84f84 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/helpers.py @@ -48,6 +48,7 @@ ) from sqlbuild.orchestration import compile_snapshot from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files if TYPE_CHECKING: from sqlbuild._native import CompileInputsView @@ -71,22 +72,31 @@ PYTHON_PIPELINE_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', tags [orders]);\n\nSELECT 1 AS order_id\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', tags [orders]);\n\n" 'SELECT order_id FROM __ref("stg_orders")\n' ), - "python/orders/partner_export/node.py": Path( - "benchmarks/duckshop/edge_cases/orchestration/python_pipeline_partner_export.py" - ).read_text(), - "python/fulfillment/carrier_sync/node.py": Path( - "benchmarks/duckshop/edge_cases/orchestration/python_pipeline_carrier_sync.py" - ).read_text(), - "python/checks/orders_present.py": Path( - "benchmarks/duckshop/edge_cases/orchestration/python_pipeline_orders_check.py" - ).read_text(), + **node_module_files( + "python/nodes/orders/partner_export/node.py", + Path( + "benchmarks/duckshop/edge_cases/orchestration/python_pipeline_partner_export.py" + ).read_text(), + ), + **node_module_files( + "python/nodes/fulfillment/carrier_sync/node.py", + Path( + "benchmarks/duckshop/edge_cases/orchestration/python_pipeline_carrier_sync.py" + ).read_text(), + ), + **node_module_files( + "python/nodes/checks/orders_present.py", + Path( + "benchmarks/duckshop/edge_cases/orchestration/python_pipeline_orders_check.py" + ).read_text(), + ), } TYPE_PROOF_FILES: dict[str, str] = { @@ -94,13 +104,13 @@ 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQBRCONTRACT105"]\n\n' '[defaults]\ncontract = "enforced"\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.',\n" " columns (order_id (type INTEGER), amount (type INTEGER)),\n" ");\n\n" "SELECT CAST(1 AS INTEGER) AS order_id, CAST(5 AS INTEGER) AS amount\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Typed orders.',\n" " columns (order_id (type INTEGER), amount (type BIGINT)),\n" ");\n\n" @@ -109,7 +119,7 @@ } # The type-proof project with its contract finding fixed, so a location's load passes its rules. PUBLISHABLE_FILES: dict[str, str] = TYPE_PROOF_FILES | { - "models/orders.sql": TYPE_PROOF_FILES["models/orders.sql"].replace( + "sql/models/orders.sql": TYPE_PROOF_FILES["sql/models/orders.sql"].replace( "SELECT order_id, amount", "SELECT order_id, CAST(amount AS BIGINT) AS amount" ), } @@ -166,52 +176,52 @@ def counted(self: object, *args: object, **kwargs: object) -> None: '[defaults]\nmaterialized = "table"\n\n[path_defaults.staging]\n' 'materialized = "view"\ntags = ["staged"]\n' ), - "seeds/payment_methods.csv": "method\ncard\n", - "seeds/payment_methods.yml": ( + "sql/seeds/payment_methods.csv": "method\ncard\n", + "sql/seeds/payment_methods.yml": ( "seeds:\n - name: payment_methods\n description: Payment methods.\n" " columns:\n - name: method\n type: VARCHAR\n" ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( "MODEL (description 'Staged orders.', tags [daily]);\n" "SELECT 1 AS order_id, '@@region' AS region -- note\n" ), - "models/staging/stg_payments.sql": ( + "sql/models/staging/stg_payments.sql": ( 'MODEL (tags [payments]);\nSELECT method FROM __seed("payment_methods")\n' ), - "models/marts/orders.sql": ( + "sql/models/marts/orders.sql": ( "MODEL (description 'Orders.', materialized incremental, incremental_strategy append," " cursor order_id, cursor_type integer);\n" 'SELECT order_id FROM __ref("stg_orders")\n' "WHERE order_id >= __cursor_start()\n" ), - "models/marts/opted_out.sql": ("MODEL (sql_analysis false);\nSELECT 1 AS order_id\n"), - "models/marts/described_columns.sql": ( + "sql/models/marts/opted_out.sql": ("MODEL (sql_analysis false);\nSELECT 1 AS order_id\n"), + "sql/models/marts/described_columns.sql": ( "MODEL (\n columns (order_id (type INTEGER, nullable false," ' audits [not_null, unique]), note (description "Free text.")),\n' ");\n" "SELECT 1 AS order_id, 'x' AS note\n" ), - "enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", - "constants/limits.sql": ( + "sql/enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/constants/limits.sql": ( "CONSTANT (name order_cap, value 3);\nCONSTANT (name held_codes, value [30, 31]);\n" ), - "models/marts/statuses.sql": ( + "sql/models/marts/statuses.sql": ( "MODEL (columns (status (type VARCHAR)));\n" 'SELECT @enum("order_status").PLACED AS status, @const("order_cap") AS cap\n' 'WHERE 30 NOT IN @const("held_codes")\n' ), - "macros/python/money.py": 'def cents(value: str) -> str:\n return f"{value} * 100"\n', - "models/marts/priced.sql": ( + "sql/macros/python/money.py": 'def cents(value: str) -> str:\n return f"{value} * 100"\n', + "sql/models/marts/priced.sql": ( "MODEL (description 'Priced orders.');\n" "SELECT @py.cents('3') AS cents, order_id FROM __ref(\"stg_orders\")\n" ), - "models/marts/hooked.sql": ( + "sql/models/marts/hooked.sql": ( "MODEL (\n description 'Hooked orders.',\n" " pre_hooks [inline_sql('SELECT @@region AS region')],\n" " post_hooks [inline_sql('SELECT @py.cents(2) AS cents')],\n);\n" "SELECT 1 AS order_id\n" ), - "models/marts/migrated.sql": ( + "sql/models/marts/migrated.sql": ( "MODEL (materialized incremental, incremental_strategy append," " columns (order_id (migrate_from id)));\nSELECT 1 AS order_id\n" ), @@ -220,11 +230,11 @@ def counted(self: object, *args: object, **kwargs: object) -> None: HEADER_CONTRACT_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", - "audits/generic/expression_is_true.sql": ( + "sql/enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/audits/generic/expression_is_true.sql": ( 'AUDIT ();\nSELECT * FROM __ref("@model") WHERE NOT (@expression)\n' ), - "python/quality.py": ( + "python/nodes/quality.py": ( "from sqlbuild.audits import AuditCase, audit_factory\n\n\n" "@audit_factory\n" "def order_checks():\n" @@ -233,17 +243,17 @@ def counted(self: object, *args: object, **kwargs: object) -> None: ' arguments={"expression": "total > 0"}),\n' " ]\n" ), - "models/order_amounts.sql": ( + "sql/models/order_amounts.sql": ( "MODEL (columns (customer_id (type INTEGER)));\n" "SELECT 1 AS customer_id, 'books' AS category, 2 AS amount\n" ), - "models/category_amounts.sql": ( + "sql/models/category_amounts.sql": ( "MODEL (\n columns (customer_id (type INTEGER)),\n" " dynamic_columns (category_amounts (pivot_column category, value_column amount," ' aggregate max, type INTEGER, name_pattern "^[a-z]+$")),\n);\n' 'PIVOT __ref("order_amounts") ON category USING MAX(amount)\n' ), - "models/order_statuses.sql": ( + "sql/models/order_statuses.sql": ( "MODEL (\n contract enforced,\n" " columns (status (type order_status, audits [not_null]), total (type INTEGER)),\n" " audit_factories [order_checks],\n);\n" @@ -257,10 +267,10 @@ def counted(self: object, *args: object, **kwargs: object) -> None: 'name = "orders"\nadapter = "duckdb"\n\n[settings]\nrequire_sql_analysis = true\n\n' "[path_defaults.legacy]\nsql_analysis = false\n" ), - "models/header_opt_out.sql": "MODEL (\n sql_analysis false\n);\nSELECT 1 AS order_id\n", - "models/legacy/path_opt_out.sql": "MODEL ();\nSELECT 1 AS order_id\n", - "models/unparsed.sql": "MODEL (sql_analysis false);\nSELECT FROM WHERE (\n", - "models/invalid_call.sql": ( + "sql/models/header_opt_out.sql": "MODEL (\n sql_analysis false\n);\nSELECT 1 AS order_id\n", + "sql/models/legacy/path_opt_out.sql": "MODEL ();\nSELECT 1 AS order_id\n", + "sql/models/unparsed.sql": "MODEL (sql_analysis false);\nSELECT FROM WHERE (\n", + "sql/models/invalid_call.sql": ( "MODEL ();\nSELECT * FROM __ref(order_name)\nCROSS JOIN __table_fn('customer_orders')\n" ), } @@ -268,20 +278,20 @@ def counted(self: object, *args: object, **kwargs: object) -> None: MODEL_SCHEMA_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", - "schemas/orders.sql": ( + "sql/enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/schemas/orders.sql": ( "SCHEMA (\n name order_shape,\n description 'Order shape.',\n" " columns (order_id (type INTEGER, nullable false), status (type order_status)),\n);\n" ), - "models/marts/_sqlbuild/schemas/local.sql": ( + "sql/models/marts/_sqlbuild/schemas/local.sql": ( "SCHEMA (\n name marts_shape,\n columns (order_id (type INTEGER)),\n);\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (\n contract enforced,\n model_schema order_shape,\n" " columns (order_id (audits [unique]), note (type VARCHAR)),\n);\n" "SELECT 1 AS order_id, 'PLACED' AS status, 'x' AS note\n" ), - "models/staging/hidden.sql": ( + "sql/models/staging/hidden.sql": ( "MODEL (\n description 'Out of reach.',\n model_schema marts_shape,\n);\n" "SELECT 1 AS order_id\n" ), @@ -289,7 +299,7 @@ def counted(self: object, *args: object, **kwargs: object) -> None: PYTHON_HOOK_FILES: dict[str, str] = { - "hooks/python/notifications.py": ( + "sql/hooks/python/notifications.py": ( "from sqlbuild.hooks import hook\n\n\n" "@hook\ndef notify(ctx, channel, *, level='info'):\n" ' """Notify a channel."""\n return None\n\n\n' @@ -303,21 +313,21 @@ def counted(self: object, *args: object, **kwargs: object) -> None: PYTHON_HOOK_PARITY_FILES: dict[str, str] = PYTHON_HOOK_FILES | { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/marts/_sqlbuild/hooks/python/local.py": ( + "sql/models/marts/_sqlbuild/hooks/python/local.py": ( "from sqlbuild.hooks import hook\n\n\n" "@hook\ndef refresh(ctx):\n" ' """Refresh marts."""\n return None\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n pre_hooks [python("notify", channel: "ops")],\n' ' post_hooks [python("flexible", any: 1), python("notify", channel: "c", level: "x")],\n' ");\n" "SELECT 1 AS order_id\n" ), - "models/marts/summary.sql": ( + "sql/models/marts/summary.sql": ( 'MODEL (post_hooks [python("refresh"), python("flexible")]);\nSELECT 1 AS order_id\n' ), - "models/staging/hidden.sql": ( + "sql/models/staging/hidden.sql": ( 'MODEL (post_hooks [python("refresh")]);\nSELECT 1 AS order_id\n' ), } @@ -325,21 +335,21 @@ def counted(self: object, *args: object, **kwargs: object) -> None: SQL_HOOK_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n\n[vars]\nregion = "eu"\n', - "enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", - "constants/limits.sql": "CONSTANT (name order_cap, value 3);\n", - "macros/python/money.py": 'def cents(value: str) -> str:\n return f"{value} * 100"\n', - "hooks/sql/grant_read.sql": ( + "sql/enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/constants/limits.sql": "CONSTANT (name order_cap, value 3);\n", + "sql/macros/python/money.py": 'def cents(value: str) -> str:\n return f"{value} * 100"\n', + "sql/hooks/sql/grant_read.sql": ( "HOOK (description 'Grant read access.');\n\n" "INSERT INTO audit.read_grants SELECT '@@CTX:destination.qualified', grantee\n" "FROM unnest([@'role']) AS granted(grantee)\n" ), - "hooks/sql/log_load.sql": ( + "sql/hooks/sql/log_load.sql": ( "HOOK (description 'Log a load.');\n\n" 'INSERT INTO @target SELECT @enum("order_status").PLACED, @const("order_cap"),' " @py.cents(@amount), '@@region' FROM __ref(\"stg_orders\")\n" ), - "models/staging/stg_orders.sql": "MODEL ();\nSELECT 1 AS order_id\n", - "models/marts/loaded.sql": ( + "sql/models/staging/stg_orders.sql": "MODEL ();\nSELECT 1 AS order_id\n", + "sql/models/marts/loaded.sql": ( "MODEL (\n schema analytics,\n" ' pre_hooks [sql("grant_read", role: ["reader", "writer"])],\n' ' post_hooks [sql("log_load", target: "audit.loads", amount: 5),' @@ -350,7 +360,7 @@ def counted(self: object, *args: object, **kwargs: object) -> None: MACRO_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n\n[vars]\nregion = "eu"\n', - "macros/python/amounts.py": ( + "sql/macros/python/amounts.py": ( '"""Amount macros."""\n\n\n' 'def cents(value):\n """Cents."""\n return f"{value} * 100"\n\n\n' 'def word():\n """A word."""\n return "x"\n' @@ -454,28 +464,28 @@ def _group_cycle_model(name: str, reads: str) -> str: # Models and a seed for the DuckShop `group_cycles` jobs, grouped into three cycles. GROUP_CYCLE_NODES: dict[str, str] = { - "seeds/regions.csv": "id\n1\n", - "seeds/regions.yml": ( + "sql/seeds/regions.csv": "id\n1\n", + "sql/seeds/regions.yml": ( "seeds:\n - name: regions\n description: Regions\n columns:\n" " - name: id\n type: INTEGER\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Synthetic stg_orders.', columns (id (type INTEGER)));\n\n" "SELECT CAST(1 AS INTEGER) AS id\n" ), - "models/stg_inventory.sql": ( + "sql/models/stg_inventory.sql": ( "MODEL (description 'Synthetic stg_inventory.', columns (id (type INTEGER)));\n\n" "SELECT CAST(1 AS INTEGER) AS id\n" ), - "models/customers.sql": _group_cycle_model("customers", "stg_orders"), - "models/orders.sql": _group_cycle_model("orders", "customers"), - "models/shipments.sql": _group_cycle_model("shipments", "stg_inventory"), - "models/inventory.sql": _group_cycle_model("inventory", "shipments"), - "models/region_report.sql": ( + "sql/models/customers.sql": _group_cycle_model("customers", "stg_orders"), + "sql/models/orders.sql": _group_cycle_model("orders", "customers"), + "sql/models/shipments.sql": _group_cycle_model("shipments", "stg_inventory"), + "sql/models/inventory.sql": _group_cycle_model("inventory", "shipments"), + "sql/models/region_report.sql": ( "MODEL (description 'Synthetic region_report.', columns (id (type INTEGER)));\n\n" 'SELECT CAST(1 AS INTEGER) AS id FROM __seed("regions")\n' ), - "models/regional_orders.sql": _group_cycle_model("regional_orders", "region_report"), + "sql/models/regional_orders.sql": _group_cycle_model("regional_orders", "region_report"), } # What compile and publish both report for that group: every cycle, then the shared-read hint. GROUP_CYCLE_MESSAGE: str = "\n".join( @@ -518,9 +528,9 @@ def copy_project(*, fixtures: tuple[str, ...], files: dict[str, str], project_di 'name = "orders"\nadapter = "duckdb"\n\n[vars]\nregion = "eu"\n\n' '[defaults]\ncontract = "enforced"\n' ), - "enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", - "constants/limits.sql": "CONSTANT (name order_cap, value 3);\n", - "macros/python/money.py": 'def cents(value: str) -> str:\n return f"{value} * 100"\n', + "sql/enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/constants/limits.sql": "CONSTANT (name order_cap, value 3);\n", + "sql/macros/python/money.py": 'def cents(value: str) -> str:\n return f"{value} * 100"\n', } _SOURCE_CONNECTION: dict[str, object] = {"database": "warehouse", "schema": "main"} @@ -531,7 +541,7 @@ def compile_source_project( """Compile a project declaring `source_yml`; return the project and its compile inputs.""" write_files( - project_dir=project_dir, files={**SOURCE_PROJECT_FILES, "sources/raw.yml": source_yml} + project_dir=project_dir, files={**SOURCE_PROJECT_FILES, "sql/sources/raw.yml": source_yml} ) project: CompiledProjectView = build_compiled_project( discovered_inputs=discover_project_inputs(project_dir=project_dir), @@ -553,18 +563,20 @@ def column_metadata(column: SourceColumnEntry) -> tuple[str | None, tuple[dict[s 'name = "orders"\nadapter = "duckdb"\n\n[vars]\nregion = "eu"\n' 'amount_type = "DECIMAL(10, 2)"\n\n[defaults]\nfunction_schema = "udfs_${region}"\n' ), - "enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", - "models/orders.sql": "MODEL (description 'Orders.', schema analytics);\nSELECT 1 AS order_id\n", - "functions/sql/order_total.sql": ( + "sql/enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/models/orders.sql": ( + "MODEL (description 'Orders.', schema analytics);\nSELECT 1 AS order_id\n" + ), + "sql/functions/sql/order_total.sql": ( "FUNCTION (description 'Order total.', tags [finance]," " arguments (amount ${amount_type}), returns ${amount_type});\nSELECT amount * 2\n" ), - "functions/sql/open_orders.sql": ( + "sql/functions/sql/open_orders.sql": ( "FUNCTION (description 'Open orders.', schema reporting," " returns table (order_id INTEGER, status VARCHAR));\n" 'SELECT order_id, @enum("order_status").PLACED AS status FROM __ref("orders")\n' ), - "functions/python/score.py": ( + "sql/functions/python/score.py": ( "from sqlbuild.functions import udf\n\n" "@udf(arguments={'value': 'INTEGER'}, returns='INTEGER', runtime_version='3.11'," " packages=['numpy'], tags=['ml'])\n" @@ -575,24 +587,24 @@ def column_metadata(column: SourceColumnEntry) -> tuple[str | None, tuple[dict[s TABLE_FUNCTION_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "snowflake"\n', - "models/readings.sql": ( + "sql/models/readings.sql": ( "MODEL (description 'Readings.');\nSELECT 1 AS device_id, 1.0 AS ts, 2.0 AS reading\n" ), - "functions/python/smooth.py": ( + "sql/functions/python/smooth.py": ( "import polars as pl\nfrom sqlbuild.functions import table_fn\n\n" "@table_fn(arguments={'device_id': 'INTEGER', 'reading': 'FLOAT'}," " returns={'device_id': 'INTEGER', 'smoothed': 'FLOAT'}, runtime_version='3.12')\n" "def main(readings: pl.DataFrame) -> pl.DataFrame:\n" ' """Smooth."""\n return readings\n' ), - "functions/python/rank_readings.py": ( + "sql/functions/python/rank_readings.py": ( "import pandas as pd\nfrom sqlbuild.functions import table_fn\n\n" "@table_fn(arguments={'reading': 'FLOAT'}, returns={'position': 'INTEGER'}," " runtime_version='3.12')\n" "def main(readings: pd.DataFrame) -> pd.DataFrame:\n" ' """Rank."""\n return readings\n' ), - "models/smoothed.sql": ( + "sql/models/smoothed.sql": ( "MODEL (description 'Smoothed.');\nSELECT s.* FROM __ref(\"readings\") r,\n" ' __table_fn("smooth")(r.device_id, r.reading) OVER (PARTITION BY r.device_id) s\n' ), @@ -660,15 +672,15 @@ def function_summary(function: CompiledFunctionView) -> tuple[object, ...]: "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n\n[settings]\ndefault_audit_severity = "warn"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', columns (order_id (type INTEGER," " audits [not_null, at_least(minimum 1, severity error)])));\nSELECT 1 AS order_id\n" ), - "models/customers.sql": "MODEL (description 'Customers.');\nSELECT 1 AS customer_id\n", - "audits/generic/at_least.sql": ( + "sql/models/customers.sql": "MODEL (description 'Customers.');\nSELECT 1 AS customer_id\n", + "sql/audits/generic/at_least.sql": ( "AUDIT (name at_least);\nSELECT * FROM @relation WHERE @column < @minimum\n" ), - "audits/singular/orders_have_customers.sql": ( + "sql/audits/singular/orders_have_customers.sql": ( "AUDIT (name orders_have_customers, run_scope final);\n" 'SELECT * FROM __ref("orders") o LEFT JOIN __ref("customers") c' " ON o.order_id = c.customer_id WHERE c.customer_id IS NULL\n" @@ -753,8 +765,8 @@ def cursor_model_files(*, read: str = "") -> dict[str, str]: """An upstream payments model and an incremental cursor model reading `read`.""" return { - "models/payments.sql": 'MODEL (description "Payments");\nSELECT 1 AS id\n', - "models/finance/daily_revenue.sql": _CURSOR_MODEL.format(read=read), + "sql/models/payments.sql": 'MODEL (description "Payments");\nSELECT 1 AS id\n', + "sql/models/finance/daily_revenue.sql": _CURSOR_MODEL.format(read=read), } @@ -763,7 +775,7 @@ def cursor_model_files(*, read: str = "") -> dict[str, str]: def _hand_built_model(name: str, sql: str) -> CompileModelInput: - relative_path: Path = Path(f"models/{name}.sql") + relative_path: Path = Path(f"sql/models/{name}.sql") return CompileModelInput( model_file=DiscoveredSqlModelFile( file_path=Path("/repo") / relative_path, @@ -806,7 +818,7 @@ def native_analysed_project(*, project_dir: Path, models: dict[str, str]) -> Com files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', **{ - f"models/{name}.sql": f"MODEL (description 'Test model.');\n\n{sql}\n" + f"sql/models/{name}.sql": f"MODEL (description 'Test model.');\n\n{sql}\n" for name, sql in models.items() }, }, diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py index c30fa54bde..68de974712 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py @@ -192,6 +192,14 @@ class NulLogTestCase(WorkerExecutionTestCase): expected_logs: list[tuple[str, str]] = field(default_factory=list) +@dataclass(frozen=True) +class PhaseEventsTestCase(WorkerExecutionTestCase): + description: str + backend: Literal["sqlite", "postgres"] = "sqlite" + # Each phase in order, and whether it reports a duration. + expected_phases: tuple[tuple[str, bool], ...] = () + + @dataclass(frozen=True) class NulFailureTestCase(WorkerExecutionTestCase): description: str @@ -1015,6 +1023,8 @@ class UnknownDependencyDiscoverTestCase: @dataclass(frozen=True) class UnknownTagTestCase: description: str - dependency: str + backend: str + first: str + edits: dict[str, str] + expected_nodes: frozenset[str] expected_error: str - expected_status: int diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/docker/compose/helpers.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/docker/compose/helpers.py index 1cb0fdfcd2..92eb47effb 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/docker/compose/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/docker/compose/helpers.py @@ -201,19 +201,23 @@ def build_projects(self) -> list[str]: images: list[str] = [] for version, sql in cases.items(): project: Path = self.directory / version - (project / "models").mkdir(parents=True) + (project / "sql" / "models").mkdir(parents=True) (project / "orchestration/jobs").mkdir(parents=True) for relative in ("sqlbuild_project.toml", "orchestration/jobs/refresh_orders_job.toml"): shutil.copyfile(Path("deploy/project") / relative, project / relative) - (project / "models/orders.sql").write_text( + (project / "sql/models/orders.sql").write_text( "MODEL (description 'Example orders.', materialized table);\n" + sql + "\n" ) - # Only source enters this build context; credentials stay in the parent process. - (project / "Dockerfile").write_text( + # Only source enters this build context; credentials stay in the parent process, and + # the Dockerfile stays beside the project, which may hold only project files. + dockerfile: Path = self.directory / f"{version}.Dockerfile" + dockerfile.write_text( f"FROM {base}\nENV SQLBUILD_GIT_REVISION={version}\n" "COPY --chown=10001:10001 . /project/\n" ) - self.docker("build", "--tag", f"{self.name}:{version}", str(project)) + self.docker( + "build", "--file", str(dockerfile), "--tag", f"{self.name}:{version}", str(project) + ) images.append( self.docker( "image", "inspect", "--format", "{{.Id}}", f"{self.name}:{version}" @@ -277,14 +281,19 @@ def close(self) -> None: @contextmanager -def platform_receiver() -> Iterator[tuple[int, list[dict[str, Any]]]]: - """Own the real webhook HTTP boundary even if stack cleanup itself fails.""" +def platform_receiver() -> Iterator[tuple[int, list[dict[str, Any]], dict[str, datetime]]]: + """Own the real webhook HTTP boundary even if stack cleanup itself fails. + + Yields the port, the delivered events, and when each event ID was first received. + """ events: list[dict[str, Any]] = [] + received_at: dict[str, datetime] = {} class Receiver(BaseHTTPRequestHandler): def do_POST(self) -> None: event: dict[str, Any] = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) assert self.headers["Idempotency-Key"] == event["event_id"] + received_at.setdefault(event["event_id"], datetime.now(UTC)) events.append(event) self.send_response(204) self.end_headers() @@ -296,23 +305,118 @@ def log_message(self, format: str, *args: object) -> None: thread: Thread = Thread(target=receiver.serve_forever, daemon=True) thread.start() try: - yield receiver.server_port, events + yield receiver.server_port, events, received_at finally: receiver.shutdown() thread.join(timeout=5) assert not thread.is_alive() +# The server's liveness timings, fixed in sqlbuild-orchestration and documented in +# website/src/content/docs/docs/cli/server.mdx; the compose stack does not override them. +# A location is broken once it has been silent for over LOCATION_SILENCE_SECONDS. +LOCATION_SILENCE_SECONDS: float = 90 +# The maintenance loop sleeps this long between health scans, after scanning and retention. +WATCHDOG_SCAN_SECONDS: float = 30 +# The platform webhook polls for new events this often, and gives up on a request after +# WEBHOOK_REQUEST_SECONDS, retrying the same event on the next poll. +WEBHOOK_POLL_SECONDS: float = 5 +WEBHOOK_REQUEST_SECONDS: float = 10 +# `sqb location serve` reports its health, which refreshes last_seen_at, this often. +LOCATION_REPORT_SECONDS: float = 30 + + +def location_check_in_deadline_seconds() -> float: + """The longest a running location can take to check in again. + + The next report is due within one report interval. A report that fails or overruns its tick + is skipped, so one further interval is allowed as slack. + """ + return 2 * LOCATION_REPORT_SECONDS + + +def wait_for_location_check_in(stack: ComposeStack, *, since: str) -> str: + """Wait until the location has reported after `since`, a control-store timestamp. + + An outage is reported once per last_seen_at. If the location has not checked in since the + server restarted, stopping it repeats an outage the watchdog may already have reported + while the server was down, and no fresh `location_broken` event is sent. + """ + timeout: float = location_check_in_deadline_seconds() + deadline: float = time.monotonic() + timeout + sql: str = ( + "SELECT MAX(last_seen_at) AS last_seen_at FROM sqb_location_instances " + f"WHERE location_id='{stack.location_id}'" + ) + while True: + fresh: list[dict[str, Any]] = stack.query( + f"{sql} HAVING MAX(last_seen_at)>'{since}'::timestamptz" + ) + if fresh: + return fresh[0]["last_seen_at"] + if time.monotonic() >= deadline: + latest: list[dict[str, Any]] = stack.query(sql) + raise AssertionError( + f"Location {stack.location_id} did not check in within {timeout:.0f}s after " + f"the server restarted at {since}; its latest check-in is " + f"{latest[0]['last_seen_at'] if latest else 'missing'} " + f"(logs in {stack.directory})" + ) + time.sleep(0.5) + + +def location_outage_deadline_seconds() -> float: + """The longest a stopped location's outage can take to reach the webhook receiver. + + The location last reported no later than the stop, so it is silent for long enough + LOCATION_SILENCE_SECONDS after it. The next scan follows within one scan interval, and a + loaded runner can stretch a scan cycle by as much again. Delivery takes one webhook poll and + request, and one retry of both is allowed. + """ + return ( + LOCATION_SILENCE_SECONDS + + 2 * WATCHDOG_SCAN_SECONDS + + 2 * (WEBHOOK_POLL_SECONDS + WEBHOOK_REQUEST_SECONDS) + ) + + +def stop_location_after_check_in( + stack: ComposeStack, events: list[dict[str, Any]], *, since: str +) -> tuple[set[str], datetime]: + """Stop the location once it has checked in after `since`, so the stop starts a fresh outage. + + Returns the IDs of the platform events received before the stop, and when it was stopped. + """ + wait_for_location_check_in(stack, since=since) + prior_events: set[str] = {event["event_id"] for event in events} + stack.compose("stop", "--timeout", "1", "location") + return prior_events, datetime.now(UTC) + + def wait_for_location_outage( - events: list[dict[str, Any]], prior_events: set[str] + events: list[dict[str, Any]], + prior_events: set[str], + received_at: dict[str, datetime], + *, + location_id: str, + stopped_at: datetime, ) -> dict[str, Any]: """Wait for fresh delivery, not an outage already received during a prior restart.""" - deadline: float = time.monotonic() + 135 + timeout: float = location_outage_deadline_seconds() + deadline: float = time.monotonic() + timeout matches: list[dict[str, Any]] = [] while not matches: - assert time.monotonic() < deadline, ( - "Native platform sink did not report the stopped location" - ) + if time.monotonic() >= deadline: + raise AssertionError( + _location_outage_failure( + events, + prior_events, + received_at, + location_id=location_id, + stopped_at=stopped_at, + timeout=timeout, + ) + ) time.sleep(0.5) matches = list( filter( @@ -324,3 +428,42 @@ def wait_for_location_outage( ) ) return matches[0] + + +def _location_outage_failure( + events: list[dict[str, Any]], + prior_events: set[str], + received_at: dict[str, datetime], + *, + location_id: str, + stopped_at: datetime, + timeout: float, +) -> str: + """Describe what the receiver heard after the stop, and any earlier outage of the location.""" + + def received(event: dict[str, Any]) -> str: + at: datetime | None = received_at.get(event["event_id"]) + if at is None: + return "unknown" + return f"{(at - stopped_at).total_seconds():+.1f}s" + + after_stop: list[str] = [ + f"{event['payload']['platform'].get('kind')} at {received(event)}" + for event in events + if event["event_id"] not in prior_events + ] + earlier_outages: list[str] = [ + f"last_seen_at {event['payload']['platform'].get('last_seen_at')} " + f"received {received(event)}" + for event in events + if event["event_id"] in prior_events + and event["payload"]["platform"].get("kind") == "location_broken" + and event["payload"]["platform"].get("location_id") == location_id + ] + return ( + "Native platform sink did not report the stopped location within " + f"{timeout:.0f}s of the stop at {stopped_at.isoformat()}. " + f"Events received after the stop (relative to it): {after_stop or 'none'}. " + "Outages of this location received before the stop, which suppress a repeat with " + f"the same last_seen_at: {earlier_outages or 'none'}." + ) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py index bdaac45e2a..72c5f8994f 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py @@ -102,6 +102,7 @@ ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files from tests.integration.src.sqlbuild.executor.audit_results.main.helpers import build_record +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files class RejectedPublicationOutput(StringIO): @@ -113,7 +114,7 @@ def write(self, text: str) -> int: # A provider whose settings only the project's .env sets; the worker must see them. REGION_PROVIDER_FILES: dict[str, str] = { - "providers/region.py": ( + "python/providers/region.py": ( "from pydantic import Field, SecretStr\n" "from sqlbuild.providers import Provider\n\n\n" "class Region(Provider):\n" @@ -121,7 +122,7 @@ def write(self, text: str) -> int: " token: SecretStr = Field(validation_alias='WORKER_ENV_TOKEN')\n" " code: int = Field(validation_alias='WORKER_ENV_REGION_CODE')\n" ), - "sources/regions.yml": ( + "sql/sources/regions.yml": ( "sources:\n" " - name: raw_regions\n" " description: The region code the provider reads.\n" @@ -131,8 +132,8 @@ def write(self, text: str) -> int: " - name: code\n" " type: BIGINT\n" ), - "python/loaders/regions.py": ( - "from providers.region import Region\n" + "python/nodes/loaders/regions/loader.py": ( + "from python.providers.region import Region\n" "from sqlbuild.loaders import loader\n\n\n" "@loader\n" "def raw_regions(ctx, region: Region):\n" @@ -870,7 +871,7 @@ def snapshot_api( directory: Path, *, server_arguments: tuple[str, ...] = (), database_url: str | None = None ) -> Iterator[SnapshotApi]: """Only this fixture seeds the control database; the code location uses HTTP exclusively.""" - directory.mkdir() + directory.mkdir(parents=True) log: Path = directory / "server.log" environment: dict[str, str] = os.environ.copy() environment.pop("SQLBUILD_CONTROL_DATABASE_URL", None) @@ -1023,10 +1024,10 @@ def scheduled_worker( "[pools]\n" + "".join(f"{name} = {limit}\n" for name, limit in test_case.pools.items()) ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" + test_case.model_sql + "\n" ), - "python/environment_guard.py": ( + "python/nodes/environment_guard.py": ( "import os\n" "if 'SQLBUILD_RUN_TOKEN' in os.environ:\n" " assert 'SQLBUILD_PLATFORM_WEBHOOK_URL' not in os.environ\n" @@ -1530,7 +1531,7 @@ def scheduler_crash_history(directory: Path, fixture: dict[str, Any]) -> dict[st '[connections.local]\ndatabase = "warehouse.duckdb"\n' '[targets.development]\nschema = "main"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\nSELECT 1 AS order_id\n" ), } @@ -1743,8 +1744,8 @@ def sqlite_rows(path: Path, sql: str) -> list[tuple[Any, ...]]: def changed_job_files(project_toml: str) -> dict[str, str]: """The DuckShop changed-builds edge case with one scheduled `changed` job.""" return { - str(path.relative_to(CHANGED_FIXTURE)): path.read_text() - for path in sorted(CHANGED_FIXTURE.glob("*/*")) + path.relative_to(CHANGED_FIXTURE).as_posix(): path.read_text() + for path in sorted(CHANGED_FIXTURE.glob("sql/*/*")) } | { "orchestration/jobs/changed_orders_job.toml": CHANGED_JOB, "sqlbuild_project.toml": project_toml, @@ -1864,13 +1865,14 @@ def hold_write_lock(database: Path) -> duckdb.DuckDBPyConnection: LOADED_ORDER_FILES: dict[str, str] = { - "sources/loaded.yml": Path( + "sql/sources/loaded.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/loaded_sources.yml" ).read_text(), - "python/loaders/loaded.py": Path( - "benchmarks/duckshop/edge_cases/orchestration/loaded_sources.py" - ).read_text(), - "models/orders.sql": Path( + **node_module_files( + "python/nodes/loaders/loaded.py", + Path("benchmarks/duckshop/edge_cases/orchestration/loaded_sources.py").read_text(), + ), + "sql/models/orders.sql": Path( "benchmarks/duckshop/edge_cases/orchestration/loaded_orders.sql" ).read_text(), **duckshop_orchestration("loaded_orders"), @@ -1878,13 +1880,16 @@ def hold_write_lock(database: Path) -> duckdb.DuckDBPyConnection: INTERMEDIATE_LOADER_FILES: dict[str, str] = { - "sources/shipments.yml": Path( + "sql/sources/shipments.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/intermediate_loader_sources.yml" ).read_text(), - "python/loaders/shipments.py": Path( - "benchmarks/duckshop/edge_cases/orchestration/intermediate_loader_sources.py" - ).read_text(), - "models/orders.sql": Path( + **node_module_files( + "python/nodes/loaders/shipments.py", + Path( + "benchmarks/duckshop/edge_cases/orchestration/intermediate_loader_sources.py" + ).read_text(), + ), + "sql/models/orders.sql": Path( "benchmarks/duckshop/edge_cases/orchestration/intermediate_loader_orders.sql" ).read_text(), **duckshop_orchestration("loaded_orders"), @@ -2316,8 +2321,8 @@ def endless_build_files(project_toml: str) -> dict[str, str]: "sqlbuild_project.toml": project_toml.replace( 'adapter = "duckdb"', 'adapter = "duckdb_cancel_marking"' ), - "adapters/duckdb_cancel_marking.py": CANCEL_MARKING_ADAPTER, - "models/orders.sql": ENDLESS_ORDERS, + "python/adapters/duckdb_cancel_marking.py": CANCEL_MARKING_ADAPTER, + "sql/models/orders.sql": ENDLESS_ORDERS, **duckshop_orchestration("development_orders"), } @@ -2477,27 +2482,39 @@ def launch_adhoc(worker: ScheduledWorker, command: list[str]) -> dict[str, Any]: # A loader after the items tagged `fulfilment`, which a `+raw_steps` reload runs as ingress. INGRESS_JOB_SETTINGS: str = "\n[settings]\nreload = true\n" INGRESS_LOADER_FILES: dict[str, str] = { - "python/ready.py": ( + "python/nodes/ready/asset.py": ( "from sqlbuild.assets import asset\n" "from sqlbuild.refs import tag\n\n\n" '@asset(depends_on=tag("fulfilment"))\n' "def ready(ctx):\n" ' """Wait for every step."""\n' ), - "python/loads.py": ( + "python/nodes/loads/fetch_steps/loader.py": ( "from sqlbuild.loaders import loader\n" - "from python.ready import ready\n\n\n" + "from python.nodes.ready.asset import ready\n" + "\n" + "\n" "@loader(depends_on=[ready], write_strategy='table', " "columns=[{'name': 'step', 'type': 'INTEGER'}])\n" "def fetch_steps(ctx):\n" ' """Fetch the steps."""\n' - ' return [{"step": 1}]\n\n\n' + ' return [{"step": 1}]\n' + ), + "python/nodes/loads/raw_steps/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.ready.asset import ready\n" + "from python.nodes.loads.fetch_steps.loader import fetch_steps\n" + "\n" + "\n" "@loader(depends_on=[fetch_steps])\n" "def raw_steps(ctx):\n" ' """Load the steps."""\n' ' return [{"step": 1}]\n' ), - "sources/raw.yml": ( + "python/nodes/loads/__init__.py": ( + "from .fetch_steps.loader import fetch_steps\nfrom .raw_steps.loader import raw_steps\n" + ), + "sql/sources/raw.yml": ( "sources:\n - name: raw_steps\n description: Steps.\n" " managed: true\n write_strategy: table\n" ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/job_settings/helpers.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/job_settings/helpers.py index 0b19541623..f3ed52be55 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/job_settings/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/job_settings/helpers.py @@ -47,12 +47,12 @@ '[targets.development]\nschema = "main"\n' '[vars]\namount = "1"\n' ), - "seeds/raw_orders.csv": "id\n1\n2\n", - "seeds/raw_orders.yml": ( + "sql/seeds/raw_orders.csv": "id\n1\n2\n", + "sql/seeds/raw_orders.yml": ( "seeds:\n - name: raw_orders\n description: Raw orders.\n columns:\n" " - name: id\n type: INTEGER\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders with their amount.', materialized incremental,\n" " incremental_strategy append, cursor id, cursor_type integer);\n" 'SELECT id, CAST(@@amount AS INTEGER) AS amount FROM __seed("raw_orders")\n' @@ -83,7 +83,7 @@ '[targets.development]\nschema = "main"\n' "[settings]\nconcurrency = 1\n" ), - "sources/loaded.yml": ( + "sql/sources/loaded.yml": ( "sources:\n" " - name: raw_customers\n description: Customers.\n managed: true\n" " write_strategy: table\n table: raw_customers\n columns:\n" @@ -92,24 +92,60 @@ " write_strategy: table\n table: raw_inventory\n columns:\n" " - name: product_id\n type: BIGINT\n" ), - "python/loaders/loaded.py": ( - '"""Two loaders that record each run in the warehouse log."""\n\n' - "import os\nfrom pathlib import Path\n\nfrom sqlbuild.loaders import loader\n\n\n" + "python/nodes/loaders/loaded/raw_customers/loader.py": ( + '"""Two loaders that record each run in the warehouse log."""\n' + "import os\n" + "from pathlib import Path\n" + "from sqlbuild.loaders import loader\n" "def _record(name):\n" ' with Path(os.environ["WAREHOUSE_LOG"]).open("a") as log:\n' - ' log.write(f"LOAD {name}\\n")\n\n\n' - "@loader\ndef raw_customers(ctx):\n" - ' """Load customers."""\n _record("raw_customers")\n' - ' return [{"customer_id": 7}]\n\n\n' - "@loader\ndef raw_inventory(ctx):\n" - ' """Load inventory."""\n _record("raw_inventory")\n' - ' return [{"product_id": 1}]\n\n\n' - '@loader(write_strategy="table")\ndef stage_inventory(ctx):\n' + ' log.write(f"LOAD {name}\\n")\n' + "\n" + "\n" + "@loader\n" + "def raw_customers(ctx):\n" + ' """Load customers."""\n' + ' _record("raw_customers")\n' + ' return [{"customer_id": 7}]\n' + ), + "python/nodes/loaders/loaded/raw_inventory/loader.py": ( + '"""Two loaders that record each run in the warehouse log."""\n' + "import os\n" + "from pathlib import Path\n" + "from sqlbuild.loaders import loader\n" + "def _record(name):\n" + ' with Path(os.environ["WAREHOUSE_LOG"]).open("a") as log:\n' + ' log.write(f"LOAD {name}\\n")\n' + "\n" + "\n" + "@loader\n" + "def raw_inventory(ctx):\n" + ' """Load inventory."""\n' + ' _record("raw_inventory")\n' + ' return [{"product_id": 1}]\n' + ), + "python/nodes/loaders/loaded/stage_inventory/loader.py": ( + '"""Two loaders that record each run in the warehouse log."""\n' + "import os\n" + "from pathlib import Path\n" + "from sqlbuild.loaders import loader\n" + "def _record(name):\n" + ' with Path(os.environ["WAREHOUSE_LOG"]).open("a") as log:\n' + ' log.write(f"LOAD {name}\\n")\n' + "\n" + "\n" + '@loader(write_strategy="table")\n' + "def stage_inventory(ctx):\n" ' """Stage inventory in the loader\'s own relation; no source declares it."""\n' ' _record("stage_inventory")\n' ' return [{"product_id": 2}]\n' ), - "models/customers.sql": ( + "python/nodes/loaders/loaded/__init__.py": ( + "from .raw_customers.loader import raw_customers\n" + "from .raw_inventory.loader import raw_inventory\n" + "from .stage_inventory.loader import stage_inventory\n" + ), + "sql/models/customers.sql": ( "MODEL (description 'Loaded customers.', materialized table);\n" 'SELECT customer_id FROM __source("raw_customers")\n' ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py index a3db6ac14c..ae2e88e5d2 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py @@ -30,6 +30,7 @@ person_request, provision_person, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files WAREHOUSE_REFUSAL: str = ( "the requested warehouse is not configured for this target on this location; " @@ -79,7 +80,7 @@ def test_given_an_ad_hoc_command_when_checked_and_launched_then_the_worker_runs_ expected_status="success", expected_rows=[(5,)], files={ - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Customers.', materialized table);\nSELECT 1 AS id\n" ) } @@ -221,8 +222,8 @@ def test_given_an_ad_hoc_command_when_checked_and_launched_then_the_worker_runs_ # landing mid-run would. REWRITE_CHECKOUT: str = ( "import json, pathlib\n" - "root = pathlib.Path(__file__).resolve().parent.parent\n" - "flag = root / 'rewrite.json'\n" + "root = pathlib.Path(__file__).resolve().parents[2]\n" + "flag = root.parent / f'{root.name}_rewrite.json'\n" "if flag.exists():\n" " for name, text in json.loads(flag.read_text()).items():\n" " (root / name).write_text(text)\n" @@ -238,7 +239,7 @@ def test_given_an_ad_hoc_command_when_checked_and_launched_then_the_worker_runs_ command=SEED, expected_selection=["seed:regions"], expected_run_nodes=[("seed:regions", "node", "success")], - rewrites={"seeds/seeds.yml": SEEDS_YML.format(region_type="INTEGER")}, + rewrites={"sql/seeds/seeds.yml": SEEDS_YML.format(region_type="INTEGER")}, ), AdhocVerbTestCase( description="audit reports each verified audit and its node's worst result", @@ -249,7 +250,7 @@ def test_given_an_ad_hoc_command_when_checked_and_launched_then_the_worker_runs_ ("audit:not_null:model:customers:id", "check", "success"), ("model:customers", "node", "success"), ], - rewrites={"models/customers.sql": CUSTOMERS_SQL.replace("not_null", "unique_x")}, + rewrites={"sql/models/customers.sql": CUSTOMERS_SQL.replace("not_null", "unique_x")}, ), AdhocVerbTestCase( description="test reports each verified SQL test and the model it tests", @@ -296,7 +297,7 @@ def test_given_an_ad_hoc_command_when_checked_and_launched_then_the_worker_runs_ command=["freshness", "--select", "raw_orders"], expected_selection=["source:raw_orders"], expected_run_nodes=[("source:raw_orders", "node", "success")], - rewrites={"sources/raw.yml": SOURCES_YML.format(table="missing_orders")}, + rewrites={"sql/sources/raw.yml": SOURCES_YML.format(table="missing_orders")}, ), AdhocVerbTestCase( description="a refused test run leaves its unchecked node not run", @@ -319,12 +320,12 @@ def test_given_an_ad_hoc_verb_when_the_checkout_changes_after_verification_then_ expected_status="success", expected_rows=[(5,)], files={ - "models/customers.sql": CUSTOMERS_SQL, + "sql/models/customers.sql": CUSTOMERS_SQL, "tests/unit/test_customers.sql": CUSTOMERS_TEST.format(expected=1), - "seeds/regions.csv": "region,label\nEU,Europe\n", - "seeds/seeds.yml": SEEDS_YML.format(region_type="VARCHAR"), - "sources/raw.yml": SOURCES_YML.format(table="raw_orders"), - "python/rewrite_checkout.py": REWRITE_CHECKOUT, + "sql/seeds/regions.csv": "region,label\nEU,Europe\n", + "sql/seeds/seeds.yml": SEEDS_YML.format(region_type="VARCHAR"), + "sql/sources/raw.yml": SOURCES_YML.format(table="raw_orders"), + **node_module_files("python/nodes/rewrite_checkout.py", REWRITE_CHECKOUT), } | test_case.files, ) @@ -367,7 +368,9 @@ def launch(command: list[str]) -> tuple[dict[str, Any], str, dict[str, Any]]: for command in test_case.prerequisites: assert launch(command)[2]["status"] == "success", (command, worker.log.read_text()) - _ = (worker.project / "rewrite.json").write_text(json.dumps(test_case.rewrites)) + _ = (worker.project.parent / f"{worker.project.name}_rewrite.json").write_text( + json.dumps(test_case.rewrites) + ) check, run_id, completed = launch(test_case.command) assert completed["status"] == test_case.expected_status, worker.log.read_text() assert check["selection"] == test_case.expected_selection @@ -462,7 +465,7 @@ def test_given_ad_hoc_loads_and_variables_when_launched_then_only_permitted_peop '[targets.development]\nschema = "main"\n' '[vars]\nday = "0"\n' ), - "models/daily_customers.sql": ( + "sql/models/daily_customers.sql": ( "MODEL (description 'Customers of one day.', materialized table);\n" "SELECT @@day AS day\n" ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_backfill.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_backfill.py index d6999c9e0b..bb34955a63 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_backfill.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_backfill.py @@ -31,7 +31,7 @@ expected_status="success", expected_rows=[(23,), (37,)], files={ - "models/orders.sql": Path( + "sql/models/orders.sql": Path( "benchmarks/duckshop/edge_cases/orchestration/backfill_integer.sql" ).read_text() }, @@ -46,7 +46,7 @@ expected_rows=[(23,), (37,)], launcher="docker", files={ - "models/orders.sql": Path( + "sql/models/orders.sql": Path( "benchmarks/duckshop/edge_cases/orchestration/backfill_timestamp.sql" ).read_text() }, @@ -72,7 +72,7 @@ def test_given_explicit_backfill_bounds_when_running_and_rerunning_a_group_then_ test_case, files=test_case.files | { - "sources/raw_orders.yml": "sources:\n - name: raw_orders\n description: Synthetic order windows.\n schema: main\n table: raw_orders\n", + "sql/sources/raw_orders.yml": "sources:\n - name: raw_orders\n description: Synthetic order windows.\n schema: main\n table: raw_orders\n", "orchestration/jobs/windowed_orders_job.toml": ( 'name = "windowed_orders_job"\n' 'description = "Windowed orders."\n' diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_calendar.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_calendar.py index 082f789c27..266d179253 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_calendar.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_calendar.py @@ -161,7 +161,7 @@ def test_given_a_served_calendar_when_time_passes_and_a_provider_fails_then_refr "def excluded_calendar(window):\n raise ValueError('excluded calendar must not evaluate')\n" ), **duckshop_orchestration("platform_orders"), - "providers/fulfillment.py": ( + "python/providers/fulfillment.py": ( "import json, os\nfrom pathlib import Path\nfrom datetime import timedelta, timezone\n" "from sqlbuild.provider.classes.provider import Provider\n" "class Fulfillment(Provider):\n" @@ -253,8 +253,8 @@ def test_given_a_served_calendar_when_time_passes_and_a_provider_fails_then_refr observations = [json.loads(line) for line in evaluations.read_text().splitlines()] assert [row["phase"] for row in observations] == ["setup", "evaluate", "teardown"] * 3 data.write_text(json.dumps({"offsets": [1]})) - (project / "models/stg_orders.sql").write_text( - PUBLISHABLE_FILES["models/stg_orders.sql"].replace( + (project / "sql/models/stg_orders.sql").write_text( + PUBLISHABLE_FILES["sql/models/stg_orders.sql"].replace( "CAST(5 AS INTEGER)", "CAST(19 AS INTEGER)" ) ) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_chain.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_chain.py index f77d48e2b9..4f8535dad4 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_chain.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_chain.py @@ -18,13 +18,14 @@ scheduled_worker, wait_for_run, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _CHAIN: str = '''\ import os import time from pathlib import Path -from providers.marker import MarkerProvider +from python.providers.marker import MarkerProvider from sqlbuild.assets import AssetContext, asset from sqlbuild.discovery import Discovered, Item, discover @@ -109,10 +110,11 @@ def test_given_a_cancel_mid_chain_when_rerun_from_failure_then_only_unfinished_s expected_status="cancelled", expected_rows=[], files={ - "python/steps.py": _CHAIN.format( - directory=str(tmp_path), max_parallel=test_case.max_parallel + **node_module_files( + "python/nodes/steps.py", + _CHAIN.format(directory=str(tmp_path), max_parallel=test_case.max_parallel), ), - "providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), + "python/providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), }, default_job_files={ "orchestration/jobs/annual_orders_job.toml": ( diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_write.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_write.py index 4ab8971345..9b5f7f1429 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_write.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_write.py @@ -20,6 +20,7 @@ scheduled_worker, wait_for_run, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _STEPS: str = """\ import time @@ -130,7 +131,8 @@ def test_given_steps_finishing_as_a_cancel_lands_when_a_write_is_cancelled_then_ warehouse_query="", expected_status="cancelled", expected_rows=[], - files={"python/steps.py": _STEPS.format(directory=str(tmp_path))} | test_case.files, + files={**node_module_files("python/nodes/steps.py", _STEPS.format(directory=str(tmp_path)))} + | test_case.files, default_job_files={ "orchestration/jobs/annual_orders_job.toml": ( 'name = "annual_orders_job"\n' diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_check_sensors.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_check_sensors.py index ae629893ff..159e27dafc 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_check_sensors.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_check_sensors.py @@ -35,7 +35,7 @@ "success", [(7,)], files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table, columns (\n" " amount (type INTEGER, audits [accepted_values (values [1], severity error)]),\n" " code (type VARCHAR, audits [accepted_values (values ['a'], severity warn)])));\n" @@ -67,11 +67,11 @@ "partial", [(0,)], files={ - "models/raw_orders.sql": ( + "sql/models/raw_orders.sql": ( "MODEL (description 'Raw orders.', materialized table);\n" "SELECT 1 AS order_id, 10 AS amount\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n" 'SELECT order_id, amount * 2 AS amount FROM __ref("raw_orders")\n' ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_compose.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_compose.py index 1d61339dcc..b6eb0a4223 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_compose.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_compose.py @@ -19,6 +19,7 @@ from tests.integration.src.sqlbuild.compiler.compiled_project.publication.docker.compose.helpers import ( ComposeStack, platform_receiver, + stop_location_after_check_in, wait_for_location_outage, ) @@ -41,7 +42,7 @@ def test_given_packaged_services_when_redeployed_and_restarted_then_pinned_runs_ test_case: ComposeDeploymentTestCase, ) -> None: stack: ComposeStack = ComposeStack(tmp_path) - with platform_receiver() as (port, events): + with platform_receiver() as (port, events, received_at): stack.environment["SQLBUILD_PLATFORM_WEBHOOK_URL"] = ( f"http://host.docker.internal:{port}/events" ) @@ -175,6 +176,7 @@ def test_given_packaged_services_when_redeployed_and_restarted_then_pinned_runs_ time.sleep(0.5) assert stack.query("SELECT count(*) AS count FROM sqb_runs")[0]["count"] == before stack.compose("up", "-d", "--wait", "server") + server_restarted_at: str = stack.query("SELECT now() AS now")[0]["now"] stack.wait( f"SELECT r.run_id,r.status,t.scheduled_for FROM sqb_runs r JOIN sqb_ticks t USING(tick_id) WHERE t.scheduled_for='{due}' AND r.status='success'" ) @@ -185,10 +187,16 @@ def test_given_packaged_services_when_redeployed_and_restarted_then_pinned_runs_ == [] ) - prior_events: set[str] = {event["event_id"] for event in events} - stack.compose("stop", "--timeout", "1", "location") - stopped_at: datetime = datetime.now(UTC) - broken: dict[str, Any] = wait_for_location_outage(events, prior_events) + prior_events, stopped_at = stop_location_after_check_in( + stack, events, since=server_restarted_at + ) + broken: dict[str, Any] = wait_for_location_outage( + events, + prior_events, + received_at, + location_id=stack.location_id, + stopped_at=stopped_at, + ) assert broken["payload"]["platform"]["location_id"] == stack.location_id assert broken["payload"]["platform"]["target"] == "development" assert ( @@ -277,7 +285,7 @@ def test_given_host_owned_source_when_using_the_development_overlay_then_reloade "benchmarks/duckshop/edge_cases/orchestration/container_deployment.json" ).read_text() ) - (project / "models/orders.sql").write_text( + (project / "sql/models/orders.sql").write_text( "MODEL (description 'Example orders.', materialized table);\n" + cases["second"] + "\n" ) second: dict[str, Any] = stack.wait( @@ -298,7 +306,7 @@ def test_given_host_owned_source_when_using_the_development_overlay_then_reloade "import duckdb,json; print(json.dumps(duckdb.connect('/warehouse/orders.duckdb',read_only=True).sql('SELECT order_id FROM orders').fetchall()))", ) assert json.loads(warehouse) == test_case.expected_warehouse_rows - (project / "models/orders.sql").write_text(cases["broken"] + "\n") + (project / "sql/models/orders.sql").write_text(cases["broken"] + "\n") stack.wait( "SELECT event_id FROM recall_events WHERE event_type='location_health' " "AND payload->'report'->'health'->>'kind'='compile_failed'", diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_custom_sensor.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_custom_sensor.py index 0f7f7500f3..036297d70c 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_custom_sensor.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_custom_sensor.py @@ -45,7 +45,7 @@ expected_origin="sensor", files={ **duckshop_orchestration("custom_orders"), - "providers/fulfillment.py": ( + "python/providers/fulfillment.py": ( "import json, os, time\nfrom pathlib import Path\n" "from sqlbuild.orchestration import RunRequest, SkipReason\n" "from sqlbuild.provider.classes.provider import Provider\n" diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py index 1807f403d1..5ac4ab5586 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py @@ -51,6 +51,7 @@ wait_for_warehouse_sync_health, ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") @@ -104,7 +105,7 @@ def test_given_development_when_reloaded_and_restarted_then_local_scope_and_paus + '\n[connections.local]\ndatabase = "warehouse.duckdb"\n' + '[targets.development]\nschema = "main"\n', "sqlbuild_local.toml": test_case.local_config, - "models/orders.sql": TYPE_PROOF_FILES["models/orders.sql"].replace( + "sql/models/orders.sql": TYPE_PROOF_FILES["sql/models/orders.sql"].replace( "SELECT order_id, amount", "SELECT order_id, CAST(amount AS BIGINT) AS amount" ), **duckshop_orchestration("development_orders"), @@ -258,7 +259,7 @@ def test_given_development_start_when_location_is_ready_then_project_python_is_d + PYTHON_PIPELINE_FILES["sqlbuild_project.toml"] + '\n[connections.local]\ndatabase = "warehouse.duckdb"\n' + '[targets.development]\nschema = "main"\n', - "python/probes/import_probe.py": probe, + **node_module_files("python/nodes/probes/import_probe.py", probe), }, ) executable: str = str(Path(sys.executable).with_name("sqb")) @@ -358,7 +359,7 @@ def test_given_a_missing_secret_when_it_is_added_to_the_env_file_then_the_next_r '[connections.local]\ndatabase = "warehouse.duckdb"\n' '[targets.development]\nschema = "main"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" 'SELECT CAST(code AS BIGINT) AS amount FROM __source("raw_regions")\n' ), @@ -428,7 +429,7 @@ def test_given_an_unparsable_env_file_when_a_run_starts_then_its_reason_names_th '[connections.local]\ndatabase = "warehouse.duckdb"\n' '[targets.development]\nschema = "main"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" 'SELECT CAST(code AS BIGINT) AS amount FROM __source("raw_regions")\n' ), @@ -488,7 +489,7 @@ def test_given_an_opened_development_server_when_started_then_it_publishes_takes + TYPE_PROOF_FILES["sqlbuild_project.toml"] + '\n[connections.local]\ndatabase = "warehouse.duckdb"\n' + '[targets.development]\nschema = "main"\n', - "models/orders.sql": TYPE_PROOF_FILES["models/orders.sql"].replace( + "sql/models/orders.sql": TYPE_PROOF_FILES["sql/models/orders.sql"].replace( "SELECT order_id, amount", "SELECT order_id, CAST(amount AS BIGINT) AS amount" ), }, diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev_terminal.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev_terminal.py index 2278f8f425..daa4e18df4 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev_terminal.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev_terminal.py @@ -42,6 +42,7 @@ statement_started, ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files SIGN_IN_ADAPTER: str = ( "import getpass, os, sys\nfrom pathlib import Path\n" @@ -142,7 +143,9 @@ def test_given_an_interactive_adapter_when_developing_then_sign_in_happens_once_ "sqlbuild_project.toml": DEVELOPMENT_PROJECT.replace( 'adapter = "duckdb"', 'adapter = "duckdb_sign_in"' ), - "adapters/duckdb_sign_in.py": SIGN_IN_ADAPTER.replace("READ_CODE", test_case.read_code), + "python/adapters/duckdb_sign_in.py": SIGN_IN_ADAPTER.replace( + "READ_CODE", test_case.read_code + ), }, ) environment: dict[str, str] = development_environment( @@ -246,7 +249,7 @@ def test_given_a_busy_code_location_when_signalled_then_it_exits_promptly_withou test_case: DevelopmentSignalStopTestCase, tmp_path: Path ) -> None: project: Path = tmp_path / "project" - hooks: Path = tmp_path / "hooks" + hooks: Path = tmp_path / "sql" / "hooks" write_files( project_dir=project, files=PUBLISHABLE_FILES | {"sqlbuild_project.toml": DEVELOPMENT_PROJECT}, @@ -351,7 +354,7 @@ def test_given_a_start_up_step_waiting_when_stopped_then_it_stops_cleanly_before project_dir=project, files=PUBLISHABLE_FILES | {"sqlbuild_project.toml": DEVELOPMENT_PROJECT}, ) - (project / ".sqlbuild").mkdir() + (project / ".sqlbuild").mkdir(parents=True) holder: sqlite3.Connection = sqlite3.connect( project / ".sqlbuild/control.sqlite3", isolation_level=None ) @@ -517,7 +520,7 @@ def test_given_an_env_file_when_developing_then_start_up_names_it_and_r_reloads_ + PUBLISHABLE_FILES["sqlbuild_project.toml"] + '\n[connections.local]\ndatabase = "warehouse.duckdb"\n' + '[targets.development]\nschema = "main"\n', - "python/env_probe.py": ENV_PROBE, + **node_module_files("python/nodes/env_probe.py", ENV_PROBE), }, ) env_file: Path = project / ".env" @@ -564,7 +567,7 @@ def test_given_an_env_file_when_developing_then_start_up_names_it_and_r_reloads_ ".env", ( "1 provider has missing secrets", - "providers/region.py:7", + "python/providers/region.py:7", "token \u2190 WORKER_ENV_TOKEN", "code \u2190 WORKER_ENV_REGION_CODE", "2 nodes need it (raw_regions, orders)", @@ -598,7 +601,7 @@ def test_given_a_provider_missing_secrets_when_developing_then_a_warning_names_t '[targets.development]\nschema = "main"\n' f'env_file = "{test_case.env_file_name}"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" 'SELECT CAST(code AS BIGINT) AS amount FROM __source("raw_regions")\n' ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_discovery_check.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_discovery_check.py index ef6802c339..61c24dd28e 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_discovery_check.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_discovery_check.py @@ -18,6 +18,7 @@ wait_for_generation, ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _NODES: str = '''\ import os @@ -97,7 +98,7 @@ def test_given_a_check_that_never_returns_when_the_location_is_stopped_then_it_e "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "python/plan/nodes.py": nodes, + **node_module_files("python/nodes/plan/nodes.py", nodes), }, ) log: Path = tmp_path / "location.log" @@ -158,9 +159,10 @@ def test_given_a_running_check_when_a_publish_waits_then_only_a_check_past_its_g "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "python/plan/nodes.py": _SLOW_ONCE.format( - directory=str(tmp_path), check_seconds=test_case.check_seconds + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + **node_module_files( + "python/nodes/plan/nodes.py", + _SLOW_ONCE.format(directory=str(tmp_path), check_seconds=test_case.check_seconds), ), }, ) @@ -190,7 +192,7 @@ def test_given_a_running_check_when_a_publish_waits_then_only_a_check_past_its_g assert process.poll() is None, log.read_text() assert time.monotonic() < deadline, log.read_text() time.sleep(0.2) - (project / "models/orders.sql").write_text( + (project / "sql/models/orders.sql").write_text( "MODEL (description 'Orders.');\nSELECT 2 AS order_id\n" ) publish_deadline: float = time.monotonic() + 45 diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_docker_worker.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_docker_worker.py index 23a507b8e9..c78f9d5d4b 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_docker_worker.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_docker_worker.py @@ -148,7 +148,7 @@ def test_given_a_scheduled_docker_job_when_published_then_a_pinned_worker_execut [], launcher="docker", files_after_publication={ - "models/orders.sql": "MODEL (description 'Orders.', materialized table);\nSELECT 41 AS amount\n" + "sql/models/orders.sql": "MODEL (description 'Orders.', materialized table);\nSELECT 41 AS amount\n" }, ) ], diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_empty_discovery.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_empty_discovery.py index 7adffd5fce..729a1cf1a9 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_empty_discovery.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_empty_discovery.py @@ -18,6 +18,7 @@ wait_for_log, ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _NODES: str = '''\ from pathlib import Path @@ -73,7 +74,7 @@ def test_given_no_items_when_checking_and_publishing_then_the_set_fails_and_the_ "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "python/plan/nodes.py": nodes, + **node_module_files("python/nodes/plan/nodes.py", nodes), }, ) log: Path = tmp_path / "location.log" @@ -104,7 +105,11 @@ def test_given_no_items_when_checking_and_publishing_then_the_set_fails_and_the_ f"Discovered set fulfilment_plan check failed: {_ERROR}", timeout=100, ) - (project / "python/plan/nodes.py").write_text(nodes + "\n# An edit runs it again.\n") + edited: dict[str, str] = node_module_files( + "python/nodes/plan/nodes.py", nodes + "\n# An edit runs it again.\n" + ) + for path, text in edited.items(): + (project / path).write_text(text) second: dict[str, Any] = wait_for_generation(api, "development", 2, process, log) health: str = str(location_health_reports(api)) @@ -114,3 +119,4 @@ def test_given_no_items_when_checking_and_publishing_then_the_set_fails_and_the_ kept: list[dict[str, Any]] = saved.get("result", {"items": []})["items"] assert tuple(item["id"] for item in kept) == test_case.expected_kept_items assert "fulfilment_plan" in health and "failed" in health, health + assert second["documents"]["discovered_assets"] == {"fulfilment_plan": ["fulfil"]} diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py index 31b9c12d30..ebd41fc80a 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py @@ -18,13 +18,14 @@ scheduled_worker, wait_for_run, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _STEPS: str = '''\ import os import time from pathlib import Path -from providers.marker import MarkerProvider +from python.providers.marker import MarkerProvider from sqlbuild.assets import AssetContext, asset from sqlbuild.discovery import Discovered, Item, discover @@ -109,9 +110,9 @@ def test_given_python_only_steps_when_the_worker_gets_one_ctrl_c_then_each_is_re "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb_unrecorded"\n' '[connections.local]\ndatabase = "warehouse.duckdb"\n' '[targets.development]\nschema = "main"\n', - "adapters/duckdb_unrecorded.py": _ADAPTER, - "python/steps.py": _STEPS.format(directory=str(tmp_path)), - "providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), + "python/adapters/duckdb_unrecorded.py": _ADAPTER, + **node_module_files("python/nodes/steps.py", _STEPS.format(directory=str(tmp_path))), + "python/providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), }, default_job_files={ "orchestration/jobs/annual_orders_job.toml": ( diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_item_logs.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_item_logs.py index a4849aa66a..487761bd83 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_item_logs.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_item_logs.py @@ -17,6 +17,7 @@ scheduled_worker, wait_for_run, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _LOGGING: str = '''\ import threading @@ -131,7 +132,7 @@ def test_given_items_logging_at_every_level_when_a_worker_runs_them_then_each_ke warehouse_query="", expected_status="", expected_rows=[], - files={"python/steps.py": steps} | test_case.files, + files={**node_module_files("python/nodes/steps.py", steps)} | test_case.files, default_job_files={ "orchestration/jobs/annual_orders_job.toml": ( 'name = "annual_orders_job"\n' diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_job_subsets.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_job_subsets.py index 1b339743b6..19623a08b5 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_job_subsets.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_job_subsets.py @@ -30,8 +30,8 @@ expected_status="success", expected_rows=[], files={ - "models/customers.sql": "MODEL (description 'Customers.', materialized table);\nSELECT 7 AS customer_id\n", - "models/products.sql": "MODEL (description 'Products.', materialized table);\nSELECT 3 AS product_id\n", + "sql/models/customers.sql": "MODEL (description 'Customers.', materialized table);\nSELECT 7 AS customer_id\n", + "sql/models/products.sql": "MODEL (description 'Products.', materialized table);\nSELECT 3 AS product_id\n", "orchestration/jobs/nightly_job.toml": ( 'name = "nightly_job"\n' 'description = "Orders and customers."\n' diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py index 2151168e92..0a0fb5e1cb 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py @@ -21,6 +21,7 @@ scheduled_worker, wait_for_run, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _CHAIN: str = '''\ import os @@ -88,20 +89,32 @@ def ship(ctx: AssetContext) -> None: job_select="+raw_steps", job_settings="\n[settings]\nreload = true\n", files={ - "python/loads.py": ( + "python/nodes/loads/fetch_steps/loader.py": ( "from sqlbuild.loaders import loader\n" - "from python.steps import ship\n\n\n" - "@loader(depends_on=[ship], write_strategy='table', " - "columns=[{'name': 'step', 'type': 'INTEGER'}])\n" + "from python.nodes.steps import ship\n" + "\n" + "\n" + "@loader(depends_on=[ship], write_strategy='table', columns=[{'name': 'step', 'type': 'INTEGER'}])\n" "def fetch_steps(ctx):\n" ' """Fetch the steps."""\n' - ' return [{"step": 1}]\n\n\n' + ' return [{"step": 1}]\n' + ), + "python/nodes/loads/raw_steps/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.steps import ship\n" + "from python.nodes.loads.fetch_steps.loader import fetch_steps\n" + "\n" + "\n" "@loader(depends_on=[fetch_steps])\n" "def raw_steps(ctx):\n" ' """Load the steps."""\n' ' return [{"step": 1}]\n' ), - "sources/raw.yml": ( + "python/nodes/loads/__init__.py": ( + "from .fetch_steps.loader import fetch_steps\n" + "from .raw_steps.loader import raw_steps\n" + ), + "sql/sources/raw.yml": ( "sources:\n - name: raw_steps\n description: Steps.\n" " managed: true\n write_strategy: table\n" ), @@ -126,7 +139,7 @@ def test_given_a_chain_of_three_when_the_second_is_interrupted_then_the_first_st warehouse_query="", expected_status="partial", expected_rows=[], - files={"python/steps.py": chain} | test_case.files, + files={**node_module_files("python/nodes/steps.py", chain)} | test_case.files, default_job_files={ "orchestration/jobs/annual_orders_job.toml": ( 'name = "annual_orders_job"\n' diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_parallel_items.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_parallel_items.py index 541dd65192..95351882ec 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_parallel_items.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_parallel_items.py @@ -20,6 +20,7 @@ scheduled_worker, wait_for_run, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _TOGETHER: str = '''\ import threading @@ -112,7 +113,11 @@ def test_given_concurrent_steps_using_sql_when_a_worker_runs_them_then_writes_an warehouse_query="", expected_status=test_case.expected_status, expected_rows=[], - files={"python/steps.py": _TOGETHER.format(depends_on=test_case.first_depends_on)}, + files={ + **node_module_files( + "python/nodes/steps.py", _TOGETHER.format(depends_on=test_case.first_depends_on) + ) + }, default_job_files={ "orchestration/jobs/annual_orders_job.toml": ( 'name = "annual_orders_job"\n' @@ -191,7 +196,7 @@ def test_given_steps_in_flight_when_cancelled_then_finished_steps_stay_and_are_n warehouse_query="", expected_status=test_case.expected_status, expected_rows=[], - files={"python/steps.py": steps}, + files={**node_module_files("python/nodes/steps.py", steps)}, default_job_files={ "orchestration/jobs/annual_orders_job.toml": ( 'name = "annual_orders_job"\n' diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_person_journey.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_person_journey.py index 5a452a73a1..a780b8151c 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_person_journey.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_person_journey.py @@ -193,7 +193,7 @@ def test_given_an_initialized_installation_when_people_run_and_reload_then_permi tmp_path / "location.stdout", ) as location: _ = wait_for_generation(worker.api, "development", 2, location, log) - model: Path = worker.project / "models/orders.sql" + model: Path = worker.project / "sql/models/orders.sql" original: str = model.read_text() _ = model.write_text(original.replace("23", "37")) edited: dict[str, Any] = wait_for_generation( diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_person_sql.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_person_sql.py index d926447448..be7da2ecd6 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_person_sql.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_person_sql.py @@ -56,9 +56,9 @@ def test_given_published_orders_when_cli_reads_sql_then_only_live_scoped_authori monkeypatch: pytest.MonkeyPatch, ) -> None: home: Path = tmp_path / "home" - home.mkdir() + home.mkdir(parents=True) empty: Path = tmp_path / "empty" - empty.mkdir() + empty.mkdir(parents=True) client_environment: dict[str, str] = environment({"HOME": str(home)}) client_environment.pop("DBUS_SESSION_BUS_ADDRESS", None) client_environment.pop("XDG_RUNTIME_DIR", None) @@ -197,7 +197,7 @@ def test_given_published_orders_when_cli_reads_sql_then_only_live_scoped_authori == current_snapshot(worker.api, "development")["record"]["snapshot_id"] ) assert sql["node_key"] == "model:orders" - assert sql["raw_sql"] == (worker.project / "models/orders.sql").read_text() + assert sql["raw_sql"] == (worker.project / "sql/models/orders.sql").read_text() with duckdb.connect() as verification: assert verification.sql(sql["compiled_sql"]).fetchall() == [ (*row, "orders " * 400) for row in test_case.expected_rows diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_plan_preview.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_plan_preview.py index 12a86a6898..352338af56 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_plan_preview.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_plan_preview.py @@ -71,8 +71,8 @@ 'name = "orders"\nadapter = "duckdb"\n[connections.local]\ndatabase = "warehouse.db"\n' '[targets.development]\nschema = "main"\n' ), - "seeds/raw_orders.csv": "id,ordered_at\n1,2026-01-01 00:00:00\n2,2026-01-01 01:00:00\n", - "seeds/raw_orders.yml": dedent( + "sql/seeds/raw_orders.csv": "id,ordered_at\n1,2026-01-01 00:00:00\n2,2026-01-01 01:00:00\n", + "sql/seeds/raw_orders.yml": dedent( """ seeds: - name: raw_orders @@ -85,7 +85,7 @@ """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Orders by timestamp cursor.", materialized incremental, @@ -99,7 +99,7 @@ """ ).strip() + "\n", - "models/daily_orders.sql": dedent( + "sql/models/daily_orders.sql": dedent( """ MODEL (description "Daily orders rebuilt over a lookback.", materialized incremental, @@ -115,7 +115,7 @@ """ ).strip() + "\n", - "models/order_count.sql": dedent( + "sql/models/order_count.sql": dedent( """ MODEL (description "Order count without a cursor.", materialized table); @@ -123,7 +123,7 @@ """ ).strip() + "\n", - "models/refunds.sql": dedent( + "sql/models/refunds.sql": dedent( """ MODEL (description "Refunds.", materialized table); @@ -131,7 +131,7 @@ """ ).strip() + "\n", - "sources/raw.yml": _SOURCES.format(expression=_EXPRESSION) + "\n", + "sql/sources/raw.yml": _SOURCES.format(expression=_EXPRESSION) + "\n", } _SELECTION: list[str] = [ "model:daily_orders", @@ -167,17 +167,17 @@ 'name = "orders"\nadapter = "duckdb"\n[connections.local]\ndatabase = "warehouse.db"\n' '[targets.development]\nschema = "main"\n' ), - "seeds/orders.csv": "id,ordered_at,amount\n1,2026-09-01,10\n2,2026-09-02,20\n", - "seeds/orders.yml": ( + "sql/seeds/orders.csv": "id,ordered_at,amount\n1,2026-09-01,10\n2,2026-09-02,20\n", + "sql/seeds/orders.yml": ( "seeds:\n- name: orders\n description: Orders.\n columns:\n" " - name: id\n type: INTEGER\n - name: ordered_at\n type: DATE\n" " - name: amount\n type: INTEGER\n" ), - "functions/sql/udf__adjust_amount.sql": ( + "sql/functions/sql/udf__adjust_amount.sql": ( "FUNCTION (description 'Adjusted amount.',\n arguments (amount INTEGER),\n" " returns INTEGER,\n);\n\namount + 1\n" ), - "models/order_amounts.sql": ( + "sql/models/order_amounts.sql": ( "MODEL (description 'Adjusted order amounts.',\n materialized incremental,\n" " incremental_strategy merge,\n unique_key [id],\n cursor ordered_at,\n" " cursor_type timestamp,\n cursor_grain day,\n" @@ -193,7 +193,7 @@ { "reason": "missing_secret", "provider": "region", - "path": "providers/region.py", + "path": "python/providers/region.py", "variables": ["WORKER_ENV_REGION_CODE", "WORKER_ENV_TOKEN"], "nodes": ["source:raw_regions"], "readers": ["model:orders"], @@ -232,7 +232,8 @@ PlanPreviewTestCase( description="an edited expression plans its declared columns and says so", edited_files={ - "sources/raw.yml": _SOURCES.format(expression=f"{_EXPRESSION} WHERE true") + "\n" + "sql/sources/raw.yml": _SOURCES.format(expression=f"{_EXPRESSION} WHERE true") + + "\n" }, injected_sql=(), expected_window_models=("orders",), @@ -315,7 +316,7 @@ def test_given_a_synced_location_when_a_plan_is_requested_then_it_plans_from_the [ ChangedPlanPreviewTestCase( description="an edited model is the only change the copy names", - edited_model="models/order_count.sql", + edited_model="sql/models/order_count.sql", edit=("AS order_count", "AS order_count, 1 AS batch"), expected_changed={ "counts": ["definition"], @@ -377,11 +378,13 @@ def test_given_an_edited_model_when_the_location_plans_what_changed_then_it_publ 'MODEL (description "Order count summary.", materialized table);\n\n' 'SELECT order_count FROM __ref("order_count")\n' ) - write_files(project_dir=project, files=_PROJECT_FILES | {"models/order_summary.sql": summary}) + write_files( + project_dir=project, files=_PROJECT_FILES | {"sql/models/order_summary.sql": summary} + ) built: subprocess.CompletedProcess[str] = run_sqb(project, "build", "--target", "development") assert built.returncode == 0, built.stderr - edited: str = _PROJECT_FILES["models/order_count.sql"].replace(*test_case.edit) - write_files(project_dir=project, files={"models/order_count.sql": edited}) + edited: str = _PROJECT_FILES["sql/models/order_count.sql"].replace(*test_case.edit) + write_files(project_dir=project, files={"sql/models/order_count.sql": edited}) # The selection the server freezes `sqb build --changed` to: every node a build runs. selection: list[str] = sorted([*_SELECTION, "model:order_summary", "seed:raw_orders"]) @@ -411,8 +414,8 @@ def test_given_a_served_location_when_syncs_complete_then_it_replans_only_after_ built: subprocess.CompletedProcess[str] = run_sqb(project, "build", "--target", "development") assert built.returncode == 0, built.stderr built_at: float = time.monotonic() - edited: str = _PROJECT_FILES["models/order_count.sql"].replace(*test_case.edit) - write_files(project_dir=project, files={"models/order_count.sql": edited}) + edited: str = _PROJECT_FILES["sql/models/order_count.sql"].replace(*test_case.edit) + write_files(project_dir=project, files={"sql/models/order_count.sql": edited}) control: Path = tmp_path / "control/.sqlbuild/control.sqlite3" log: Path = tmp_path / "location.log" @@ -502,7 +505,7 @@ def test_given_plan_requests_when_the_location_plans_them_then_only_variables_co project: Path = tmp_path / "project" files: dict[str, str] = _PROJECT_FILES | { "sqlbuild_project.toml": _PROJECT_FILES["sqlbuild_project.toml"] + '[vars]\nbatch = "1"\n', - "models/order_count.sql": _PROJECT_FILES["models/order_count.sql"].replace( + "sql/models/order_count.sql": _PROJECT_FILES["sql/models/order_count.sql"].replace( "AS order_count", "AS order_count, @@batch AS batch" ), "tests/unit/test_refunds.sql": _REFUNDS_TEST, @@ -533,7 +536,7 @@ def test_given_plan_requests_when_the_location_plans_them_then_only_variables_co UnknownSourceAccessTestCase( description="a source the synced state does not list is unknown, not probed", added_files={ - "sources/customers.yml": dedent( + "sql/sources/customers.yml": dedent( """ sources: - name: raw_customers @@ -546,7 +549,7 @@ def test_given_plan_requests_when_the_location_plans_them_then_only_variables_co """ ).strip() + "\n", - "models/customers.sql": ( + "sql/models/customers.sql": ( 'MODEL (description "Customers.", materialized table);\n' 'SELECT customer_id FROM __source("raw_customers")\n' ), @@ -584,7 +587,7 @@ def test_given_an_unlisted_source_when_the_location_previews_a_plan_then_its_rea '[targets.dev]\nconnection = "warehouse"\ndatabase = "ANALYTICS"\n' 'schema = "DEV"\n' ), - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_orders @@ -598,7 +601,7 @@ def test_given_an_unlisted_source_when_the_location_previews_a_plan_then_its_rea """ ).strip() + "\n", - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" 'SELECT order_id FROM __source("raw_orders")\n' ), @@ -629,7 +632,7 @@ def test_given_a_synced_copy_when_a_preview_reads_source_freshness_then_it_is_un FailedPlanTestCase( description="a full_refresh false caller of a changed function cannot rebuild", files=_FUNCTION_CALLER_FILES, - edited_file="functions/sql/udf__adjust_amount.sql", + edited_file="sql/functions/sql/udf__adjust_amount.sql", edit=("amount + 1", "amount + 100"), selection=["model:order_amounts"], expected_code="S203", @@ -686,7 +689,7 @@ def test_given_a_provider_missing_secrets_when_the_location_plans_then_the_plan_ '[connections.local]\ndatabase = "warehouse.db"\n' '[targets.dev]\nschema = "main"\n[vars]\nbatch = "1"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" 'SELECT CAST(code AS BIGINT) AS amount FROM __source("raw_regions")\n' ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_project_roles.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_project_roles.py index 47eebd80a4..dd7931c0b8 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_project_roles.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_project_roles.py @@ -55,8 +55,8 @@ def test_given_project_roles_when_published_then_person_sql_follows_selector_cov '[connections.local]\ndatabase = "warehouse.duckdb"\n' '[targets.development]\nschema = "main"\n' ), - "models/orders.sql": tagged_model("orders", "support"), - "models/customers.sql": tagged_model("customers", "pii"), + "sql/models/orders.sql": tagged_model("orders", "support"), + "sql/models/customers.sql": tagged_model("customers", "pii"), "roles.toml": roles, }, ) @@ -90,7 +90,7 @@ def test_given_project_roles_when_published_then_person_sql_follows_selector_cov assert read_person_sql(api, session, "model:customers") == (403, test_case.expected_denial) write_files( project_dir=project, - files={"models/customers.sql": tagged_model("customers", "pii, support")}, + files={"sql/models/customers.sql": tagged_model("customers", "pii, support")}, ) grown: subprocess.CompletedProcess[str] = publish_generation(project, api, 2) assert grown.returncode == 0, grown.stderr diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_publication.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_publication.py index a1cd6af2d2..6443550f54 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_publication.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_publication.py @@ -76,7 +76,7 @@ def test_given_retained_compiler_data_when_publishing_then_http_updates_atomical # DuckShop's edge-case jobs take these pools, which its project file declares. "sqlbuild_project.toml": PUBLISHABLE_FILES["sqlbuild_project.toml"] + "\n[pools]\nedge_inventory_limit = 1\nedge_products_limit = 1\n", - "models/orders.sql": PUBLISHABLE_FILES["models/orders.sql"].replace( + "sql/models/orders.sql": PUBLISHABLE_FILES["sql/models/orders.sql"].replace( "MODEL (", "MODEL (tags ['edge_case'],", 1 ), } @@ -104,7 +104,7 @@ def test_given_retained_compiler_data_when_publishing_then_http_updates_atomical assert frozenset(initial["nodes"]) == test_case.expected_nodes assert initial["nodes"]["model:orders"]["definition"]["deps"] == ["model:stg_orders"] edited: dict[str, str] = files | { - "models/stg_orders.sql": PUBLISHABLE_FILES["models/stg_orders.sql"].replace( + "sql/models/stg_orders.sql": PUBLISHABLE_FILES["sql/models/stg_orders.sql"].replace( "CAST(5 AS INTEGER)", "CAST(9 AS INTEGER)" ) } @@ -262,9 +262,9 @@ def test_given_a_code_location_when_publishing_from_cli_then_compilation_isolate assert len(metadata[0]) == 40 assert metadata[1:] == (1, "Orders Contributor", "sha256:synthetic-orders-image") - staging: Path = project_dir / "models/stg_orders.sql" + staging: Path = project_dir / "sql/models/stg_orders.sql" _ = staging.write_text( - files["models/stg_orders.sql"].replace("CAST(5 AS INTEGER)", "CAST(11 AS INTEGER)") + files["sql/models/stg_orders.sql"].replace("CAST(5 AS INTEGER)", "CAST(11 AS INTEGER)") ) assert run_cli([*arguments, "--generation", "2"]) == 0 second_output: CaptureResult[str] = capsys.readouterr() @@ -281,7 +281,7 @@ def test_given_a_code_location_when_publishing_from_cli_then_compilation_isolate assert "Location command failed." in failed_output.err assert current_snapshot(api, test_case.target)["record"] == second - _ = staging.write_text(files["models/stg_orders.sql"]) + _ = staging.write_text(files["sql/models/stg_orders.sql"]) monkeypatch.setenv("SQLBUILD_LOCATION_TOKEN", "invalid-credential") assert run_cli([*arguments, "--generation", "3"]) != 0 rejected_output: CaptureResult[str] = capsys.readouterr() diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_reload.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_reload.py index bc9730285e..9b6cb688b4 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_reload.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_reload.py @@ -78,7 +78,7 @@ def test_given_a_served_location_when_inputs_change_or_restart_then_generations_ + f"\n[connections.local]\ndatabase = {json.dumps(test_case.database)}\n" + f'\n[targets.{json.dumps(test_case.target)}]\nschema = "main"\n', **orchestration, - "sinks/orders.py": 'print("Loading orders sink", flush=True)\n', + "python/event_sinks/orders.py": 'print("Loading orders sink", flush=True)\n', } write_files(project_dir=project, files=files) _ = subprocess.run(["git", "init", "-q", str(project)], check=True, capture_output=True) @@ -101,8 +101,8 @@ def test_given_a_served_location_when_inputs_change_or_restart_then_generations_ "--target", test_case.target, ] - log: Path = project / "location.log" - publications: Path = project / "publications.jsonl" + log: Path = tmp_path / "location.log" + publications: Path = tmp_path / "publications.jsonl" with location_process(arguments, log, publications, env=environment) as process: first: dict[str, Any] = wait_for_generation(api, test_case.target, 1, process, log) first_interpreter: int = int(compiler_pid.read_text()) @@ -117,10 +117,10 @@ def test_given_a_served_location_when_inputs_change_or_restart_then_generations_ log, ) assert initial_health["report"]["session_id"] == heartbeat["report"]["session_id"] - staging: Path = project / "models/stg_orders.sql" + staging: Path = project / "sql/models/stg_orders.sql" for value in (11, 12, 13): _ = staging.write_text( - files["models/stg_orders.sql"].replace( + files["sql/models/stg_orders.sql"].replace( "CAST(5 AS INTEGER)", f"CAST({value} AS INTEGER)" ) ) @@ -143,7 +143,9 @@ def test_given_a_served_location_when_inputs_change_or_restart_then_generations_ ) assert current_snapshot(api, test_case.target)["record"] == second["record"] _ = staging.write_text( - files["models/stg_orders.sql"].replace("CAST(5 AS INTEGER)", "CAST(14 AS INTEGER)") + files["sql/models/stg_orders.sql"].replace( + "CAST(5 AS INTEGER)", "CAST(14 AS INTEGER)" + ) ) recovered: dict[str, Any] = wait_for_generation(api, test_case.target, 3, process, log) assert int(compiler_pid.read_text()) == first_interpreter @@ -269,7 +271,7 @@ def test_given_a_busy_location_when_stopped_then_its_interpreter_is_reaped( "sqlbuild_project.toml": PUBLISHABLE_FILES["sqlbuild_project.toml"] + '\n[connections.local]\ndatabase = "warehouse.duckdb"\n' + '\n[targets.development]\nschema = "main"\n', - "adapters/slow.py": ( + "python/adapters/slow.py": ( "import os, sys, time\nfrom pathlib import Path\n" f"if {test_case.blocked_command!r} in sys.argv:\n" f" Path({str(child_pid)!r}).write_text(str(os.getpid()))\n" diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_republish.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_republish.py index fb242e6ecb..d4cdb7a30d 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_republish.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_republish.py @@ -43,6 +43,7 @@ successful, ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _NODES: str = '''\ import json @@ -124,8 +125,8 @@ def test_given_a_changed_external_plan_when_republishing_then_the_readback_shows "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "python/plan/nodes.py": _NODES.format(plan=str(plan)), + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + **node_module_files("python/nodes/plan/nodes.py", _NODES.format(plan=str(plan))), }, ) executable: str = str(Path(sys.executable).with_name("sqb")) @@ -183,7 +184,7 @@ def test_given_a_saved_login_session_when_republishing_then_the_request_names_th assert binary is not None installation: tuple[Path, Path] = Path(binary), tmp_path home: Path = tmp_path / "home" - home.mkdir() + home.mkdir(parents=True) values: dict[str, str] = environment({"HOME": str(home)}) for name in ("DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR", "SQLBUILD_API_KEY"): values.pop(name, None) @@ -209,7 +210,7 @@ def test_given_a_saved_login_session_when_republishing_then_the_request_names_th "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n' 'default_target = "production"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.production]\nschema = "main"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", }, ) with gateway(tmp_path) as (origin, certificate, transport): @@ -292,9 +293,10 @@ def test_given_a_republish_waiting_on_a_check_when_the_grace_passes_then_the_rep "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "python/plan/nodes.py": _CHECKED.format( - directory=str(tmp_path), check_seconds=test_case.check_seconds + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + **node_module_files( + "python/nodes/plan/nodes.py", + _CHECKED.format(directory=str(tmp_path), check_seconds=test_case.check_seconds), ), }, ) @@ -385,8 +387,8 @@ def test_given_a_service_account_key_over_network_http_when_republishing_then_it "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "python/plan/nodes.py": _NODES.format(plan=str(plan)), + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + **node_module_files("python/nodes/plan/nodes.py", _NODES.format(plan=str(plan))), }, ) successful(administer(installation, ["create-user", "orders-admin"])) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py index 2209900d38..ee9a4c53f7 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py @@ -48,14 +48,14 @@ def test_given_a_partial_group_when_retrying_from_failure_then_successful_nodes_ test_case = replace( test_case, files={ - "models/broken_orders.sql": Path( + "sql/models/broken_orders.sql": Path( "benchmarks/duckshop/edge_cases/orchestration/rerun_from_failure.sql" ).read_text(), - "models/totals.sql": ( + "sql/models/totals.sql": ( "MODEL (description 'Downstream totals.', materialized table);\n" 'SELECT amount FROM __ref("broken_orders")\n' ), - "models/inventory.sql": ( + "sql/models/inventory.sql": ( "MODEL (description 'Independent inventory.', materialized table);\n" "SELECT 29 AS amount\n" ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rules_at_load.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rules_at_load.py index 54dffdc1d4..819464881a 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rules_at_load.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rules_at_load.py @@ -46,7 +46,7 @@ { "code": "SQBRMODEL102", "message": "SELECT * is allowed only inside dependency import CTEs", - "path": "models/orders.sql", + "path": "sql/models/orders.sql", "line": 2, } ], @@ -65,7 +65,7 @@ def test_given_a_rule_finding_when_a_location_loads_then_nothing_is_published_an project_dir=project, files={ "sqlbuild_project.toml": _PROJECT + _SELECT_STAR_RULE, - "models/orders.sql": _MODEL + test_case.model_sql + "\n", + "sql/models/orders.sql": _MODEL + test_case.model_sql + "\n", }, ) @@ -95,7 +95,7 @@ def test_given_a_published_snapshot_when_plans_are_previewed_then_rules_ran_only project_dir=project, files={ "sqlbuild_project.toml": _PROJECT + _SELECT_STAR_RULE, - "models/orders.sql": _MODEL + test_case.model_sql + "\n", + "sql/models/orders.sql": _MODEL + test_case.model_sql + "\n", }, ) built: subprocess.CompletedProcess[str] = run_sqb(project, "build", "--target", "development") diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py index 95e43dedd0..b003916e51 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py @@ -10,6 +10,7 @@ from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( NulFailureTestCase, NulLogTestCase, + PhaseEventsTestCase, PythonFailureTestCase, RunOutputTestCase, ) @@ -31,12 +32,12 @@ "success", [(17,)], files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table,\n" ' post_hooks [python("chatty")]);\n' "SELECT 17 AS amount\n" ), - "hooks/python/chatty.py": ( + "sql/hooks/python/chatty.py": ( "import sys\n\n" "from sqlbuild.hooks import hook\n\n\n" "@hook\n" @@ -65,12 +66,12 @@ "success", [(17,)], files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table,\n" ' post_hooks [python("chatty")]);\n' "SELECT 17 AS amount\n" ), - "hooks/python/chatty.py": ( + "sql/hooks/python/chatty.py": ( "from sqlbuild.hooks import hook\n\n\n" "@hook\n" "def chatty(ctx):\n" @@ -141,7 +142,7 @@ def test_given_a_node_printing_a_large_log_when_a_worker_runs_it_then_its_lines_ "partial", [(17,)], files={ - "python/assets/score_orders.py": ( + "python/nodes/assets/score_orders/asset.py": ( "from sqlbuild.assets import asset\n\n\n" "def lookup_0(row):\n" " return row['customer_segment']\n\n\n" @@ -190,12 +191,12 @@ def test_given_a_failing_python_node_when_a_worker_runs_it_then_its_run_error_is NUL_LOG_FILES: dict[str, str] = { - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table,\n" ' post_hooks [python("raw")]);\n' "SELECT 17 AS amount\n" ), - "hooks/python/raw.py": ( + "sql/hooks/python/raw.py": ( "from sqlbuild.hooks import hook\n\n\n" "@hook\n" "def raw(ctx):\n" @@ -267,7 +268,7 @@ def test_given_a_nul_in_a_ctx_log_message_when_a_worker_reports_it_then_the_log_ NUL_FAILURE_FILES: dict[str, str] = { - "python/assets/score_orders.py": ( + "python/nodes/assets/score_orders/asset.py": ( "from sqlbuild.assets import asset\n\n\n" "@asset(description='Scores orders.')\n" "def score_orders(ctx):\n" @@ -336,3 +337,67 @@ def test_given_a_nul_in_an_exception_when_its_traceback_is_reported_then_the_fai finishes, worker.log.read_text()[-4000:], ) + + +@pytest.mark.parametrize( + "test_case", + [ + PhaseEventsTestCase( + "SQLite", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "success", + [(17,)], + backend="sqlite", + expected_phases=( + ("discovered", True), + ("compiled", True), + ("matched", True), + ("connected", True), + ("inspected", True), + ("planned", True), + ("connected", True), + ("started_execution", False), + ), + ), + PhaseEventsTestCase( + "PostgreSQL", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "success", + [(17,)], + backend="postgres", + expected_phases=( + ("discovered", True), + ("compiled", True), + ("matched", True), + ("connected", True), + ("inspected", True), + ("planned", True), + ("connected", True), + ("started_execution", False), + ), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_worker_run_when_it_prepares_then_each_phase_is_a_run_event_with_its_duration( + test_case: PhaseEventsTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with ( + control_database(test_case.backend) as url, + scheduled_worker(tmp_path, monkeypatch, test_case, database_url=url) as worker, + ): + run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) + database: str = url or f"sqlite://{worker.control_store}" + phases: list[tuple[str, bool]] = [ + (str(phase), duration is not None) + for phase, duration in control_query( + database, + "SELECT payload->>'phase', duration_ms FROM recall_events " + "WHERE event_type='invocation_phase' ORDER BY occurred_at, storage_id", + ) + ] + + assert run["status"] == test_case.expected_status, worker.log.read_text()[-4000:] + assert phases == list(test_case.expected_phases), phases diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_running_items.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_running_items.py index 1a0a8f3420..1a8cd39d79 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_running_items.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_running_items.py @@ -18,6 +18,7 @@ scheduled_worker, wait_for_run, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _HELD: str = '''\ import time @@ -107,7 +108,7 @@ def test_given_running_steps_when_reading_the_server_then_only_those_with_a_slot warehouse_query="", expected_status="success", expected_rows=[], - files={"python/steps.py": steps} | test_case.files, + files={**node_module_files("python/nodes/steps.py", steps)} | test_case.files, default_job_files={ "orchestration/jobs/annual_orders_job.toml": ( 'name = "annual_orders_job"\n' diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_secret_advice.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_secret_advice.py index 2a60639e9b..e9ef333008 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_secret_advice.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_secret_advice.py @@ -71,7 +71,7 @@ def test_given_a_missing_secret_when_a_command_runs_then_the_advice_fits_that_co '[targets.development]\nschema = "main"\n' f'env_file = "{test_case.env_file_name}"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" 'SELECT CAST(code AS BIGINT) AS amount FROM __source("raw_regions")\n' ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_sensor_functions.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_sensor_functions.py index fc6d7aecb2..180322c271 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_sensor_functions.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_sensor_functions.py @@ -72,7 +72,7 @@ ) FILES: dict[str, str] = { - "providers/recorder.py": RECORDER, + "python/providers/recorder.py": RECORDER, "orchestration/jobs/orders_export_job.toml": ( 'name = "orders_export_job"\ndescription = "Export orders."\nselect = "orders"\n' ), @@ -191,7 +191,7 @@ def test_given_sensor_functions_when_events_arrive_and_people_try_them_then_tick ) monkeypatch.setenv("SQLBUILD_TEST_ENV_FILE", str(dotenv)) home: Path = tmp_path / "home" - home.mkdir() + home.mkdir(parents=True) client_environment: dict[str, str] = environment({"HOME": str(home)}) client_environment.pop("DBUS_SESSION_BUS_ADDRESS", None) client_environment.pop("XDG_RUNTIME_DIR", None) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_source_sensor.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_source_sensor.py index 54e7ee6a14..56b3b83496 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_source_sensor.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_source_sensor.py @@ -29,6 +29,7 @@ wait_for_generation, wait_for_run, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -43,7 +44,7 @@ expected_origin="sensor", files={ **duckshop_orchestration("source_orders"), - "sources/orders.yml": Path( + "sql/sources/orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/source_orders.yml" ).read_text(), }, @@ -58,13 +59,16 @@ expected_origin="sensor", files={ **duckshop_orchestration("stale_orders"), - "sources/orders.yml": Path( + "sql/sources/orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/managed_orders.yml" ).read_text(), - "python/loaders/orders.py": Path( - "benchmarks/duckshop/edge_cases/orchestration/orders_loader.py" - ).read_text(), - "source_observations.json": Path( + **node_module_files( + "python/nodes/loaders/orders.py", + Path( + "benchmarks/duckshop/edge_cases/orchestration/orders_loader.py" + ).read_text(), + ), + ".source_observations.json": Path( "benchmarks/duckshop/edge_cases/orchestration/source_stale_journey.json" ).read_text(), }, @@ -79,7 +83,7 @@ expected_origin="sensor", files={ **duckshop_orchestration("changed_source_orders"), - "sources/orders.yml": Path( + "sql/sources/orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/source_orders.yml" ).read_text(), }, @@ -94,7 +98,7 @@ def test_given_external_source_versions_when_a_location_resyncs_then_only_change ) -> None: data: dict[str, Any] = json.loads( test_case.files.get( - "source_observations.json", + ".source_observations.json", Path( "benchmarks/duckshop/edge_cases/orchestration/source_data_sensor.json" ).read_text(), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_statistics.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_statistics.py index b581d46616..2bff4fdcea 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_statistics.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_statistics.py @@ -53,10 +53,10 @@ def test_given_relation_dropped_during_sampling_when_read_fails_then_catalog_can _ = adapter.execute(connection=connection, sql=fixture["create_sql"]) adapter.close(connection) (project / "orchestration/calendars/unexpected_calendar.py").unlink() - (project / "models").mkdir() - (project / "models/orders.sql").write_text(fixture["model"]) + (project / "sql" / "models").mkdir(parents=True) + (project / "sql/models/orders.sql").write_text(fixture["model"]) hook: Path = tmp_path / "sampling-hook" - hook.mkdir() + hook.mkdir(parents=True) dropped: Path = hook / "dropped" (hook / "sitecustomize.py").write_text( "from pathlib import Path\n" diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_unknown_item_dependency.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_unknown_item_dependency.py index e5229e3d2b..2a0714f654 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_unknown_item_dependency.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_unknown_item_dependency.py @@ -5,7 +5,6 @@ import sys from pathlib import Path from typing import Any -from urllib.error import HTTPError import pytest @@ -15,14 +14,14 @@ UnknownTagTestCase, ) from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( - current_snapshot, + control_database, location_health_reports, location_process, snapshot_api, wait_for_generation, - wait_for_log, ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _PLAN: str = '''\ from sqlbuild.assets import AssetContext, asset @@ -59,6 +58,11 @@ def support(ctx: AssetContext) -> None: ''' _KEPT: frozenset[str] = frozenset({"asset:fulfil[pack]", "asset:support[triage]"}) _PLACEHOLDER: frozenset[str] = frozenset({"asset:fulfil[*]", "asset:support[triage]"}) +_TAGGED_ORDERS: str = "MODEL (description 'Orders.', tags [finance]);\nSELECT 1 AS order_id\n" +_RETAGGED_ORDERS: str = "MODEL (description 'Orders.', tags [finance]);\nSELECT 2 AS order_id\n" +_UNTAGGED_ORDERS: str = "MODEL (description 'Orders.');\nSELECT 2 AS order_id\n" +_UNKNOWN_RETURNS: str = "item 'pack' depends on tag 'returns', which no node carries" +_UNKNOWN_FINANCE: str = "item 'pack' depends on tag 'finance', which no node carries" @pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") @@ -109,7 +113,7 @@ def support(ctx: AssetContext) -> None: description="a reused set whose model was removed", first='model("inventory")', then='model("inventory")', - removed=("models/inventory.sql",), + removed=("sql/models/inventory.sql",), missing="inventory", expected_nodes=_PLACEHOLDER, ), @@ -127,15 +131,15 @@ def test_given_an_item_naming_what_the_project_lacks_when_publishing_then_only_i "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "models/inventory.sql": "MODEL (description 'Stock.');\nSELECT 1 AS item_id\n", - "python/plan/nodes.py": first, - "python/support/nodes.py": _GOOD, - "sources/raw.yml": ( + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "sql/models/inventory.sql": "MODEL (description 'Stock.');\nSELECT 1 AS item_id\n", + **node_module_files("python/nodes/plan/nodes.py", first), + "python/nodes/support/nodes/asset.py": _GOOD, + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n schema: main\n" ), - "seeds/regions.csv": "region_id\n1\n", - "seeds/regions.yml": ( + "sql/seeds/regions.csv": "region_id\n1\n", + "sql/seeds/regions.yml": ( "seeds:\n - name: regions\n description: Regions.\n columns:\n" " - name: region_id\n type: INTEGER\n" ), @@ -163,10 +167,14 @@ def test_given_an_item_naming_what_the_project_lacks_when_publishing_then_only_i arguments, log, tmp_path / "location.stdout", env=environment ) as process: _ = wait_for_generation(api, "development", 1, process, log) - (project / "models/orders.sql").write_text( + (project / "sql/models/orders.sql").write_text( "MODEL (description 'Orders.');\nSELECT 2 AS order_id\n" ) - (project / "python/plan/nodes.py").write_text(_PLAN.format(dependency=test_case.then)) + edited: dict[str, str] = node_module_files( + "python/nodes/plan/nodes.py", _PLAN.format(dependency=test_case.then) + ) + for path, text in edited.items(): + (project / path).write_text(text) for removed in test_case.removed: (project / removed).unlink() published: dict[str, Any] = wait_for_generation(api, "development", 2, process, log) @@ -206,8 +214,10 @@ def test_given_an_item_naming_what_the_project_lacks_when_compiling_with_discove "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "python/plan/nodes.py": _PLAN.format(dependency=test_case.dependency), + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + **node_module_files( + "python/nodes/plan/nodes.py", _PLAN.format(dependency=test_case.dependency) + ), }, ) @@ -230,15 +240,61 @@ def test_given_an_item_naming_what_the_project_lacks_when_compiling_with_discove "test_case", [ UnknownTagTestCase( - description="an unknown tag still fails the whole publish", - dependency='tag("returns")', - expected_error="asset 'fulfil[pack]' depends on tag 'returns', which no node carries", - expected_status=404, - ) + description="an unknown tag on first discovery fails only its set, which compiles as its placeholder on SQLite", + backend="sqlite", + first='tag("returns")', + edits={"sql/models/orders.sql": _RETAGGED_ORDERS}, + expected_nodes=_PLACEHOLDER, + expected_error=_UNKNOWN_RETURNS, + ), + UnknownTagTestCase( + description="an item that newly names an unknown tag keeps its set's last good items on SQLite", + backend="sqlite", + first='model("orders")', + edits=node_module_files( + "python/nodes/plan/nodes.py", _PLAN.format(dependency='tag("returns")') + ), + expected_nodes=_KEPT, + expected_error=_UNKNOWN_RETURNS, + ), + UnknownTagTestCase( + description="last good items naming a tag the project dropped compile as the placeholder on SQLite", + backend="sqlite", + first='tag("finance")', + edits={"sql/models/orders.sql": _UNTAGGED_ORDERS}, + expected_nodes=_PLACEHOLDER, + expected_error=_UNKNOWN_FINANCE, + ), + UnknownTagTestCase( + description="an unknown tag on first discovery fails only its set, which compiles as its placeholder on PostgreSQL", + backend="postgres", + first='tag("returns")', + edits={"sql/models/orders.sql": _RETAGGED_ORDERS}, + expected_nodes=_PLACEHOLDER, + expected_error=_UNKNOWN_RETURNS, + ), + UnknownTagTestCase( + description="an item that newly names an unknown tag keeps its set's last good items on PostgreSQL", + backend="postgres", + first='model("orders")', + edits=node_module_files( + "python/nodes/plan/nodes.py", _PLAN.format(dependency='tag("returns")') + ), + expected_nodes=_KEPT, + expected_error=_UNKNOWN_RETURNS, + ), + UnknownTagTestCase( + description="last good items naming a tag the project dropped compile as the placeholder on PostgreSQL", + backend="postgres", + first='tag("finance")', + edits={"sql/models/orders.sql": _UNTAGGED_ORDERS}, + expected_nodes=_PLACEHOLDER, + expected_error=_UNKNOWN_FINANCE, + ), ], ids=lambda case: case.description, ) -def test_given_an_item_naming_a_tag_no_node_carries_when_publishing_then_nothing_publishes( +def test_given_an_item_naming_a_tag_no_node_carries_when_publishing_then_only_its_set_fails( test_case: UnknownTagTestCase, tmp_path: Path ) -> None: project: Path = tmp_path / "project" @@ -248,16 +304,21 @@ def test_given_an_item_naming_a_tag_no_node_carries_when_publishing_then_nothing "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' '[targets.development]\nschema = "main"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "python/plan/nodes.py": _PLAN.format(dependency=test_case.dependency), - "python/support/nodes.py": _GOOD.replace( + "sql/models/orders.sql": _TAGGED_ORDERS, + **node_module_files( + "python/nodes/plan/nodes.py", _PLAN.format(dependency=test_case.first) + ), + "python/nodes/support/nodes/asset.py": _GOOD.replace( 'after = (model("orders"), source("raw_orders"), seed("regions"), job("orders_job"))', 'after = (model("orders"),)', ), }, ) log: Path = tmp_path / "location.log" - with snapshot_api(tmp_path / "control") as api: + with ( + control_database(test_case.backend) as database_url, + snapshot_api(tmp_path / "control", database_url=database_url) as api, + ): arguments: list[str] = [ str(Path(sys.executable).with_name("sqb")), "--project-dir", @@ -275,8 +336,16 @@ def test_given_an_item_naming_a_tag_no_node_carries_when_publishing_then_nothing with location_process( arguments, log, tmp_path / "location.stdout", env=environment ) as process: - wait_for_log(process, log, test_case.expected_error, timeout=60) - with pytest.raises(HTTPError) as unpublished: - _ = current_snapshot(api, "development") + _ = wait_for_generation(api, "development", 1, process, log) + for path, text in test_case.edits.items(): + (project / path).write_text(text) + published: dict[str, Any] = wait_for_generation(api, "development", 2, process, log) + health: str = str(location_health_reports(api)) - assert unpublished.value.code == test_case.expected_status + assets: set[str] = set(filter(lambda key: key.startswith("asset:"), published["nodes"])) + assert assets == test_case.expected_nodes, log.read_text() + saved: dict[str, Any] = published["documents"]["discovered"] + assert saved["support_plan"]["status"] == "ok" + assert saved["fulfilment_plan"]["status"] == "failed" + assert test_case.expected_error in saved["fulfilment_plan"]["error"] + assert "fulfilment_plan" in health and "failed" in health, health diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_catalog.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_catalog.py index 670d19029b..37f43e5edd 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_catalog.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_catalog.py @@ -201,7 +201,7 @@ def test_given_served_location_when_catalog_changes_then_facts_and_current_proje _ = adapter.execute(connection=connection, sql=fixture["create_sql"]) adapter.close(connection) (project / "orchestration/calendars/unexpected_calendar.py").unlink() - write_files(project_dir=project, files={"models/orders.sql": fixture["model"]}) + write_files(project_dir=project, files={"sql/models/orders.sql": fixture["model"]}) expected: dict[str, Any] = fixture["record"] | {"relation_type": test_case.expected_table_type} control: Path = tmp_path / "control/.sqlbuild/control.sqlite3" log: Path = tmp_path / "location.log" diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_metadata.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_metadata.py index 154523ccb2..1f6db0e237 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_metadata.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_metadata.py @@ -448,7 +448,7 @@ def test_given_a_served_location_when_state_event_history_is_rebuilt_and_retaine test_case.append_history(adapter, connection, fixture) adapter.close(connection) (project / "orchestration/calendars/unexpected_calendar.py").unlink() - write_files(project_dir=project, files={"models/orders.sql": fixture["model"]}) + write_files(project_dir=project, files={"sql/models/orders.sql": fixture["model"]}) with snapshot_api(tmp_path / "control") as api: log: Path = tmp_path / "location.log" control: Path = tmp_path / "control/.sqlbuild/control.sqlite3" @@ -995,7 +995,7 @@ def test_given_a_served_location_when_warehouse_history_changes_then_periodic_re (project / "orchestration/calendars/unexpected_calendar.py").unlink() write_files( project_dir=project, - files={"models/orders.sql": fixture["model"]}, + files={"sql/models/orders.sql": fixture["model"]}, ) with snapshot_api(tmp_path / "control") as api: log: Path = tmp_path / "location.log" @@ -1127,7 +1127,7 @@ def test_given_a_duckdb_location_when_its_sync_completes_then_it_opens_no_resume (project / "orchestration/calendars/unexpected_calendar.py").unlink() with (project / "sqlbuild_project.toml").open("a") as config: _ = config.write(fixture["dynamic"]) - write_files(project_dir=project, files={"models/orders.sql": fixture["model"]}) + write_files(project_dir=project, files={"sql/models/orders.sql": fixture["model"]}) with snapshot_api(tmp_path / "control") as api: log: Path = tmp_path / "location.log" with location_process( @@ -1201,7 +1201,7 @@ def test_given_durable_mirror_when_late_rows_arrive_then_incremental_overlap_pre (project / "orchestration/calendars/unexpected_calendar.py").unlink() write_files( project_dir=project, - files={"models/orders.sql": "MODEL (description 'Orders.'); SELECT 17 AS amount"}, + files={"sql/models/orders.sql": "MODEL (description 'Orders.'); SELECT 17 AS amount"}, ) # Every build of the one node stays, so the overlap, not retention, decides what is mirrored. with snapshot_api( @@ -1506,9 +1506,9 @@ def test_given_change_tokens_when_a_served_location_resyncs_then_only_changed_or "benchmarks/duckshop/edge_cases/orchestration/automatic_warehouse_history.json" ).read_text() ) - write_files(project_dir=project, files={"models/orders.sql": fixture["model"]}) + write_files(project_dir=project, files={"sql/models/orders.sql": fixture["model"]}) hook: Path = tmp_path / "token-hook" - hook.mkdir() + hook.mkdir(parents=True) tokens: Path = hook / "tokens.json" reads: Path = hook / "reads.log" sessions: Path = hook / "sessions.log" @@ -1676,9 +1676,9 @@ def test_given_a_served_location_when_a_sync_has_many_pages_then_pages_run_back_ "benchmarks/duckshop/edge_cases/orchestration/automatic_warehouse_history.json" ).read_text() ) - write_files(project_dir=project, files={"models/orders.sql": fixture["model"]}) + write_files(project_dir=project, files={"sql/models/orders.sql": fixture["model"]}) shim: Path = tmp_path / "git-shim" - shim.mkdir() + shim.mkdir(parents=True) calls: Path = shim / "calls.log" calls.write_text("") (shim / "git").write_text(f'#!/bin/sh\necho "$*" >> {calls}\nexec {shutil.which("git")} "$@"\n') diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_work.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_work.py index 6a6d928a3f..dc54eb798b 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_work.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_work.py @@ -56,7 +56,7 @@ def test_given_a_published_location_when_an_owner_requests_work_then_results_ret "sqlbuild_project.toml": PUBLISHABLE_FILES["sqlbuild_project.toml"] + f"\n[connections.local]\ndatabase = {json.dumps(test_case.database)}\n" + '\n[targets."preview #1"]\nschema = "main"\n', - "adapters/slow.py": ( + "python/adapters/slow.py": ( "import os, sys, time\nfrom pathlib import Path\n" f"if 'debug' in sys.argv and Path({str(blocked)!r}).exists():\n" f" Path({str(child_pid)!r}).write_text(str(os.getpid()))\n" @@ -160,8 +160,8 @@ def test_given_a_published_location_when_an_owner_requests_work_then_results_ret enqueue, env=owner_environment, capture_output=True, text=True, check=True ) _ = wait_for_interpreter(process, child_pid, log) - _ = (project / "models/stg_orders.sql").write_text( - PUBLISHABLE_FILES["models/stg_orders.sql"].replace( + _ = (project / "sql/models/stg_orders.sql").write_text( + PUBLISHABLE_FILES["sql/models/stg_orders.sql"].replace( "CAST(5 AS INTEGER)", "CAST(17 AS INTEGER)" ) ) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py index a565813818..a987e2cf1d 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py @@ -64,6 +64,7 @@ worker_result, ) from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files ENV_FILE_REGION_FILES: dict[str, str] = { ".env": "WORKER_ENV_REGION_CODE=42\nWORKER_ENV_TOKEN=worker-token\n" @@ -126,7 +127,7 @@ expected_totals=("cancelled", None), expected_marts_started=False, files={ - "models/broken_orders.sql": ( + "sql/models/broken_orders.sql": ( "MODEL (description 'Critical orders.', materialized table, critical true);\n" "WITH source(value) AS (VALUES ('invalid')) SELECT CAST(value AS INTEGER) AS amount FROM source\n" ), @@ -139,23 +140,23 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail test_case: GroupExecutionTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: project_dir: Path = tmp_path / "project" - project_dir.mkdir() + project_dir.mkdir(parents=True) with duckdb.connect(str(project_dir / "warehouse.duckdb")) as warehouse: warehouse.execute("CREATE TABLE broken_orders AS SELECT 99 AS amount") test_case = replace( test_case, files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Independent orders.', materialized table);\n" 'SELECT amount FROM __ref("stg_orders")\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\nSELECT 11 AS amount\n" ), - "models/broken_orders.sql": ( + "sql/models/broken_orders.sql": ( "MODEL (description 'Source values.', materialized table);\n" + test_case.model_sql ), - "models/totals.sql": ( + "sql/models/totals.sql": ( "MODEL (description 'Dependent totals.', materialized table);\n" 'SELECT amount FROM __ref("broken_orders")\n' ), @@ -238,15 +239,15 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "partial", [(0,)], files={ - "models/raw_orders.sql": ( + "sql/models/raw_orders.sql": ( "MODEL (description 'Raw orders.', materialized table);\n" "SELECT 1 AS order_id, 10 AS amount\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n" 'SELECT order_id, amount * 2 AS amount FROM __ref("raw_orders")\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals.', materialized table);\n" 'SELECT SUM(amount) AS total FROM __ref("stg_orders")\n' ), @@ -280,15 +281,15 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "partial", [(0,)], files={ - "models/raw_orders.sql": ( + "sql/models/raw_orders.sql": ( "MODEL (description 'Raw orders.', materialized table);\n" "SELECT 1 AS order_id, 10 AS amount\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n" 'SELECT order_id, amount * 2 AS amount FROM __ref("raw_orders")\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals.', materialized table);\n" 'SELECT SUM(amount) AS total FROM __ref("stg_orders")\n' ), @@ -322,15 +323,15 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "partial", [(0,)], files={ - "models/raw_orders.sql": ( + "sql/models/raw_orders.sql": ( "MODEL (description 'Raw orders.', materialized table);\n" "SELECT 1 AS order_id, 10 AS amount\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n" 'SELECT order_id, amount * 2 AS amount FROM __ref("raw_orders")\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals.', materialized table);\n" 'SELECT SUM(amount) AS total FROM __ref("stg_orders")\n' ), @@ -364,20 +365,20 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "partial", [(0,)], files={ - "functions/sql/udf__order_band.sql": ( + "sql/functions/sql/udf__order_band.sql": ( "FUNCTION (description 'Size band of an order amount.', " "arguments (amount INT), returns VARCHAR);\n" "CASE WHEN amount >= 20 THEN 'large' ELSE 'small' END\n" ), - "models/raw_orders.sql": ( + "sql/models/raw_orders.sql": ( "MODEL (description 'Raw orders.', materialized table);\n" "SELECT 1 AS order_id, 10 AS amount\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n" 'SELECT order_id, __udf("udf__order_band")(amount) AS band FROM __ref("raw_orders")\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals.', materialized table);\n" 'SELECT band, COUNT(*) AS orders FROM __ref("stg_orders") GROUP BY band\n' ), @@ -413,20 +414,20 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "success", [(2,)], files={ - "functions/sql/udf__order_band.sql": ( + "sql/functions/sql/udf__order_band.sql": ( "FUNCTION (description 'Size band of an order amount.', " "arguments (amount INT), returns VARCHAR);\n" "CASE WHEN amount >= 20 THEN 'large' ELSE 'small' END\n" ), - "models/raw_orders.sql": ( + "sql/models/raw_orders.sql": ( "MODEL (description 'Raw orders.', materialized table);\n" "SELECT 1 AS order_id, 10 AS amount\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', materialized table);\n" 'SELECT order_id, __udf("udf__order_band")(amount) AS band FROM __ref("raw_orders")\n' ), - "models/order_totals.sql": ( + "sql/models/order_totals.sql": ( "MODEL (description 'Order totals.', materialized table);\n" 'SELECT band, COUNT(*) AS orders FROM __ref("stg_orders") GROUP BY band\n' ), @@ -457,16 +458,16 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "success", [(1,)], files={ - "functions/sql/udf__band.sql": ( + "sql/functions/sql/udf__band.sql": ( "FUNCTION (description 'Band.', arguments (amount INT), returns VARCHAR);\n" "CASE WHEN amount >= 20 THEN 'large' ELSE 'small' END\n" ), - "models/parity_lookup.sql": ( + "sql/models/parity_lookup.sql": ( "MODEL (description 'Lookup.', materialized table, " "columns (id (type INTEGER, audits [not_null])));\n" "SELECT CAST(NULL AS INTEGER) AS id\n" ), - "models/parity_events.sql": ( + "sql/models/parity_events.sql": ( "MODEL (description 'Events.', materialized incremental, " "incremental_strategy append);\n" 'SELECT 1 AS event_id, __udf("udf__band")(5) AS band\n' @@ -475,7 +476,7 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "TEST();\n\nWITH\n__ref__parity_lookup AS (SELECT 1 AS id),\n" "__expected__parity_events AS (SELECT 99 AS event_id, 'x' AS band)\nSELECT 1\n" ), - "audits/singular/events_have_lookups.sql": ( + "sql/audits/singular/events_have_lookups.sql": ( 'AUDIT (name "events_have_lookups", severity error);\n' 'SELECT e.event_id FROM __ref("parity_events") e ' 'LEFT JOIN __ref("parity_lookup") l ON e.event_id = l.id WHERE l.id IS NULL\n' @@ -531,18 +532,18 @@ def test_given_a_failing_unit_test_when_a_worker_builds_then_its_model_fails_and "partial", [(2,), (11,)], files={ - "sources/raw.yml": Path( + "sql/sources/raw.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/worker_freshness_skip.yml" ).read_text(), - "models/stale_orders.sql": ( + "sql/models/stale_orders.sql": ( "MODEL (description 'Stale orders.', materialized table);\n" 'SELECT order_id FROM __source("raw_orders")\n' ), - "models/late_orders.sql": ( + "sql/models/late_orders.sql": ( "MODEL (description 'Late orders.', materialized table);\n" 'SELECT order_id FROM __source("raw_orders")\n' ), - "models/returns.sql": ( + "sql/models/returns.sql": ( "MODEL (description 'Returns.', materialized table);\n" 'SELECT return_id FROM __source("raw_returns")\n' ), @@ -594,11 +595,11 @@ def test_given_a_stale_source_when_a_worker_builds_then_blocked_nodes_finish_ski expected_status="partial", expected_rows=[(0,)], files={ - "seeds/order_codes.csv": "code\nA\nZ\n", - "seeds/order_codes.yml": Path( + "sql/seeds/order_codes.csv": "code\nA\nZ\n", + "sql/seeds/order_codes.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/worker_failed_seed_audit.yml" ).read_text(), - "models/coded_orders.sql": ( + "sql/models/coded_orders.sql": ( "MODEL (description 'Coded orders.', materialized table);\n" 'SELECT code FROM __seed("order_codes")\n' ), @@ -656,7 +657,7 @@ def test_given_a_failing_seed_audit_when_a_worker_builds_then_its_seed_fails_wit pools={"orders_limit": 2, "inventory_limit": 2}, launcher_settings={"pool_caps": {"orders_limit": 1, "inventory_limit": 1}}, files={ - "models/inventory.sql": ( + "sql/models/inventory.sql": ( "MODEL (description 'Inventory.', materialized table);\nSELECT 23 AS amount\n" ), "orchestration/jobs/orders_job.toml": ( @@ -736,14 +737,14 @@ def test_given_opposing_group_limits_when_scheduled_then_each_group_holds_every_ [ SnapshotWorkerTestCase( description="unselected dependency drift", - model_file="models/stg_orders.sql", + model_file="sql/models/stg_orders.sql", original_sql="CAST(5 AS INTEGER)", replacement_sql="CAST(17 AS INTEGER)", expected_error="node content differs", ), SnapshotWorkerTestCase( description="selected model drift", - model_file="models/orders.sql", + model_file="sql/models/orders.sql", original_sql="SELECT order_id, amount", replacement_sql="SELECT order_id, amount * CAST(2 AS BIGINT) AS amount", expected_error="node content differs", @@ -878,12 +879,15 @@ def test_given_a_retained_baseline_when_starting_a_worker_then_verification_and_ "success", [(1,)], files={ - "sources/orders.yml": Path( + "sql/sources/orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/managed_orders.yml" ).read_text(), - "python/loaders/orders.py": Path( - "benchmarks/duckshop/edge_cases/orchestration/orders_loader.py" - ).read_text(), + **node_module_files( + "python/nodes/loaders/orders.py", + Path( + "benchmarks/duckshop/edge_cases/orchestration/orders_loader.py" + ).read_text(), + ), }, ), WorkerExecutionTestCase( @@ -977,7 +981,7 @@ def test_given_a_retained_baseline_when_starting_a_worker_then_verification_and_ [(23,)], expected_node_count=2, files={ - "sources/raw_orders.yml": Path( + "sql/sources/raw_orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/source_orders.yml" ).read_text(), **duckshop_orchestration("upstream_source_orders"), @@ -998,7 +1002,7 @@ def test_given_a_retained_baseline_when_starting_a_worker_then_verification_and_ [(0,)], expected_node_counts={"success": 1, "failed": 1}, files={ - "sources/raw_orders.yml": Path( + "sql/sources/raw_orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/source_orders.yml" ).read_text(), **duckshop_orchestration("upstream_source_orders"), @@ -1035,7 +1039,7 @@ def test_given_a_retained_baseline_when_starting_a_worker_then_verification_and_ [(46,)], expected_node_count=2, files={ - "functions/sql/order_total.sql": ( + "sql/functions/sql/order_total.sql": ( "FUNCTION (description 'Order total.', " "arguments (amount BIGINT), returns BIGINT);\nSELECT amount * 2\n" ) @@ -1049,7 +1053,7 @@ def test_given_a_retained_baseline_when_starting_a_worker_then_verification_and_ [(31,)], expected_node_count=2, files={ - "functions/sql/order_amounts.sql": ( + "sql/functions/sql/order_amounts.sql": ( "FUNCTION (description 'Order amounts.', returns table (amount BIGINT));\n" "SELECT CAST(31 AS BIGINT) AS amount\n" ) @@ -1264,7 +1268,7 @@ def test_given_a_busy_control_store_when_a_build_runs_then_the_scheduler_retries "SELECT amount FROM orders", "success", [(17,)], - files={"python/checks/orders.py": "initial"}, + files={"python/nodes/checks/orders/checks.py": "initial"}, ), WorkerExecutionTestCase( "attached Python check changed after publication", @@ -1272,8 +1276,8 @@ def test_given_a_busy_control_store_when_a_build_runs_then_the_scheduler_retries "SELECT amount FROM orders", "failed", [], - files={"python/checks/orders.py": "initial"}, - files_after_publication={"python/checks/orders.py": "changed"}, + files={"python/nodes/checks/orders/checks.py": "initial"}, + files_after_publication={"python/nodes/checks/orders/checks.py": "changed"}, ), ], ids=lambda case: case.description, @@ -1347,7 +1351,10 @@ def test_given_an_attached_check_when_a_worker_executes_then_its_own_outcome_is_ Path("benchmarks/duckshop/edge_cases/orchestration/attached_checks.json").read_text() ) test_case = replace( - test_case, files={"python/checks/orders.py": fixture[test_case.description]} + test_case, + files={ + **node_module_files("python/nodes/checks/orders.py", fixture[test_case.description]) + }, ) with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) @@ -1386,11 +1393,11 @@ def test_given_an_attached_check_when_a_worker_executes_then_its_own_outcome_is_ "success", [(59,)], files={ - "python/checks/orders.py": "failed", + "python/nodes/checks/orders/checks.py": "failed", "orchestration/jobs/annual_orders_job.toml": "on_failure_job", "orchestration/jobs/refresh_inventory_job.toml": "on_failure_destination", "orchestration/sensors/failed_orders_sensor.py": "on_failure_sensor", - "models/inventory.sql": "inventory", + "sql/models/inventory.sql": "inventory", }, ), WorkerExecutionTestCase( @@ -1400,11 +1407,11 @@ def test_given_an_attached_check_when_a_worker_executes_then_its_own_outcome_is_ "success", [(59,)], files={ - "python/checks/orders.py": "failed", + "python/nodes/checks/orders/checks.py": "failed", "orchestration/jobs/annual_orders_job.toml": "on_failure_job", "orchestration/jobs/refresh_inventory_job.toml": "on_failure_destination", "orchestration/sensors/failed_orders_sensor.py": "on_check_event_sensor", - "models/inventory.sql": "inventory", + "sql/models/inventory.sql": "inventory", }, ), ], @@ -1450,11 +1457,11 @@ def test_given_an_attached_check_failure_when_a_sensor_observes_it_then_its_dest "cancelled", [(17,)], files={ - "python/checks/orders.py": "cancelled", + "python/nodes/checks/orders/checks.py": "cancelled", "orchestration/jobs/annual_orders_job.toml": "on_failure_job", "orchestration/jobs/refresh_inventory_job.toml": "on_failure_destination", "orchestration/sensors/failed_orders_sensor.py": "on_failure_sensor", - "models/inventory.sql": "inventory", + "sql/models/inventory.sql": "inventory", }, ), ], @@ -1585,7 +1592,7 @@ def test_given_a_real_group_completion_when_a_run_sensor_matches_then_one_destin [(67,)], expected_origin="sensor", files={ - "models/stg_orders.sql": "MODEL (description 'Staging orders.');\nSELECT 71 AS amount\n", + "sql/models/stg_orders.sql": "MODEL (description 'Staging orders.');\nSELECT 71 AS amount\n", "orchestration/jobs/source_orders_job.toml": ( 'name = "source_orders_job"\ndescription = "Source orders."\nselect = "orders"\n' ), @@ -1683,10 +1690,10 @@ def test_given_an_executing_scheduled_worker_when_cancelled_then_the_statement_s '[connections.local]\ndatabase = "warehouse.duckdb"\n' '[targets.development]\nschema = "main"\nconcurrency = 2\n' ), - "models/refunds.sql": ( + "sql/models/refunds.sql": ( "MODEL (description 'Refunds.', materialized table);\nSELECT 2 AS amount\n" ), - "models/returns.sql": ( + "sql/models/returns.sql": ( "MODEL (description 'Returns.', materialized table);\n" 'SELECT amount FROM __ref("orders")\n' ), @@ -1735,7 +1742,7 @@ def test_given_a_rejected_node_report_when_concurrent_then_the_run_stops_before_ "cancelled", [(0,)], files={ - "models/totals.sql": ( + "sql/models/totals.sql": ( "MODEL (description 'Downstream totals.', materialized table);\n" 'SELECT amount FROM __ref("orders")\n' ), @@ -2089,7 +2096,7 @@ def test_given_a_provider_missing_secrets_when_a_location_publishes_then_its_hea '[connections.local]\ndatabase = "warehouse.duckdb"\n' f'[targets.development]\nschema = "main"\nallow_missing_secrets = [{allowed}]\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" 'SELECT CAST(code AS BIGINT) AS amount FROM __source("raw_regions")\n' ), @@ -2103,7 +2110,7 @@ def test_given_a_provider_missing_secrets_when_a_location_publishes_then_its_hea assert health["providers"] == [ { "provider": "region", - "path": "providers/region.py", + "path": "python/providers/region.py", "settings": [ {"field": "token", "variable": "WORKER_ENV_TOKEN", "line": 7}, {"field": "code", "variable": "WORKER_ENV_REGION_CODE", "line": 8}, @@ -2183,7 +2190,7 @@ def test_given_a_provider_missing_secrets_when_a_location_publishes_then_its_hea "SELECT amount FROM orders", "success", [(23,)], - files={"sources/raw.yml": FRESHNESS_SOURCES}, + files={"sql/sources/raw.yml": FRESHNESS_SOURCES}, ), ["freshness", "--select", "raw_orders"], "success", @@ -2221,38 +2228,41 @@ def test_given_a_worker_run_when_its_output_is_captured_then_it_holds_no_json_re NODE_RESULT_FILES: dict[str, str] = { - "python/loaders.py": ( - "from sqlbuild.compiler.python_nodes.types import SkipMode\n" - "from sqlbuild.loaders import loader\n\n\n" - "@loader\n" - "def raw_gate(ctx):\n" - ' """A gate that stays closed."""\n' - ' return ctx.skip(reason="gate closed", mode=SkipMode.HARD)\n\n\n' - "@loader(depends_on=[raw_gate])\n" - "def raw_gated(ctx):\n" - ' """Rows behind the gate."""\n' - ' return [{"gated_id": 1}]\n\n\n' - "@loader\n" - "def raw_events(ctx):\n" - ' """Three events."""\n' - ' return [{"event_id": event_id} for event_id in range(3)]\n' + **node_module_files( + "python/nodes/loaders/node_results.py", + ( + "from sqlbuild.compiler.python_nodes.types import SkipMode\n" + "from sqlbuild.loaders import loader\n\n\n" + "@loader\n" + "def raw_gate(ctx):\n" + ' """A gate that stays closed."""\n' + ' return ctx.skip(reason="gate closed", mode=SkipMode.HARD)\n\n\n' + "@loader(depends_on=[raw_gate])\n" + "def raw_gated(ctx):\n" + ' """Rows behind the gate."""\n' + ' return [{"gated_id": 1}]\n\n\n' + "@loader\n" + "def raw_events(ctx):\n" + ' """Three events."""\n' + ' return [{"event_id": event_id} for event_id in range(3)]\n' + ), ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_gated\n description: Gated rows.\n managed: true\n" " write_strategy: table\n" " - name: raw_events\n description: Events.\n managed: true\n" " write_strategy: table\n" ), - "models/events.sql": ( + "sql/models/events.sql": ( "MODEL (description 'Events.', materialized table);\n" 'SELECT event_id FROM __source("raw_events")\n' ), - "models/event_view.sql": ( + "sql/models/event_view.sql": ( "MODEL (description 'Events as a view.', materialized view);\n" 'SELECT event_id FROM __ref("events")\n' ), - "models/gated.sql": ( + "sql/models/gated.sql": ( "MODEL (description 'Gated rows.', materialized table);\n" 'SELECT gated_id FROM __source("raw_gated")\n' ), @@ -2293,7 +2303,7 @@ def test_given_a_worker_run_when_its_output_is_captured_then_it_holds_no_json_re [], files=NODE_RESULT_FILES | { - "python/broken.py": ( + "python/nodes/broken.py": ( "import os\n" "if 'SQLBUILD_RUN_TOKEN' in os.environ:\n" " raise RuntimeError('this module breaks inside a worker')\n" diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_audits.py b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_audits.py index d10fcc3fb3..35da12931d 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_audits.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_audits.py @@ -105,7 +105,7 @@ def test_given_audit_when_compiling_then_native_project_holds_its_attachment( NativeAuditErrorTestCase( description="attachment of an unknown generic audit", files={ - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (description 'Customers.', columns (customer_id (type INTEGER," " audits [at_most(maximum 3)])));\nSELECT 1 AS customer_id\n" ), @@ -115,13 +115,13 @@ def test_given_audit_when_compiling_then_native_project_holds_its_attachment( NativeAuditErrorTestCase( description="singular audit reading an unknown model", files={ - "audits/singular/orders_have_customers.sql": ( + "sql/audits/singular/orders_have_customers.sql": ( "AUDIT (name orders_have_customers);\n" 'SELECT * FROM __ref("orders") JOIN __ref("missing_customers") ON TRUE\n' ), }, expected_message=( - "Audit file audits/singular/orders_have_customers.sql references unknown model" + "Audit file sql/audits/singular/orders_have_customers.sql references unknown model" " 'missing_customers'" ), ), @@ -140,7 +140,7 @@ def test_given_audit_when_compiling_then_native_project_holds_its_attachment( NativeAuditErrorTestCase( description="unknown singular audit run scope", files={ - "audits/singular/orders_have_customers.sql": ( + "sql/audits/singular/orders_have_customers.sql": ( "AUDIT (name orders_have_customers, run_scope always);\n" 'SELECT * FROM __ref("orders") JOIN __ref("customers") ON TRUE\n' ), @@ -150,19 +150,19 @@ def test_given_audit_when_compiling_then_native_project_holds_its_attachment( NativeAuditErrorTestCase( description="model-attached audit that does not read its model", files={ - "audits/generic/at_least.sql": ( + "sql/audits/generic/at_least.sql": ( 'AUDIT (name at_least);\nSELECT * FROM __ref("customers") WHERE @minimum > 0\n' ), }, expected_message=( - "models/orders.sql audit 'at_least': model-attached audit must reference the" + "sql/models/orders.sql audit 'at_least': model-attached audit must reference the" " attached model 'orders' via __ref()" ), ), NativeAuditErrorTestCase( description="singular audit reading a dbt model", files={ - "audits/singular/orders_have_customers.sql": ( + "sql/audits/singular/orders_have_customers.sql": ( "AUDIT (name orders_have_customers);\n" 'SELECT * FROM __ref("orders") JOIN __dbt_ref("customers") ON TRUE\n' ), @@ -174,7 +174,7 @@ def test_given_audit_when_compiling_then_native_project_holds_its_attachment( NativeAuditErrorTestCase( description="thresholds on a violation audit attachment", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', columns (order_id (type INTEGER," " audits [at_least(minimum 1, thresholds (warn (above 1)))])));\n" "SELECT 1 AS order_id\n" @@ -185,43 +185,43 @@ def test_given_audit_when_compiling_then_native_project_holds_its_attachment( NativeAuditErrorTestCase( description="standalone measurement audit with a non-numeric threshold", files={ - "audits/singular/coverage.sql": 'AUDIT (name coverage, evaluation measurement, value rate, thresholds (warn (above \'x\')));\nMEASURE (SELECT COUNT(*) AS rate FROM __ref("orders") JOIN __ref("customers") ON TRUE);\n' + "sql/audits/singular/coverage.sql": 'AUDIT (name coverage, evaluation measurement, value rate, thresholds (warn (above \'x\')));\nMEASURE (SELECT COUNT(*) AS rate FROM __ref("orders") JOIN __ref("customers") ON TRUE);\n' }, expected_message=( - "audits/singular/coverage.sql standalone measurement audit invalid thresholds:" + "sql/audits/singular/coverage.sql standalone measurement audit invalid thresholds:" " above threshold requires one numeric value" ), ), NativeAuditErrorTestCase( description="standalone measurement audit with negative minimum samples", files={ - "audits/singular/coverage.sql": 'AUDIT (name coverage, evaluation measurement, value rate, thresholds (warn (above 1)), minimum_samples -1);\nMEASURE (SELECT COUNT(*) AS rate FROM __ref("orders") JOIN __ref("customers") ON TRUE);\n' + "sql/audits/singular/coverage.sql": 'AUDIT (name coverage, evaluation measurement, value rate, thresholds (warn (above 1)), minimum_samples -1);\nMEASURE (SELECT COUNT(*) AS rate FROM __ref("orders") JOIN __ref("customers") ON TRUE);\n' }, expected_message=( - "audits/singular/coverage.sql standalone measurement audit 'minimum_samples'" + "sql/audits/singular/coverage.sql standalone measurement audit 'minimum_samples'" " must be a non-negative integer" ), ), NativeAuditErrorTestCase( description="generic audit attachment missing an argument", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', columns (order_id (type INTEGER, audits [at_least])));\n" "SELECT 1 AS order_id\n" ) }, - expected_message="models/orders.sql is missing argument 'minimum' for generic audit 'at_least'", + expected_message="sql/models/orders.sql is missing argument 'minimum' for generic audit 'at_least'", ), NativeAuditErrorTestCase( description="generic audit attachment overriding its implicit column", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', columns (order_id (type INTEGER, audits [at_least(minimum 1, column other_id)])));\n" "SELECT 1 AS order_id\n" ) }, expected_message=( - "models/orders.sql audit 'at_least' must not override implicit column from" + "sql/models/orders.sql audit 'at_least' must not override implicit column from" " attached context" ), ), @@ -247,14 +247,14 @@ def test_given_invalid_audit_when_compiling_then_native_attachment_rejects_it( NativeMeasurementPolicyTestCase( description="error threshold makes the standalone audit an error", files={ - "audits/singular/coverage.sql": 'AUDIT (name coverage, evaluation measurement, value rate, thresholds (warn (above 1), error (above 5)), minimum_samples 3);\nMEASURE (SELECT COUNT(*) AS rate FROM __ref("orders") JOIN __ref("customers") ON TRUE);\n' + "sql/audits/singular/coverage.sql": 'AUDIT (name coverage, evaluation measurement, value rate, thresholds (warn (above 1), error (above 5)), minimum_samples 3);\nMEASURE (SELECT COUNT(*) AS rate FROM __ref("orders") JOIN __ref("customers") ON TRUE);\n' }, expected_policy=("above", 1.0, "above", 5.0, 3, "error"), ), NativeMeasurementPolicyTestCase( description="warn-only threshold keeps an unbounded authored sample count", files={ - "audits/singular/coverage.sql": 'AUDIT (name coverage, evaluation measurement, value rate, thresholds (warn (above 1)), minimum_samples 99999999999999999999);\nMEASURE (SELECT COUNT(*) AS rate FROM __ref("orders") JOIN __ref("customers") ON TRUE);\n' + "sql/audits/singular/coverage.sql": 'AUDIT (name coverage, evaluation measurement, value rate, thresholds (warn (above 1)), minimum_samples 99999999999999999999);\nMEASURE (SELECT COUNT(*) AS rate FROM __ref("orders") JOIN __ref("customers") ON TRUE);\n' }, expected_policy=("above", 1.0, None, None, 99999999999999999999, "warn"), ), diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_compiled_project.py b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_compiled_project.py index 8069fe5340..f32340ac1c 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_compiled_project.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_compiled_project.py @@ -131,7 +131,7 @@ def test_given_repeated_output_schemas_when_serializing_then_columns_share_immut files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', **{ - f"models/orders_{index}.sql": ( + f"sql/models/orders_{index}.sql": ( 'MODEL (description "Order identifiers");\n' "SELECT CAST(1 AS INT) AS order_id, CAST(NULL AS INT) AS missing_id, " "CAST('ready' AS VARCHAR) AS status" @@ -261,7 +261,7 @@ def test_given_project_when_running_native_model_loop_then_inputs_match_recorded ModelLoopErrorTestCase( description="blank header description", model_sql="MODEL (description ' ');\nSELECT 1 AS order_id\n", - expected_message="models/orders.sql model 'description' must be a non-empty string", + expected_message="sql/models/orders.sql model 'description' must be a non-empty string", expected_code="P001", ), ModelLoopErrorTestCase( @@ -301,7 +301,7 @@ def test_given_project_when_running_native_model_loop_then_inputs_match_recorded description="unknown audit factory", model_sql="MODEL (audit_factories [order_checks]);\nSELECT 1 AS order_id\n", expected_message=( - "model 'orders' in models/orders.sql references unknown audit factory " + "model 'orders' in sql/models/orders.sql references unknown audit factory " "'order_checks'. Available audit factories: none discovered" ), expected_code="P001", @@ -319,7 +319,7 @@ def test_given_project_when_running_native_model_loop_then_inputs_match_recorded description="dbt reference without a dbt manifest", model_sql='MODEL ();\nSELECT * FROM __dbt_ref("raw_orders")\n', expected_message=( - 'Model file models/orders.sql uses __dbt_ref("raw_orders") but no dbt manifest ' + 'Model file sql/models/orders.sql uses __dbt_ref("raw_orders") but no dbt manifest ' "was found" ), expected_code="C214", @@ -327,7 +327,7 @@ def test_given_project_when_running_native_model_loop_then_inputs_match_recorded ModelLoopErrorTestCase( description="unclosed reference call located in the model file", model_sql='MODEL ();\nSELECT *\nFROM __ref("stg_orders"\n', - expected_message="models/orders.sql:3:6: SQL reference contains an unclosed parenthesis", + expected_message="sql/models/orders.sql:3:6: SQL reference contains an unclosed parenthesis", expected_code="P001", ), ModelLoopErrorTestCase( @@ -436,7 +436,7 @@ def test_given_project_when_running_native_model_loop_then_inputs_match_recorded model_sql='MODEL (post_hooks [sql("grant_read")]);\nSELECT 1 AS id\n', expected_message=( "{model_path} post_hooks[0] sql(\"grant_read\") is missing argument 'role' for " - "SQL hook 'grant_read' in hooks/sql/grant_read.sql" + "SQL hook 'grant_read' in sql/hooks/sql/grant_read.sql" ), expected_code="P001", files=SQL_HOOK_FILES, @@ -449,7 +449,7 @@ def test_given_project_when_running_native_model_loop_then_inputs_match_recorded ), expected_message=( '{model_path} pre_hooks[0] sql("grant_read") passes unknown argument(s) to ' - "SQL hook 'grant_read' in hooks/sql/grant_read.sql: mode, scope" + "SQL hook 'grant_read' in sql/hooks/sql/grant_read.sql: mode, scope" ), expected_code="P001", files=SQL_HOOK_FILES, @@ -513,8 +513,8 @@ def test_given_invalid_model_when_running_native_model_loop_then_attachment_erro fixtures=(), files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", - "models/orders.sql": test_case.model_sql, + "sql/enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/models/orders.sql": test_case.model_sql, } | test_case.files, project_dir=tmp_path / "project", @@ -524,7 +524,7 @@ def test_given_invalid_model_when_running_native_model_loop_then_attachment_erro _ = build_inputs_with_native_loop(project_dir=project_dir) assert raised.value.message == test_case.expected_message.format( - model_path=project_dir / "models" / "orders.sql" + model_path=project_dir / "sql" / "models" / "orders.sql" ) assert raised.value.code == test_case.expected_code @@ -566,7 +566,7 @@ def test_given_unparseable_model_when_validating_immediately_then_syntax_error_i fixtures=(), files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/orders.sql": test_case.model_sql, + "sql/models/orders.sql": test_case.model_sql, }, project_dir=tmp_path / "project", ) @@ -575,7 +575,7 @@ def test_given_unparseable_model_when_validating_immediately_then_syntax_error_i _ = build_inputs_with_native_loop(project_dir=project_dir, defer_validation=False) assert raised.value.message == test_case.expected_message.format( - model_path=project_dir / "models" / "orders.sql" + model_path=project_dir / "sql" / "models" / "orders.sql" ) assert raised.value.code == "P001" assert test_case.expected_help_fragment in (raised.value.help or "") @@ -620,8 +620,8 @@ def test_given_ordinary_compile_when_compiling_then_no_python_project_is_constru [ ModelPathScopeErrorTestCase( description="a folder holding the identity separator is read as an identity", - model_path="models/a:b/orders.sql", - expected_message="Unknown qualified identity kind: 'models/a'", + model_path="sql/models/a:b/orders.sql", + expected_message="Unknown qualified identity kind: 'sql/models/a'", expected_code="S002", ), ], @@ -636,7 +636,7 @@ def test_given_model_path_scope_rejects_when_running_native_model_loop_then_scop fixtures=(), files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", test_case.model_path: "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", }, project_dir=tmp_path / "project", diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_functions.py b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_functions.py index 5a6503a97d..f2c146b1db 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_functions.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_functions.py @@ -133,30 +133,30 @@ def test_given_function_when_compiling_then_native_project_holds_its_attachment( NativeFunctionErrorTestCase( description="table function called with the wrong argument count", files={ - "functions/sql/customer_orders.sql": ( + "sql/functions/sql/customer_orders.sql": ( "FUNCTION (description 'Customer orders.', arguments (customer_id INTEGER)," " returns table (order_id INTEGER));\nSELECT customer_id AS order_id\n" ), - "models/report.sql": ( + "sql/models/report.sql": ( "MODEL (description 'Report.');\n" 'SELECT * FROM __table_fn("customer_orders")(1, 2)\n' ), }, expected_message=( - "Model file models/report.sql table function 'customer_orders' expects 1" + "Model file sql/models/report.sql table function 'customer_orders' expects 1" " argument but received 2" ), ), NativeFunctionErrorTestCase( description="function body reading an unknown model", files={ - "functions/sql/lookup.sql": ( + "sql/functions/sql/lookup.sql": ( "FUNCTION (description 'Lookup.', returns INTEGER);\n" 'SELECT COUNT(*) FROM __ref("missing_orders")\n' ), }, expected_message=( - "SQL function file functions/sql/lookup.sql references unknown model" + "SQL function file sql/functions/sql/lookup.sql references unknown model" " 'missing_orders'" ), ), @@ -195,8 +195,8 @@ def test_given_invalid_function_when_compiling_then_native_attachment_rejects_it 'name = "orders"\nadapter = "snowflake"\n' '[defaults]\nfunction_dataframe = "pandas"\n' ), - "functions/python/smooth.py": TABLE_FUNCTION_PROJECT_FILES[ - "functions/python/smooth.py" + "sql/functions/python/smooth.py": TABLE_FUNCTION_PROJECT_FILES[ + "sql/functions/python/smooth.py" ].replace("readings: pl.DataFrame", "readings"), }, expected_summaries={ @@ -225,13 +225,13 @@ def test_given_python_table_functions_when_compiling_then_each_keeps_its_columns NativeFunctionErrorTestCase( description="a Python table function called without a partition", files={ - "models/smoothed.sql": ( + "sql/models/smoothed.sql": ( "MODEL (description 'Smoothed.');\nSELECT s.* FROM __ref(\"readings\") r,\n" ' __table_fn("smooth")(r.device_id, r.reading) OVER () s\n' ), }, expected_message=( - "Model file models/smoothed.sql calls Python table function 'smooth' without" + "Model file sql/models/smoothed.sql calls Python table function 'smooth' without" " OVER (PARTITION BY ...)" ), ), @@ -255,24 +255,24 @@ def test_given_python_table_functions_when_compiling_then_each_keeps_its_columns NativeFunctionErrorTestCase( description="a polars table function with a fractional NUMBER argument", files={ - "functions/python/smooth.py": TABLE_FUNCTION_PROJECT_FILES[ - "functions/python/smooth.py" + "sql/functions/python/smooth.py": TABLE_FUNCTION_PROJECT_FILES[ + "sql/functions/python/smooth.py" ].replace("'reading': 'FLOAT'}", "'reading': 'NUMBER(10, 2)'}"), }, expected_message=( - "Python function functions/python/smooth.py argument 'reading' is NUMBER(10, 2)," + "Python function sql/functions/python/smooth.py argument 'reading' is NUMBER(10, 2)," " which Snowflake passes to a polars frame as Python Decimal objects" ), ), NativeFunctionErrorTestCase( description="a table function returning a scalar type", files={ - "functions/python/rank_readings.py": TABLE_FUNCTION_PROJECT_FILES[ - "functions/python/rank_readings.py" + "sql/functions/python/rank_readings.py": TABLE_FUNCTION_PROJECT_FILES[ + "sql/functions/python/rank_readings.py" ].replace("returns={'position': 'INTEGER'}", "returns='INTEGER'"), }, expected_message=( - "functions/python/rank_readings.py returns must map each column name to its type" + "sql/functions/python/rank_readings.py returns must map each column name to its type" ), ), ], diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_parameter_boundaries.py b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_parameter_boundaries.py index 4e0b9cfa9b..8b04f93776 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_parameter_boundaries.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_parameter_boundaries.py @@ -65,8 +65,8 @@ def test_given_adapter_parameter_when_attaching_native_test_then_actual_sql_uses project_dir=tmp_path, files={ "sqlbuild_project.toml": f'name = "orders"\nadapter = "{test_case.adapter_name}"\n', - "models/raw_orders.sql": 'MODEL (description "Raw orders");\nSELECT 1 AS value\n', - "models/orders.sql": 'MODEL (description "Orders");\nSELECT value FROM __ref("raw_orders")\n', + "sql/models/raw_orders.sql": 'MODEL (description "Raw orders");\nSELECT 1 AS value\n', + "sql/models/orders.sql": 'MODEL (description "Orders");\nSELECT value FROM __ref("raw_orders")\n', "tests/unit/order_values.sql": ( f"TEST (parameters (value {test_case.declaration}), cases (single (value {test_case.literal})));\n" 'WITH __ref__raw_orders AS (SELECT @param("value") AS value), ' @@ -107,8 +107,8 @@ def test_given_quoted_hook_argument_when_attaching_then_inserted_marker_is_not_r project_dir=tmp_path, files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "hooks/sql/notify.sql": "HOOK (description \"Record a label\");\nSELECT @'label'\n", - "models/orders.sql": ( + "sql/hooks/sql/notify.sql": "HOOK (description \"Record a label\");\nSELECT @'label'\n", + "sql/models/orders.sql": ( f'MODEL (description "Orders", pre_hooks [sql("notify", label: {json.dumps(test_case.argument)})]);\nSELECT 1 AS order_id\n' ), }, diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_resource_diagnostics.py b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_resource_diagnostics.py index bcf36d13a1..d7b5bec1a5 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_resource_diagnostics.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/test_native_resource_diagnostics.py @@ -32,13 +32,13 @@ NativeResourceDiagnosticTestCase( description="MODEL header after leading blank lines", files={ - "models/order_totals.sql": "\n \t\n\n MODEL (materialized table);\nSELECT 1 AS id\n" + "sql/models/order_totals.sql": "\n \t\n\n MODEL (materialized table);\nSELECT 1 AS id\n" }, expected_diagnostics=( ( "P010", "model 'order_totals' has no description", - "models/order_totals.sql", + "sql/models/order_totals.sql", 4, 5, None, @@ -48,13 +48,13 @@ NativeResourceDiagnosticTestCase( description="FUNCTION header after a leading blank line", files={ - "functions/sql/is_large_order.sql": "\nFUNCTION (returns BOOLEAN);\n\nSELECT TRUE\n" + "sql/functions/sql/is_large_order.sql": "\nFUNCTION (returns BOOLEAN);\n\nSELECT TRUE\n" }, expected_diagnostics=( ( "P010", "function 'is_large_order' has no description", - "functions/sql/is_large_order.sql", + "sql/functions/sql/is_large_order.sql", 2, 1, None, @@ -63,12 +63,12 @@ ), NativeResourceDiagnosticTestCase( description="HOOK header on the first line", - files={"hooks/sql/analyze_orders.sql": "HOOK ();\nSELECT 1\n"}, + files={"sql/hooks/sql/analyze_orders.sql": "HOOK ();\nSELECT 1\n"}, expected_diagnostics=( ( "P010", "hook 'analyze_orders' has no description", - "hooks/sql/analyze_orders.sql", + "sql/hooks/sql/analyze_orders.sql", 1, 1, None, @@ -77,12 +77,12 @@ ), NativeResourceDiagnosticTestCase( description="@udf decorator after docstring and comment mentions", - files={"functions/python/is_large_order.py": _UDF_AFTER_MENTIONS}, + files={"sql/functions/python/is_large_order.py": _UDF_AFTER_MENTIONS}, expected_diagnostics=( ( "P010", "function 'is_large_order' has no description", - "functions/python/is_large_order.py", + "sql/functions/python/is_large_order.py", 6, 1, None, @@ -92,9 +92,9 @@ NativeResourceDiagnosticTestCase( description="second seed entry of its YAML file", files={ - "seeds/product_labels.csv": "product_type_id\n1\n", - "seeds/product_types.csv": "product_type_id\n1\n", - "seeds/product_types.yml": ( + "sql/seeds/product_labels.csv": "product_type_id\n1\n", + "sql/seeds/product_types.csv": "product_type_id\n1\n", + "sql/seeds/product_types.yml": ( "seeds:\n - name: product_labels\n description: Labels\n columns:\n" " - name: product_type_id\n type: INTEGER\n" " - name: product_types\n columns:\n" @@ -105,7 +105,7 @@ ( "P010", "seed 'product_types' has no description", - "seeds/product_types.yml", + "sql/seeds/product_types.yml", 7, 1, None, @@ -116,7 +116,7 @@ description="cursor model reading only constants is located at its cursor entry", files=cursor_model_files(), expected_diagnostics=( - ("P011", _CURSOR_MESSAGE, "models/finance/daily_revenue.sql", 5, 3, 22), + ("P011", _CURSOR_MESSAGE, "sql/models/finance/daily_revenue.sql", 5, 3, 22), ), ), NativeResourceDiagnosticTestCase( @@ -127,10 +127,10 @@ NativeResourceDiagnosticTestCase( description="audit factory only one model attaches", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders", audit_factories [quality]);\nSELECT 1 AS id\n' ), - "python/factories/quality.py": ( + "python/nodes/factories/quality.py": ( "from sqlbuild.audits import audit_factory\n\n\n" "@audit_factory\ndef quality():\n return []\n\n\n" "@audit_factory\ndef unused_quality():\n return []\n" @@ -141,7 +141,7 @@ "C216", "Audit factory 'unused_quality' is not referenced by any model and will " "not produce audits", - "python/factories/quality.py", + "python/nodes/factories/quality.py", 9, 1, None, diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/test_orchestration_snapshot.py b/tests/integration/src/sqlbuild/compiler/compiled_project/test_orchestration_snapshot.py index 84d6ab3001..dd0c05f015 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/test_orchestration_snapshot.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/test_orchestration_snapshot.py @@ -77,12 +77,12 @@ _PROVIDER_PROJECT: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Orders.');\n\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL (description 'Orders.');\n\nSELECT 1 AS order_id\n", } _PRICE_MODELS: dict[str, str] = { - "models/stg_prices.sql": ( + "sql/models/stg_prices.sql": ( 'MODEL (description "Staged prices");\n' "SELECT 'W-1' AS window_id, CAST(12345 AS BIGINT) AS price_minor, " "CAST('2026-03-30 08:00:00' AS TIMESTAMP) AS loaded_at\n" @@ -97,9 +97,9 @@ "model and seed catalog", TYPE_PROOF_FILES | { - "seeds/payment_methods.csv": PARITY_FILES["seeds/payment_methods.csv"], - "seeds/payment_methods.yml": PARITY_FILES["seeds/payment_methods.yml"], - "models/payments.sql": ( + "sql/seeds/payment_methods.csv": PARITY_FILES["sql/seeds/payment_methods.csv"], + "sql/seeds/payment_methods.yml": PARITY_FILES["sql/seeds/payment_methods.yml"], + "sql/models/payments.sql": ( "MODEL (description 'Payment methods.');\n" 'SELECT method FROM __seed("payment_methods")\n' ), @@ -110,7 +110,7 @@ "attached audits", TYPE_PROOF_FILES | { - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', columns (order_id (audits [not_null])));\n" 'SELECT order_id, amount FROM __ref("stg_orders")\n' ), @@ -122,21 +122,25 @@ { path: value for path, value in FUNCTION_PROJECT_FILES.items() - if path != "enums/status.sql" + if path != "sql/enums/status.sql" } - | {"functions/sql/_enums/status.sql": FUNCTION_PROJECT_FILES["enums/status.sql"]}, + | { + "sql/functions/sql/_enums/status.sql": FUNCTION_PROJECT_FILES[ + "sql/enums/status.sql" + ] + }, frozenset({"model", "udf", "table_fn"}), ), SnapshotCatalogTestCase( "Python hooks", TYPE_PROOF_FILES | { - "hooks/python/notifications.py": ( + "sql/hooks/python/notifications.py": ( "from sqlbuild.hooks import hook\n\n" "@hook\ndef notify(ctx, channel):\n" ' """Notify support."""\n return None\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', pre_hooks [python('notify', channel: 'support')]);\n" 'SELECT order_id, amount FROM __ref("stg_orders")\n' ), @@ -153,9 +157,9 @@ ).read_text() )[source] for path, source in ( - ("python/notify/orders.py", "side_effect"), - ("python/assets/orders.py", "asset"), - ("python/checks/orders.py", "initial"), + ("python/nodes/notify/notify_support/asset.py", "side_effect"), + ("python/nodes/assets/order_export/asset.py", "asset"), + ("python/nodes/checks/orders/checks.py", "initial"), ) }, frozenset({"model", "asset", "check"}), @@ -164,8 +168,8 @@ "SQL hooks", TYPE_PROOF_FILES | { - "hooks/sql/record_load.sql": "HOOK (description 'Record load.');\nSELECT 3 AS load_count\n", - "models/orders.sql": ( + "sql/hooks/sql/record_load.sql": "HOOK (description 'Record load.');\nSELECT 3 AS load_count\n", + "sql/models/orders.sql": ( "MODEL (description 'Orders.', pre_hooks [sql('record_load')]);\n" 'SELECT order_id FROM __ref("stg_orders")\n' ), @@ -176,7 +180,7 @@ "source catalog", TYPE_PROOF_FILES | { - "sources/orders.yml": ( + "sql/sources/orders.yml": ( "sources:\n - name: raw_orders\n description: Raw orders.\n" " schema: raw\n table: orders\n" " columns:\n - name: order_id\n type: INTEGER\n" @@ -198,9 +202,9 @@ | { path: (Path("benchmarks/duckshop/project") / path).read_text() for path in ( - "seeds/edge_cases/edge_quantity_steps.csv", - "seeds/edge_cases/edge_quantity_steps.yml", - "functions/sql/edge_cases/edge_next_quantity.sql", + "sql/seeds/edge_cases/edge_quantity_steps.csv", + "sql/seeds/edge_cases/edge_quantity_steps.yml", + "sql/functions/sql/edge_cases/edge_next_quantity.sql", ) }, frozenset({"model", "seed", "udf"}), @@ -281,9 +285,9 @@ def test_given_semantic_edits_when_publishing_then_local_identities_keep_planner | { path: (Path("benchmarks/duckshop/project") / path).read_text() for path in ( - "seeds/edge_cases/edge_quantity_steps.csv", - "seeds/edge_cases/edge_quantity_steps.yml", - "functions/sql/edge_cases/edge_next_quantity.sql", + "sql/seeds/edge_cases/edge_quantity_steps.csv", + "sql/seeds/edge_cases/edge_quantity_steps.yml", + "sql/functions/sql/edge_cases/edge_next_quantity.sql", ) } ) @@ -346,7 +350,7 @@ def test_given_semantic_edits_when_publishing_then_local_identities_keep_planner ), SnapshotRejectionTestCase( description="compiler errors cannot replace the last good publication", - files=TYPE_PROOF_FILES | {"models/orders.sql": "MODEL ();\nSELECT 1 AS order_id\n"}, + files=TYPE_PROOF_FILES | {"sql/models/orders.sql": "MODEL ();\nSELECT 1 AS order_id\n"}, nodes={}, expected_compiler_errors=True, expected_message="cannot publish a project with compiler errors", @@ -385,16 +389,16 @@ def test_given_invalid_compilation_or_forged_nodes_when_publishing_then_no_snaps description="published column lineage follows passthroughs, casts and aggregations", files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.');\n\n" "SELECT 1 AS order_id, 'eu' AS region, '5.00' AS amount_text\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Typed orders.');\n\n" "SELECT order_id, region, CAST(amount_text AS DECIMAL(10, 2)) AS amount\n" 'FROM __ref("stg_orders")\n' ), - "models/region_revenue.sql": ( + "sql/models/region_revenue.sql": ( "MODEL (description 'Revenue by region.');\n\n" "SELECT region, SUM(amount) AS revenue\n" 'FROM __ref("orders")\nGROUP BY region\n' @@ -441,7 +445,7 @@ def test_given_a_compiled_project_when_publishing_then_its_column_lineage_is_a_s description="a provider is published with its fields and consumers but no values", files=_PROVIDER_PROJECT | { - "providers/fulfillment.py": ( + "python/providers/fulfillment.py": ( "from typing import Literal\n\n" "from pydantic import AliasChoices, Field, SecretStr\n" "from pydantic_settings import SettingsConfigDict\n" @@ -458,18 +462,18 @@ def test_given_a_compiled_project_when_publishing_then_its_column_lineage_is_a_s " None, validation_alias=AliasChoices('SHIP_TIMEOUT', 'TIMEOUT')\n" " )\n" ), - "python/tasks/publish_orders.py": ( - "from providers.fulfillment import FulfillmentApi\n" + "python/nodes/tasks/publish_orders/asset.py": ( + "from python.providers.fulfillment import FulfillmentApi\n" "from sqlbuild.assets import asset\n\n\n" "@asset\n" "def publish_orders(fulfillment_api: FulfillmentApi):\n" ' """Send orders to fulfillment."""\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', post_hooks [python(\"notify_fulfillment\")]);\n\n" "SELECT 1 AS order_id\n" ), - "hooks/python/notify_fulfillment.py": ( + "sql/hooks/python/notify_fulfillment.py": ( "from sqlbuild.hooks import hook\n\n\n" "@hook\n" "def notify_fulfillment(ctx, fulfillment_api):\n" @@ -481,9 +485,9 @@ def test_given_a_compiled_project_when_publishing_then_its_column_lineage_is_a_s "providers": [ { "name": "fulfillment_api", - "class": "providers.fulfillment.FulfillmentApi", + "class": "python.providers.fulfillment.FulfillmentApi", "description": "Client for the fulfillment service.\n\nSends shipped orders.", - "path": "providers/fulfillment.py", + "path": "python/providers/fulfillment.py", "settings": [ { "name": "api_key", @@ -563,7 +567,7 @@ def test_given_a_compiled_project_when_publishing_then_its_column_lineage_is_a_s description="a prefix that applies only to aliases leaves plain field names unprefixed", files=_PROVIDER_PROJECT | { - "providers/inventory.py": ( + "python/providers/inventory.py": ( "from pydantic import Field\n" "from pydantic_settings import SettingsConfigDict\n" "from sqlbuild.providers import Provider\n\n\n" @@ -581,9 +585,9 @@ def test_given_a_compiled_project_when_publishing_then_its_column_lineage_is_a_s "providers": [ { "name": "inventory_api", - "class": "providers.inventory.InventoryApi", + "class": "python.providers.inventory.InventoryApi", "description": "Client for the inventory service.", - "path": "providers/inventory.py", + "path": "python/providers/inventory.py", "settings": [ { "name": "region", @@ -653,7 +657,7 @@ def test_given_project_providers_when_publishing_then_they_are_a_snapshot_docume "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n\n[vars]\nreporting_currency = "USD"\n' ), - "models/_macros/sql/minor_to_major.sql": ( + "sql/models/_macros/sql/minor_to_major.sql": ( "MACRO (\n" ' description "Minor units to major units",\n' " arguments (amount BIGINT, places INT CONST DEFAULT 2),\n" @@ -661,12 +665,12 @@ def test_given_project_providers_when_publishing_then_they_are_a_snapshot_docume ");\n\n" "ROUND(@amount / 100, @places)::DECIMAL(18, 2)\n" ), - "models/_macros/python/rounding.py": ( + "sql/models/_macros/python/rounding.py": ( "def round_half_even(ctx, expression: str, places: int = 2) -> str:\n" " return f'ROUND_EVEN({expression}, {places})'\n" ), **_PRICE_MODELS, - "models/price_spans.sql": ( + "sql/models/price_spans.sql": ( "MODEL (\n" ' description "Prices with rewritten expressions",\n' " materialized incremental,\n" @@ -703,7 +707,7 @@ def test_given_project_providers_when_publishing_then_they_are_a_snapshot_docume files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', **_PRICE_MODELS, - "models/price_refs.sql": ( + "sql/models/price_refs.sql": ( 'MODEL (description "Price references");\n' 'SELECT __ref("stg_prices").window_id AS window_id, ' "'EUR' AS currency FROM __ref(\"stg_prices\")\n" @@ -731,7 +735,7 @@ def test_given_rewritten_model_sql_when_publishing_then_expression_ranges_slice_ files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', **_PRICE_MODELS, - "models/price_columns.sql": ( + "sql/models/price_columns.sql": ( 'MODEL (description "Price columns");\n' 'SELECT p.window_id, p.price_minor FROM __ref("stg_prices") AS p\n' ), @@ -751,7 +755,7 @@ def test_given_rewritten_model_sql_when_publishing_then_expression_ranges_slice_ '[defaults]\ndatabase = "WAREHOUSE"\nschema = "MAIN"\n\n' '[vars]\nreporting_currency = "USD"\n' ), - "sources/edge_cases.yml": ( + "sql/sources/edge_cases.yml": ( "sources:\n" " - name: edge__price_windows\n" " description: Price windows\n" @@ -764,7 +768,7 @@ def test_given_rewritten_model_sql_when_publishing_then_expression_ranges_slice_ " type: TIMESTAMP_NTZ\n" ), # A second consumer keeps the DuckShop macros project-wide, as they are there. - "models/price_checks.sql": ( + "sql/models/price_checks.sql": ( 'MODEL (description "Price checks");\n' "SELECT @sql.money_from_minor(150, 2) AS amount, " '@py.round_half_even("1.25", 1) AS rounded\n' @@ -772,10 +776,10 @@ def test_given_rewritten_model_sql_when_publishing_then_expression_ranges_slice_ **{ path: (_DUCKSHOP / path).read_text() for path in ( - "macros/sql/money_from_minor.sql", - "macros/sql/safe_divide.sql", - "macros/python/rounding.py", - "models/intermediate/edge_cases/int_edge_expression_spans.sql", + "sql/macros/sql/money_from_minor.sql", + "sql/macros/sql/safe_divide.sql", + "sql/macros/python/rounding.py", + "sql/models/intermediate/edge_cases/int_edge_expression_spans.sql", ) }, }, @@ -1303,18 +1307,18 @@ def test_given_invalid_declarations_when_compiling_then_native_validation_reject description="DuckShop layer jobs that share a function wait only by lineage", files={ **duckshop_orchestration("shared_function_layers"), - "functions/sql/order_cents.sql": ( + "sql/functions/sql/order_cents.sql": ( "FUNCTION (description 'Amount in cents.'," " arguments (amount INTEGER), returns INTEGER);\nSELECT amount * 100\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.', tags [staging],\n" " columns (order_id (type INTEGER), cents (type INTEGER)),\n" ");\n\n" "SELECT CAST(1 AS INTEGER) AS order_id," ' __udf("order_cents")(CAST(5 AS INTEGER)) AS cents\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Typed orders.', tags [marts],\n" " columns (order_id (type INTEGER), cents (type INTEGER)),\n" ");\n\n" @@ -1337,7 +1341,7 @@ def test_given_invalid_declarations_when_compiling_then_native_validation_reject for path in (_DUCKSHOP / "orchestration").rglob("*") if path.is_file() }, - "models/orders.sql": TYPE_PROOF_FILES["models/orders.sql"].replace( + "sql/models/orders.sql": TYPE_PROOF_FILES["sql/models/orders.sql"].replace( "MODEL (", "MODEL (tags ['edge_case'],", 1 ), "sqlbuild_project.toml": TYPE_PROOF_FILES["sqlbuild_project.toml"] @@ -1610,7 +1614,7 @@ def test_given_invalid_declarations_when_compiling_then_native_validation_reject description="source_new_data selectors freeze only source nodes without event kinds", files={ **duckshop_orchestration("source_orders"), - "sources/orders.yml": Path( + "sql/sources/orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/source_orders.yml" ).read_text(), }, @@ -1634,7 +1638,7 @@ def test_given_invalid_declarations_when_compiling_then_native_validation_reject description="source_stale freezes source nodes and a positive timestamp-age threshold", files={ **duckshop_orchestration("stale_orders"), - "sources/orders.yml": Path( + "sql/sources/orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/source_orders.yml" ).read_text(), }, @@ -1876,11 +1880,13 @@ def test_given_declaration_modules_when_compiling_then_native_discovery_collects SnapshotDiscoveryRejectionTestCase( description="DuckShop jobs cannot reuse a model name", files=duckshop_orchestration("name_collision") - | {"models/orders_job.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n"}, + | { + "sql/models/orders_job.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n" + }, expected_error=DiscoveryConflictError, expected_message=re.escape( "Project resource name 'orders_job' is declared as both model in " - "models/orders_job.sql and job in orchestration/jobs/orders_job.toml" + "sql/models/orders_job.sql and job in orchestration/jobs/orders_job.toml" + ORCHESTRATION_NAME_CONFLICT ), ), @@ -2013,7 +2019,7 @@ def test_given_declaration_modules_when_compiling_then_native_discovery_collects "after_seconds=60", "after_seconds=0", ), - "sources/orders.yml": Path( + "sql/sources/orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/source_orders.yml" ).read_text(), }, @@ -2029,7 +2035,7 @@ def test_given_declaration_modules_when_compiling_then_native_discovery_collects "after_seconds=60", "after_seconds=True", ), - "sources/orders.yml": Path( + "sql/sources/orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/source_orders.yml" ).read_text(), }, @@ -2045,7 +2051,7 @@ def test_given_declaration_modules_when_compiling_then_native_discovery_collects "after_seconds=60", "after_seconds=2**32", ), - "sources/orders.yml": Path( + "sql/sources/orders.yml": Path( "benchmarks/duckshop/edge_cases/orchestration/source_orders.yml" ).read_text(), }, @@ -2278,7 +2284,7 @@ def test_given_projects_compiled_in_one_process_when_one_imports_orchestration_t ), PythonJobSelectionTestCase( description="a python folder selects every node under it", - select="python/orders", + select="python/nodes/orders", expected_selection=("asset:partner_orders_file",), ), PythonJobSelectionTestCase( @@ -2312,8 +2318,8 @@ def test_given_python_selectors_when_publishing_jobs_then_selections_match_the_c PythonJobGroupTestCase( description="a job waits for the job building the Python node its task depends on", jobs=( - ("orders_export_job", "python/orders/partner_export"), - ("carrier_sync_job", "python/fulfillment/carrier_sync"), + ("orders_export_job", "python/nodes/orders/partner_export"), + ("carrier_sync_job", "python/nodes/fulfillment/carrier_sync"), ), expected_groups={ "orders_nightly_job_group": { diff --git a/tests/integration/src/sqlbuild/compiler/contracts/helpers.py b/tests/integration/src/sqlbuild/compiler/contracts/helpers.py index 22f6abcf2f..0741901ce1 100644 --- a/tests/integration/src/sqlbuild/compiler/contracts/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/contracts/helpers.py @@ -54,25 +54,25 @@ type: VARCHAR """ _MODELS: dict[str, str] = { - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( 'MODEL (\n description "Staged orders",\n contract enforced,\n columns (\n' " order_id (type INTEGER, nullable false),\n amount (type DOUBLE),\n ),\n);\n\n" 'SELECT order_id, customer_id, amount, status FROM __source("raw_orders")\n' ), - "models/marts/customer_totals.sql": ( + "sql/models/marts/customer_totals.sql": ( 'MODEL (\n description "Totals per customer",\n columns (\n' " customer_id (type BIGINT),\n total_amount (type DECIMAL(18, 2)),\n ),\n);\n\n" "SELECT customer_id, SUM(amount) AS total_amount, COUNT(*) AS order_count,\n" " MAX(status) AS last_status\n" 'FROM __ref("stg_orders")\nGROUP BY customer_id\n' ), - "models/marts/order_flags.sql": ( + "sql/models/marts/order_flags.sql": ( 'MODEL (\n description "Order flags",\n);\n\n' "SELECT order_id, amount > 10 AS is_large, CAST(NULL AS VARCHAR) AS note,\n" " status AS Status_Label\n" 'FROM __ref("stg_orders")\n' ), - "models/marts/all_orders.sql": ( + "sql/models/marts/all_orders.sql": ( 'MODEL (\n description "Every order column",\n);\n\nSELECT * FROM __ref("stg_orders")\n' ), } @@ -129,7 +129,7 @@ "Order_ID", ] _ENFORCED_MODEL: str = "stg_orders" -_NAMED_SCHEMA_PATH: Path = Path("schemas/orders_schema.sql") +_NAMED_SCHEMA_PATH: Path = Path("sql/schemas/orders_schema.sql") _LIFECYCLE_KEYS: tuple[str, ...] = ("contract", "materialized", "incremental_mode") _FAMILY_NAMES: tuple[str, ...] = ("amount_*", "Amount_*", "count_*", "label_*") _REASONS: tuple[str | None, ...] = (None, "", "no supported pivot") @@ -169,7 +169,7 @@ def compiled_contract_project(*, project_dir: Path) -> CompiledProjectView: files: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": _SOURCES, + "sql/sources/raw.yml": _SOURCES, **_MODELS, } for relative_path, contents in files.items(): diff --git a/tests/integration/src/sqlbuild/compiler/discovery/helpers.py b/tests/integration/src/sqlbuild/compiler/discovery/helpers.py index cc2621b29a..b4829d0158 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/helpers.py @@ -1041,7 +1041,7 @@ def native_yaml_tags_and_values( return [{True: "error", False: "ok"}[failure] for failure in failed], [row[1] for row in loaded] -VALIDATION_MODEL: tuple[str, bytes] = ("models/orders.sql", b"MODEL ();\nSELECT 1 AS order_id") +VALIDATION_MODEL: tuple[str, bytes] = ("sql/models/orders.sql", b"MODEL ();\nSELECT 1 AS order_id") def seed_project_files(*, header: bytes, settings: bytes = b"") -> tuple[tuple[str, bytes], ...]: @@ -1049,9 +1049,9 @@ def seed_project_files(*, header: bytes, settings: bytes = b"") -> tuple[tuple[s return ( VALIDATION_MODEL, - ("seeds/countries.csv", header + b"\nGB,United Kingdom\n"), + ("sql/seeds/countries.csv", header + b"\nGB,United Kingdom\n"), ( - "seeds/countries.yml", + "sql/seeds/countries.yml", b"seeds:\n - name: countries\n" + settings + b" columns:\n - name: code\n type: VARCHAR\n" @@ -1085,7 +1085,7 @@ def model_file_record() -> DiscoveredSqlModelFile: return DiscoveredSqlModelFile( file_path=Path("/project/models/orders.sql"), - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), contents="MODEL ();\nselect 1 as order_id", header_values={}, header_column_locations={}, diff --git a/tests/integration/src/sqlbuild/compiler/discovery/test_deep_header_values.py b/tests/integration/src/sqlbuild/compiler/discovery/test_deep_header_values.py index 8ba06c193e..5966e16455 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/test_deep_header_values.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/test_deep_header_values.py @@ -45,13 +45,15 @@ def test_given_header_values_at_the_limit_when_discovering_on_a_deep_stack_then_ ) -> None: write_project( project_dir=tmp_path, - files=(("models/orders.sql", f"MODEL ({test_case.header});\nSELECT 1 AS id\n".encode()),), + files=( + ("sql/models/orders.sql", f"MODEL ({test_case.header});\nSELECT 1 AS id\n".encode()), + ), ) parsed: object = on_deep_stack( frames=test_case.stack_frames, call=lambda: parse_header_values( header=test_case.header, - file_path=tmp_path / "models/orders.sql", + file_path=tmp_path / "sql/models/orders.sql", statement_name="MODEL", header_line=1, ), diff --git a/tests/integration/src/sqlbuild/compiler/discovery/test_discovery_failure_text.py b/tests/integration/src/sqlbuild/compiler/discovery/test_discovery_failure_text.py index a4f0f132d8..dd4d15a9d0 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/test_discovery_failure_text.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/test_discovery_failure_text.py @@ -18,9 +18,9 @@ write_project, ) -_MODEL: tuple[str, bytes] = ("models/orders.sql", b"MODEL ();\nSELECT 1 AS order_id") -_HOOK: tuple[str, bytes] = ("hooks/sql/refresh.sql", b"HOOK (descri\x00ption 'x');\nSELECT 1") -_CONSTANT: tuple[str, bytes] = ("constants/limits.sql", b"CONSTANT (name cap, valu\x00e 1);") +_MODEL: tuple[str, bytes] = ("sql/models/orders.sql", b"MODEL ();\nSELECT 1 AS order_id") +_HOOK: tuple[str, bytes] = ("sql/hooks/sql/refresh.sql", b"HOOK (descri\x00ption 'x');\nSELECT 1") +_CONSTANT: tuple[str, bytes] = ("sql/constants/limits.sql", b"CONSTANT (name cap, valu\x00e 1);") @pytest.mark.parametrize( @@ -28,7 +28,7 @@ [ FailureTextTestCase( description="a NUL in a model header key", - files=(("models/orders.sql", b"MODEL (descri\x00ption 'x');\nSELECT 1"),), + files=(("sql/models/orders.sql", b"MODEL (descri\x00ption 'x');\nSELECT 1"),), expected_error_type="ModelSqlParseError", expected_message_suffix="has unsupported keys: descri\x00ption", ), @@ -48,7 +48,7 @@ description="a NUL in an audit header key", files=( _MODEL, - ("audits/generic/positive.sql", b"AUDIT (sever\x00ity warn);\nSELECT 1"), + ("sql/audits/generic/positive.sql", b"AUDIT (sever\x00ity warn);\nSELECT 1"), ), expected_error_type="SqlAuditParseError", expected_message_suffix="has unsupported keys: sever\x00ity", @@ -58,7 +58,7 @@ files=( _MODEL, ( - "functions/sql/cents.sql", + "sql/functions/sql/cents.sql", b'FUNCTION (arguments (), returns INTEGER, descri\x00ption "x");\nSELECT 1', ), ), @@ -67,9 +67,9 @@ ), FailureTextTestCase( description="a raw entry name in a declaration group", - files=(_MODEL, (os.fsdecode(b"models/orders/_sqlbuild/caf\xe9.txt"), b"x")), + files=(_MODEL, (os.fsdecode(b"sql/models/orders/_sqlbuild/caf\xe9.txt"), b"x")), expected_error_type="DeclarationParseError", - expected_message_suffix="unsupported entries: models/orders/_sqlbuild/caf\\xe9.txt", + expected_message_suffix="unsupported entries: sql/models/orders/_sqlbuild/caf\\xe9.txt", ), ], ids=lambda case: case.description, diff --git a/tests/integration/src/sqlbuild/compiler/discovery/test_native_declaration_files.py b/tests/integration/src/sqlbuild/compiler/discovery/test_native_declaration_files.py index 41ec9cd017..1435b3a317 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/test_native_declaration_files.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/test_native_declaration_files.py @@ -56,38 +56,38 @@ b"SELECT amount * 2\n" ) _EVERY_KIND: tuple[tuple[str, bytes], ...] = ( - ("models/marts/orders.sql", _MODEL), - ("macros/python/money.py", _MACRO), - ("macros/python/__init__.py", b""), - ("models/marts/_macros/python/local.py", _MACRO), - ("enums/status.sql", _ENUMS), - ("models/marts/_enums/tier.sql", b"ENUM (name tier, members [GOLD]);\n"), - ("models/marts/_sqlbuild/constants/limits.sql", _CONSTANTS), - ("constants/global.sql", b"CONSTANT (name ratio, value 1.5);\n"), - ("models/marts/_sqlbuild/_audits/generic/is_true.sql", _AUDIT), - ("models/marts/_sqlbuild/audits/singular/orders_ok.sql", _AUDIT), - ("models/marts/_sqlbuild/_schemas/order_shape.sql", _SCHEMA), - ("models/marts/_sqlbuild/hooks/sql/record_marts_refresh.sql", _HOOK), - ("audits/generic/is_true.sql", _AUDIT), - ("audits/generic/nested/measured.sql", _MEASUREMENTS), - ("audits/singular/orders_ok.sql", _AUDIT), - ("schemas/order_shape.sql", _SCHEMA), - ("hooks/sql/record_refresh.sql", _HOOK), - ("hooks/sql/_private.sql", b"not a hook"), - ("functions/sql/double_amount.sql", _FUNCTION), - ("functions/sql/finance/net_amount.sql", _FUNCTION), - ("functions/sql/_macros/python/helpers.py", _MACRO), - ("seeds/channels.csv", b"id\n1\n"), + ("sql/models/marts/orders.sql", _MODEL), + ("sql/macros/python/money.py", _MACRO), + ("sql/macros/python/__init__.py", b""), + ("sql/models/marts/_macros/python/local.py", _MACRO), + ("sql/enums/status.sql", _ENUMS), + ("sql/models/marts/_enums/tier.sql", b"ENUM (name tier, members [GOLD]);\n"), + ("sql/models/marts/_sqlbuild/constants/limits.sql", _CONSTANTS), + ("sql/constants/global.sql", b"CONSTANT (name ratio, value 1.5);\n"), + ("sql/models/marts/_sqlbuild/_audits/generic/is_true.sql", _AUDIT), + ("sql/models/marts/_sqlbuild/audits/singular/orders_ok.sql", _AUDIT), + ("sql/models/marts/_sqlbuild/_schemas/order_shape.sql", _SCHEMA), + ("sql/models/marts/_sqlbuild/hooks/sql/record_marts_refresh.sql", _HOOK), + ("sql/audits/generic/is_true.sql", _AUDIT), + ("sql/audits/generic/nested/measured.sql", _MEASUREMENTS), + ("sql/audits/singular/orders_ok.sql", _AUDIT), + ("sql/schemas/order_shape.sql", _SCHEMA), + ("sql/hooks/sql/record_refresh.sql", _HOOK), + ("sql/hooks/sql/_private.sql", b"not a hook"), + ("sql/functions/sql/double_amount.sql", _FUNCTION), + ("sql/functions/sql/finance/net_amount.sql", _FUNCTION), + ("sql/functions/sql/_macros/python/helpers.py", _MACRO), + ("sql/seeds/channels.csv", b"id\n1\n"), ( - "seeds/seeds.yml", + "sql/seeds/seeds.yml", b"seeds:\n - name: channels\n description: Sales channels.\n" b" columns:\n - name: id\n type: INTEGER\n" b" - name: stores\n description: Stores.\n" b" columns:\n - name: id\n type: INTEGER\n", ), - ("seeds/regional/stores.csv", b"id\n2\n"), - ("seeds/readme.md", b"seeds"), - ("seeds/archive.csv/notes.txt", b"a directory named like a seed"), + ("sql/seeds/regional/stores.csv", b"id\n2\n"), + ("sql/seeds/readme.md", b"seeds"), + ("sql/seeds/archive.csv/notes.txt", b"a directory named like a seed"), ) @@ -97,7 +97,7 @@ GeneratedDeclarationFileTestCase( description="generated enum files", kind="enum", - relative_path="enums/generated.sql", + relative_path="sql/enums/generated.sql", case_count=150, expected_minimum_parsed=20, expected_minimum_failed=60, @@ -106,7 +106,7 @@ GeneratedDeclarationFileTestCase( description="generated constant files", kind="constant", - relative_path="models/marts/_constants/generated.sql", + relative_path="sql/models/marts/_constants/generated.sql", case_count=150, expected_minimum_parsed=60, expected_minimum_failed=30, @@ -115,7 +115,7 @@ GeneratedDeclarationFileTestCase( description="generated reusable schema files", kind="model_schema", - relative_path="schemas/generated.sql", + relative_path="sql/schemas/generated.sql", case_count=150, expected_minimum_parsed=50, expected_minimum_failed=30, @@ -124,7 +124,7 @@ GeneratedDeclarationFileTestCase( description="generated audit files", kind="audit", - relative_path="models/marts/_sqlbuild/audits/generic/generated.sql", + relative_path="sql/models/marts/_sqlbuild/audits/generic/generated.sql", case_count=150, expected_minimum_parsed=30, expected_minimum_failed=60, @@ -133,7 +133,7 @@ GeneratedDeclarationFileTestCase( description="generated SQL hook files", kind="sql_hook", - relative_path="hooks/sql/generated.sql", + relative_path="sql/hooks/sql/generated.sql", case_count=150, expected_minimum_parsed=40, expected_minimum_failed=40, @@ -142,7 +142,7 @@ GeneratedDeclarationFileTestCase( description="generated SQL function files", kind="sql_function", - relative_path="functions/sql/generated.sql", + relative_path="sql/functions/sql/generated.sql", case_count=150, expected_minimum_parsed=50, expected_minimum_failed=30, @@ -173,8 +173,8 @@ def test_given_generated_declaration_files_when_discovering_then_native_parses_o DeclarationFilesParityTestCase( description="the first failing enum file in path order is reported", files=( - ("enums/a_status.sql", b"ENUM (name a_status, members [placed]);\n"), - ("enums/b_status.sql", b"ENUM (name b_status);\n"), + ("sql/enums/a_status.sql", b"ENUM (name a_status, members [placed]);\n"), + ("sql/enums/b_status.sql", b"ENUM (name b_status);\n"), ), expected_failure_type="DeclarationParseError", expected_message_fragment="member identifiers must be uppercase: 'placed'", @@ -183,7 +183,7 @@ def test_given_generated_declaration_files_when_discovering_then_native_parses_o description="an earlier constant's value fails before a later constant's name", files=( ( - "constants/limits.sql", + "sql/constants/limits.sql", b"CONSTANT (name launch, value 'soon', type DATE);\n" b"CONSTANT (name Bad, value 1);\n", ), @@ -195,7 +195,7 @@ def test_given_generated_declaration_files_when_discovering_then_native_parses_o description="an earlier schema's columns fail before a later schema's keys", files=( ( - "schemas/shapes.sql", + "sql/schemas/shapes.sql", b"SCHEMA (name first_shape, columns (id (nullable maybe)));\n" b"SCHEMA (name second_shape, extra 1, columns (id (type INT)));\n", ), @@ -205,34 +205,34 @@ def test_given_generated_declaration_files_when_discovering_then_native_parses_o ), DeclarationFilesParityTestCase( description="a non-canonical declaration name fails with the identity help", - files=(("enums/status.sql", b"ENUM (name OrderStatus, members [PLACED]);\n"),), + files=(("sql/enums/status.sql", b"ENUM (name OrderStatus, members [PLACED]);\n"),), expected_failure_type="ResourceIdentityError", expected_message_fragment="use snake_case 'order_status'", ), DeclarationFilesParityTestCase( description="a nested declaration root fails before any file is parsed", files=( - ("models/marts/_enums/macros/python/money.py", _MACRO), - ("enums/status.sql", b"broken"), + ("sql/models/marts/_enums/macros/python/money.py", _MACRO), + ("sql/enums/status.sql", b"broken"), ), expected_failure_type="DeclarationParseError", expected_message_fragment="is nested inside another declaration tree", ), DeclarationFilesParityTestCase( description="an unreadable audit file fails with Python's decode error", - files=(("audits/generic/is_true.sql", b"AUDIT ();\nSELECT '\xff'\n"),), + files=(("sql/audits/generic/is_true.sql", b"AUDIT ();\nSELECT '\xff'\n"),), expected_failure_type="UnicodeDecodeError", expected_message_fragment="invalid start byte", ), DeclarationFilesParityTestCase( description="an unreadable macro file fails with Python's decode error", - files=(("macros/python/money.py", b"# \xc3"),), + files=(("sql/macros/python/money.py", b"# \xc3"),), expected_failure_type="UnicodeDecodeError", expected_message_fragment="unexpected end of data", ), DeclarationFilesParityTestCase( description="a hook with an unsupported key fails with the key suggestion", - files=(("hooks/sql/refresh.sql", b'HOOK (descripton "Refresh");\nSELECT 1\n'),), + files=(("sql/hooks/sql/refresh.sql", b'HOOK (descripton "Refresh");\nSELECT 1\n'),), expected_failure_type="SqlHookParseError", expected_message_fragment="has unsupported keys: descripton", ), @@ -240,7 +240,7 @@ def test_given_generated_declaration_files_when_discovering_then_native_parses_o description="a measurement audit without MEASURE fails", files=( ( - "audits/generic/measured.sql", + "sql/audits/generic/measured.sql", b"AUDIT (evaluation measurement, value total);\nSELECT 1\n", ), ), @@ -249,7 +249,7 @@ def test_given_generated_declaration_files_when_discovering_then_native_parses_o ), DeclarationFilesParityTestCase( description="a SQL function without a body fails", - files=(("functions/sql/empty.sql", b"FUNCTION (returns INT);\n \n"),), + files=(("sql/functions/sql/empty.sql", b"FUNCTION (returns INT);\n \n"),), expected_failure_type="ModelSqlParseError", expected_message_fragment="must contain SQL after FUNCTION(...)", ), @@ -272,7 +272,7 @@ def test_given_declaration_files_when_discovering_then_inputs_or_failures_are_ex DeepDeclarationHeaderTestCase( description="a constant value nested 1k levels", kind="constant", - relative_path="constants/limits.sql", + relative_path="sql/constants/limits.sql", prefix="CONSTANT (name cap, value 3);\nCONSTANT (\n name regions,\n value ", suffix=",\n);\n", depth=1_000, @@ -282,7 +282,7 @@ def test_given_declaration_files_when_discovering_then_inputs_or_failures_are_ex DeepDeclarationHeaderTestCase( description="a hook description nested 20k levels", kind="sql_hook", - relative_path="hooks/sql/refresh.sql", + relative_path="sql/hooks/sql/refresh.sql", prefix="HOOK (\n description ", suffix=",\n);\n\nSELECT 1\n", depth=20_000, @@ -292,7 +292,7 @@ def test_given_declaration_files_when_discovering_then_inputs_or_failures_are_ex DeepDeclarationHeaderTestCase( description="a function return type nested 100k levels", kind="sql_function", - relative_path="functions/sql/doubled.sql", + relative_path="sql/functions/sql/doubled.sql", prefix='FUNCTION (\n description "Doubles",\n returns ', suffix=",\n);\nSELECT 2\n", depth=100_000, @@ -302,7 +302,7 @@ def test_given_declaration_files_when_discovering_then_inputs_or_failures_are_ex DeepDeclarationHeaderTestCase( description="a later audit block's value nested 100k levels", kind="audit", - relative_path="audits/generic/is_true.sql", + relative_path="sql/audits/generic/is_true.sql", prefix="AUDIT (name first);\nSELECT 1\nAUDIT (\n name second,\n value ", suffix=",\n);\nSELECT 2\n", depth=100_000, @@ -338,12 +338,12 @@ def test_given_deeply_nested_declaration_header_when_discovering_then_its_line_i description="broken files of every kind become the same faults", files=( *_EVERY_KIND, - ("enums/broken.sql", b"ENUM (name broken);\n"), - ("constants/broken.sql", b"CONSTANT (name Broken, value 1);\n"), - ("schemas/broken.sql", b"SCHEMA (name broken_shape);\n"), - ("audits/generic/broken.sql", b"SELECT 1\n"), - ("hooks/sql/broken.sql", b"HOOK ();\n"), - ("functions/sql/broken.sql", b"SELECT 1\n"), + ("sql/enums/broken.sql", b"ENUM (name broken);\n"), + ("sql/constants/broken.sql", b"CONSTANT (name Broken, value 1);\n"), + ("sql/schemas/broken.sql", b"SCHEMA (name broken_shape);\n"), + ("sql/audits/generic/broken.sql", b"SELECT 1\n"), + ("sql/hooks/sql/broken.sql", b"HOOK ();\n"), + ("sql/functions/sql/broken.sql", b"SELECT 1\n"), ), expected_resource_faults=3, expected_declaration_faults=3, diff --git a/tests/integration/src/sqlbuild/compiler/discovery/test_native_model_discovery.py b/tests/integration/src/sqlbuild/compiler/discovery/test_native_model_discovery.py index a38c6bb87d..141057d38f 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/test_native_model_discovery.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/test_native_model_discovery.py @@ -47,7 +47,7 @@ def test_given_runtime_and_root_when_discovering_natively_then_supported_runs_an test_case: NativeRuntimeTestCase, tmp_path: Path ) -> None: project_dir: Path = tmp_path / test_case.project_name - write_project(project_dir=project_dir, files=(("models/orders.sql", _VALID_MODEL),)) + write_project(project_dir=project_dir, files=(("sql/models/orders.sql", _VALID_MODEL),)) capture: FailureCapture = FailureCapture() models: list[DiscoveredSqlModelFile] = [] @@ -72,7 +72,7 @@ def test_given_runtime_and_root_when_discovering_natively_then_supported_runs_an [ SharedSnapshotTestCase( description="a Python file created after the model walk stays unseen", - created_file="models/marts/late.py", + created_file="sql/models/marts/late.py", ), ], ids=lambda case: case.description, @@ -80,7 +80,7 @@ def test_given_runtime_and_root_when_discovering_natively_then_supported_runs_an def test_given_native_model_walk_when_globbing_models_later_in_the_pass_then_the_walk_is_shared( test_case: SharedSnapshotTestCase, tmp_path: Path ) -> None: - write_project(project_dir=tmp_path, files=(("models/marts/orders.sql", _VALID_MODEL),)) + write_project(project_dir=tmp_path, files=(("sql/models/marts/orders.sql", _VALID_MODEL),)) with directory_snapshot_scope(project_dir=tmp_path): _ = discover_model_files( project_dir=tmp_path, diff --git a/tests/integration/src/sqlbuild/compiler/discovery/test_native_project_validation.py b/tests/integration/src/sqlbuild/compiler/discovery/test_native_project_validation.py index 103c7ccd6e..9dc3fd77a0 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/test_native_project_validation.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/test_native_project_validation.py @@ -28,7 +28,7 @@ files=seed_project_files(header=b"code,name"), expected_error_type="SeedDiscoveryError", expected_message=( - "seeds/countries.csv header ('code', 'name') does not match declared seed " + "sql/seeds/countries.csv header ('code', 'name') does not match declared seed " "columns ('code', 'label') for 'countries'" ), ), @@ -40,37 +40,37 @@ ), expected_error_type="SeedDiscoveryError", expected_message=( - "seeds/countries.csv header ('code', 'label', 'extra') does not match declared " + "sql/seeds/countries.csv header ('code', 'label', 'extra') does not match declared " "seed columns ('code', 'label') for 'countries'" ), ), ProjectValidationTestCase( description="a seed CSV without a declaration", - files=(VALIDATION_MODEL, ("seeds/regions.csv", b"code\nEU\n")), + files=(VALIDATION_MODEL, ("sql/seeds/regions.csv", b"code\nEU\n")), expected_error_type="SeedDiscoveryError", expected_message=( - "Seed CSV seeds/regions.csv has no matching declaration for seed 'regions' under " - "seeds/**/*.yml" + "Seed CSV sql/seeds/regions.csv has no matching declaration for seed 'regions' under " + "sql/seeds/**/*.yml" ), ), ProjectValidationTestCase( description="two model files with one name", files=( VALIDATION_MODEL, - ("models/marts/orders.sql", b"MODEL ();\nSELECT 2 AS order_id"), + ("sql/models/marts/orders.sql", b"MODEL ();\nSELECT 2 AS order_id"), ), expected_error_type="DiscoveryConflictError", expected_message=( - "Duplicate model file name found for 'orders' in models/marts/orders.sql and " - "models/orders.sql" + "Duplicate model file name found for 'orders' in sql/models/marts/orders.sql and " + "sql/models/orders.sql" ), ), ProjectValidationTestCase( description="a non-canonical model identity", - files=(("models/Orders.sql", b"MODEL ();\nSELECT 1 AS order_id"),), + files=(("sql/models/Orders.sql", b"MODEL ();\nSELECT 1 AS order_id"),), expected_error_type="ResourceIdentityError", expected_message=( - "Invalid model identity 'Orders' in models/Orders.sql; use snake_case 'orders'" + "Invalid model identity 'Orders' in sql/models/Orders.sql; use snake_case 'orders'" ), ), ], diff --git a/tests/integration/src/sqlbuild/compiler/discovery/test_native_read_errors.py b/tests/integration/src/sqlbuild/compiler/discovery/test_native_read_errors.py index cbc207d2f9..610c10c91c 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/test_native_read_errors.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/test_native_read_errors.py @@ -42,7 +42,7 @@ def test_given_undecodable_files_when_reading_natively_then_errors_equal_read_te ) -> None: rng: random.Random = random.Random(test_case.seed) files: tuple[tuple[str, bytes], ...] = tuple( - (f"sources/file_{index}.yml", random_undecodable_bytes(rng=rng)) + (f"sql/sources/file_{index}.yml", random_undecodable_bytes(rng=rng)) for index in range(test_case.case_count) ) write_project(project_dir=tmp_path, files=files) @@ -63,7 +63,7 @@ def test_given_undecodable_files_when_reading_natively_then_errors_equal_read_te [ UnreadableFileTestCase( description="an undecodable model", - relative_path="models/orders.sql", + relative_path="sql/models/orders.sql", data=_STAGING + b"\xff", expected_error="UnicodeDecodeError", expected_message=( @@ -90,7 +90,7 @@ def test_given_undecodable_files_when_reading_natively_then_errors_equal_read_te ), UnreadableFileTestCase( description="an undecodable source file", - relative_path="sources/raw.yml", + relative_path="sql/sources/raw.yml", data=b"sources: []\n# \xc0\n", expected_error="UnicodeDecodeError", expected_message=( @@ -99,10 +99,10 @@ def test_given_undecodable_files_when_reading_natively_then_errors_equal_read_te ), UnreadableFileTestCase( description="a directory named like a schema file", - relative_path="models/marts/schema.yml/notes.txt", + relative_path="sql/models/marts/schema.yml/notes.txt", data=b"", expected_error="IsADirectoryError", - expected_message="[Errno 21] Is a directory: '{project}/models/marts/schema.yml'", + expected_message="[Errno 21] Is a directory: '{project}/sql/models/marts/schema.yml'", ), ], ids=lambda case: case.description, @@ -112,7 +112,7 @@ def test_given_unreadable_file_when_discovering_then_python_read_error_is_raised ) -> None: write_project( project_dir=tmp_path, - files=(("models/staging.sql", _STAGING), (test_case.relative_path, test_case.data)), + files=(("sql/models/staging.sql", _STAGING), (test_case.relative_path, test_case.data)), ) failure: tuple[str, str] = compile_failure(project_dir=tmp_path) diff --git a/tests/integration/src/sqlbuild/compiler/discovery/test_native_undecodable_paths.py b/tests/integration/src/sqlbuild/compiler/discovery/test_native_undecodable_paths.py index d9011ef856..b037c48500 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/test_native_undecodable_paths.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/test_native_undecodable_paths.py @@ -24,14 +24,14 @@ _TEST: bytes = b'TEST (name "keeps_orders");\nSELECT 1\n' _SOURCE: bytes = b"sources:\n - name: raw_orders\n" _FILES: tuple[tuple[str, bytes], ...] = ( - ("models/orders.sql", _MODEL), - (os.fsdecode(b"models/caf\xe9.sql"), _MODEL), - (os.fsdecode(b"models/notes\xe9.txt"), b"x"), + ("sql/models/orders.sql", _MODEL), + (os.fsdecode(b"sql/models/caf\xe9.sql"), _MODEL), + (os.fsdecode(b"sql/models/notes\xe9.txt"), b"x"), ("tests/unit/orders.sql", _TEST), (os.fsdecode(b"tests/unit/old\xe9/orders.sql"), _TEST), - ("sources/raw.yml", _SOURCE), + ("sql/sources/raw.yml", _SOURCE), ) -_BAD_SOURCE: tuple[str, bytes] = (os.fsdecode(b"sources/caf\xe9.yml"), _SOURCE) +_BAD_SOURCE: tuple[str, bytes] = (os.fsdecode(b"sql/sources/caf\xe9.yml"), _SOURCE) _RENAME: str = " is not valid UTF-8; rename it so SQLBuild can read it" _ORDER_STATUS: bytes = b"ENUM (name order_status, members [PLACED]);\n" _TIER: bytes = b"ENUM (name tier, members [GOLD]);\n" @@ -49,11 +49,11 @@ description="scope discovery faults each unreadable path and keeps the rest", reader="scope", files=(*_FILES, _BAD_SOURCE), - expected_models=("models/orders.sql",), - expected_sources=("sources/raw.yml",), + expected_models=("sql/models/orders.sql",), + expected_sources=("sql/sources/raw.yml",), expected_faults=( - (_FILES[1][0], f"Project path ./models/caf\\xe9.sql{_RENAME}"), - (_BAD_SOURCE[0], f"Project path ./sources/caf\\xe9.yml{_RENAME}"), + (_FILES[1][0], f"Project path ./sql/models/caf\\xe9.sql{_RENAME}"), + (_BAD_SOURCE[0], f"Project path ./sql/sources/caf\\xe9.yml{_RENAME}"), (_FILES[4][0], f"Project path ./tests/unit/old\\xe9/orders.sql{_RENAME}"), ), ), @@ -61,16 +61,16 @@ description="a valid name is not blamed for a raw sibling with the same lossy name", reader="scope", files=( - ("models/orders.sql", _MODEL), - ("models/st\ufffd.sql", b"MODEL ();\nSELECT 2 AS id"), - (os.fsdecode(b"models/st\xe8.sql"), b"garbage"), + ("sql/models/orders.sql", _MODEL), + ("sql/models/st\ufffd.sql", b"MODEL ();\nSELECT 2 AS id"), + (os.fsdecode(b"sql/models/st\xe8.sql"), b"garbage"), ), - expected_models=("models/orders.sql", "models/st\ufffd.sql"), + expected_models=("sql/models/orders.sql", "sql/models/st\ufffd.sql"), expected_sources=(), expected_faults=( ( - os.fsdecode(b"models/st\xe8.sql"), - f"Project path ./models/st\\xe8.sql{_RENAME}", + os.fsdecode(b"sql/models/st\xe8.sql"), + f"Project path ./sql/models/st\\xe8.sql{_RENAME}", ), ), ), @@ -78,15 +78,15 @@ description="model descriptions skip an unreadable model path", reader="descriptions", files=(*_FILES, _BAD_SOURCE), - expected_models=("models/orders.sql",), + expected_models=("sql/models/orders.sql",), expected_sources=(), ), UndecodablePathToleranceTestCase( description="selected contracts never read an unselected model path", reader="selected contracts", files=_FILES, - expected_models=("models/orders.sql",), - expected_sources=("sources/raw.yml",), + expected_models=("sql/models/orders.sql",), + expected_sources=("sql/sources/raw.yml",), ), ], ids=lambda case: case.description, @@ -110,21 +110,21 @@ def test_given_undecodable_paths_when_discovering_tolerantly_then_each_read_path [ UndecodableDeclarationNameTestCase( description="an enum file whose name is not UTF-8", - relative_path=b"enums/st\xe9.sql", + relative_path=b"sql/enums/st\xe9.sql", contents=_ORDER_STATUS, - expected_path="enums/st\\xe9.sql", + expected_path="sql/enums/st\\xe9.sql", ), UndecodableDeclarationNameTestCase( description="a scoped enum directory whose name is not UTF-8", - relative_path=b"models/a\xe8/_enums/y.sql", + relative_path=b"sql/models/a\xe8/_enums/y.sql", contents=_TIER, - expected_path="models/a\\xe8/_enums/y.sql", + expected_path="sql/models/a\\xe8/_enums/y.sql", ), UndecodableDeclarationNameTestCase( description="a SQL hook whose name is not UTF-8", - relative_path=b"hooks/sql/refresh_\xff.sql", + relative_path=b"sql/hooks/sql/refresh_\xff.sql", contents=b"HOOK ();\nSELECT 1\n", - expected_path="hooks/sql/refresh_\\xff.sql", + expected_path="sql/hooks/sql/refresh_\\xff.sql", ), ], ids=lambda case: case.description, @@ -135,7 +135,7 @@ def test_given_declaration_file_named_with_invalid_utf8_when_discovering_then_d0 write_project( project_dir=tmp_path, files=( - ("models/orders.sql", _MODEL), + ("sql/models/orders.sql", _MODEL), (os.fsdecode(test_case.relative_path), test_case.contents), ), ) diff --git a/tests/integration/src/sqlbuild/compiler/discovery/test_native_yaml_and_path_failures.py b/tests/integration/src/sqlbuild/compiler/discovery/test_native_yaml_and_path_failures.py index cb29494219..e9b6e790b4 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/test_native_yaml_and_path_failures.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/test_native_yaml_and_path_failures.py @@ -27,7 +27,7 @@ description="block, flow, quoted, folded and literal values with anchors and merges", files=( ( - "sources/raw.yml", + "sql/sources/raw.yml", b"---\n# raw\n" + _SOURCE_HEAD + b" description: >\n Raw\n" b" orders.\n meta: &m {owner: 'data', tags: [a, \"b\"]}\n" b" - name: raw_items\n description: |\n Items.\n" @@ -37,19 +37,21 @@ ), AuthoredFileFailureTestCase( description="invalid YAML names the file and position", - files=(("sources/raw.yml", _SOURCE_HEAD + b" description: [unclosed\n"),), + files=(("sql/sources/raw.yml", _SOURCE_HEAD + b" description: [unclosed\n"),), expected_error="SourceParseError", expected_message=( - "{project}/sources/raw.yml contains invalid YAML at line 4, column 1: while " + "{project}/sql/sources/raw.yml contains invalid YAML at line 4, column 1: while " "parsing a flow sequence, expected ',' or ']'" ), ), AuthoredFileFailureTestCase( description="a binary value is unsupported at its node", - files=(("sources/raw.yml", _SOURCE_HEAD + b" meta:\n blob: !!binary aGk=\n"),), + files=( + ("sql/sources/raw.yml", _SOURCE_HEAD + b" meta:\n blob: !!binary aGk=\n"), + ), expected_error="SourceParseError", expected_message=( - "{project}/sources/raw.yml uses YAML that SQLBuild does not support at line 4, " + "{project}/sql/sources/raw.yml uses YAML that SQLBuild does not support at line 4, " "column 22: values tagged !!binary" ), expected_help=_HELP, @@ -58,51 +60,51 @@ description="a tab inside a quoted value and a directive load", files=( ( - "sources/raw.yml", + "sql/sources/raw.yml", b"%YAML 1.2\n---\n" + _SOURCE_HEAD + b' description: "Raw\torders"\n', ), ), ), AuthoredFileFailureTestCase( description="a recursive alias is unsupported at the alias", - files=(("sources/raw.yml", b"sources: []\nmeta: &a [*a]\n"),), + files=(("sql/sources/raw.yml", b"sources: []\nmeta: &a [*a]\n"),), expected_error="SourceParseError", expected_message=( - "{project}/sources/raw.yml uses YAML that SQLBuild does not support at line 2, " + "{project}/sql/sources/raw.yml uses YAML that SQLBuild does not support at line 2, " "column 11: recursive aliases" ), expected_help=_HELP, ), AuthoredFileFailureTestCase( description="an invalid schema file fails as a schema file", - files=(("models/marts/schema.yml", b"models: [\n"),), + files=(("sql/models/marts/schema.yml", b"models: [\n"),), expected_error="SchemaParseError", expected_message=( - "{project}/models/marts/schema.yml contains invalid YAML at line 2, column 1: " + "{project}/sql/models/marts/schema.yml contains invalid YAML at line 2, column 1: " "while parsing a node, did not find expected node content" ), ), AuthoredFileFailureTestCase( description="names discovery never reads may be any bytes", files=( - ("models/orders.sql", _MODEL), - (os.fsdecode(b"models/notes\xe9.txt"), b"x"), - (os.fsdecode(b"models/old\xe9/readme.md"), b"x"), - (os.fsdecode(b"macros/x\xe9.txt"), b"x"), + ("sql/models/orders.sql", _MODEL), + (os.fsdecode(b"sql/models/notes\xe9.txt"), b"x"), + (os.fsdecode(b"sql/models/old\xe9/readme.md"), b"x"), + (os.fsdecode(b"sql/macros/x\xe9.txt"), b"x"), (os.fsdecode(b"tests/unit/x\xe9.txt"), b"x"), (os.fsdecode(b"tests/scenarios/x\xe9.md"), b"x"), - (os.fsdecode(b"sources/x\xe9.txt"), b"x"), - (os.fsdecode(b"seeds/x\xe9.txt"), b"x"), - (os.fsdecode(b"data\xe9.csv"), b"x"), + (os.fsdecode(b"sql/sources/x\xe9.txt"), b"x"), + (os.fsdecode(b"sql/seeds/x\xe9.txt"), b"x"), + (os.fsdecode(b"tests/data\xe9.csv"), b"x"), (os.fsdecode(b"target/x\xe9"), b"x"), ), ), AuthoredFileFailureTestCase( description="a model below a directory that is not UTF-8 is shown lossily", - files=((os.fsdecode(b"models/old\xe9/orders.sql"), _MODEL),), + files=((os.fsdecode(b"sql/models/old\xe9/orders.sql"), _MODEL),), expected_error="ProjectPathError", expected_message=( - "Project path {project}/models/old\\xe9/orders.sql is not valid UTF-8; rename it " + "Project path {project}/sql/models/old\\xe9/orders.sql is not valid UTF-8; rename it " "so SQLBuild can read it" ), ), @@ -117,19 +119,19 @@ ), AuthoredFileFailureTestCase( description="a source path that is not UTF-8 is shown lossily", - files=((os.fsdecode(b"sources/caf\xe9.yml"), _SOURCE_HEAD),), + files=((os.fsdecode(b"sql/sources/caf\xe9.yml"), _SOURCE_HEAD),), expected_error="ProjectPathError", expected_message=( - "Project path {project}/sources/caf\\xe9.yml is not valid UTF-8; rename it so " + "Project path {project}/sql/sources/caf\\xe9.yml is not valid UTF-8; rename it so " "SQLBuild can read it" ), ), AuthoredFileFailureTestCase( description="a model path that is not UTF-8 is shown lossily", - files=((os.fsdecode(b"models/caf\xe9.sql"), b"MODEL ();\nSELECT 1 AS id"),), + files=((os.fsdecode(b"sql/models/caf\xe9.sql"), b"MODEL ();\nSELECT 1 AS id"),), expected_error="ProjectPathError", expected_message=( - "Project path {project}/models/caf\\xe9.sql is not valid UTF-8; rename it so " + "Project path {project}/sql/models/caf\\xe9.sql is not valid UTF-8; rename it so " "SQLBuild can read it" ), ), diff --git a/tests/integration/src/sqlbuild/compiler/discovery/test_native_yaml_file_discovery.py b/tests/integration/src/sqlbuild/compiler/discovery/test_native_yaml_file_discovery.py index f139b2ac9a..acd257500a 100644 --- a/tests/integration/src/sqlbuild/compiler/discovery/test_native_yaml_file_discovery.py +++ b/tests/integration/src/sqlbuild/compiler/discovery/test_native_yaml_file_discovery.py @@ -25,7 +25,7 @@ description="a big decimal integer loads exactly as a value and an explicit key", files=( ( - "sources/a.yml", + "sql/sources/a.yml", ( f"sources:\n - name: orders\n meta:\n big: {_BIG_DECIMAL}\n" f" ? {_BIG_DECIMAL}\n : key\n" @@ -46,15 +46,15 @@ ), NativeYamlLoadTestCase( description="a hexadecimal integer beyond 64 bits fails", - files=(("sources/a.yml", f"sources: []\nmeta: {{v: {_BIG_HEX}}}\n".encode()),), + files=(("sql/sources/a.yml", f"sources: []\nmeta: {{v: {_BIG_HEX}}}\n".encode()),), expected_native_tags=("error",), expected_values=(), ), NativeYamlLoadTestCase( description="an invalid file fails on its own and a later file still loads", files=( - ("sources/a.yml", b"sources: [\n"), - ("sources/b.yml", b"sources: []\nmeta: {v: on, w: 0o17}\n"), + ("sql/sources/a.yml", b"sources: [\n"), + ("sql/sources/b.yml", b"sources: []\nmeta: {v: on, w: 0o17}\n"), ), expected_native_tags=("error", "ok"), expected_values=({"sources": [], "meta": {"v": "on", "w": 15}},), diff --git a/tests/integration/src/sqlbuild/compiler/explicit_references/helpers.py b/tests/integration/src/sqlbuild/compiler/explicit_references/helpers.py index 789c586e04..424a53625e 100644 --- a/tests/integration/src/sqlbuild/compiler/explicit_references/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/explicit_references/helpers.py @@ -32,12 +32,13 @@ ) _DISABLED: str = _PROJECT + "\n[references]\nenforce_explicit = false\n" _OLD_NAMES_OFF: str = _PROJECT + "\n[migrations]\nold_name_views = false\n" -_HOOK_PATH: str = "models/marts/_sqlbuild/_hooks/python/lookups.py" -_SQL_HOOK_PATH: str = "models/marts/_sqlbuild/_hooks/sql/record_rows.sql" -_TASK_PATH: str = "python/tasks/export.py" -_CHECK_PATH: str = "python/checks/orders.py" -_ASSET_PATH: str = "python/assets/snapshot.py" -_LOADER_PATH: str = "python/loaders/raw.py" +_HOOK_PATH: str = "sql/models/marts/_sqlbuild/_hooks/python/lookups.py" +_SQL_HOOK_PATH: str = "sql/models/marts/_sqlbuild/_hooks/sql/record_rows.sql" +_TASK_PATH: str = "python/nodes/tasks/export/asset.py" +_CHECK_PATH: str = "python/nodes/checks/orders/checks.py" +_ASSET_PATH: str = "python/nodes/assets/snapshot/asset.py" +_REGIONS_LOADER_PATH: str = "python/nodes/loaders/raw_regions/loader.py" +_CUSTOMERS_LOADER_PATH: str = "python/nodes/loaders/raw_customers/loader.py" _HOOKED: str = 'MODEL (description "Orders.", post_hooks [python("refresh_lookup")]);' _NAMED_SQL_HOOK: str = 'MODEL (description "Orders.", post_hooks [sql("record_rows")]);' @@ -78,29 +79,37 @@ def _asset(body: str) -> str: ) -def _loaders(*, depends_on: str, body: str) -> str: - return ( - "from sqlbuild.loaders import loader\n\n\n" - "@loader\ndef raw_regions(ctx):\n '''Test loader raw_regions.'''\n" - " return [{'id': 1}]\n\n\n" - f"@loader(depends_on=[{depends_on}])\ndef raw_customers(ctx):\n{body}" - " return [{'id': 1}]\n" - ) +def _loaders(*, depends_on: str, body: str) -> dict[str, str]: + """Loaders raw_regions and raw_customers, each in its unit folder, at their old line numbers.""" + + return { + _REGIONS_LOADER_PATH: ( + "from sqlbuild.loaders import loader\n\n\n" + "@loader\ndef raw_regions(ctx):\n '''Test loader raw_regions.'''\n" + " return [{'id': 1}]\n" + ), + _CUSTOMERS_LOADER_PATH: ( + "from sqlbuild.loaders import loader\n\n" + "from python.nodes.loaders.raw_regions.loader import raw_regions\n\n\n\n\n\n\n" + f"@loader(depends_on=[{depends_on}])\ndef raw_customers(ctx):\n{body}" + " return [{'id': 1}]\n" + ), + } _MODELS: dict[str, str] = { - "models/marts/customers.sql": _model("SELECT 1 AS customer_id"), - "models/marts/orders.sql": _model("SELECT 1 AS order_id", header=_HOOKED), + "sql/models/marts/customers.sql": _model("SELECT 1 AS customer_id"), + "sql/models/marts/orders.sql": _model("SELECT 1 AS order_id", header=_HOOKED), } _SEED: dict[str, str] = { - "seeds/country_codes.yml": ( + "sql/seeds/country_codes.yml": ( "seeds:\n - name: country_codes\n description: Country codes.\n" " columns:\n - name: code\n type: VARCHAR\n" ), - "seeds/country_codes.csv": "code\nGB\n", + "sql/seeds/country_codes.csv": "code\nGB\n", } _MANAGED: dict[str, str] = { - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_regions\n description: Raw regions.\n managed: true\n" " write_strategy: table\n columns:\n - name: id\n type: INTEGER\n" @@ -109,7 +118,7 @@ def _loaders(*, depends_on: str, body: str) -> str: ), } _EXTERNAL: dict[str, str] = { - "sources/landing.yml": ( + "sql/sources/landing.yml": ( "sources:\n - name: landing_orders\n description: Landing orders.\n" " schema: landing\n table: orders_feed\n" " - name: computed\n description: Computed.\n expression: SELECT 1 AS id\n" @@ -130,7 +139,7 @@ def _gate_model(sql: str, audits: str) -> str: **_MODELS, **_MANAGED, _HOOK_PATH: _hook(), - _LOADER_PATH: _loaders(depends_on="", body=""), + **_loaders(depends_on="", body=""), _TASK_PATH: _task( ' ctx.query("SELECT * FROM raw_customers JOIN customers ON true")\n' ' ctx.execute_sql(sql="DELETE FROM main.orders")\n' @@ -185,7 +194,7 @@ def _gate_model(sql: str, audits: str) -> str: **_MANAGED, **_SEED, _HOOK_PATH: _hook(), - _LOADER_PATH: _loaders( + **_loaders( depends_on="raw_regions", body=( ' ctx.query("SELECT * FROM raw_customers JOIN raw_regions ON true")\n' @@ -201,7 +210,7 @@ def _gate_model(sql: str, audits: str) -> str: **_MODELS, **_MANAGED, _HOOK_PATH: _hook(), - _LOADER_PATH: _loaders( + **_loaders( depends_on="", body=' ctx.query("SELECT * FROM raw_regions")\n', ), @@ -211,21 +220,21 @@ def _gate_model(sql: str, audits: str) -> str: ( "old names kept as compatibility views", { - "models/marts/customers.sql": _model( + "sql/models/marts/customers.sql": _model( "SELECT 1 AS customer_id", header=( 'MODEL (description "Customers.", materialized table, ' "migrate_from legacy_customers);" ), ), - "models/marts/orders.sql": _model( + "sql/models/marts/orders.sql": _model( "SELECT 1 AS order_id", header=( 'MODEL (description "Orders.", materialized table, ' 'migrate_from "archive.old_orders");' ), ), - "models/marts/regions.sql": _model( + "sql/models/marts/regions.sql": _model( "SELECT 1 AS region_id", header=( 'MODEL (description "Regions.", materialized table, migrate_from customers);' @@ -241,14 +250,14 @@ def _gate_model(sql: str, audits: str) -> str: ( "old names off leave old relations unmatched", { - "models/marts/customers.sql": _model( + "sql/models/marts/customers.sql": _model( "SELECT 1 AS customer_id", header=( 'MODEL (description "Customers.", materialized table, ' "migrate_from legacy_customers);" ), ), - "models/marts/orders.sql": _model("SELECT 1 AS order_id"), + "sql/models/marts/orders.sql": _model("SELECT 1 AS order_id"), _TASK_PATH: _task(' ctx.query("SELECT * FROM legacy_customers")\n'), }, _OLD_NAMES_OFF, @@ -293,17 +302,17 @@ def _gate_model(sql: str, audits: str) -> str: 'HOOK (description "Records rows.");\n' 'INSERT INTO audit_log SELECT count(*) FROM __ref("item_totals")\n' ), - "models/marts/orders.sql": _model("SELECT 1 AS order_id", header=_HOOKED), - "models/marts/customers.sql": _model('SELECT * FROM __ref("orders")'), - "models/marts/items.sql": _model("SELECT 1 AS item_id", header=_NAMED_SQL_HOOK), - "models/marts/item_totals.sql": _model( + "sql/models/marts/orders.sql": _model("SELECT 1 AS order_id", header=_HOOKED), + "sql/models/marts/customers.sql": _model('SELECT * FROM __ref("orders")'), + "sql/models/marts/items.sql": _model("SELECT 1 AS item_id", header=_NAMED_SQL_HOOK), + "sql/models/marts/item_totals.sql": _model( 'SELECT * FROM __ref("items")', header=( 'MODEL (description "Totals.", pre_hooks ' "[inline_sql('SELECT * FROM __ref(\"item_rollup\")')]);" ), ), - "models/marts/item_rollup.sql": _model('SELECT * FROM __ref("item_totals")'), + "sql/models/marts/item_rollup.sql": _model('SELECT * FROM __ref("item_totals")'), }, _PROJECT, ), @@ -312,44 +321,48 @@ def _gate_model(sql: str, audits: str) -> str: { **_SEED, **_EXTERNAL, - "audits/generic/gated_lookup.sql": _GATED_AUDIT.format(read='__ref("enriched")'), - "audits/generic/source_lookup.sql": _GATED_AUDIT.format(read='__ref("landing_view")'), - "models/marts/base.sql": _gate_model("SELECT 'GB' AS code", "gated_lookup"), - "models/marts/enriched.sql": _model('SELECT * FROM __ref("base")'), - "audits/generic/seed_lookup.sql": _GATED_AUDIT.format(read='__ref("coded")'), - "models/marts/landing_view.sql": _model('SELECT * FROM __source("landing_audited")'), - "models/marts/coded.sql": _model('SELECT * FROM __seed("audited_codes")'), - "sources/landing_audits.yml": ( + "sql/audits/generic/gated_lookup.sql": _GATED_AUDIT.format(read='__ref("enriched")'), + "sql/audits/generic/source_lookup.sql": _GATED_AUDIT.format( + read='__ref("landing_view")' + ), + "sql/models/marts/base.sql": _gate_model("SELECT 'GB' AS code", "gated_lookup"), + "sql/models/marts/enriched.sql": _model('SELECT * FROM __ref("base")'), + "sql/audits/generic/seed_lookup.sql": _GATED_AUDIT.format(read='__ref("coded")'), + "sql/models/marts/landing_view.sql": _model( + 'SELECT * FROM __source("landing_audited")' + ), + "sql/models/marts/coded.sql": _model('SELECT * FROM __seed("audited_codes")'), + "sql/sources/landing_audits.yml": ( "sources:\n - name: landing_audited\n description: Landing audited.\n" " schema: landing\n audits:\n - source_lookup\n" ), - "seeds/audited_codes.yml": ( + "sql/seeds/audited_codes.yml": ( "seeds:\n - name: audited_codes\n description: Audited codes.\n" " columns:\n - name: code\n type: VARCHAR\n" " audits:\n - seed_lookup\n" ), - "seeds/audited_codes.csv": "code\nGB\n", + "sql/seeds/audited_codes.csv": "code\nGB\n", }, _PROJECT, ), ( "audit gates, hook cycles and hard-coded names together", { - "audits/generic/gated_lookup.sql": _GATED_AUDIT.format(read='__ref("enriched")'), - "models/marts/base.sql": _gate_model("SELECT 'GB' AS code", "gated_lookup"), - "models/marts/enriched.sql": _model('SELECT * FROM __ref("base")'), + "sql/audits/generic/gated_lookup.sql": _GATED_AUDIT.format(read='__ref("enriched")'), + "sql/models/marts/base.sql": _gate_model("SELECT 'GB' AS code", "gated_lookup"), + "sql/models/marts/enriched.sql": _model('SELECT * FROM __ref("base")'), _HOOK_PATH: _hook( reads='model("customers")', body=' ctx.query("SELECT * FROM legacy_orders JOIN orders ON true")\n', ), - "models/marts/orders.sql": _model( + "sql/models/marts/orders.sql": _model( "SELECT 1 AS order_id", header=( 'MODEL (description "Orders.", materialized table, ' 'migrate_from legacy_orders, post_hooks [python("refresh_lookup")]);' ), ), - "models/marts/customers.sql": _model('SELECT * FROM __ref("orders")'), + "sql/models/marts/customers.sql": _model('SELECT * FROM __ref("orders")'), _TASK_PATH: _task(' ctx.query("SELECT * FROM enriched")\n'), }, _PROJECT, diff --git a/tests/integration/src/sqlbuild/compiler/graph/helpers.py b/tests/integration/src/sqlbuild/compiler/graph/helpers.py index 77d4d681fc..513aa719ce 100644 --- a/tests/integration/src/sqlbuild/compiler/graph/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/graph/helpers.py @@ -6,13 +6,15 @@ ORDERS_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( "MODEL (description 'Staged orders.', tags [daily]);\nSELECT 1 AS order_id\n" ), - "models/marts/orders.sql": ( + "sql/models/marts/orders.sql": ( "MODEL (description 'Orders.');\nSELECT order_id FROM __ref(\"stg_orders\")\n" ), - "models/marts/customers.sql": "MODEL (description 'Customers.');\nSELECT 1 AS customer_id\n", + "sql/models/marts/customers.sql": ( + "MODEL (description 'Customers.');\nSELECT 1 AS customer_id\n" + ), } MODEL_NAMES: frozenset[str] = frozenset({"stg_orders", "orders", "customers"}) diff --git a/tests/integration/src/sqlbuild/compiler/graph/test_native_project_graph.py b/tests/integration/src/sqlbuild/compiler/graph/test_native_project_graph.py index 416390bb84..72b929440a 100644 --- a/tests/integration/src/sqlbuild/compiler/graph/test_native_project_graph.py +++ b/tests/integration/src/sqlbuild/compiler/graph/test_native_project_graph.py @@ -35,7 +35,7 @@ ), NativeGraphSelectionTestCase( description="models-rooted folder", - select=("--select", "models/marts"), + select=("--select", "sql/models/marts"), expected_models=frozenset({"orders", "customers"}), expected_graph_builds=2, ), diff --git a/tests/integration/src/sqlbuild/compiler/lineage/helpers.py b/tests/integration/src/sqlbuild/compiler/lineage/helpers.py index a7a0aedc77..1bbca0ab72 100644 --- a/tests/integration/src/sqlbuild/compiler/lineage/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/lineage/helpers.py @@ -191,9 +191,9 @@ def generated_lineage_files(*, rng: random.Random, model_count: int) -> dict[str files: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": _SOURCES, - "seeds/regions.yml": _SEEDS, - "seeds/regions.csv": "region,region_label\neast,East\n", + "sql/sources/raw.yml": _SOURCES, + "sql/seeds/regions.yml": _SEEDS, + "sql/seeds/regions.csv": "region,region_label\neast,East\n", } relations: list[tuple[str, tuple[str, ...]]] = list(_INITIAL_RELATIONS.items()) for index in range(model_count): @@ -202,7 +202,7 @@ def generated_lineage_files(*, rng: random.Random, model_count: int) -> dict[str sql, columns = template(rng, inputs) name: str = f"orders_model_{index}" opt_out: str = _OPT_OUTS[rng.random() < _OPT_OUT_SHARE] - files[f"models/layer_{index % 3}/{name}.sql"] = ( + files[f"sql/models/layer_{index % 3}/{name}.sql"] = ( f'MODEL (description "Generated orders model {index}"{opt_out});\n\n{sql}\n' ) relations.append((f'__ref("{name}")', columns)) diff --git a/tests/integration/src/sqlbuild/compiler/lineage/test_native_fast_lineage.py b/tests/integration/src/sqlbuild/compiler/lineage/test_native_fast_lineage.py index 3065726e4f..e9d5e46ec1 100644 --- a/tests/integration/src/sqlbuild/compiler/lineage/test_native_fast_lineage.py +++ b/tests/integration/src/sqlbuild/compiler/lineage/test_native_fast_lineage.py @@ -134,11 +134,11 @@ def test_given_root_star_over_opted_out_model_when_building_fast_lineage_then_re project_dir=tmp_path / "project", files={ **generated_lineage_files(rng=random.Random(5), model_count=_MODEL_COUNT), - "models/orders_staged.sql": ( + "sql/models/orders_staged.sql": ( 'MODEL (description "Staged orders", sql_analysis false);\n\n' 'SELECT customer_id, order_id FROM __source("raw_orders")\n' ), - "models/orders_all.sql": ( + "sql/models/orders_all.sql": ( 'MODEL (description "All orders");\n\nSELECT * FROM __ref("orders_staged")\n' ), }, diff --git a/tests/integration/src/sqlbuild/compiler/model_config/helpers.py b/tests/integration/src/sqlbuild/compiler/model_config/helpers.py index b34b5cd08a..86190ddeea 100644 --- a/tests/integration/src/sqlbuild/compiler/model_config/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/model_config/helpers.py @@ -128,7 +128,7 @@ '[targets.dev]\nconnection = "local"\n' "schema = \"${coalesce(ENV:SQB_MISSING_SCHEMA, 'dev')}_${CTX:model.name}\"\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n materialized table,\n description "Orders.",\n' " tags [\"${if(eq(CTX:run.target, 'dev'), 'development', 'release')}\"],\n" " columns (\n" @@ -136,7 +136,7 @@ ' status (audits [accepted_values (values ["placed", "shipped"])]),\n' " ),\n);\n\nSELECT 1 AS order_id, 'placed' AS status\n" ), - "models/customers.sql": ( + "sql/models/customers.sql": ( "MODEL (\n materialized view,\n columns (customer_id (type INTEGER)),\n);\n\n" "SELECT 1 AS customer_id\n" ), @@ -154,12 +154,12 @@ """Validations the loop runs after parsing a header, which the YAML schema parsers never run.""" _PARITY_PROJECT: str = 'name = "orders"\nadapter = "duckdb"\n' _PARITY_FILES: dict[str, str] = { - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Orders.', materialized incremental, incremental_strategy append);\n" "SELECT 1 AS order_id\n" ), **{ - f"audits/generic/{name}.sql": 'AUDIT ();\nSELECT * FROM __ref("@model") WHERE FALSE\n' + f"sql/audits/generic/{name}.sql": 'AUDIT ();\nSELECT * FROM __ref("@model") WHERE FALSE\n' for name in ("a",) }, } @@ -506,10 +506,10 @@ def column_metadata_outcome(*, project_dir: Path, header_column: str) -> tuple[o "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n\n[vars]\ncolumn_type = "BIGINT"\n' ), - "macros/python/amounts.py": ( + "sql/macros/python/amounts.py": ( 'def cents(column: str) -> str:\n return f"{column} * 100"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( f"MODEL (description 'Orders.', columns ({header_column}));\nSELECT 1 AS amount\n" ), } @@ -551,7 +551,7 @@ def column_metadata_outcome(*, project_dir: Path, header_column: str) -> tuple[o '[path_defaults."marts"]\nrow_diff_exclude_columns = ["loaded_at"]\ntags = ["mart"]\n\n' '[targets.dev]\nconnection = "local"\nschema = "${region}_${CTX:model.name}"\n' ), - "models/marts/orders.sql": 'MODEL (description "Orders.");\n\nSELECT 1 AS order_id\n', + "sql/models/marts/orders.sql": 'MODEL (description "Orders.");\n\nSELECT 1 AS order_id\n', } @@ -653,7 +653,7 @@ def header_column_paths(*, project_dir: Path, headers: tuple[str, ...]) -> tuple files: dict[str, str] = { "sqlbuild_project.toml": CONFIG_VALUE_PROJECT["sqlbuild_project.toml"], **{ - f"models/marts/orders_{index}.sql": f"MODEL ({header});\n\nSELECT 1 AS order_id\n" + f"sql/models/marts/orders_{index}.sql": f"MODEL ({header});\n\nSELECT 1 AS order_id\n" for index, header in enumerate(headers) }, } diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/_test_types.py b/tests/integration/src/sqlbuild/compiler/pipeline/_test_types.py index 2abc0dd5ca..5f2fd988cd 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/_test_types.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/_test_types.py @@ -431,6 +431,8 @@ class SetDependencyPlanTestCase: depends_on: str expected_models: tuple[str, ...] expected_sql_deps: tuple[str, ...] + # The dependant: an asset, or a loader, which takes a job or a tag the same way. + kind: str = "asset" @dataclass(frozen=True) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/helpers.py b/tests/integration/src/sqlbuild/compiler/pipeline/helpers.py index 99922d006a..c62d1dbab6 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/helpers.py @@ -25,6 +25,7 @@ from sqlbuild.adapters.postgres.classes.postgres_adapter import PostgresAdapter from sqlbuild.compiler.compile.types import CompiledModelView, CompiledProjectView from sqlbuild.runtime.contracts.models import ConnectionHooks +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files if TYPE_CHECKING: from sqlbuild.compiler.compile.types import AuditInput @@ -156,8 +157,8 @@ def write_semantic_binding_project( project_toml: str = SEMANTIC_BINDING_PROJECT_TOML, ) -> None: _ = (project_dir / "sqlbuild_project.toml").write_text(project_toml, encoding="utf-8") - models_dir: Path = project_dir / "models" - models_dir.mkdir() + models_dir: Path = project_dir / "sql" / "models" + models_dir.mkdir(parents=True) _ = (models_dir / "upstream.sql").write_text(upstream_sql, encoding="utf-8") _ = (models_dir / "downstream.sql").write_text(downstream_sql, encoding="utf-8") @@ -170,8 +171,8 @@ def compile_reshaped_star_model( (project_dir / "sqlbuild_project.toml").write_text( _RESHAPED_STAR_PROJECT_TOML, encoding="utf-8" ) - models: Path = project_dir / "models" - models.mkdir() + models: Path = project_dir / "sql" / "models" + models.mkdir(parents=True) for name, sql in RESHAPED_STAR_UPSTREAM_MODELS.items(): (models / f"{name}.sql").write_text( f"MODEL (description 'Test model.', materialized table);\n{sql}", encoding="utf-8" @@ -246,10 +247,19 @@ def postgres_semantic_shapes( return semantic_shapes(project=project) +# The import and decorator of each kind of node that can depend on a job or a tag. +_SET_DEPENDANT_DECORATORS: dict[str, str] = { + "asset": "from sqlbuild.assets import asset\n\n\n@asset", + "loader": "from sqlbuild.loaders import loader\n\n\n@loader", +} + + def set_dependency_project( - *, depends_on: str, job_files: tuple[tuple[str, str], ...] = () + *, depends_on: str, job_files: tuple[tuple[str, str], ...] = (), kind: str = "asset" ) -> dict[str, str]: - """Four models, a `nightly_job` over three of them, and a `report` task on `depends_on`.""" + """Four models, a `nightly_job` over three of them, and a `report` asset or loader.""" + + decorator: str = _SET_DEPENDANT_DECORATORS[kind] model: str = "MODEL (description 'Test model {name}.', materialized table{tags});\n{sql}\n" files: dict[str, str] = { @@ -257,22 +267,22 @@ def set_dependency_project( 'name = "set_dependencies"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' '[connection]\ndatabase = ":memory:"\n\n[targets.dev]\nschema = "dev"\n' ), - "models/stg_orders.sql": model.format(name="stg_orders", tags="", sql="SELECT 1 AS id"), - "models/orders.sql": model.format( + "sql/models/stg_orders.sql": model.format(name="stg_orders", tags="", sql="SELECT 1 AS id"), + "sql/models/orders.sql": model.format( name="orders", tags=", tags [finance]", sql='SELECT id FROM __ref("stg_orders")' ), - "models/order_items.sql": model.format( + "sql/models/order_items.sql": model.format( name="order_items", tags=", tags [finance]", sql='SELECT id FROM __ref("stg_orders")' ), - "models/customers.sql": model.format(name="customers", tags="", sql="SELECT 2 AS id"), + "sql/models/customers.sql": model.format(name="customers", tags="", sql="SELECT 2 AS id"), "orchestration/jobs/nightly_job.toml": ( 'name = "nightly_job"\ndescription = "Nightly."\n' 'select = "stg_orders orders order_items"\n' ), - "python/tasks/report.py": ( - "from sqlbuild.refs import job, model, tag\nfrom sqlbuild.assets import asset\n\n\n" - f"@asset(depends_on={depends_on})\n" - 'def report(ctx):\n """Test task report."""\n return None\n' + **node_module_files( + "python/nodes/tasks/report.py", + f"from sqlbuild.refs import job, model, tag\n{decorator}(depends_on={depends_on})\n" + 'def report(ctx):\n """Test task report."""\n return None\n', ), } files.update(dict(job_files)) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_attached_audit_gates.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_attached_audit_gates.py index b73a779ad9..8289dc012a 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_attached_audit_gates.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_attached_audit_gates.py @@ -17,7 +17,7 @@ ) _ORDER_CHECK: dict[str, str] = { - "audits/generic/order_check.sql": ( + "sql/audits/generic/order_check.sql": ( 'AUDIT ();\nSELECT o.* FROM @relation o LEFT JOIN __ref("valid_codes") v USING (code)\n' ), } @@ -25,8 +25,8 @@ "sqlbuild_project.toml": ( 'name = "gate_demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = ":memory:"\n' ), - "models/valid_codes.sql": "MODEL (description 'Test model valid_codes.', materialized table);\nSELECT 'A' AS code\n", - "audits/singular/reconcile.sql": ( + "sql/models/valid_codes.sql": "MODEL (description 'Test model valid_codes.', materialized table);\nSELECT 'A' AS code\n", + "sql/audits/singular/reconcile.sql": ( 'AUDIT ();\nSELECT o.* FROM __ref("orders") o JOIN __ref("valid_codes") v USING (code)\n' ), } @@ -59,7 +59,7 @@ def test_given_gate_edge_when_planning_singular_audit_then_attachment_uses_linea tmp_path, _PROJECT_FILES | test_case.generic_audit_files - | {"models/orders.sql": f"{test_case.orders_header}\nSELECT 'A' AS code\n"}, + | {"sql/models/orders.sql": f"{test_case.orders_header}\nSELECT 'A' AS code\n"}, ) result: CompilePipelineResult = run_compile_pipeline_for_project( diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_audit_factories.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_audit_factories.py index 9ec41a52a7..3873396f9e 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_audit_factories.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_audit_factories.py @@ -34,11 +34,11 @@ def test_given_generated_and_direct_attachments_when_compiled_then_audit_inputs_ tmp_path, { "sqlbuild_project.toml": 'name = "audit_factory"\nadapter = "duckdb"\n', - "audits/generic/expression_is_true.sql": """ + "sql/audits/generic/expression_is_true.sql": """ AUDIT (); SELECT * FROM __ref("@model") WHERE NOT (@expression) """, - "python/factories/quality.py": """ + "python/nodes/factories/quality.py": """ from sqlbuild.compiler.compile.types import AuditInput from sqlbuild.audits import AuditCase, AuditSeverity, audit_factory @@ -49,7 +49,7 @@ def order_quality(): AuditCase(name="bounded_amount", definition="expression_is_true", arguments={"expression": "amount < 1000"}, severity=AuditSeverity.WARN), ] """, - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", audit_factories [order_quality]); SELECT 10 AS amount """, @@ -60,7 +60,7 @@ def order_quality(): write_repo_files( tmp_path, { - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", audits [ expression_is_true (name "positive_amount", expression "amount > 0", severity error), diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_binding_waves.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_binding_waves.py index 3388d7ed45..17ca26e680 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_binding_waves.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_binding_waves.py @@ -23,16 +23,16 @@ def test_given_inferred_producer_when_binding_consumers_then_binds_and_invalidat (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n expression: SELECT 1 AS id, 2 AS quantity\n" ) - (tmp_path / "models").mkdir() - producer: Path = tmp_path / "models/orders.sql" + (tmp_path / "sql" / "models").mkdir(parents=True) + producer: Path = tmp_path / "sql/models/orders.sql" producer.write_text( 'MODEL (description "Test model orders.", materialized view); SELECT id FROM __source("raw_orders")' ) - (tmp_path / "models/report.sql").write_text( + (tmp_path / "sql/models/report.sql").write_text( "MODEL (description 'Test model report.', materialized view); " + test_case.sql ) args: list[str] = ["--project-dir", str(tmp_path), "compile", "--json"] diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_completed_shape_cache.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_completed_shape_cache.py index 630a1d03da..9ab3bcb5ea 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_completed_shape_cache.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_completed_shape_cache.py @@ -31,19 +31,19 @@ def test_given_completed_shape_when_an_unrelated_model_changes_then_cached_colum (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n table: orders\n contract: enforced\n columns:\n - name: id\n type: INTEGER\n - name: quantity\n type: INTEGER\n" ) - (tmp_path / "models").mkdir() - (tmp_path / "models/order_inputs.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/order_inputs.sql").write_text( 'MODEL (description "Test model order_inputs.", materialized view); SELECT id, quantity FROM __source("raw_orders")' ) - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql/models/orders.sql").write_text( "MODEL (description 'Test model orders.', materialized view);\n" + test_case.sql.replace('__source("raw_orders")', '__ref("order_inputs")') ) - edited: Path = tmp_path / "models/customers.sql" + edited: Path = tmp_path / "sql/models/customers.sql" edited.write_text( "MODEL (description 'Test model customers.', materialized view); SELECT 1 AS id" ) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_diff_selectors.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_diff_selectors.py index 2716700155..bc0aa9ddeb 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_diff_selectors.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_diff_selectors.py @@ -23,19 +23,19 @@ '[connection]\ndatabase = ":memory:"\n\n' '[targets.dev]\nschema = "dev_schema"\n' ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table\ntags [staging]);\n\nSELECT 1 AS order_id" ), - "models/staging/stg_customers.sql": ( + "sql/models/staging/stg_customers.sql": ( "MODEL (description 'Test model stg_customers.', materialized table\ntags [staging]);\n\nSELECT 1 AS customer_id" ), - "models/intermediate/int_orders.sql": ( + "sql/models/intermediate/int_orders.sql": ( 'MODEL (description "Test model int_orders.", materialized table\ntags [core]);\n\nSELECT order_id FROM __ref("stg_orders")' ), - "models/marts/fact_orders.sql": ( + "sql/models/marts/fact_orders.sql": ( 'MODEL (description "Test model fact_orders.", materialized table\ntags [core, mart]);\n\nSELECT order_id FROM __ref("int_orders")' ), - "models/marts/dim_customers.sql": ( + "sql/models/marts/dim_customers.sql": ( 'MODEL (description "Test model dim_customers.", materialized table\ntags [mart]);\n\nSELECT customer_id FROM __ref("stg_customers")' ), } @@ -52,13 +52,13 @@ ), DiffSelectorIntegrationTestCase( description="path selector returns models under folder", - select=("path:models/staging",), + select=("path:sql/models/staging",), exclude=(), expected_model_names=frozenset(("stg_orders", "stg_customers")), ), DiffSelectorIntegrationTestCase( description="Windows-style path selector returns models under folder", - select=("path:models\\staging",), + select=("path:sql\\models\\staging",), exclude=(), expected_model_names=frozenset(("stg_orders", "stg_customers")), ), @@ -88,7 +88,7 @@ ), DiffSelectorIntegrationTestCase( description="comma selector intersects resolved sets", - select=("tag:core,path:models/marts",), + select=("tag:core,path:sql/models/marts",), exclude=(), expected_model_names=frozenset(("fact_orders",)), ), diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_expression_catalog_cache.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_expression_catalog_cache.py index 5326d7e785..c791c88c4c 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_expression_catalog_cache.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_expression_catalog_cache.py @@ -34,12 +34,12 @@ def test_given_equal_source_expressions_when_compiling_then_infers_once_and_inva (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text( 'MODEL (description "Test model orders.", materialized view); SELECT id FROM __source("raw_orders")' ) - (tmp_path / "sources").mkdir() - source: Path = tmp_path / "sources/orders.yml" + (tmp_path / "sql" / "sources").mkdir(parents=True) + source: Path = tmp_path / "sql/sources/orders.yml" source.write_text( f"sources:\n - name: raw_orders\n description: Test source raw_orders.\n expression: {test_case.expression}\n - name: raw_customers\n description: Test source raw_customers.\n expression: {test_case.expression}\n" ) @@ -76,12 +76,12 @@ def test_given_distinct_source_expressions_when_compiling_then_infers_them_in_on (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text( 'MODEL (description "Test model orders.", materialized view); SELECT id FROM __source("raw_orders")' ) - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n" f" - name: raw_orders\n description: Test source raw_orders.\n expression: {test_case.orders_expression}\n" f" - name: raw_customers\n description: Test source raw_customers.\n expression: {test_case.customers_expression}\n" @@ -125,7 +125,7 @@ def test_given_restored_project_without_catalog_when_reading_shapes_then_infers_ project_dir=tmp_path, files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "sources/sources.yml": sources, + "sql/sources/sources.yml": sources, }, ) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_macro_declaration_context.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_macro_declaration_context.py index ab9240bd8e..f6c822ebd5 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_macro_declaration_context.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_macro_declaration_context.py @@ -59,13 +59,13 @@ def test_given_active_adapter_when_macro_renders_constant_then_uses_adapter_sql( f'name = "demo"\nadapter = "{test_case.adapter_name}"\n\n' "[settings]\nsql_analysis = false\n" ), - "models/_constants/policy.sql": ( + "sql/models/_constants/policy.sql": ( 'CONSTANT (name regions, value ["north", "south"], render_as array);\n' ), - "models/_macros/python/policy.py": ( + "sql/models/_macros/python/policy.py": ( "def region_array(ctx) -> str:\n return ctx.render_constant('regions')\n" ), - "models/summary.sql": ( + "sql/models/summary.sql": ( "MODEL (description 'Test model summary.', materialized view, database warehouse, schema analytics);\n\n" "SELECT @py.region_array() AS regions" ), @@ -89,13 +89,13 @@ def test_given_active_adapter_when_macro_renders_constant_then_uses_adapter_sql( description="grouped private macro reads grouped private constant and enum", project_files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "models/orders/_sqlbuild/_constants/policy.sql": ( + "sql/models/orders/_sqlbuild/_constants/policy.sql": ( "CONSTANT (name minimum_quantity, value 2);\n" ), - "models/orders/_sqlbuild/_enums/status.sql": ( + "sql/models/orders/_sqlbuild/_enums/status.sql": ( "ENUM (name order_status, members [ACTIVE]);\n" ), - "models/orders/_sqlbuild/_macros/python/policy.py": ( + "sql/models/orders/_sqlbuild/_macros/python/policy.py": ( "def order_policy(ctx) -> str:\n" " quantity = ctx.render_constant('minimum_quantity')\n" " status = ctx.render_enum_member(\n" @@ -103,7 +103,7 @@ def test_given_active_adapter_when_macro_renders_constant_then_uses_adapter_sql( " )\n" ' return f"{quantity} AS minimum_quantity, {status} AS status"\n' ), - "models/orders/summary.sql": ( + "sql/models/orders/summary.sql": ( 'MODEL (description "Order summary.");\nSELECT @py.order_policy()' ), }, @@ -115,10 +115,10 @@ def test_given_active_adapter_when_macro_renders_constant_then_uses_adapter_sql( "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n[scopes]\nenforce_placement = false\n' ), - "models/orders/_sqlbuild/macros/python/policy.py": ( + "sql/models/orders/_sqlbuild/macros/python/policy.py": ( "def minimum_quantity() -> str:\n return '2'\n" ), - "models/orders/history/summary.sql": ( + "sql/models/orders/history/summary.sql": ( 'MODEL (description "Historical order summary.");\n' "SELECT @py.minimum_quantity() AS minimum_quantity" ), @@ -149,8 +149,8 @@ def test_given_grouped_declarations_when_compiling_then_scope_resolves_from_owne description="project macro test is discovered from mirrored macro path", project_files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "macros/python/orders/policy.py": "def order_policy() -> str:\n return '2'\n", - "models/orders/summary.sql": ( + "sql/macros/python/orders/policy.py": "def order_policy() -> str:\n return '2'\n", + "sql/models/orders/summary.sql": ( 'MODEL (description "Order summary.");\nSELECT @py.order_policy() AS quantity' ), "tests/unit/macros/orders/test_order_policy__returns_quantity.sql": ( @@ -194,14 +194,14 @@ def test_given_macro_test_in_mirrored_path_when_compiling_then_test_is_attached( "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n[scopes]\nenforce_placement = true\n' ), - "models/orders/_sqlbuild/_constants/policy.sql": ( + "sql/models/orders/_sqlbuild/_constants/policy.sql": ( "CONSTANT (name minimum_quantity, value 2);\n" ), - "models/orders/_sqlbuild/_macros/python/policy.py": ( + "sql/models/orders/_sqlbuild/_macros/python/policy.py": ( "def order_policy(ctx) -> str:\n" " return ctx.render_constant('minimum_quantity')\n" ), - "models/orders/summary.sql": ( + "sql/models/orders/summary.sql": ( 'MODEL (description "Order summary.");\nSELECT @py.order_policy() AS quantity' ), "tests/unit/macros/models/orders/test_order_policy__returns_quantity.sql": ( @@ -221,14 +221,14 @@ def test_given_macro_test_in_mirrored_path_when_compiling_then_test_is_attached( "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n[scopes]\nenforce_placement = false\n' ), - "models/orders/_sqlbuild/_macros/python/policy.py": ( + "sql/models/orders/_sqlbuild/_macros/python/policy.py": ( "def order_policy() -> str:\n return '2'\n" ), - "models/orders/order_summary.sql": ( + "sql/models/orders/order_summary.sql": ( 'MODEL (description "Order summary.");\n' 'SELECT @py.order_policy() AS quantity FROM __ref("order_input")' ), - "models/order_input.sql": ( + "sql/models/order_input.sql": ( 'MODEL (description "Order input.");\nSELECT 1 AS order_id' ), "tests/unit/orders/_sqlbuild/macros/python/fixtures.py": ( @@ -253,20 +253,20 @@ def test_given_macro_test_in_mirrored_path_when_compiling_then_test_is_attached( "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n[scopes]\nenforce_placement = false\n' ), - "models/orders/_sqlbuild/_macros/python/policy.py": ( + "sql/models/orders/_sqlbuild/_macros/python/policy.py": ( "def order_policy() -> str:\n return '2'\n" ), - "models/orders/order_summary.sql": ( + "sql/models/orders/order_summary.sql": ( 'MODEL (description "Order summary.");\n' 'SELECT @py.order_policy() AS quantity FROM __ref("order_input")' ), - "models/order_input.sql": ( + "sql/models/order_input.sql": ( 'MODEL (description "Order input.");\nSELECT 1 AS order_id' ), - "models/products/_sqlbuild/_macros/python/policy.py": ( + "sql/models/products/_sqlbuild/_macros/python/policy.py": ( "def product_policy() -> str:\n return '3'\n" ), - "models/products/product_summary.sql": ( + "sql/models/products/product_summary.sql": ( 'MODEL (description "Product summary.");\n' 'SELECT @py.product_policy() AS quantity FROM __ref("order_input")' ), @@ -324,12 +324,12 @@ def test_given_macro_context_declarations_when_compiling_resources_then_all_expa "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[settings]\nsql_analysis = false\n' ), - "constants/policy.sql": "CONSTANT (name minimum_quantity, value 2);\n", - "macros/python/policy.py": ( + "sql/constants/policy.sql": "CONSTANT (name minimum_quantity, value 2);\n", + "sql/macros/python/policy.py": ( "def minimum_quantity(ctx) -> str:\n" " return str(ctx.constants['minimum_quantity'])\n" ), - "models/summary.sql": ( + "sql/models/summary.sql": ( "MODEL (description 'Test model summary.', materialized view, audits [minimum_quantity]);\n\n" "SELECT @py.minimum_quantity() AS minimum_quantity" ), @@ -338,7 +338,7 @@ def test_given_macro_context_declarations_when_compiling_resources_then_all_expa " SELECT @py.minimum_quantity() AS minimum_quantity\n),\n" "__macro_expected__ AS (\n SELECT 2 AS minimum_quantity\n)\nSELECT 1" ), - "audits/generic/minimum_quantity.sql": ( + "sql/audits/generic/minimum_quantity.sql": ( 'AUDIT ();\n\nSELECT * FROM __ref("@model") ' "WHERE minimum_quantity < @py.minimum_quantity()" ), @@ -361,14 +361,14 @@ def test_given_macro_context_declarations_when_compiling_resources_then_all_expa description="sibling private constant remains inaccessible", project_files={ "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders/_constants/policy.sql": ( + "sql/models/orders/_constants/policy.sql": ( "CONSTANT (name minimum_quantity, value 2);\n" ), - "macros/python/policy.py": ( + "sql/macros/python/policy.py": ( "def minimum_quantity(ctx) -> str:\n" " return str(ctx.constants['minimum_quantity'])\n" ), - "models/products/summary.sql": ( + "sql/models/products/summary.sql": ( "MODEL (description 'Test model summary.', materialized view);\n\nSELECT @py.minimum_quantity() AS minimum_quantity" ), }, @@ -378,10 +378,10 @@ def test_given_macro_context_declarations_when_compiling_resources_then_all_expa description="grouped private macro remains inaccessible to descendant model", project_files={ "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders/_sqlbuild/_macros/python/policy.py": ( + "sql/models/orders/_sqlbuild/_macros/python/policy.py": ( "def minimum_quantity() -> str:\n return '2'\n" ), - "models/orders/history/summary.sql": ( + "sql/models/orders/history/summary.sql": ( 'MODEL (description "Historical order summary.");\n' "SELECT @py.minimum_quantity() AS minimum_quantity" ), @@ -394,13 +394,13 @@ def test_given_macro_context_declarations_when_compiling_resources_then_all_expa "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n[scopes]\nenforce_placement = false\n' ), - "models/products/_sqlbuild/_macros/python/policy.py": ( + "sql/models/products/_sqlbuild/_macros/python/policy.py": ( "def product_policy() -> str:\n return '3'\n" ), - "models/products/product_input.sql": ( + "sql/models/products/product_input.sql": ( 'MODEL (description "Product input.");\nSELECT 1 AS product_id' ), - "models/orders/order_summary.sql": ( + "sql/models/orders/order_summary.sql": ( 'MODEL (description "Order summary.");\n' 'SELECT product_id FROM __ref("product_input")' ), @@ -420,12 +420,14 @@ def test_given_macro_context_declarations_when_compiling_resources_then_all_expa description="unknown constant reports visible alternatives", project_files={ "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/_constants/policy.sql": ("CONSTANT (name minimum_quantity, value 2);\n"), - "models/_macros/python/policy.py": ( + "sql/models/_constants/policy.sql": ( + "CONSTANT (name minimum_quantity, value 2);\n" + ), + "sql/models/_macros/python/policy.py": ( "def missing_quantity(ctx) -> str:\n" " return ctx.render_constant('maximum_quantity')\n" ), - "models/summary.sql": ( + "sql/models/summary.sql": ( "MODEL (description 'Test model summary.', materialized view);\n\nSELECT @py.missing_quantity() AS maximum_quantity" ), }, @@ -437,16 +439,16 @@ def test_given_macro_context_declarations_when_compiling_resources_then_all_expa description="unknown enum member reports available alternatives", project_files={ "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/_enums/status.sql": ( + "sql/models/_enums/status.sql": ( "ENUM (name order_status, members [ACTIVE, PAUSED]);\n" ), - "models/_macros/python/policy.py": ( + "sql/models/_macros/python/policy.py": ( "def missing_status(ctx) -> str:\n" " return ctx.render_enum_member(\n" " enum_name='order_status', member_name='CLOSED'\n" " )\n" ), - "models/summary.sql": ( + "sql/models/summary.sql": ( "MODEL (description 'Test model summary.', materialized view);\n\nSELECT @py.missing_status() AS status" ), }, diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_macro_load_count.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_macro_load_count.py index bc54222250..5f42dc23b6 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_macro_load_count.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_macro_load_count.py @@ -22,7 +22,8 @@ _COUNTING_MACRO_MODULE: str = ( "from pathlib import Path\n" "\n" - "_LOG_PATH = Path(__file__).resolve().parents[3] / 'macro_import_log.txt'\n" + "_PROJECT = Path(__file__).resolve().parents[4]\n" + "_LOG_PATH = _PROJECT.parent / f'{_PROJECT.name}_macro_import_log.txt'\n" "with _LOG_PATH.open('a', encoding='utf-8') as handle:\n" " handle.write('import\\n')\n" "\n" @@ -39,8 +40,8 @@ description="user macro modules execute once across compile and manifest generation", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/_macros/python/counting.py": _COUNTING_MACRO_MODULE, - "models/orders.sql": ( + "sql/models/_macros/python/counting.py": _COUNTING_MACRO_MODULE, + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id, @py.order_tag() AS tag" ), }, @@ -67,7 +68,9 @@ def test_given_side_effect_macro_when_compiling_manifest_then_imports_macros_onc adapter_type="duckdb", ) - import_log: str = (tmp_path / "macro_import_log.txt").read_text(encoding="utf-8") + import_log: str = (tmp_path.parent / f"{tmp_path.name}_macro_import_log.txt").read_text( + encoding="utf-8" + ) assert import_log.count("import") == test_case.expected_macro_import_count @@ -78,13 +81,13 @@ def test_given_side_effect_macro_when_compiling_manifest_then_imports_macros_onc description="private helper composition reaches scope and manifest dependency", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/_macros/python/shared.py": "def shared() -> str:\n return 'order_id'\n", - "models/_macros/python/orders.py": ( - "from models._macros.python.shared import shared\n\n" + "sql/models/_macros/python/shared.py": "def shared() -> str:\n return 'order_id'\n", + "sql/models/_macros/python/orders.py": ( + "from sql.models._macros.python.shared import shared\n\n" "def _helper() -> str:\n return shared()\n\n" "def order_column() -> str:\n return _helper()\n" ), - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT @py.order_column()", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT @py.order_column()", }, macro_name="order_column", expected_dependencies=("shared",), diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_main.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_main.py index a4ab39c006..d9e7e93251 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_main.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_main.py @@ -53,7 +53,7 @@ description="typed cte passthrough satisfies the model contract", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT '12' AS amount\n" @@ -62,13 +62,13 @@ " type: VARCHAR\n" " nullable: false\n" ), - "schemas/orders.sql": ( + "sql/schemas/orders.sql": ( "SCHEMA (\n" " name order_amount,\n" " columns (amount (type INTEGER, nullable false)),\n" ");\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (\n" ' description "Test model orders.",\n' " contract enforced,\n" @@ -134,8 +134,8 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i (tmp_path / "sqlbuild_project.toml").write_text( f'{_PROJECT_TOML}\n[rules]\nselect = ["SQLCLEAN004"]\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\n' "WITH orders(order_id) AS (VALUES (1), (2))\nSELECT order_id FROM orders LIMIT 1\n", @@ -160,7 +160,7 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i description="single table model with no schema defaults to adapter schema", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id" ), }, @@ -180,7 +180,7 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i description="view materialization produces create or replace view DDL", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/active_orders.sql": ( + "sql/models/active_orders.sql": ( "MODEL (description 'Test model active_orders.', materialized view);\n\nSELECT order_id FROM orders WHERE status = 'active'" ), }, @@ -200,7 +200,7 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i description="model with explicit schema and database populates manifest target", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n materialized table\n schema analytics\n" " database warehouse\n);\n\n" "SELECT 1 AS order_id" @@ -222,10 +222,10 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i description="two models with ref dependency resolves ref to qualified name", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT 1 AS order_id" ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT order_id FROM __ref("stg_orders")' ), }, @@ -252,10 +252,10 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i warehouse_setup_sql=("CREATE TABLE main.payments AS SELECT 1 AS payment_id",), project_files={ "sqlbuild_project.toml": _FILE_PROJECT_TOML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_payments\n description: Test source raw_payments.\n schema: main\n table: payments\n" ), - "models/stg_payments.sql": ( + "sql/models/stg_payments.sql": ( 'MODEL (description "Test model stg_payments.", materialized table);\n\nSELECT payment_id FROM __source("raw_payments")' ), }, @@ -275,10 +275,10 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i description="multiple models in subdirectories preserves relative paths", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS order_id" ), - "models/marts/fact_orders.sql": ( + "sql/models/marts/fact_orders.sql": ( 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT order_id FROM __ref("stg_orders")' ), }, @@ -304,7 +304,7 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i description="Python macro receives constants and enums visible to its caller", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/_constants/policy.sql": ( + "sql/models/_constants/policy.sql": ( "CONSTANT (name minimum_quantity, value 2);\n" 'CONSTANT (name regions, value ["north", "south"]);\n' "CONSTANT (name unique_ids, value {2, 1});\n" @@ -312,10 +312,10 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i 'CONSTANT (name adjustment, type decimal, value "2.50");\n' 'CONSTANT (name display_name, value "O\'Reilly");\n' ), - "models/_enums/status.sql": ( + "sql/models/_enums/status.sql": ( 'ENUM (name order_status, members (ACTIVE "active", PAUSED "paused"));\n' ), - "models/_macros/python/policy.py": ( + "sql/models/_macros/python/policy.py": ( "from sqlbuild.compiler.compile.models import MacroContext\n\n\n" "def policy_columns(ctx: MacroContext) -> str:\n" " minimum = ctx.constants['minimum_quantity']\n" @@ -339,7 +339,7 @@ def test_given_rule_finding_when_running_shared_compile_pipeline_then_planning_i ' f"{optional} AS optional_quantity, {has_closed} AS has_closed"\n' " )\n" ), - "models/policy_summary.sql": ( + "sql/models/policy_summary.sql": ( "MODEL (description 'Test model policy_summary.', materialized view);\n\nSELECT @py.policy_columns()" ), }, @@ -434,8 +434,8 @@ def test_given_project_files_when_running_compile_pipeline_then_produces_valid_o description="run selector resolves Python task without SQL-only planning", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", - "python/tasks/orders.py": ( + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def prepare_orders(ctx):\n" @@ -476,7 +476,7 @@ def test_given_python_run_selector_when_running_compile_pipeline_then_tracks_pyt description="reports compile progress from compile pipeline", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", }, expected_progress_prefixes=("Compiling project...", "Compiled project."), ) @@ -509,7 +509,7 @@ def test_given_progress_callback_when_running_compile_pipeline_then_reports_comp description="reports compile progress from project graph build", project_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", }, expected_progress_prefixes=("Compiling project...", "Compiled project."), ) @@ -553,7 +553,7 @@ def test_given_progress_callback_when_building_project_graph_then_reports_compil 'warehouse = "TEST_WH"\n' 'schema = "TEST_SCHEMA"\n' ), - "models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS order_id\n", + "sql/models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS order_id\n", }, expected_error_fragment="snowflake execution requires explicit target database", ) @@ -595,7 +595,7 @@ def test_given_snowflake_local_override_without_target_namespace_when_compiling_ 'database = "${ENV:TEST_DB}"\n' 'schema = "${ENV:TEST_SCHEMA}"\n' ), - "models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS order_id\n", + "sql/models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS order_id\n", }, expected_database="LOCAL_DB", expected_schema="LOCAL_SCHEMA", @@ -612,7 +612,7 @@ def test_given_snowflake_local_override_without_target_namespace_when_compiling_ 'database = "DEFAULTS_DB"\n' 'schema = "DEFAULTS_SCHEMA"\n' ), - "models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS order_id\n", + "sql/models/stg_orders.sql": "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS order_id\n", }, expected_database="DEFAULTS_DB", expected_schema="DEFAULTS_SCHEMA", @@ -660,10 +660,10 @@ def test_given_snowflake_local_target_namespace_when_compiling_then_targets_reso "[targets.prod]\n" 'schema = "prod_schema"\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT 1 AS order_id" ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( 'MODEL (description "Test model fact_orders.", materialized table);\n\nSELECT order_id FROM __ref("stg_orders")' ), }, @@ -724,16 +724,16 @@ def test_given_project_with_defer_to_when_compiling_then_resolves_refs_to_deferr "[settings]\n" "sql_analysis = true\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT id, amount FROM __source("raw")' ), - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( "MODEL (description 'Test model fact_orders.', materialized table);\n\n" "WITH local_helper AS (SELECT 1 AS one) " 'SELECT id, amount + one AS adjusted FROM __ref("stg_orders") ' "CROSS JOIN local_helper" ), - "sources/raw.yml": "sources:\n - name: raw\n description: Test source raw.\n schema: main\n table: raw\n", + "sql/sources/raw.yml": "sources:\n - name: raw\n description: Test source raw.\n schema: main\n table: raw\n", "tests/unit/test_chain.sql": ( "TEST();\n\n" "WITH\n" @@ -844,10 +844,10 @@ def test_given_append_cursor_model_when_compiling_then_sql_uses_expected_lower_b "sqlbuild_project.toml": ( f'name = "demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = "{db_path}"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n schema: main\n table: raw_orders\n" ), - "models/orders.sql": model_header, + "sql/models/orders.sql": model_header, }, ) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_measurement_audits.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_measurement_audits.py index 3881d06fef..183faad2ad 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_measurement_audits.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_measurement_audits.py @@ -42,7 +42,7 @@ def test_given_attached_measurement_audit_when_compiling_then_full_contract_reac "[connection]\n" 'database = ":memory:"\n' ), - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", materialized table, audits [ @@ -60,7 +60,7 @@ def test_given_attached_measurement_audit_when_compiling_then_full_contract_reac SELECT 1 AS order_id """, - "audits/generic/valid_order_rate.sql": """ + "sql/audits/generic/valid_order_rate.sql": """ AUDIT ( evaluation measurement, value valid_rate, @@ -137,8 +137,8 @@ def test_given_generic_measurement_definition_with_policy_when_compiling_then_de tmp_path, { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.', audits [rate (thresholds (warn (below 100)))]); SELECT 1", - "audits/generic/rate.sql": """ + "sql/models/orders.sql": "MODEL (description 'Test model orders.', audits [rate (thresholds (warn (below 100)))]); SELECT 1", + "sql/audits/generic/rate.sql": """ AUDIT (evaluation measurement, value rate, thresholds (warn (below 100))); MEASURE (SELECT 100 AS rate FROM @relation); """, @@ -168,8 +168,8 @@ def test_given_measurement_attachment_without_thresholds_when_compiling_then_pol tmp_path, { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.', audits [rate]); SELECT 1", - "audits/generic/rate.sql": """ + "sql/models/orders.sql": "MODEL (description 'Test model orders.', audits [rate]); SELECT 1", + "sql/audits/generic/rate.sql": """ AUDIT (evaluation measurement, value rate); MEASURE (SELECT 100 AS rate FROM @relation); """, @@ -199,10 +199,10 @@ def test_given_measurement_attachment_with_severity_when_compiling_then_conflict tmp_path, { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', audits [rate (severity warn, thresholds (warn (below 100)))]); SELECT 1" ), - "audits/generic/rate.sql": """ + "sql/audits/generic/rate.sql": """ AUDIT (evaluation measurement, value rate); MEASURE (SELECT 100 AS rate FROM @relation); """, @@ -233,9 +233,9 @@ def test_given_standalone_measurement_with_header_policy_when_compiling_then_it_ tmp_path, { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id", - "models/customers.sql": "MODEL (description 'Test model customers.');\nSELECT 1 AS order_id", - "audits/singular/rate.sql": """ + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS order_id", + "sql/models/customers.sql": "MODEL (description 'Test model customers.');\nSELECT 1 AS order_id", + "sql/audits/singular/rate.sql": """ AUDIT ( evaluation measurement, value rate, diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_native_binding_catalog.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_native_binding_catalog.py index 46abce3a20..6992945fcf 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_native_binding_catalog.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_native_binding_catalog.py @@ -57,8 +57,8 @@ def test_given_quoted_case_semantics_when_compiling_then_resolves_native_aliases (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n[rules]\nselect = []\n[connection]\nsession_parameters = { QUOTED_IDENTIFIERS_IGNORE_CASE = true }\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text( "MODEL (description 'Test model orders.', database warehouse, schema analytics);\n" + test_case.sql ) @@ -90,11 +90,11 @@ def test_given_quoted_typo_when_validating_then_keeps_authored_spelling_and_span (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n[rules]\nselect = []\n[connection]\nsession_parameters = { QUOTED_IDENTIFIERS_IGNORE_CASE = true }\n' ) - (tmp_path / "models").mkdir() + (tmp_path / "sql" / "models").mkdir(parents=True) sql: str = ( "MODEL (description 'Test model.', database warehouse, schema analytics);\n" + test_case.sql ) - (tmp_path / "models/orders.sql").write_text(sql) + (tmp_path / "sql/models/orders.sql").write_text(sql) assert main(["--project-dir", str(tmp_path), "compile", "--json", "--no-cache"]) == 1 payload: dict[str, Any] = json.loads(capsys.readouterr().out) (diagnostic,) = payload["diagnostics"] @@ -119,12 +119,12 @@ def test_given_catalog_when_rebinding_physical_shapes_then_does_not_reuse_stale_ (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n[rules]\nselect = []\n[connection]\nsession_parameters = { QUOTED_IDENTIFIERS_IGNORE_CASE = true }\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n table: orders\n" ) - (tmp_path / "models/report.sql").write_text( + (tmp_path / "sql/models/report.sql").write_text( "MODEL (description 'Test model report.', database warehouse, schema analytics);\n" + test_case.sql ) @@ -182,12 +182,12 @@ def test_given_case_sensitive_snowflake_when_rebinding_listed_columns_then_unquo (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n table: orders\n" ) - (tmp_path / "models/report.sql").write_text( + (tmp_path / "sql/models/report.sql").write_text( "MODEL (description 'Test model report.', database warehouse, schema analytics);\n" + test_case.sql ) @@ -281,16 +281,16 @@ def test_given_case_sensitive_dialect_when_listed_columns_bind_as_declared_then_ (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "{test_case.dialect}"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n table: orders\n" " contract: enforced\n columns:\n" + "".join( f" - name: {name}\n type: {kind}\n" for name, kind in _DECLARED_ORDERS ) ) - (tmp_path / "models/report.sql").write_text( + (tmp_path / "sql/models/report.sql").write_text( "MODEL (description 'Test model report.', database warehouse, schema analytics);\n" 'SELECT order_id, status FROM __source("orders")' ) @@ -375,9 +375,9 @@ def test_given_source_gaining_columns_when_rebinding_then_reanalyses_models_they (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n table: orders\n" " contract: enforced\n columns:\n" + "".join( @@ -385,7 +385,7 @@ def test_given_source_gaining_columns_when_rebinding_then_reanalyses_models_they ) ) for name, sql in test_case.models: - (tmp_path / f"models/{name}.sql").write_text( + (tmp_path / f"sql/models/{name}.sql").write_text( f"MODEL (description 'Test model {name}.', database warehouse, schema analytics);\n" + sql ) @@ -434,8 +434,8 @@ def test_given_sql_when_case_policy_enabled_then_fused_validation_is_reused( 'name = "orders"\nadapter = "snowflake"\n[rules]\nselect = []\n' "[connection]\nsession_parameters = { QUOTED_IDENTIFIERS_IGNORE_CASE = true }\n" ) - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text( "MODEL (description 'Test model orders.', database warehouse, schema analytics);\n" + test_case.sql ) @@ -481,8 +481,8 @@ def test_given_target_cache_policy_when_compiling_twice_then_reuses_only_enabled f"compile_cache = {str(test_case.enabled).lower()}\n" "[targets.local.connection]\nsession_parameters = { QUOTED_IDENTIFIERS_IGNORE_CASE = true }\n" ) - (tmp_path / "models").mkdir() - model: Path = tmp_path / "models/orders.sql" + (tmp_path / "sql" / "models").mkdir(parents=True) + model: Path = tmp_path / "sql/models/orders.sql" model.write_text( 'MODEL (description "Test model orders.", database warehouse, schema analytics);\nSELECT SUM("Active") FROM (SELECT TRUE AS "Active") q' ) @@ -532,12 +532,12 @@ def test_given_quoted_catalog_binding_when_compiling_then_preserves_bound_expres 'name = "orders"\nadapter = "snowflake"\n[rules]\nselect = []\n' "[connection]\nsession_parameters = { QUOTED_IDENTIFIERS_IGNORE_CASE = true }\n" ) - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n expression: SELECT 1 AS id, 2 AS amount\n" ) - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text( "MODEL (description 'Test model orders.', database warehouse, schema analytics); " + test_case.sql ) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_python_source_reads.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_python_source_reads.py index 9226cd4452..c6e8ae0711 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_python_source_reads.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_python_source_reads.py @@ -23,16 +23,16 @@ '[targets.prod]\nschema = "prod"\nloader_schema = "raw_prod"\n' ) _PROJECT_FILES: dict[str, str] = { - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n managed: true\n write_strategy: table\n" " columns:\n - name: order_id\n type: INTEGER\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from sqlbuild.loaders import loader\n\n\n" "@loader\ndef raw_orders(ctx):\n '''Test loader raw_orders.'''\n return [{'order_id': 1}]\n" ), - "models/order_marker.sql": "MODEL (description 'Test model order_marker.', materialized table);\nSELECT 1 AS n\n", - "python/tasks/count.py": ( + "sql/models/order_marker.sql": "MODEL (description 'Test model order_marker.', materialized table);\nSELECT 1 AS n\n", + "python/nodes/tasks/count/asset.py": ( "from sqlbuild.refs import source\nfrom sqlbuild.assets import asset\n\n\n" '@asset(depends_on=source("raw_orders"))\n' "def count_task(ctx):\n" diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_review_bindings.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_review_bindings.py index 71cbad4e22..71bdcb4889 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_review_bindings.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_review_bindings.py @@ -45,13 +45,13 @@ def test_given_open_sources_when_validating_clauses_then_only_closed_shapes_prov (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n table: orders\n - name: customers\n description: Test source customers.\n table: customers\n" " - name: known\n description: Test source known.\n table: known\n contract: enforced\n columns:\n - name: id\n type: INTEGER\n" ) - (tmp_path / "models").mkdir() - (tmp_path / "models/report.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/report.sql").write_text( "MODEL (description 'Test model report.', materialized view);\n" + test_case.sql ) result: int = main(["--project-dir", str(tmp_path), "compile", "--no-cache", "--json"]) @@ -99,7 +99,7 @@ def test_given_nested_function_calls_when_compiling_then_native_normalization_do (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - functions: Path = tmp_path / "functions/sql" + functions: Path = tmp_path / "sql/functions/sql" functions.mkdir(parents=True) (functions / "table_fn__orders.sql").write_text( "FUNCTION (description 'Test function table_fn__orders.', arguments (x INTEGER), returns table (id INTEGER)); SELECT x AS id" @@ -107,8 +107,8 @@ def test_given_nested_function_calls_when_compiling_then_native_normalization_do (functions / "udf__quantity.sql").write_text( "FUNCTION (description 'Test function udf__quantity.', arguments (x INTEGER), returns INTEGER); x + 1" ) - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text( "MODEL (description 'Test model orders.', materialized view); " + test_case.sql ) assert main(["--project-dir", str(tmp_path), "compile", "--no-cache", "--json"]) == 0 @@ -155,10 +155,10 @@ def test_given_inferred_output_when_binding_downstream_then_preserves_dialect_id (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "{test_case.dialect}"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() + (tmp_path / "sql" / "models").mkdir(parents=True) header: str = "MODEL (description 'Test model.', materialized view, database warehouse, schema analytics);\n" - (tmp_path / "models/orders.sql").write_text(header + f"SELECT 1 AS {test_case.projection}") - (tmp_path / "models/report.sql").write_text( + (tmp_path / "sql/models/orders.sql").write_text(header + f"SELECT 1 AS {test_case.projection}") + (tmp_path / "sql/models/report.sql").write_text( header + f'SELECT {test_case.reference} FROM __ref("orders")' ) result: int = main(["--project-dir", str(tmp_path), "compile", "--no-cache", "--json"]) @@ -194,9 +194,9 @@ def test_given_metadata_predicates_when_compiling_then_allows_dialect_coercion_a (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text(test_case.sql) - (tmp_path / "models/customers.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text(test_case.sql) + (tmp_path / "sql/models/customers.sql").write_text( "MODEL (description 'Test model customers.', materialized view); SELECT 1 AS CUSTOMER_ID" ) result: int = main(["--project-dir", str(tmp_path), "compile", "--no-cache", "--json"]) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_selection_lineage.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_selection_lineage.py index 2d2b1984d1..1151fbf44a 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_selection_lineage.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_selection_lineage.py @@ -18,18 +18,18 @@ _PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_payments\n description: Test source raw_payments.\n" " expression: SELECT 1 AS payment_id\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id\n" ), - "models/stg_payments.sql": ( + "sql/models/stg_payments.sql": ( "MODEL (description 'Test model stg_payments.', materialized table, audits [orders_backed]);\n\n" 'SELECT payment_id FROM __source("raw_payments")' ), - "audits/generic/orders_backed.sql": ( + "sql/audits/generic/orders_backed.sql": ( "AUDIT ();\n\n" "SELECT m.*\n" 'FROM __ref("@model") m\n' diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_binding.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_binding.py index 4cca144777..c2bde6da94 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_binding.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_binding.py @@ -133,7 +133,7 @@ def test_given_complete_contract_when_clause_references_missing_column_then_comp assert "(context:" not in output assert "model: downstream" in output assert ( - f"--> models/downstream.sql:2:{test_case.query_sql.index(test_case.missing_column) + 1}" + f"--> sql/models/downstream.sql:2:{test_case.query_sql.index(test_case.missing_column) + 1}" in output ) @@ -161,7 +161,7 @@ def test_given_two_complete_contracts_when_unqualified_column_is_ambiguous_then_ 'SELECT id FROM __ref("upstream") l CROSS JOIN __ref("other") r\n' ), ) - _ = (tmp_path / "models" / "other.sql").write_text( + _ = (tmp_path / "sql" / "models" / "other.sql").write_text( _AUTHORITATIVE_MODEL, encoding="utf-8", ) @@ -233,10 +233,10 @@ def test_given_source_contract_default_when_compiling_then_effective_policy_cont 'name = "semantic_binding"\nadapter = "duckdb"\n\n[defaults]\ncontract = "enforced"\n', encoding="utf-8", ) - sources_dir: Path = tmp_path / "sources" - models_dir: Path = tmp_path / "models" - sources_dir.mkdir() - models_dir.mkdir() + sources_dir: Path = tmp_path / "sql" / "sources" + models_dir: Path = tmp_path / "sql" / "models" + sources_dir.mkdir(parents=True) + models_dir.mkdir(parents=True) _ = (sources_dir / "raw.yml").write_text( f"""sources: - name: raw_orders @@ -286,7 +286,7 @@ def test_given_complete_inferred_intermediate_when_downstream_column_is_missing_ 'SELECT id FROM __ref("intermediate") WHERE missing_derived = TRUE\n' ), ) - _ = (tmp_path / "models" / "intermediate.sql").write_text( + _ = (tmp_path / "sql" / "models" / "intermediate.sql").write_text( 'MODEL (description "Test model intermediate.", materialized view);\nSELECT id FROM __ref("upstream")\n', encoding="utf-8", ) @@ -360,7 +360,7 @@ def test_given_cached_dependent_error_when_upstream_analysis_disabled_then_stale 'MODEL (description "Test model.", materialized view);\nSELECT runtime_column FROM __ref("intermediate")\n' ), ) - intermediate_path: Path = tmp_path / "models" / "intermediate.sql" + intermediate_path: Path = tmp_path / "sql" / "models" / "intermediate.sql" _ = intermediate_path.write_text( 'MODEL (description "Test model intermediate.", materialized view);\nSELECT id FROM __ref("upstream")\n', encoding="utf-8", @@ -406,8 +406,8 @@ def test_given_cli_analysis_disabled_when_sql_is_unsupported_then_compile_succee _ = (tmp_path / "sqlbuild_project.toml").write_text( 'name = "semantic_binding"\nadapter = "duckdb"\n', encoding="utf-8" ) - models_dir: Path = tmp_path / "models" - models_dir.mkdir() + models_dir: Path = tmp_path / "sql" / "models" + models_dir.mkdir(parents=True) _ = (models_dir / "vendor.sql").write_text( "MODEL (description 'Test model vendor.', materialized view);\nSELEC unsupported vendor sql\n", encoding="utf-8", @@ -611,10 +611,10 @@ def test_given_untyped_source_when_cast_flows_through_ctes_then_declared_type_ma 'name = "semantic_binding"\nadapter = "snowflake"\n' + _UNPROVEN_RANKING_RULES, encoding="utf-8", ) - sources_dir: Path = tmp_path / "sources" - models_dir: Path = tmp_path / "models" - sources_dir.mkdir() - models_dir.mkdir() + sources_dir: Path = tmp_path / "sql" / "sources" + models_dir: Path = tmp_path / "sql" / "models" + sources_dir.mkdir(parents=True) + models_dir.mkdir(parents=True) _ = (sources_dir / "raw.yml").write_text( """sources: - name: raw_orders diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_diagnostic_ux.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_diagnostic_ux.py index ca21d34d7f..11bfc8d4d0 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_diagnostic_ux.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_diagnostic_ux.py @@ -21,7 +21,7 @@ [ DiagnosticUxCase( "root typo", - (("models/marts/fact_orders.sql", " o.quantity,", " o.qty,"),), + (("sql/models/marts/fact_orders.sql", " o.quantity,", " o.qty,"),), expected_fragments=( "Unknown column 'qty' in stg_orders (as o)", "^^^", @@ -33,9 +33,9 @@ DiagnosticUxCase( "both root errors", ( - ("models/marts/fact_orders.sql", " o.quantity,", " o.qty,"), + ("sql/models/marts/fact_orders.sql", " o.quantity,", " o.qty,"), ( - "models/marts/fact_orders.sql", + "sql/models/marts/fact_orders.sql", "p ON o.order_id = p.order_id", "p ON o.order_id = p.order_id\nWHERE o.ordered_at > 5", ), @@ -52,8 +52,8 @@ DiagnosticUxCase( "independent same input error", ( - ("models/marts/fact_orders.sql", " o.quantity,", " o.qty,"), - ("models/marts/hourly_order_activity.sql", "SUM(o.quantity)", "SUM(o.missing)"), + ("sql/models/marts/fact_orders.sql", " o.quantity,", " o.qty,"), + ("sql/models/marts/hourly_order_activity.sql", "SUM(o.quantity)", "SUM(o.missing)"), ), expected_errors=2, expected_fragments=( @@ -63,10 +63,10 @@ ), DiagnosticUxCase( "independent closed input error", - (("models/marts/fact_orders.sql", " o.quantity,", " o.qty,"),), + (("sql/models/marts/fact_orders.sql", " o.quantity,", " o.qty,"),), extra_files=( ( - "models/independent.sql", + "sql/models/independent.sql", 'MODEL (description "Test model independent.", materialized view);\nSELECT w.missing FROM __seed("waffle_types") w CROSS JOIN __ref("fact_orders") o\n', ), ), @@ -78,7 +78,7 @@ ), DiagnosticUxCase( "explicit output alias remains authoritative", - (("models/marts/fact_orders.sql", " o.quantity,", " o.qty AS qty,"),), + (("sql/models/marts/fact_orders.sql", " o.quantity,", " o.qty AS qty,"),), expected_errors=3, expected_fragments=("Unknown column 'quantity' in fact_orders", "error[B302]"), ), @@ -87,15 +87,15 @@ (), extra_files=( ( - "models/available.sql", + "sql/models/available.sql", "MODEL (description 'Test model available.', materialized view); SELECT 1 AS qty", ), ( - "models/predicate_bad.sql", + "sql/models/predicate_bad.sql", 'MODEL (description "Test model predicate_bad.", materialized view); SELECT a.qty FROM __ref("available") a CROSS JOIN __ref("stg_orders") o WHERE o.qty > 5', ), ( - "models/independent_use.sql", + "sql/models/independent_use.sql", 'MODEL (description "Test model independent_use.", materialized view); SELECT quantity FROM __ref("predicate_bad")', ), ), @@ -107,14 +107,14 @@ ), DiagnosticUxCase( "open source detail", - (("models/marts/fact_orders.sql", " o.quantity,", " o.qty,"),), + (("sql/models/marts/fact_orders.sql", " o.quantity,", " o.qty,"),), extra_files=( ( - "sources/optional.yml", + "sql/sources/optional.yml", "sources:\n - name: external_orders\n description: Test source external_orders.\n table: external_orders\n", ), ( - "models/open_read.sql", + "sql/models/open_read.sql", 'MODEL (description "Test model open_read.", materialized view);\nSELECT id FROM __source("external_orders")\n', ), ), @@ -139,12 +139,12 @@ (), extra_files=( ( - "models/wide.sql", + "sql/models/wide.sql", "MODEL (description 'Test model wide.', materialized view);\nSELECT 1 AS quantity, " + ", ".join(f"1 AS field_{index}" for index in range(20)), ), ( - "models/wide_bad.sql", + "sql/models/wide_bad.sql", 'MODEL (description "Test model wide_bad.", materialized view);\nSELECT w.qty FROM __ref("wide") w', ), ), diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_scopes.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_scopes.py index 992e9b586e..4f05031ae3 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_scopes.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_scopes.py @@ -124,8 +124,8 @@ def test_given_semantic_scope_when_compiling_then_closed_shapes_are_checked( downstream_sql=test_case.header + test_case.downstream, project_toml=SEMANTIC_BINDING_PROJECT_TOML + '\n[rules]\nignore = ["SQLCLEAN039"]\n', ) - (tmp_path / "sources").mkdir(exist_ok=True) - (tmp_path / "sources" / "orders.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True, exist_ok=True) + (tmp_path / "sql" / "sources" / "orders.yml").write_text( "sources:\n" " - name: open_orders\n description: Test source open_orders.\n table: orders\n" " - name: closed_orders\n description: Test source closed_orders.\n table: orders\n contract: enforced\n" diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_snowflake_release.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_snowflake_release.py index b55df74441..4f11fbc410 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_snowflake_release.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_snowflake_release.py @@ -86,9 +86,9 @@ def test_given_snowflake_semantics_when_compiling_then_preserves_native_verdicts (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "sources").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n table: orders\n contract: enforced\n columns:\n" " - {name: order_id, type: INTEGER}\n" " - {name: quantity, type: INTEGER}\n" @@ -96,7 +96,7 @@ def test_given_snowflake_semantics_when_compiling_then_preserves_native_verdicts " - {name: ordered_on, type: DATE}\n" " - {name: ordered_at, type: TIMESTAMP}\n" ) - (tmp_path / "models/report.sql").write_text( + (tmp_path / "sql/models/report.sql").write_text( "MODEL (description 'Test model report.', materialized view, database warehouse, schema analytics);\n" + test_case.sql ) @@ -132,8 +132,8 @@ def test_given_snowflake_query_when_inferring_rich_types_then_preserves_proven_o test_case: SnowflakeOutputInferenceCase, tmp_path: Path ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "snowflake"\n') - (tmp_path / "models").mkdir() - (tmp_path / "models/report.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/report.sql").write_text( "MODEL (description 'Test model report.', materialized view, database warehouse, schema analytics);\n" + test_case.sql ) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_triage.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_triage.py index f4656ffeb9..e7ffff2bab 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_triage.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_semantic_triage.py @@ -44,13 +44,13 @@ def test_given_cursor_families_when_compiling_then_accepts_temporal_pairs_only( (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "snowflake"\n[rules]\nselect = []\n' ) - (tmp_path / "sources").mkdir() - (tmp_path / "models").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n table: orders\n contract: enforced\n" f" columns:\n - name: ordered_at\n type: {test_case.column_type}\n" ) - (tmp_path / "models/recent_orders.sql").write_text( + (tmp_path / "sql/models/recent_orders.sql").write_text( "MODEL (description 'Test model recent_orders.', materialized incremental, database warehouse, schema analytics, " f"incremental_strategy append, cursor ordered_at, cursor_type {test_case.cursor_type}, " 'cursor_grain day);\nSELECT ordered_at FROM __source("orders")' @@ -83,13 +83,13 @@ def test_given_effective_target_when_binding_quotes_then_honours_session_setting '[targets.selected]\nschema = "preserve"\n[targets.selected.connection]\n' + test_case.setting ) - (tmp_path / "sources").mkdir() - (tmp_path / "models").mkdir() - (tmp_path / "sources/orders.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/sources/orders.yml").write_text( "sources:\n - name: orders\n description: Test source orders.\n table: orders\n contract: enforced\n" " columns:\n - name: customer\n type: VARCHAR\n" ) - (tmp_path / "models/quoted_orders.sql").write_text( + (tmp_path / "sql/models/quoted_orders.sql").write_text( "MODEL (description 'Test model quoted_orders.', materialized view, database warehouse, schema analytics);\n" 'SELECT o."customer" FROM __source("orders") o' ) @@ -139,22 +139,22 @@ def test_given_type_error_root_when_binding_dependants_then_recovers_only_poison (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text( "MODEL (description 'Test model orders.', materialized view, contract enforced, columns (quantity (type INTEGER), " "ordered_at (type TIMESTAMP)));\nSELECT CAST(1 AS INTEGER) AS quantity, " "CAST('2026-04-01' AS TIMESTAMP) AS ordered_at" ) - (tmp_path / "models/broken.sql").write_text( + (tmp_path / "sql/models/broken.sql").write_text( f"MODEL (description 'Test model broken.', materialized view{test_case.root_contract});\nSELECT quantity + ordered_at AS total, " 'ordered_at FROM __ref("orders")' ) - (tmp_path / "models/downstream.sql").write_text( + (tmp_path / "sql/models/downstream.sql").write_text( "MODEL (description 'Test model downstream.', materialized view);\nSELECT total > ordered_at AS compared" + test_case.independent_sql + ' FROM __ref("broken")' ) - (tmp_path / "models/final_orders.sql").write_text( + (tmp_path / "sql/models/final_orders.sql").write_text( 'MODEL (description "Test model final_orders.", materialized view);\nSELECT compared AS final_value FROM __ref("downstream")' ) main(["--project-dir", str(tmp_path), "compile", "--json"]) @@ -182,8 +182,8 @@ def test_given_repetitive_sql_when_mapping_diagnostic_then_preserves_authored_sp test_case: SemanticTriageCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - (tmp_path / "models").mkdir() - (tmp_path / "models/orders.sql").write_text( + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/models/orders.sql").write_text( "MODEL (description 'Test model orders.', materialized view);\nSELECT CAST(1 AS INTEGER) AS quantity" ) projections: str = ",\n".join(f"quantity + {index} AS amount_{index}" for index in range(300)) @@ -192,7 +192,7 @@ def test_given_repetitive_sql_when_mapping_diagnostic_then_preserves_authored_sp + projections + "\nFROM __ref(\"orders\")\nWHERE quantity > TIMESTAMP '2026-04-01'" ) - (tmp_path / "models/report.sql").write_text(sql) + (tmp_path / "sql/models/report.sql").write_text(sql) assert main(["--project-dir", str(tmp_path), "compile", "--no-cache", "--json"]) == 1 result: dict[str, Any] = json.loads(capsys.readouterr().out) assert tuple(item["code"] for item in result["diagnostics"]) == test_case.expected_codes @@ -215,12 +215,12 @@ def test_given_cached_validation_when_warm_or_schema_changed_then_reuses_only_ma (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - (tmp_path / "sources").mkdir() - (tmp_path / "models").mkdir() - source: Path = tmp_path / "sources/orders.yml" + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql" / "models").mkdir(parents=True) + source: Path = tmp_path / "sql/sources/orders.yml" declaration: str = "sources:\n - name: orders\n description: Test source orders.\n table: orders\n contract: enforced\n columns:\n - name: quantity\n type: INTEGER\n" source.write_text(declaration) - (tmp_path / "models/totals.sql").write_text( + (tmp_path / "sql/models/totals.sql").write_text( 'MODEL (description "Test model totals.", materialized view);\nSELECT quantity + 1 AS total FROM __source("orders")' ) args: list[str] = ["--project-dir", str(tmp_path), "compile", "--json"] @@ -256,7 +256,7 @@ def test_given_a_type_error_upstream_of_a_model_with_its_own_error_when_compilin (tmp_path / "sqlbuild_project.toml").write_text( f'name = "orders"\nadapter = "{test_case.adapter}"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() + (tmp_path / "sql" / "models").mkdir(parents=True) header: str = ( "MODEL (description 'Test model.', materialized view, database warehouse, schema analytics" ) @@ -267,7 +267,7 @@ def test_given_a_type_error_upstream_of_a_model_with_its_own_error_when_compilin "downstream": f'{header});\nSELECT bad > ordered_at AS compared, missing FROM __ref("upstream")', } for name, sql in files.items(): - (tmp_path / "models" / f"{name}.sql").write_text(sql) + (tmp_path / "sql" / "models" / f"{name}.sql").write_text(sql) assert main(["--project-dir", str(tmp_path), "compile", "--json", "--no-cache"]) == 1 result: dict[str, Any] = json.loads(capsys.readouterr().out) found: dict[tuple[str, str], list[str]] = { @@ -292,7 +292,7 @@ def test_given_repeated_root_messages_when_recovering_then_preserves_each_output (tmp_path / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n[rules]\nselect = []\n' ) - (tmp_path / "models").mkdir() + (tmp_path / "sql" / "models").mkdir(parents=True) files: dict[str, str] = { "orders": "MODEL (description 'Test model.', materialized view, contract enforced, columns (quantity (type INTEGER), ordered_at (type TIMESTAMP)));\nSELECT CAST(1 AS INTEGER) AS quantity, CAST('2026-04-01' AS TIMESTAMP) AS ordered_at", "broken": 'MODEL (description "Test model.", materialized view, contract enforced, columns (total_a (type INTEGER), total_b (type INTEGER), ordered_at (type TIMESTAMP)));\nSELECT quantity + ordered_at AS total_a, quantity + ordered_at AS total_b, ordered_at FROM __ref("orders")', @@ -300,7 +300,7 @@ def test_given_repeated_root_messages_when_recovering_then_preserves_each_output "final_orders": 'MODEL (description "Test model.", materialized view);\nSELECT a, b FROM __ref("downstream")', } for name, sql in files.items(): - (tmp_path / "models" / f"{name}.sql").write_text(sql) + (tmp_path / "sql" / "models" / f"{name}.sql").write_text(sql) assert main(["--project-dir", str(tmp_path), "compile", "--json", "--no-cache"]) == 1 result: dict[str, Any] = json.loads(capsys.readouterr().out) assert tuple(item["code"] for item in result["diagnostics"]) == test_case.expected_codes @@ -353,10 +353,10 @@ def test_given_udf_argument_columns_when_compiling_then_checks_declared_argument test_case: FunctionArgumentTypeCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: (tmp_path / "sqlbuild_project.toml").write_text('name = "orders"\nadapter = "duckdb"\n') - (tmp_path / "sources").mkdir() - (tmp_path / "models").mkdir() - (tmp_path / "functions/sql").mkdir(parents=True) - (tmp_path / "sources/raw.yml").write_text( + (tmp_path / "sql" / "sources").mkdir(parents=True) + (tmp_path / "sql" / "models").mkdir(parents=True) + (tmp_path / "sql/functions/sql").mkdir(parents=True) + (tmp_path / "sql/sources/raw.yml").write_text( "sources:\n" " - name: orders\n description: Test source orders.\n table: orders\n contract: enforced\n columns:\n" " - name: id\n type: INTEGER\n" @@ -367,10 +367,10 @@ def test_given_udf_argument_columns_when_compiling_then_checks_declared_argument " - name: id\n type: INTEGER\n" " - name: customer_name\n type: VARCHAR\n" ) - (tmp_path / "functions/sql/add_one.sql").write_text( + (tmp_path / "sql/functions/sql/add_one.sql").write_text( "FUNCTION (description 'Test function add_one.',\n arguments (input_value DOUBLE),\n returns DOUBLE,\n);\n\ninput_value + 1\n" ) - (tmp_path / "models/order_totals.sql").write_text( + (tmp_path / "sql/models/order_totals.sql").write_text( f"MODEL (description 'Test model order_totals.', materialized table);\n\nSELECT {test_case.projection}\n" 'FROM __source("orders") o JOIN __source("customers") c ON o.customer_id = c.id\n' ) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_set_dependencies.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_set_dependencies.py index 83d6db7c3e..42aabfbe54 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_set_dependencies.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_set_dependencies.py @@ -32,7 +32,7 @@ _GROUP_FILES: tuple[tuple[str, str], ...] = ( ( - "models/customer_orders.sql", + "sql/models/customer_orders.sql", "MODEL (description 'Test model customer_orders.', materialized table);\n" 'SELECT o.id FROM __ref("orders") AS o JOIN __ref("customers") AS c ON o.id = c.id\n', ), @@ -72,6 +72,20 @@ expected_models=("order_items", "stg_orders"), expected_sql_deps=("model:order_items",), ), + SetDependencyPlanTestCase( + description="a loader's job dependency reads the job's end nodes", + depends_on='[job("nightly_job")]', + expected_models=("order_items", "orders", "stg_orders"), + expected_sql_deps=("model:order_items", "model:orders"), + kind="loader", + ), + SetDependencyPlanTestCase( + description="a loader's tag dependency reads its tagged end nodes", + depends_on='[tag("finance", exclude="orders")]', + expected_models=("order_items", "stg_orders"), + expected_sql_deps=("model:order_items",), + kind="loader", + ), SetDependencyPlanTestCase( description="a model named and reached through a job is read once", depends_on='(model("orders"), job("nightly_job"))', @@ -86,14 +100,18 @@ def test_given_set_dependency_when_planning_the_assets_upstream_then_selects_the tmp_path: Path, write_repo_files: Callable[[Path, dict[str, str]], None], ) -> None: - write_repo_files(tmp_path, set_dependency_project(depends_on=test_case.depends_on)) + write_repo_files( + tmp_path, set_dependency_project(depends_on=test_case.depends_on, kind=test_case.kind) + ) discovered: DiscoveredProjectInputs = discover_project_inputs(project_dir=tmp_path) result: CompilePipelineResult = run_compile_pipeline( discovered_inputs=discovered, adapter=DuckDbAdapter(), options=CompilePipelineOptions( - no_sql_validation=True, select=("+asset:report",), resolve_python_run_selectors=True + no_sql_validation=True, + select=(f"+{test_case.kind}:report",), + resolve_python_run_selectors=True, ), hooks=ConnectionHooks(), ) diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_set_operation_types.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_set_operation_types.py index 517118e98c..c12b38af17 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_set_operation_types.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_set_operation_types.py @@ -53,8 +53,8 @@ def test_given_mixed_branch_types_when_compiling_then_known_types_match_duckdb( tmp_path: Path, ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_PROJECT_CONFIG, encoding="utf-8") - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( f"MODEL (description 'Test model orders.', materialized table);\n{test_case.query_sql}", encoding="utf-8", @@ -92,8 +92,8 @@ def test_given_union_type_recovery_when_compiling_then_cte_lineage_is_preserved( tmp_path: Path, ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(_PROJECT_CONFIG, encoding="utf-8") - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( "MODEL (description 'Test model orders.', materialized table, contract enforced, columns (amount (type DOUBLE)));\n" "SELECT CAST(2.5 AS DOUBLE) AS amount", diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_sql_test_input_extraction.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_sql_test_input_extraction.py index b4f86a36ea..9c122414e9 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_sql_test_input_extraction.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_sql_test_input_extraction.py @@ -30,9 +30,9 @@ def test_given_expanded_mixed_mode_tests_when_compiling_project_then_complete_in tmp_path, { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS order_id\n", - "models/_constants/order_id.sql": "CONSTANT (name order_id, value 7);\n", - "functions/sql/increment.sql": ( + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS order_id\n", + "sql/models/_constants/order_id.sql": "CONSTANT (name order_id, value 7);\n", + "sql/functions/sql/increment.sql": ( "FUNCTION (description 'Test function increment.', arguments (value INTEGER), returns INTEGER);\n\nvalue + 1\n" ), "tests/unit/a_orders.sql": ( diff --git a/tests/integration/src/sqlbuild/compiler/pipeline/test_star_shape_order.py b/tests/integration/src/sqlbuild/compiler/pipeline/test_star_shape_order.py index 5ca44672d5..90421c88b1 100644 --- a/tests/integration/src/sqlbuild/compiler/pipeline/test_star_shape_order.py +++ b/tests/integration/src/sqlbuild/compiler/pipeline/test_star_shape_order.py @@ -15,11 +15,11 @@ description="quoted upstream column keeps its quoting through a star listed first", files={ "sqlbuild_project.toml": 'name = "orders"\nadapter = "postgres"\n', - "models/a_orders_wide.sql": ( + "sql/models/a_orders_wide.sql": ( "MODEL (description 'Every order column.', schema analytics);\n" 'SELECT * FROM __ref("z_orders")\n' ), - "models/z_orders.sql": ( + "sql/models/z_orders.sql": ( "MODEL (description 'Orders.', schema analytics);\n" "SELECT 1 AS \"OrderId\", 'placed' AS status\n" ), diff --git a/tests/integration/src/sqlbuild/compiler/planner/_helpers/fixtures/test_type_scope.py b/tests/integration/src/sqlbuild/compiler/planner/_helpers/fixtures/test_type_scope.py index 31ba55728a..a082397ecf 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/_helpers/fixtures/test_type_scope.py +++ b/tests/integration/src/sqlbuild/compiler/planner/_helpers/fixtures/test_type_scope.py @@ -40,11 +40,11 @@ def test_given_unrelated_project_types_when_completing_fixture_then_eager_work_i tmp_path, { "sqlbuild_project.toml": 'name = "fixture_scope"\nadapter = "duckdb"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Order facts.");\n' 'SELECT order_id, status FROM __source("raw_orders")' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n - name: raw_orders\n description: Order input.\n" " expression: SELECT 1 AS order_id, 'open' AS status\n" " contract: enforced\n columns:\n" diff --git a/tests/integration/src/sqlbuild/compiler/planner/_helpers/helpers.py b/tests/integration/src/sqlbuild/compiler/planner/_helpers/helpers.py index 750a365eda..174431bbd6 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/_helpers/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/planner/_helpers/helpers.py @@ -120,7 +120,7 @@ def build_project_with_targets( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=model_name), deps=deps, name=model_name, - relative_path=Path(f"models/{model_name}.sql"), + relative_path=Path(f"sql/models/{model_name}.sql"), query_sql=f"SELECT * FROM {model_name}", config=CompileModelConfig(), destination=CompiledRelationLocation( @@ -144,7 +144,7 @@ def build_project_with_targets( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=spec.name), deps=(), name=spec.name, - relative_path=Path(f"models/{spec.name}.sql"), + relative_path=Path(f"sql/models/{spec.name}.sql"), query_sql=f"SELECT * FROM {spec.name}", config=CompileModelConfig( values={ @@ -173,13 +173,13 @@ def build_project_with_targets( deps=(), name=seed_name, seed_file=DiscoveredSeedFile( - file_path=Path(f"seeds/{seed_name}.csv"), - relative_path=Path(f"seeds/{seed_name}.csv"), + file_path=Path(f"sql/seeds/{seed_name}.csv"), + relative_path=Path(f"sql/seeds/{seed_name}.csv"), ), schema_entry=SchemaSeedEntry(name=seed_name, columns=()), schema_file=DiscoveredSchemaFile( - file_path=Path("seeds/schema.yml"), - relative_path=Path("seeds/schema.yml"), + file_path=Path("sql/seeds/schema.yml"), + relative_path=Path("sql/seeds/schema.yml"), contents="", model_entries=(), seed_entries=(), @@ -207,8 +207,8 @@ def build_project_with_targets( name=source_spec[0], schema=source_spec[1], table=source_spec[2] ), source_file=DiscoveredSourceFile( - file_path=Path("sources/sources.yml"), - relative_path=Path("sources/sources.yml"), + file_path=Path("sql/sources/sources.yml"), + relative_path=Path("sql/sources/sources.yml"), contents="", source_entries=(), ), diff --git a/tests/integration/src/sqlbuild/compiler/planner/_helpers/resolve/helpers.py b/tests/integration/src/sqlbuild/compiler/planner/_helpers/resolve/helpers.py index 50736f687b..61adc7c873 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/_helpers/resolve/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/planner/_helpers/resolve/helpers.py @@ -72,15 +72,15 @@ def compile_resolution_project(project_dir: Path) -> CompiledProjectView: 'name = "resolution"\nadapter = "duckdb"\n' '[connection]\ndatabase = ":memory:"\n[defaults]\nschema = "staging"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders", alias "orders_alias"); SELECT 9 AS order_id' ), - "functions/sql/order_lookup.sql": ( + "sql/functions/sql/order_lookup.sql": ( 'FUNCTION (description "Order lookup", arguments (id INTEGER), ' "returns table (order_id INTEGER)); " 'SELECT order_id FROM __ref("orders") WHERE order_id = id' ), - "models/report.sql": ( + "sql/models/report.sql": ( 'MODEL (description "Report", pre_hooks [inline_sql(\'SELECT order_id ' 'FROM __ref("orders")\')]); SELECT o.order_id FROM __ref("orders") o ' 'JOIN __table_fn("order_lookup")(9) f ON o.order_id = f.order_id' @@ -145,7 +145,7 @@ def build_model( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), deps=(), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), query_sql=query_sql, config=CompileModelConfig(values=config), destination=CompiledRelationLocation( diff --git a/tests/integration/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py b/tests/integration/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py index 418c09cced..18c9ed6cb8 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py @@ -126,7 +126,7 @@ def build_test_and_project( ), deps=dependencies, name=model_name, - relative_path=Path(f"models/{model_name}.sql"), + relative_path=Path(f"sql/models/{model_name}.sql"), query_sql=query_sql, config=CompileModelConfig(), destination=CompiledRelationLocation( diff --git a/tests/integration/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/test_execute_chain.py b/tests/integration/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/test_execute_chain.py index 41d31d176e..7230abdb95 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/test_execute_chain.py +++ b/tests/integration/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/test_execute_chain.py @@ -61,10 +61,10 @@ def test_given_parameterized_model_test_when_compiled_and_executed_then_duckdb_p tmp_path, { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n expression: SELECT 1 AS order_id\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\nSELECT order_id FROM __source("raw_orders")\n' ), "tests/unit/orders.sql": f""" diff --git a/tests/integration/src/sqlbuild/compiler/planner/_helpers/test_audit_entry.py b/tests/integration/src/sqlbuild/compiler/planner/_helpers/test_audit_entry.py index a037846175..f333578836 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/_helpers/test_audit_entry.py +++ b/tests/integration/src/sqlbuild/compiler/planner/_helpers/test_audit_entry.py @@ -24,8 +24,8 @@ ) _STUB_FILE: DiscoveredAuditFile = DiscoveredAuditFile( - file_path=Path("audits/generic/not_null.sql"), - relative_path=Path("audits/generic/not_null.sql"), + file_path=Path("sql/audits/generic/not_null.sql"), + relative_path=Path("sql/audits/generic/not_null.sql"), contents="", blocks=(), ) diff --git a/tests/integration/src/sqlbuild/compiler/planner/_helpers/test_fixture_planning.py b/tests/integration/src/sqlbuild/compiler/planner/_helpers/test_fixture_planning.py index 05edf41a93..c82333f6fd 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/_helpers/test_fixture_planning.py +++ b/tests/integration/src/sqlbuild/compiler/planner/_helpers/test_fixture_planning.py @@ -74,10 +74,10 @@ def test_given_partial_fixture_when_compiling_and_planning_then_completes_requir "[connection]\n" 'database = ":memory:"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( f'MODEL (description "Test model orders.");\n\n{test_case.query_sql}\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT 1 AS order_id, 'open' AS status\n" @@ -143,7 +143,7 @@ def test_given_upper_case_reads_through_star_import_when_planning_then_fills_eac tmp_path, { "sqlbuild_project.toml": f'name = "fixture_fill_demo"\n{test_case.project_toml}', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw__orders\n description: Raw order records\n" " database: example_db\n" @@ -154,7 +154,7 @@ def test_given_upper_case_reads_through_star_import_when_planning_then_fills_eac " - name: customer_id\n type: VARCHAR\n" " - name: status\n type: VARCHAR\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Orders with their status.", database example_db, ' "schema analytics);\n\n" 'WITH raw__orders AS (SELECT * FROM __source("raw__orders")),\n' @@ -217,11 +217,11 @@ def test_given_untyped_null_fixture_when_planning_then_applies_authoritative_typ "[connection]\n" 'database = ":memory:"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\nSELECT TRY_CAST(status AS DOUBLE) AS parsed_status " 'FROM __source("raw_orders")\n' ), - "sources/raw_orders.yml": ( + "sql/sources/raw_orders.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " expression: SELECT '1.5' AS status\n" @@ -287,8 +287,8 @@ def test_given_source_contract_when_completing_fixture_then_respects_authoritati tmp_path, { "sqlbuild_project.toml": 'name = "fixture_schema_demo"\nadapter = "duckdb"\n[connection]\ndatabase = ":memory:"\n', - "models/orders.sql": 'MODEL (description "Order facts."); SELECT order_id FROM __source("raw_orders")', - "sources/raw_orders.yml": ( + "sql/models/orders.sql": 'MODEL (description "Order facts."); SELECT order_id FROM __source("raw_orders")', + "sql/sources/raw_orders.yml": ( "sources:\n - name: raw_orders\n description: Raw order facts.\n" " expression: SELECT 1 AS order_id\n" f"{test_case.contract}" diff --git a/tests/integration/src/sqlbuild/compiler/planner/main/helpers.py b/tests/integration/src/sqlbuild/compiler/planner/main/helpers.py index 9a963f36b6..565f0be70a 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/main/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/planner/main/helpers.py @@ -116,7 +116,7 @@ def build_project_from_test_case( ), deps=(*model_deps, *function_deps), name=model_name, - relative_path=Path(f"models/{model_name}.sql"), + relative_path=Path(f"sql/models/{model_name}.sql"), query_sql=query_sql, config=CompileModelConfig(values=config_values), destination=CompiledRelationLocation( @@ -142,12 +142,12 @@ def build_project_from_test_case( name=seed_name, seed_file=DiscoveredSeedFile( file_path=seed_file_path, - relative_path=Path(f"seeds/{seed_name}.csv"), + relative_path=Path(f"sql/seeds/{seed_name}.csv"), ), schema_entry=SchemaSeedEntry(name=seed_name, columns=()), schema_file=DiscoveredSchemaFile( - file_path=Path("seeds/schema.yml"), - relative_path=Path("seeds/schema.yml"), + file_path=Path("sql/seeds/schema.yml"), + relative_path=Path("sql/seeds/schema.yml"), contents="", model_entries=(), seed_entries=(), @@ -176,7 +176,7 @@ def build_project_from_test_case( ), deps=(), name=function_name, - relative_path=Path(f"functions/{language.value}/{function_name}.sql"), + relative_path=Path(f"sql/functions/{language.value}/{function_name}.sql"), arguments=(FunctionArgument(name="value", type="INTEGER"),), returns="INTEGER", body_sql=body_sql, @@ -239,8 +239,8 @@ def build_project_from_source_cursor_input_test_case( name=test_case.source_name, source_entry=source_entry, source_file=DiscoveredSourceFile( - file_path=Path("sources/raw.yml"), - relative_path=Path("sources/raw.yml"), + file_path=Path("sql/sources/raw.yml"), + relative_path=Path("sql/sources/raw.yml"), contents="", source_entries=(source_entry,), ), @@ -252,7 +252,7 @@ def build_project_from_source_cursor_input_test_case( ), deps=(source.key,), name=test_case.model_name, - relative_path=Path(f"models/{test_case.model_name}.sql"), + relative_path=Path(f"sql/models/{test_case.model_name}.sql"), query_sql=f'SELECT * FROM __source("{test_case.source_name}")', references=( CompileSqlReference( @@ -385,7 +385,7 @@ def build_project_from_format_test_case( ), deps=deps, name=model_name, - relative_path=Path(f"models/{model_name}.sql"), + relative_path=Path(f"sql/models/{model_name}.sql"), query_sql=query_sql, config=CompileModelConfig(values=config_values), destination=CompiledRelationLocation( @@ -411,12 +411,12 @@ def build_project_from_format_test_case( name=seed_name, seed_file=DiscoveredSeedFile( file_path=seed_file_path, - relative_path=Path(f"seeds/{seed_name}.csv"), + relative_path=Path(f"sql/seeds/{seed_name}.csv"), ), schema_entry=SchemaSeedEntry(name=seed_name, columns=()), schema_file=DiscoveredSchemaFile( - file_path=Path("seeds/schema.yml"), - relative_path=Path("seeds/schema.yml"), + file_path=Path("sql/seeds/schema.yml"), + relative_path=Path("sql/seeds/schema.yml"), contents="", model_entries=(), seed_entries=(), @@ -689,12 +689,12 @@ def plan_source_reading_project( project_files: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" f" schema: {source_schema}\n" f" table: {source_table}\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", ' 'materialized table);\n\nSELECT * FROM __source("raw_orders")\n' ), diff --git a/tests/integration/src/sqlbuild/compiler/planner/main/test_deferred_migration_origins.py b/tests/integration/src/sqlbuild/compiler/planner/main/test_deferred_migration_origins.py index 8e3ed8f858..218a0b7ecb 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/main/test_deferred_migration_origins.py +++ b/tests/integration/src/sqlbuild/compiler/planner/main/test_deferred_migration_origins.py @@ -25,11 +25,11 @@ '[targets.dev]\nschema = "dev"\n\n' '[targets.prod]\nschema = "prod"\n' ), - "models/order_ledger.sql": ( + "sql/models/order_ledger.sql": ( 'MODEL (description "Test model order_ledger.", materialized table, ' f"migrate_from {_UNLISTED_DATABASE}.prod.order_history);\n\nSELECT 1 AS order_id\n" ), - "models/order_report.sql": ( + "sql/models/order_report.sql": ( 'MODEL (description "Test model order_report.", materialized table);\n\n' 'SELECT order_id FROM __ref("order_ledger")\n' ), diff --git a/tests/integration/src/sqlbuild/compiler/project_assembly/helpers.py b/tests/integration/src/sqlbuild/compiler/project_assembly/helpers.py index 584e112eb7..268c1d96bb 100644 --- a/tests/integration/src/sqlbuild/compiler/project_assembly/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/project_assembly/helpers.py @@ -72,7 +72,7 @@ def generated_assembly_files(*, rng: random.Random, model_count: int) -> dict[st *[f'__ref("orders_{index}")' for index in range(model_count - 1)], ] models: dict[str, str] = { - f"models/orders_{index}.sql": ( + f"sql/models/orders_{index}.sql": ( f'MODEL (\n description "Generated orders model {index}",\n' f"{rng.choice(_HOOKS)}{rng.choice(_AUDITS)});\n\n" f"SELECT 1 AS n FROM {rng.choice(references[: 4 + index])}\n" @@ -86,16 +86,16 @@ def generated_assembly_files(*, rng: random.Random, model_count: int) -> dict[st '[vars]\nenv_name = "prod"\nn = "3"\nflag = "true"\n\n' f"[defaults]\n{rng.choice(_DEFAULTS)}\n[targets.dev]\n{rng.choice(_TARGETS)}" ), - "seeds/lookups.yml": ( + "sql/seeds/lookups.yml": ( "seeds:\n" f" - name: countries\n description: Countries.\n{rng.choice(_SEED_NAMESPACES)}" " columns:\n - name: n\n type: INTEGER\n" f" - name: regions\n description: Regions.\n{rng.choice(_SEED_NAMESPACES)}" " columns:\n - name: n\n type: INTEGER\n" ), - "seeds/countries.csv": "n\n1\n", - "seeds/regions.csv": "n\n2\n", - "sources/raw.yml": ( + "sql/seeds/countries.csv": "n\n1\n", + "sql/seeds/regions.csv": "n\n2\n", + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Raw orders.\n managed: true\n" f" write_strategy: table\n{rng.choice(_SOURCE_NAMESPACES)}" @@ -104,11 +104,11 @@ def generated_assembly_files(*, rng: random.Random, model_count: int) -> dict[st f"{rng.choice(_SOURCE_NAMESPACES)}" " columns:\n - name: n\n type: INTEGER\n" ), - "python/loaders/raw.py": ( + "python/nodes/loaders/raw/loader.py": ( "from sqlbuild.loaders import loader\n\n\n" "@loader\ndef raw_orders(ctx):\n '''Load raw orders.'''\n return [{'n': 1}]\n" ), - "functions/sql/order_numbers.sql": ( + "sql/functions/sql/order_numbers.sql": ( 'FUNCTION (\n description "Order numbers.",\n arguments (p_n INTEGER),\n' " returns table (n INTEGER)\n);\n\n" 'SELECT n FROM __ref("orders_0") WHERE n = p_n\n' @@ -300,9 +300,9 @@ def _edge_seeds(*namespaces: str) -> str: def _edge_seed_files(*namespaces: str) -> dict[str, str]: return { - "seeds/lookups.yml": _edge_seeds(*namespaces), - "models/orders.sql": _EDGE_MODEL, - **{f"seeds/s{index}.csv": "n\n1\n" for index in range(len(namespaces))}, + "sql/seeds/lookups.yml": _edge_seeds(*namespaces), + "sql/models/orders.sql": _EDGE_MODEL, + **{f"sql/seeds/s{index}.csv": "n\n1\n" for index in range(len(namespaces))}, } @@ -312,9 +312,9 @@ def _edge_target(text: str) -> str: def _edge_source_files(ns: str = "") -> dict[str, str]: return { - "sources/raw.yml": _EDGE_SOURCE.format(ns=ns), - "python/loaders/raw.py": _EDGE_LOADER, - "models/orders.sql": _EDGE_MODEL, + "sql/sources/raw.yml": _EDGE_SOURCE.format(ns=ns), + "python/nodes/loaders/raw/loader.py": _EDGE_LOADER, + "sql/models/orders.sql": _EDGE_MODEL, } @@ -439,7 +439,7 @@ def _edge_source_files(ns: str = "") -> dict[str, str]: { "sqlbuild_project.toml": _edge_target('schema = "dev"\n'), **_edge_seed_files(' schema: "${ENV:SQB_EDGE_UNSET}"\n'), - "models/orders.sql": 'MODEL (description "Orders");\n\nSELECT FROM WHERE (\n', + "sql/models/orders.sql": 'MODEL (description "Orders");\n\nSELECT FROM WHERE (\n', }, None, ), @@ -448,8 +448,8 @@ def _edge_source_files(ns: str = "") -> dict[str, str]: { "sqlbuild_project.toml": _edge_target('schema = "${ENV:SQB_EDGE_UNSET}"\n'), **_edge_source_files(), - "seeds/lookups.yml": _edge_seeds(' schema: "${var:nope}"\n'), - "seeds/s0.csv": "n\n1\n", + "sql/seeds/lookups.yml": _edge_seeds(' schema: "${var:nope}"\n'), + "sql/seeds/s0.csv": "n\n1\n", }, None, ), diff --git a/tests/integration/src/sqlbuild/compiler/project_assembly/test_native_project_assembly.py b/tests/integration/src/sqlbuild/compiler/project_assembly/test_native_project_assembly.py index 7b1a47655d..f0a89a1976 100644 --- a/tests/integration/src/sqlbuild/compiler/project_assembly/test_native_project_assembly.py +++ b/tests/integration/src/sqlbuild/compiler/project_assembly/test_native_project_assembly.py @@ -54,8 +54,8 @@ ) _OPT_OUT_HEADER: str = 'MODEL (\n description "Orders",\n sql_analysis false,\n' _SEED_FILES: dict[str, str] = { - "seeds/countries.csv": "n\n1\n", - "models/orders.sql": _ORDERS_MODEL, + "sql/seeds/countries.csv": "n\n1\n", + "sql/models/orders.sql": _ORDERS_MODEL, } @@ -157,7 +157,7 @@ def test_given_projects_python_rejects_when_assembling_natively_then_matches_pyt description="model SQL the parser rejects", files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": 'MODEL (description "Orders");\n\nSELECT FROM WHERE (\n', + "sql/models/orders.sql": 'MODEL (description "Orders");\n\nSELECT FROM WHERE (\n', }, expected_message_fragment=( "the duckdb parser cannot read Syntax error at or near 'WHERE' at line 3, column 13" @@ -167,7 +167,7 @@ def test_given_projects_python_rejects_when_assembling_natively_then_matches_pyt description="hook SQL the parser rejects", files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n description "Orders",\n pre_hooks [inline_sql("SELECT FROM (")],\n' ");\n\nSELECT 1 AS n\n" ), @@ -215,7 +215,7 @@ def test_given_windows_environment_when_assembling_natively_then_env_lookups_mat project_dir=tmp_path, files={ "sqlbuild_project.toml": _PROJECT_TOML, - "seeds/lookups.yml": seed_yml(test_case.seed_schema), + "sql/seeds/lookups.yml": seed_yml(test_case.seed_schema), **_SEED_FILES, }, ) @@ -231,9 +231,9 @@ def test_given_windows_environment_when_assembling_natively_then_env_lookups_mat OptOutTestCase( description="parseable, unparseable and unparseable-hook opt-outs", models={ - "models/parses.sql": f"{_OPT_OUT_HEADER});\n\nSELECT 1 AS n\n", - "models/broken_query.sql": f"{_OPT_OUT_HEADER});\n\nSELECT FROM WHERE (\n", - "models/broken_hook.sql": ( + "sql/models/parses.sql": f"{_OPT_OUT_HEADER});\n\nSELECT 1 AS n\n", + "sql/models/broken_query.sql": f"{_OPT_OUT_HEADER});\n\nSELECT FROM WHERE (\n", + "sql/models/broken_hook.sql": ( f'{_OPT_OUT_HEADER} post_hooks [inline_sql("SELECT FROM (")],\n);\n\n' "SELECT 1 AS n\n" ), @@ -264,7 +264,7 @@ def test_given_sql_analysis_opt_outs_when_attaching_natively_then_python_rejecti description="a T-SQL hook the parser once panicked on", files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (\n description "Orders",\n' ' pre_hooks [inline_sql("SELECT IF(region > 1, re")],\n);\n\nSELECT 1 AS n\n' ), diff --git a/tests/integration/src/sqlbuild/compiler/scopes/helpers.py b/tests/integration/src/sqlbuild/compiler/scopes/helpers.py index 816040d7cf..a03cd837fc 100644 --- a/tests/integration/src/sqlbuild/compiler/scopes/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/scopes/helpers.py @@ -57,31 +57,31 @@ ) SCOPED_PROJECT: dict[str, str] = { "sqlbuild_project.toml": PROJECT_CONFIG, - "sources/raw.yml": RAW_SOURCES, - "macros/python/money.py": 'def cents(value: str) -> str:\n return f"{value} * 100"\n', - "enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", - "models/sales/_sqlbuild/macros/python/labels.py": ( + "sql/sources/raw.yml": RAW_SOURCES, + "sql/macros/python/money.py": 'def cents(value: str) -> str:\n return f"{value} * 100"\n', + "sql/enums/status.sql": "ENUM (name order_status, members [PLACED, SHIPPED]);\n", + "sql/models/sales/_sqlbuild/macros/python/labels.py": ( "def sales_label(value: str) -> str:\n return f\"'sales:' || {value}\"\n" ), - "models/sales/_sqlbuild/constants/limits.sql": "CONSTANT (name sales_cap, value 3);\n", - "models/sales/eu/_macros/python/rates.py": ( + "sql/models/sales/_sqlbuild/constants/limits.sql": "CONSTANT (name sales_cap, value 3);\n", + "sql/models/sales/eu/_macros/python/rates.py": ( 'def eu_rate(value: str) -> str:\n return f"{value} * 2"\n' ), - "models/sales/eu/_enums/region.sql": "ENUM (name eu_region, members [NORTH, SOUTH]);\n", - "models/sales/orders.sql": ( + "sql/models/sales/eu/_enums/region.sql": "ENUM (name eu_region, members [NORTH, SOUTH]);\n", + "sql/models/sales/orders.sql": ( 'MODEL (\n description "Orders",\n enums (\n _state [OPEN, CLOSED],\n ),\n);\n\n' "SELECT\n order_id,\n @py.sales_label('1') AS label,\n" ' @const("sales_cap") AS cap,\n @enum("_state").OPEN AS state,\n' ' @enum("order_status").PLACED AS status\nFROM __source("raw_orders")\n' ), - "models/sales/eu/eu_orders.sql": ( + "sql/models/sales/eu/eu_orders.sql": ( 'MODEL (\n description "EU orders",\n);\n\n' "SELECT\n order_id,\n @py.eu_rate('2') AS rate,\n" " @enum(\"eu_region\").NORTH AS region,\n @py.cents('3') AS cents,\n" " @py.sales_label('4') AS label,\n @const(\"sales_cap\") AS cap\n" 'FROM __ref("orders")\n' ), - "models/other/customers.sql": ( + "sql/models/other/customers.sql": ( 'MODEL (\n description "Customers",\n);\n\n' "SELECT 1 AS customer_id, @enum(\"order_status\").SHIPPED AS status, @py.cents('5') AS " "cents\n" @@ -131,14 +131,14 @@ class ScopeOutcome: "__expected__orders (SELECT 1)", ) _FOLDERS: tuple[str, ...] = ( - "models/sales", - "models/sales/eu", - "models/sales/eu/north", - "models/other", - "models/other/archive", + "sql/models/sales", + "sql/models/sales/eu", + "sql/models/sales/eu/north", + "sql/models/other", + "sql/models/other/archive", ) _PLACEMENTS: tuple[str, ...] = ( - "{kind}s/f{index}", + "sql/{kind}s/f{index}", "{folder}/{kind}s/f{index}", "{folder}/_sqlbuild/{kind}s/f{index}", "{folder}/_{kind}s/f{index}", @@ -161,7 +161,7 @@ def generated_scope_files(*, rng: random.Random) -> dict[str, str]: files: dict[str, str] = { "sqlbuild_project.toml": PROJECT_CONFIG, - "sources/raw.yml": RAW_SOURCES, + "sql/sources/raw.yml": RAW_SOURCES, } models: list[str] = [f"model_{index}" for index in range(rng.randint(1, 6))] for index, model in enumerate(models): @@ -213,7 +213,7 @@ def _macro_writer(*, path: str, index: int, variant: int) -> tuple[str, str, tup name: str = f"macro_{index}" root, stem = path.rsplit("/", 1) return ( - f"{root}/python/{stem}.py", + f"{root}/python/nodes/{stem}.py", f"def {name}(value: str) -> str:\n return value\n", (name,), ) diff --git a/tests/integration/src/sqlbuild/compiler/scopes/test_native_scope_parity.py b/tests/integration/src/sqlbuild/compiler/scopes/test_native_scope_parity.py index ac321e4907..1688518d20 100644 --- a/tests/integration/src/sqlbuild/compiler/scopes/test_native_scope_parity.py +++ b/tests/integration/src/sqlbuild/compiler/scopes/test_native_scope_parity.py @@ -43,7 +43,7 @@ description="a global enum duplicating a scoped enum fails with Python's diagnostics", files={ **SCOPED_PROJECT, - "enums/region.sql": "ENUM (name eu_region, members [EAST]);\n", + "sql/enums/region.sql": "ENUM (name eu_region, members [EAST]);\n", }, expected_error="Duplicate declaration 'enum:eu_region'", ), @@ -102,7 +102,7 @@ description="non-ASCII folders keep Python's repr order of path keys", files={ **SCOPED_PROJECT, - "models/sales/r\u00e9gion/regional.sql": ( + "sql/models/sales/r\u00e9gion/regional.sql": ( 'MODEL (\n description "Regional",\n);\n\n' 'SELECT order_id, @const("sales_cap") AS cap\nFROM __ref("orders")\n' ), @@ -113,7 +113,7 @@ description="a test granted a deeper macro's folder through a macro test", files={ **SCOPED_PROJECT, - "models/sales/eu/_macros/python/rates.py": ( + "sql/models/sales/eu/_macros/python/rates.py": ( 'def eu_rate(value: str) -> str:\n return f"{value} * 2"\n\n\n' "def eu_label(value: str) -> str:\n return eu_rate(value)\n" ), diff --git a/tests/integration/src/sqlbuild/compiler/semantic_checks/helpers.py b/tests/integration/src/sqlbuild/compiler/semantic_checks/helpers.py index b27312b62d..ed6f1739d3 100644 --- a/tests/integration/src/sqlbuild/compiler/semantic_checks/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/semantic_checks/helpers.py @@ -168,7 +168,7 @@ def generated_semantic_files( 'name = "orders_semantics"\nadapter = "duckdb"\n\n[connection]\n' f'database = "orders.duckdb"\n{settings}' ), - "sources/raw.yml": _SOURCES, + "sql/sources/raw.yml": _SOURCES, } relations: list[tuple[str, tuple[str, ...]]] = list(_RELATIONS.items()) for index in range(model_count): @@ -176,7 +176,7 @@ def generated_semantic_files( sql, outputs = _TEMPLATES[index % len(_TEMPLATES)](rng, relation, columns) name: str = f"orders_model_{index}" opt_out: str = _OPT_OUTS[rng.random() < _OPT_OUT_SHARE] - files[f"models/layer_{index % 3}/{name}.sql"] = ( + files[f"sql/models/layer_{index % 3}/{name}.sql"] = ( f'MODEL (description "Generated orders model {index}"{opt_out});\n\n{sql}\n' ) relations.append((f'__ref("{name}")', outputs)) @@ -226,7 +226,7 @@ def one_model_completion( files: dict[str, str] = generated_semantic_files( rng=random.Random(0), model_count=0, require_analysis=True ) - files["models/probe.sql"] = f'MODEL (description "Probe");\n\n{sql}\n' + files["sql/models/probe.sql"] = f'MODEL (description "Probe");\n\n{sql}\n' native: CompiledProjectView = completed_natively( captured_under_dialect(project_dir=project_dir, files=files, dialect=dialect) ) @@ -245,7 +245,7 @@ def model_findings( rng=random.Random(0), model_count=0, require_analysis=True ) for name, sql in models.items(): - files[f"models/{name}.sql"] = f'MODEL (description "{name}");\n\n{sql}\n' + files[f"sql/models/{name}.sql"] = f'MODEL (description "{name}");\n\n{sql}\n' native: CompiledProjectView = completed_natively( captured_under_dialect(project_dir=project_dir, files=files, dialect=dialect) ) @@ -547,11 +547,11 @@ def generated_metadata_files(*, rng: random.Random, model_count: int) -> dict[st 'name = "orders_metadata"\nadapter = "duckdb"\n\n[connection]\n' 'database = "orders.duckdb"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Orders feed.\n" f"{_SOURCE_SQL}{columns}{_LOADED_SOURCE.format(cursor=rng.choice(_LOADED_CURSORS))}" ), - "python/loaders/raw_events.py": _LOADER, + "python/nodes/loaders/raw_events/loader.py": _LOADER, "tests/unit/test_orders_model_0.sql": ( "TEST();\n\nWITH\n__source__raw_orders AS (\n" " SELECT 1 AS order_id, 10 AS customer_id, CAST(5 AS DOUBLE) AS amount," @@ -562,12 +562,12 @@ def generated_metadata_files(*, rng: random.Random, model_count: int) -> dict[st ), } for name in _FUNCTIONS: - files[f"functions/sql/{name}.sql"] = _function_file(name) + files[f"sql/functions/sql/{name}.sql"] = _function_file(name) relations: list[_Relation] = [('__source("raw_orders")', "", _SOURCE_COLUMNS)] for index in range(model_count): relation: _Relation = rng.choice(relations) name: str = f"orders_model_{index}" - files[f"models/layer_{index % 3}/{name}.sql"] = ( + files[f"sql/models/layer_{index % 3}/{name}.sql"] = ( f'MODEL (\n description "Generated orders model {index}",\n' f"{_header(rng, index, relation)});\n\n{_query(rng, relation)}\n" ) diff --git a/tests/integration/src/sqlbuild/compiler/sql_test_glue/helpers.py b/tests/integration/src/sqlbuild/compiler/sql_test_glue/helpers.py index 1ededa33e6..58882217e7 100644 --- a/tests/integration/src/sqlbuild/compiler/sql_test_glue/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/sql_test_glue/helpers.py @@ -205,16 +205,16 @@ def generated_sql_test_files( def _project_files() -> dict[str, str]: files: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_TOML, - "sources/raw.yml": _SOURCES, - "seeds/regions.yml": _SEEDS, - "seeds/regions.csv": "region,label\neast,East\n", - "macros/python/amounts.py": _MACROS, - "functions/sql/udf__is_big.sql": _UDF, - "functions/sql/table_fn__customer_orders.sql": _TABLE_FUNCTION, - "models/daily_orders.sql": _DAILY_ORDERS, + "sql/sources/raw.yml": _SOURCES, + "sql/seeds/regions.yml": _SEEDS, + "sql/seeds/regions.csv": "region,label\neast,East\n", + "sql/macros/python/amounts.py": _MACROS, + "sql/functions/sql/udf__is_big.sql": _UDF, + "sql/functions/sql/table_fn__customer_orders.sql": _TABLE_FUNCTION, + "sql/models/daily_orders.sql": _DAILY_ORDERS, } files.update( - (f"models/{name}.sql", f'MODEL (description "Model {name}.");\n\n{sql}\n') + (f"sql/models/{name}.sql", f'MODEL (description "Model {name}.");\n\n{sql}\n') for name, sql in _BASE_MODELS.items() ) return files @@ -262,7 +262,7 @@ def edge_sql_test_files(*, extra_files: dict[str, str]) -> dict[str, str]: '"5E-1000027"', '"9.99999999999999999999999999995E+999999"' ) EDGE_UNICODE_MACRO_SCOPE: dict[str, str] = { - "models/weird_amounts.sql": ( + "sql/models/weird_amounts.sql": ( 'MODEL (description "Model weird_amounts.");\n\n' 'WITH o AS (SELECT amount FROM __source("raw_orders"))\nSELECT amount@\u00f6re FROM o\n' ), diff --git a/tests/integration/src/sqlbuild/executor/build/concurrent/test_concurrent_build.py b/tests/integration/src/sqlbuild/executor/build/concurrent/test_concurrent_build.py index 8d1810466c..73a9224dc8 100644 --- a/tests/integration/src/sqlbuild/executor/build/concurrent/test_concurrent_build.py +++ b/tests/integration/src/sqlbuild/executor/build/concurrent/test_concurrent_build.py @@ -19,6 +19,7 @@ run_concurrent_build, verify_concurrent_warehouse_state, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files _PROJECT_YML: str = ( 'name = "demo"\n' @@ -38,10 +39,10 @@ max_concurrency=2, project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/alpha.sql": ( + "sql/models/alpha.sql": ( "MODEL (description 'Test model alpha.', materialized table);\n\nSELECT 1 AS id, 'alpha' AS name" ), - "models/beta.sql": ( + "sql/models/beta.sql": ( "MODEL (description 'Test model beta.', materialized table);\n\nSELECT 2 AS id, 'beta' AS name" ), }, @@ -63,18 +64,18 @@ max_concurrency=3, project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/staging/stg_raw.sql": ( + "sql/models/staging/stg_raw.sql": ( "MODEL (description 'Test model stg_raw.', materialized view);\n\nSELECT 10 AS id, 'row' AS val" ), - "models/branch_a.sql": ( + "sql/models/branch_a.sql": ( "MODEL (description 'Test model branch_a.', materialized table);\n\n" "SELECT id, val || '_a' AS val FROM __ref(\"stg_raw\")" ), - "models/branch_b.sql": ( + "sql/models/branch_b.sql": ( "MODEL (description 'Test model branch_b.', materialized table);\n\n" "SELECT id, val || '_b' AS val FROM __ref(\"stg_raw\")" ), - "models/merged.sql": ( + "sql/models/merged.sql": ( "MODEL (description 'Test model merged.', materialized table);\n\n" "SELECT a.id, a.val AS a_val, b.val AS b_val " 'FROM __ref("branch_a") a ' @@ -95,13 +96,13 @@ max_concurrency=2, project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/layer_1.sql": ( + "sql/models/layer_1.sql": ( "MODEL (description 'Test model layer_1.', materialized table);\n\nSELECT 100 AS val" ), - "models/layer_2.sql": ( + "sql/models/layer_2.sql": ( 'MODEL (description "Test model layer_2.", materialized table);\n\nSELECT val * 2 AS val FROM __ref("layer_1")' ), - "models/layer_3.sql": ( + "sql/models/layer_3.sql": ( 'MODEL (description "Test model layer_3.", materialized table);\n\nSELECT val + 1 AS val FROM __ref("layer_2")' ), }, @@ -163,7 +164,7 @@ def test_given_concurrent_provider_backed_loaders_when_executing_then_share_prov tmp_path, { "sqlbuild_project.toml": _PROJECT_YML, - "providers/concurrent_marker.py": dedent( + "python/providers/concurrent_marker.py": dedent( f""" from pathlib import Path from time import sleep @@ -192,9 +193,11 @@ def mark(self, label): """ ).strip() + "\n", - "python/loaders/events.py": dedent( - """ - from providers.concurrent_marker import ConcurrentMarkerProvider + **node_module_files( + "python/nodes/loaders/events.py", + dedent( + """ + from python.providers.concurrent_marker import ConcurrentMarkerProvider from sqlbuild.loaders import loader @@ -211,9 +214,10 @@ def raw_beta(ctx, concurrent_marker_provider: ConcurrentMarkerProvider): concurrent_marker_provider.mark("beta") return [{"event_id": 2}] """ - ).strip() - + "\n", - "sources/raw.yml": dedent( + ).strip() + + "\n", + ), + "sql/sources/raw.yml": dedent( """ sources: - name: raw_alpha @@ -233,10 +237,10 @@ def raw_beta(ctx, concurrent_marker_provider: ConcurrentMarkerProvider): """ ).strip() + "\n", - "models/fact_alpha.sql": ( + "sql/models/fact_alpha.sql": ( 'MODEL (description "Test model fact_alpha.", materialized table);\n\nSELECT * FROM __source("raw_alpha")\n' ), - "models/fact_beta.sql": ( + "sql/models/fact_beta.sql": ( 'MODEL (description "Test model fact_beta.", materialized table);\n\nSELECT * FROM __source("raw_beta")\n' ), }, @@ -275,10 +279,10 @@ def raw_beta(ctx, concurrent_marker_provider: ConcurrentMarkerProvider): max_concurrency=2, project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/broken.sql": ( + "sql/models/broken.sql": ( "MODEL (description 'Test model broken.', materialized table);\n\nSELECT * FROM nonexistent_table" ), - "models/healthy.sql": ( + "sql/models/healthy.sql": ( "MODEL (description 'Test model healthy.', materialized table);\n\nSELECT 42 AS val" ), }, @@ -299,13 +303,13 @@ def raw_beta(ctx, concurrent_marker_provider: ConcurrentMarkerProvider): max_concurrency=2, project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/broken.sql": ( + "sql/models/broken.sql": ( "MODEL (description 'Test model broken.', materialized table);\n\nSELECT * FROM nonexistent_table" ), - "models/downstream.sql": ( + "sql/models/downstream.sql": ( 'MODEL (description "Test model downstream.", materialized table);\n\nSELECT 1 AS id FROM __ref("broken")' ), - "models/independent.sql": ( + "sql/models/independent.sql": ( "MODEL (description 'Test model independent.', materialized table);\n\nSELECT 99 AS val" ), }, @@ -329,10 +333,10 @@ def raw_beta(ctx, concurrent_marker_provider: ConcurrentMarkerProvider): max_concurrency=1, project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/aaa_broken.sql": ( + "sql/models/aaa_broken.sql": ( "MODEL (description 'Test model aaa_broken.', materialized table);\n\nSELECT * FROM nonexistent_table" ), - "models/zzz_independent.sql": ( + "sql/models/zzz_independent.sql": ( "MODEL (description 'Test model zzz_independent.', materialized table);\n\nSELECT 1 AS id" ), }, diff --git a/tests/integration/src/sqlbuild/executor/build/concurrent/test_microbatch_concurrency.py b/tests/integration/src/sqlbuild/executor/build/concurrent/test_microbatch_concurrency.py index ed4d0986b8..831f475e7e 100644 --- a/tests/integration/src/sqlbuild/executor/build/concurrent/test_microbatch_concurrency.py +++ b/tests/integration/src/sqlbuild/executor/build/concurrent/test_microbatch_concurrency.py @@ -114,7 +114,7 @@ def test_given_three_batch_ceiling_when_incremental_runs_then_batches_overlap( """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -124,7 +124,7 @@ def test_given_three_batch_ceiling_when_incremental_runs_then_batches_overlap( """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( """ MODEL (description "Test model orders.", materialized incremental, @@ -149,7 +149,7 @@ def test_given_three_batch_ceiling_when_incremental_runs_then_batches_overlap( """ ).strip() + "\n", - "models/shipments.sql": dedent( + "sql/models/shipments.sql": dedent( """ MODEL (description "Test model shipments.", materialized incremental, diff --git a/tests/integration/src/sqlbuild/executor/build/concurrent/test_ordering_invariant.py b/tests/integration/src/sqlbuild/executor/build/concurrent/test_ordering_invariant.py index a29f568635..b0d1a2a407 100644 --- a/tests/integration/src/sqlbuild/executor/build/concurrent/test_ordering_invariant.py +++ b/tests/integration/src/sqlbuild/executor/build/concurrent/test_ordering_invariant.py @@ -55,19 +55,19 @@ max_concurrency=3, project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/staging/stg_a.sql": ( + "sql/models/staging/stg_a.sql": ( "MODEL (description 'Test model stg_a.', materialized view);\n\nSELECT 1 AS id" ), - "models/staging/stg_b.sql": ( + "sql/models/staging/stg_b.sql": ( "MODEL (description 'Test model stg_b.', materialized view);\n\nSELECT 2 AS id" ), - "models/mid_a.sql": ( + "sql/models/mid_a.sql": ( 'MODEL (description "Test model mid_a.", materialized table);\n\nSELECT id FROM __ref("stg_a")' ), - "models/mid_b.sql": ( + "sql/models/mid_b.sql": ( 'MODEL (description "Test model mid_b.", materialized table);\n\nSELECT id FROM __ref("stg_b")' ), - "models/final.sql": ( + "sql/models/final.sql": ( "MODEL (description 'Test model final.', materialized table);\n\n" "SELECT a.id AS a_id, b.id AS b_id " 'FROM __ref("mid_a") a ' diff --git a/tests/integration/src/sqlbuild/executor/build/concurrent/test_stateless_sequential_microbatch.py b/tests/integration/src/sqlbuild/executor/build/concurrent/test_stateless_sequential_microbatch.py index 83944e2890..a5fae0c3be 100644 --- a/tests/integration/src/sqlbuild/executor/build/concurrent/test_stateless_sequential_microbatch.py +++ b/tests/integration/src/sqlbuild/executor/build/concurrent/test_stateless_sequential_microbatch.py @@ -74,7 +74,7 @@ def test_given_sequential_microbatch_when_repeated_then_uses_only_physical_water """ ).strip() + "\n", - "sources/raw.yml": dedent( + "sql/sources/raw.yml": dedent( """ sources: - name: raw_events @@ -84,7 +84,7 @@ def test_given_sequential_microbatch_when_repeated_then_uses_only_physical_water """ ).strip() + "\n", - "models/orders.sql": dedent( + "sql/models/orders.sql": dedent( f""" MODEL (description "Test model orders.", materialized incremental, diff --git a/tests/integration/src/sqlbuild/executor/build/custom/helpers.py b/tests/integration/src/sqlbuild/executor/build/custom/helpers.py index cdcdd0b9b0..aa2f9c2119 100644 --- a/tests/integration/src/sqlbuild/executor/build/custom/helpers.py +++ b/tests/integration/src/sqlbuild/executor/build/custom/helpers.py @@ -65,7 +65,7 @@ def build_custom_plan_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.CUSTOM, action=PlanAction.CUSTOM, reason=reason, diff --git a/tests/integration/src/sqlbuild/executor/build/custom/test_advanced_custom_materialization.py b/tests/integration/src/sqlbuild/executor/build/custom/test_advanced_custom_materialization.py index 0eab5b6f8d..76c49e962d 100644 --- a/tests/integration/src/sqlbuild/executor/build/custom/test_advanced_custom_materialization.py +++ b/tests/integration/src/sqlbuild/executor/build/custom/test_advanced_custom_materialization.py @@ -299,10 +299,10 @@ def test_given_custom_materialization_when_audit_finds_rows_in_staging_then_bloc description="custom materialization dispatched through scheduler alongside regular table", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/regular.sql": ( + "sql/models/regular.sql": ( "MODEL (description 'Test model regular.', materialized table);\n\nSELECT 1 AS id, 'regular' AS name" ), - "models/custom_model.sql": ( + "sql/models/custom_model.sql": ( "MODEL (description 'Test model custom_model.', materialized test_custom);\n\nSELECT 2 AS id, 'custom' AS name" ), }, @@ -320,10 +320,10 @@ def test_given_custom_materialization_when_audit_finds_rows_in_staging_then_bloc description="custom materialization downstream of regular table receives correct data", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/upstream.sql": ( + "sql/models/upstream.sql": ( "MODEL (description 'Test model upstream.', materialized table);\n\nSELECT 10 AS id, 'upstream' AS origin" ), - "models/downstream_custom.sql": ( + "sql/models/downstream_custom.sql": ( 'MODEL (description "Test model downstream_custom.", materialized test_custom);\n\nSELECT id, origin FROM __ref("upstream")' ), }, @@ -345,7 +345,7 @@ def test_given_build_with_custom_materialization_when_scheduled_then_routes_corr ) -> None: adapter: DuckDbAdapter = DuckDbAdapter() project_dir: Path = tmp_path / "project" - project_dir.mkdir() + project_dir.mkdir(parents=True) db_path: Path = tmp_path / "test.duckdb" relative_path: str @@ -355,9 +355,9 @@ def test_given_build_with_custom_materialization_when_scheduled_then_routes_corr file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(contents, encoding="utf-8") - # Also create the materializations/ directory with test_custom.py - mat_dir: Path = project_dir / "materializations" - mat_dir.mkdir() + # Also create the python/materializations/ directory with test_custom.py + mat_dir: Path = project_dir / "python" / "materializations" + mat_dir.mkdir(parents=True) (mat_dir / "test_custom.py").write_text( "def materialize(ctx):\n" " ctx.adapter.create_table_as(\n" diff --git a/tests/integration/src/sqlbuild/executor/build/custom/test_custom_materialization.py b/tests/integration/src/sqlbuild/executor/build/custom/test_custom_materialization.py index 7879a17227..776a953ecb 100644 --- a/tests/integration/src/sqlbuild/executor/build/custom/test_custom_materialization.py +++ b/tests/integration/src/sqlbuild/executor/build/custom/test_custom_materialization.py @@ -213,7 +213,7 @@ def test_given_custom_materialization_when_failing_then_reports_failure( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/custom.py"), + relative_path=Path("sql/hooks/python/custom.py"), name="insert_hook_log", function=insert_custom_hook_log, ), @@ -250,7 +250,7 @@ def test_given_custom_materialization_when_failing_then_reports_failure( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/custom.py"), + relative_path=Path("sql/hooks/python/custom.py"), name="fail_hook", function=fail_custom_hook, ), @@ -267,7 +267,7 @@ def test_given_custom_materialization_when_failing_then_reports_failure( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/custom.py"), + relative_path=Path("sql/hooks/python/custom.py"), name="fail_hook", function=fail_custom_hook, ), diff --git a/tests/integration/src/sqlbuild/executor/build/helpers.py b/tests/integration/src/sqlbuild/executor/build/helpers.py index 10c2bcbc94..eb4c16a35a 100644 --- a/tests/integration/src/sqlbuild/executor/build/helpers.py +++ b/tests/integration/src/sqlbuild/executor/build/helpers.py @@ -221,7 +221,7 @@ def capped_dependency_warehouse_files(*, project_dir: Path) -> dict[str, str]: 'name = "capped_dependency"\nadapter = "duckdb"\n\n' f"[connection]\ndatabase = {json.dumps(str(database_path))}\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_events\n description: Test source raw_events.\n" " schema: main\n table: raw_events\n" ), @@ -237,13 +237,13 @@ def compile_capped_microbatch_intermediary_project( project_dir=project_dir, project_files={ **capped_dependency_warehouse_files(project_dir=project_dir), - "models/capped_events.sql": capped_dependency_producer_sql( + "sql/models/capped_events.sql": capped_dependency_producer_sql( action=MicrobatchLimitAction.CAP_FROM_END ), - "models/intermediate_events.sql": capped_microbatch_intermediary_sql( + "sql/models/intermediate_events.sql": capped_microbatch_intermediary_sql( input_role=input_role ), - "models/downstream_events.sql": capped_dependency_consumer_sql( + "sql/models/downstream_events.sql": capped_dependency_consumer_sql( watermark_mode="all", input_name="intermediate_events" ), }, @@ -267,12 +267,12 @@ def compile_capped_dependency_project( project_files: dict[str, str] = { **capped_dependency_warehouse_files(project_dir=project_dir), - "models/capped_events.sql": capped_dependency_producer_sql(action=action), - "models/downstream_events.sql": consumer_sql, + "sql/models/capped_events.sql": capped_dependency_producer_sql(action=action), + "sql/models/downstream_events.sql": consumer_sql, } upstream_name: str = "capped_events" for intermediary_name in intermediary_names: - project_files[f"models/{intermediary_name}.sql"] = dependency_view_sql( + project_files[f"sql/models/{intermediary_name}.sql"] = dependency_view_sql( upstream_name=upstream_name ) upstream_name = intermediary_name diff --git a/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/helpers.py b/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/helpers.py index 5a402a41aa..3be1f22b3f 100644 --- a/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/helpers.py +++ b/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/helpers.py @@ -563,7 +563,7 @@ def _show_schema_identity(match: re.Match[str]) -> _Identity: "[path_defaults.marts]\n" 'schema = "marts"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " database: analytics\n" @@ -577,15 +577,15 @@ def _show_schema_identity(match: re.Match[str]) -> _Identity: " - name: amount\n" " type: NUMBER(10, 2)\n" ), - "models/marts/orders_table.sql": ( + "sql/models/marts/orders_table.sql": ( "MODEL (description 'Test model orders_table.',\n materialized table,\n);\n\n" 'SELECT order_id, ordered_at, amount FROM __source("raw_orders")\n' ), - "models/marts/orders_view.sql": ( + "sql/models/marts/orders_view.sql": ( 'MODEL (description "Test model orders_view.",' '\n materialized view,\n);\n\nSELECT order_id, amount FROM __ref("orders_table")\n' ), - "models/marts/orders_merge.sql": ( + "sql/models/marts/orders_merge.sql": ( "MODEL (description 'Test model orders_merge.',\n" " materialized incremental,\n" " incremental_strategy merge,\n" @@ -598,7 +598,7 @@ def _show_schema_identity(match: re.Match[str]) -> _Identity: ");\n\n" 'SELECT order_id, ordered_at, amount FROM __source("raw_orders")\n' ), - "models/marts/orders_daily.sql": ( + "sql/models/marts/orders_daily.sql": ( "MODEL (description 'Test model orders_daily.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -627,11 +627,11 @@ def write_bundles_project(*, project_dir: Path, select: str) -> None: 'account = "example"\nuser = "example"\ndatabase = "analytics"\nschema = "marts"\n\n' '[defaults]\ndatabase = "analytics"\nschema = "marts"\nmaterialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_bundles\n description: Test source raw_bundles.\n" " database: analytics\n schema: raw\n table: bundles\n" ), - "models/bundle_report.sql": ( + "sql/models/bundle_report.sql": ( "MODEL (description 'Test model bundle_report.');\n" f'SELECT {select} FROM __source("raw_bundles")\n' ), @@ -774,7 +774,7 @@ def write_model_copies( ) index: int for index in range(count): - _ = (project_dir / "models" / "marts" / f"order_copy_{index}.sql").write_text( + _ = (project_dir / "sql" / "models" / "marts" / f"order_copy_{index}.sql").write_text( f"MODEL ({header_options}description 'Copy {index} of the orders.', " "materialized table);\n\n" 'SELECT order_id, ordered_at, amount FROM __ref("orders_table")\n', @@ -824,20 +824,20 @@ def quoted_configured_column_files( 'database = "analytics"\nschema = "marts"\n\n' '[defaults]\ndatabase = "analytics"\nschema = "marts"\nmaterialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_listings\n description: Partner listings in quoted camelCase.\n" " database: analytics\n schema: raw\n table: listings\n" " - name: raw_listing_events\n description: Partner listing events.\n" " database: analytics\n schema: raw\n table: listing_events\n" ), - "models/listing_history.sql": ( + "sql/models/listing_history.sql": ( "MODEL (\n description 'Listing price history.',\n materialized snapshot,\n" f" unique_key [{unique_key}],\n snapshot_strategy timestamp,\n" f" updated_at {updated_at},\n);\n\n" 'SELECT "listingId", "unitPrice", "updatedAt" FROM __source("raw_listings")\n' ), - "models/listing_activity.sql": ( + "sql/models/listing_activity.sql": ( "MODEL (\n description 'Listing events by hour.',\n materialized incremental,\n" " incremental_strategy delete_insert,\n incremental_mode microbatch,\n" " microbatch_strategy watermark,\n cursor_watermark_mode all,\n" @@ -876,14 +876,14 @@ def write_shifts_project(*, project_dir: Path, declared_type: str) -> None: files: dict[str, str] = { "sqlbuild_project.toml": _SHIFTS_PROJECT, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_shifts\n description: Shift rows.\n" " database: analytics\n schema: raw\n table: shifts\n" " contract: enforced\n columns:\n" " - name: shift_id\n type: NUMBER(38,0)\n" f" - name: starts_at\n type: {declared_type}\n" ), - "models/shift_report.sql": _SHIFTS_MODEL, + "sql/models/shift_report.sql": _SHIFTS_MODEL, } relative: str content: str diff --git a/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/test_quoted_mixed_case_columns.py b/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/test_quoted_mixed_case_columns.py index 961f7c6652..3541b2e8d9 100644 --- a/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/test_quoted_mixed_case_columns.py +++ b/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/test_quoted_mixed_case_columns.py @@ -28,7 +28,7 @@ 'database = "analytics"\nschema = "marts"\n\n' '[defaults]\ndatabase = "analytics"\nschema = "marts"\nmaterialized = "table"\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_listings\n description: Partner listings in quoted camelCase.\n" " database: analytics\n schema: raw\n table: listings\n" @@ -36,12 +36,12 @@ " - name: '\"listingId\"'\n type: VARCHAR\n" " - name: '\"unitPriceMinor\"'\n type: NUMBER(38,0)\n" ), - "models/stg_listings.sql": ( + "sql/models/stg_listings.sql": ( "MODEL (description 'Listings renamed to snake case.');\n\n" 'SELECT s."listingId" AS listing_id, s."unitPriceMinor" AS unit_price_minor\n' 'FROM __source("raw_listings") AS s\n' ), - "models/listing_export.sql": ( + "sql/models/listing_export.sql": ( "MODEL (\n description 'Listings in the partner feed format.',\n" ' columns ("listingId" (nullable false, audits [not_null]),),\n);\n\n' 'WITH final AS (\n SELECT l.listing_id AS "listingId"\n' @@ -115,7 +115,7 @@ def test_given_enforced_contract_on_quoted_alias_when_building_then_runtime_cont ) -> None: files: dict[str, str] = { **_PROJECT_FILES, - "models/listing_export.sql": ( + "sql/models/listing_export.sql": ( "MODEL (\n description 'Listings in the partner feed format.',\n" " contract enforced,\n" f" columns ({test_case.declared_name} (type VARCHAR),),\n);\n\n" diff --git a/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/test_statement_overhead.py b/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/test_statement_overhead.py index c517180c94..05d1cc35a7 100644 --- a/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/test_statement_overhead.py +++ b/tests/integration/src/sqlbuild/executor/build/snowflake_metadata/test_statement_overhead.py @@ -64,7 +64,7 @@ def test_given_materialization_switch_when_building_then_each_kind_replaces_the_ ) -> None: write_orders_project(project_dir=tmp_path) warehouse: SimulatedSnowflakeWarehouse = orders_warehouse() - model: Path = tmp_path / "models" / "marts" / "orders_view.sql" + model: Path = tmp_path / "sql" / "models" / "marts" / "orders_view.sql" source: str = model.read_text(encoding="utf-8") table_types: list[tuple[str, ...]] = [] builds: list[OfflineBuild] = [] @@ -184,7 +184,7 @@ def test_given_external_change_before_promotion_when_building_then_promotion_rea for _ in range(test_case.builds_before) ) warehouse.external_changes.append((re.compile(test_case.before_statement), test_case.change)) - model: Path = tmp_path / "models" / "marts" / "orders_table.sql" + model: Path = tmp_path / "sql" / "models" / "marts" / "orders_table.sql" _ = model.write_text( model.read_text(encoding="utf-8").replace("SELECT ", "SELECT 1 AS revision, ", 1), encoding="utf-8", diff --git a/tests/integration/src/sqlbuild/executor/build/test_build_execution.py b/tests/integration/src/sqlbuild/executor/build/test_build_execution.py index 62c6dbaa2f..d3ae50a483 100644 --- a/tests/integration/src/sqlbuild/executor/build/test_build_execution.py +++ b/tests/integration/src/sqlbuild/executor/build/test_build_execution.py @@ -103,7 +103,7 @@ description="cursor delete_insert with a unique_key replaces a row whose cursor moved", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Latest version of each order.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -114,7 +114,7 @@ ");\n\n" 'SELECT id, updated_at FROM __source("raw_orders")' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), @@ -144,7 +144,7 @@ description="delete_insert by replace_key replaces every row of a delta's key values", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/forecasts.sql": ( + "sql/models/forecasts.sql": ( "MODEL (description 'Forecast lines, several per version.',\n" " materialized incremental,\n" " incremental_strategy delete_insert,\n" @@ -152,7 +152,7 @@ ");\n\n" 'SELECT forecast_version, line_no, amount FROM __source("raw_forecasts")' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_forecasts\n description: Test source raw_forecasts.\n" " schema: main\n table: raw_forecasts\n" ), @@ -186,14 +186,14 @@ description="sql udf builds before dependent model", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "functions/sql/is_positive_int.sql": ( + "sql/functions/sql/is_positive_int.sql": ( "FUNCTION (description 'Test function is_positive_int.',\n" " arguments (a_string VARCHAR),\n" " returns BOOLEAN\n" ");\n\n" "regexp_matches(a_string, '^[0-9]+$')" ), - "models/validated_orders.sql": ( + "sql/models/validated_orders.sql": ( "MODEL (description 'Test model validated_orders.', materialized table);\n\n" "WITH input(value) AS (VALUES ('123'), ('abc'))\n" 'SELECT input.value, __udf("is_positive_int")(input.value) AS is_positive ' @@ -219,7 +219,7 @@ description="python udf builds before dependent model", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "functions/python/is_positive_int.py": ( + "sql/functions/python/is_positive_int.py": ( "from sqlbuild.functions import udf\n\n" "@udf(\n" " arguments={'a_string': 'VARCHAR'},\n" @@ -229,7 +229,7 @@ "def main(a_string):\n" " '''Test function main.'''\n return bool(a_string and a_string.isdigit())\n" ), - "models/validated_orders.sql": ( + "sql/models/validated_orders.sql": ( "MODEL (description 'Test model validated_orders.', materialized table);\n\n" "WITH input(value) AS (VALUES ('123'), ('abc'))\n" 'SELECT input.value, __udf("is_positive_int")(input.value) AS is_positive ' @@ -258,7 +258,7 @@ "[targets.dev]\n" 'schema = "dev"\n' ), - "functions/python/is_positive_int.py": ( + "sql/functions/python/is_positive_int.py": ( "from sqlbuild.functions import udf\n\n" "@udf(\n" " arguments={'a_string': 'VARCHAR'},\n" @@ -268,7 +268,7 @@ "def main(a_string):\n" " '''Test function main.'''\n return bool(a_string and a_string.isdigit())\n" ), - "models/validated_orders.sql": ( + "sql/models/validated_orders.sql": ( "MODEL (description 'Test model validated_orders.', materialized table);\n\n" "WITH input(value) AS (VALUES ('123'), ('abc'))\n" 'SELECT input.value, __udf("is_positive_int")(input.value) AS is_positive ' @@ -295,8 +295,8 @@ description="two independent models both succeed", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id, 'alice' AS name", - "models/payments.sql": ( + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id, 'alice' AS name", + "sql/models/payments.sql": ( "MODEL (description 'Test model payments.', materialized table);\n\nSELECT 10 AS payment_id, 500 AS amount" ), }, @@ -315,10 +315,10 @@ description="dependent models execute in topo order and downstream reads upstream", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT 42 AS id, 'bob' AS name" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\n" 'SELECT id, name FROM __ref("stg_orders") WHERE id = 42' ), @@ -347,7 +347,7 @@ 'schema = "dev_schema"\n' ), "sqlbuild_local.toml": 'target = "dev"\n', - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id, 'alice' AS name", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id, 'alice' AS name", }, expected_status=BuildStatus.SUCCESS, expected_success_count=1, @@ -358,8 +358,8 @@ description="run_audits false skips all audits but tables still built", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT 1 AS id", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT 1 AS id", + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, run_audits=False, expected_status=BuildStatus.SUCCESS, @@ -371,8 +371,8 @@ description="passing model audit does not block and table is promoted", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT 1 AS id", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT 1 AS id", + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, expected_status=BuildStatus.SUCCESS, expected_success_count=1, @@ -383,7 +383,7 @@ description="built-in not null audit does not require project generic definition", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT 1 AS id", + "sql/models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT 1 AS id", }, expected_status=BuildStatus.SUCCESS, expected_success_count=1, @@ -394,7 +394,7 @@ description="built-in unique audit ignores duplicate null values", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table, columns (id (audits [unique])));\n\n" "WITH input(id) AS (VALUES (1), (NULL), (NULL))\nSELECT input.id FROM input" ), @@ -410,7 +410,7 @@ description="built-in accepted values audit ignores nulls and allows listed values", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table, columns (status (audits [accepted_values " '(values ["placed", "completed"])])));\n\n' "WITH input(status) AS (VALUES ('placed'), ('completed'), (NULL))\nSELECT input.status FROM input" @@ -430,8 +430,8 @@ description="built-in relationships audit allows matching referenced values", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/customers.sql": "MODEL (description 'Test model customers.', materialized table);\n\nSELECT 1 AS id", - "models/orders.sql": ( + "sql/models/customers.sql": "MODEL (description 'Test model customers.', materialized table);\n\nSELECT 1 AS id", + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table, columns (customer_id (audits [relationships " '(to __ref("customers"), field id)])));\n\n' 'SELECT id AS customer_id FROM __ref("customers") UNION ALL SELECT NULL' @@ -451,8 +451,8 @@ description="warn audit records warning but build succeeds", project_files={ "sqlbuild_project.toml": _PROJECT_YML_WARN, - "models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, expected_status=BuildStatus.SUCCESS, expected_success_count=1, @@ -464,10 +464,10 @@ description="source audit warn does not block dependent models", project_files={ "sqlbuild_project.toml": _PROJECT_YML_WARN, - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __source("raw_orders")' ), - "sources/raw.yml": _RAW_ORDERS_WITH_NOT_NULL_AUDIT, + "sql/sources/raw.yml": _RAW_ORDERS_WITH_NOT_NULL_AUDIT, }, setup_sql=("CREATE TABLE main.raw_orders AS SELECT NULL AS id",), expected_status=BuildStatus.SUCCESS, @@ -480,13 +480,13 @@ description="end audit warn succeeds build with warning", project_files={ "sqlbuild_project.toml": _PROJECT_YML_WARN, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id" ), - "models/payments.sql": ( + "sql/models/payments.sql": ( "MODEL (description 'Test model payments.', materialized table);\n\nSELECT 2 AS payment_id" ), - "audits/singular/cross_check.sql": ( + "sql/audits/singular/cross_check.sql": ( 'AUDIT ();\n\nSELECT o.id FROM __ref("orders") o CROSS JOIN __ref("payments") p' ), }, @@ -503,14 +503,14 @@ description="run_audits false skips source model and end audits but tables still built", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __source("raw_orders")' ), - "models/payments.sql": ( + "sql/models/payments.sql": ( "MODEL (description 'Test model payments.', materialized table);\n\nSELECT 1 AS payment_id" ), - "sources/raw.yml": _RAW_ORDERS_WITH_NOT_NULL_AUDIT, - "audits/singular/cross_check.sql": ( + "sql/sources/raw.yml": _RAW_ORDERS_WITH_NOT_NULL_AUDIT, + "sql/audits/singular/cross_check.sql": ( 'AUDIT ();\n\nSELECT o.id FROM __ref("orders") o CROSS JOIN __ref("payments") p' ), }, @@ -538,8 +538,8 @@ 'default_audit_severity = "warn"\n' 'table_promotion_mode = "immediate"\n' ), - "models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, expected_status=BuildStatus.SUCCESS, expected_success_count=1, @@ -551,7 +551,7 @@ description="build writes fingerprints when query tracking is enabled", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS id", }, expected_status=BuildStatus.SUCCESS, expected_success_count=1, @@ -567,8 +567,8 @@ description="immediate promotion with passing audit creates table", project_files={ "sqlbuild_project.toml": _PROJECT_YML_IMMEDIATE, - "models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT 5 AS id", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT 5 AS id", + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, expected_status=BuildStatus.SUCCESS, expected_success_count=1, @@ -607,10 +607,10 @@ def test_given_build_plan_when_executing_then_succeeds( description="view model creates view and downstream table reads it", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized view);\n\nSELECT 1 AS id, 'alice' AS name" ), - "models/dim_orders.sql": ( + "sql/models/dim_orders.sql": ( 'MODEL (description "Test model dim_orders.", materialized table);\n\nSELECT id, name FROM __ref("stg_orders")' ), }, @@ -626,9 +626,9 @@ def test_given_build_plan_when_executing_then_succeeds( description="view with audit succeeds when audit passes", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": _VIEW_WITH_ID_NOT_NULL_AUDIT + "sql/models/stg_orders.sql": _VIEW_WITH_ID_NOT_NULL_AUDIT + "SELECT 1 AS id, 'alice' AS name", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, expected_status=BuildStatus.SUCCESS, expected_success_count=1, @@ -664,10 +664,10 @@ def test_given_view_build_plan_when_executing_then_succeeds( description="view failure blocks downstream table", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/bad_view.sql": ( + "sql/models/bad_view.sql": ( "MODEL (description 'Test model bad_view.', materialized view);\n\nSELECT * FROM nonexistent_source_table" ), - "models/downstream.sql": ( + "sql/models/downstream.sql": ( 'MODEL (description "Test model downstream.", materialized table);\n\nSELECT * FROM __ref("bad_view")' ), }, @@ -709,9 +709,9 @@ def test_given_view_build_plan_when_executing_then_fails( description="view with run_audits false still creates view", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": _VIEW_WITH_ID_NOT_NULL_AUDIT + "sql/models/stg_orders.sql": _VIEW_WITH_ID_NOT_NULL_AUDIT + "SELECT 1 AS id, 'alice' AS name", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, run_audits=False, expected_status=BuildStatus.SUCCESS, @@ -747,10 +747,10 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="model failure blocks downstream and blocked table does not exist", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT * FROM nonexistent_table" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __ref("stg_orders")' ), }, @@ -768,7 +768,7 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="table runtime contract failure blocks promotion", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " materialized table,\n" " contract enforced,\n" @@ -791,7 +791,7 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="snapshot runtime contract failure blocks target creation", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " contract enforced,\n" @@ -823,7 +823,7 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="incremental runtime contract failure blocks dml", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " materialized incremental,\n" " contract enforced,\n" @@ -838,7 +838,7 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( ");\n\n" 'SELECT * FROM __source("raw_orders")' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), @@ -866,7 +866,7 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="duckdb python udf with explicit schema fails clearly", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "functions/python/is_positive_int.py": ( + "sql/functions/python/is_positive_int.py": ( "from sqlbuild.functions import udf\n\n" "@udf(\n" " arguments={'a_string': 'VARCHAR'},\n" @@ -877,7 +877,7 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( "def main(a_string):\n" " '''Test function main.'''\n return bool(a_string and a_string.isdigit())\n" ), - "models/validated_orders.sql": ( + "sql/models/validated_orders.sql": ( "MODEL (description 'Test model validated_orders.', materialized table);\n\n" 'SELECT __udf("is_positive_int")(' "'123'" @@ -902,13 +902,13 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="independent branch succeeds with real data despite sibling failure", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT * FROM nonexistent_table" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __ref("stg_orders")' ), - "models/payments.sql": ( + "sql/models/payments.sql": ( "MODEL (description 'Test model payments.', materialized table);\n\nSELECT 99 AS payment_id, 750 AS amount" ), }, @@ -930,8 +930,8 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="failing error audit blocks promotion and table has no final data", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, expected_status=BuildStatus.FAILED, expected_failure_count=1, @@ -943,7 +943,7 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="built-in unique audit blocks duplicate non-null values", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table, columns (id (audits [unique])));\n\n" "WITH input(id) AS (VALUES (1), (1), (NULL))\nSELECT input.id FROM input" ), @@ -958,7 +958,7 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="built-in accepted values audit blocks unlisted values", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table, columns (status (audits [accepted_values " '(values ["placed", "completed"])])));\n\n' "SELECT 'cancelled' AS status" @@ -974,8 +974,8 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="built-in relationships audit blocks missing referenced values", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/customers.sql": "MODEL (description 'Test model customers.', materialized table);\n\nSELECT 1 AS id", - "models/orders.sql": ( + "sql/models/customers.sql": "MODEL (description 'Test model customers.', materialized table);\n\nSELECT 1 AS id", + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table, columns (customer_id (audits [relationships " '(to __ref("customers"), field id)])));\n\n' 'SELECT 2 AS customer_id FROM __ref("customers")' @@ -995,13 +995,13 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="end audit error fails build but completed tables are preserved", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 7 AS id, 'carol' AS name" ), - "models/payments.sql": ( + "sql/models/payments.sql": ( "MODEL (description 'Test model payments.', materialized table);\n\nSELECT 1 AS payment_id" ), - "audits/singular/cross_check.sql": ( + "sql/audits/singular/cross_check.sql": ( 'AUDIT ();\n\nSELECT o.id FROM __ref("orders") o CROSS JOIN __ref("payments") p' ), }, @@ -1017,10 +1017,10 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="fail_fast stops after first failure and second model never materialized", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/aaa_broken.sql": ( + "sql/models/aaa_broken.sql": ( "MODEL (description 'Test model aaa_broken.', materialized table);\n\nSELECT * FROM nonexistent_table" ), - "models/zzz_healthy.sql": ( + "sql/models/zzz_healthy.sql": ( "MODEL (description 'Test model zzz_healthy.', materialized table);\n\nSELECT 1 AS id" ), }, @@ -1035,10 +1035,10 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="source audit error blocks dependent models and tables do not exist", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __source("raw_orders")' ), - "sources/raw.yml": _RAW_ORDERS_WITH_NOT_NULL_AUDIT, + "sql/sources/raw.yml": _RAW_ORDERS_WITH_NOT_NULL_AUDIT, }, setup_sql=("CREATE TABLE main.raw_orders AS SELECT NULL AS id",), expected_status=BuildStatus.FAILED, @@ -1052,13 +1052,13 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="source audit error transitively blocks entire dependent chain", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( 'MODEL (description "Test model stg_orders.", materialized table);\n\nSELECT id FROM __source("raw_orders")' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __ref("stg_orders")' ), - "sources/raw.yml": _RAW_ORDERS_WITH_NOT_NULL_AUDIT, + "sql/sources/raw.yml": _RAW_ORDERS_WITH_NOT_NULL_AUDIT, }, setup_sql=("CREATE TABLE main.raw_orders AS SELECT NULL AS id",), expected_status=BuildStatus.FAILED, @@ -1075,8 +1075,8 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="immediate promotion failing audit leaves target updated but build fails", project_files={ "sqlbuild_project.toml": _PROJECT_YML_IMMEDIATE, - "models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, expected_status=BuildStatus.FAILED, expected_failure_count=1, @@ -1088,12 +1088,12 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="pre_hook failure blocks model and downstream table does not exist", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.',\n materialized table\n" " pre_hooks [inline_sql('SELECT * FROM missing_hook_table')]\n);\n\n" "SELECT 1 AS id" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __ref("stg_orders")' ), }, @@ -1110,12 +1110,12 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="post_hook failure blocks downstream but failed model table exists", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.',\n materialized table\n" " post_hooks [inline_sql('SELECT * FROM missing_hook_table')]\n);\n\n" "SELECT 88 AS id" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.", materialized table);\n\nSELECT id FROM __ref("stg_orders")' ), }, @@ -1133,10 +1133,10 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="two independent failures both recorded in non fail_fast", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/broken_a.sql": ( + "sql/models/broken_a.sql": ( "MODEL (description 'Test model broken_a.', materialized table);\n\nSELECT * FROM nonexistent_a" ), - "models/broken_b.sql": ( + "sql/models/broken_b.sql": ( "MODEL (description 'Test model broken_b.', materialized table);\n\nSELECT * FROM nonexistent_b" ), }, @@ -1153,8 +1153,8 @@ def test_given_view_with_run_audits_false_when_executing_then_succeeds( description="staged audit failure preserves existing target with old data", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/models/orders.sql": _TABLE_WITH_ID_NOT_NULL_AUDIT + "SELECT NULL AS id", + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, setup_sql=("CREATE TABLE main.orders AS SELECT 999 AS id",), expected_status=BuildStatus.FAILED, @@ -1194,7 +1194,7 @@ def test_given_build_plan_when_executing_then_fails( description="passing unit test allows model to materialize", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT 1 AS id, 'alice' AS name" ), "tests/unit/test_stg_orders.sql": _PASSING_TEST_SQL, @@ -1209,7 +1209,7 @@ def test_given_build_plan_when_executing_then_fails( description="failing unit test blocks model materialization", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT 1 AS id, 'alice' AS name" ), "tests/unit/test_stg_orders.sql": _FAILING_TEST_SQL, @@ -1226,7 +1226,7 @@ def test_given_build_plan_when_executing_then_fails( description="run_tests false skips test and model materializes", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT 1 AS id, 'alice' AS name" ), "tests/unit/test_stg_orders.sql": _FAILING_TEST_SQL, @@ -1242,10 +1242,10 @@ def test_given_build_plan_when_executing_then_fails( description="failing test blocks target model and downstream chain", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\nSELECT 1 AS id, 'alice' AS name" ), - "models/dim_orders.sql": ( + "sql/models/dim_orders.sql": ( 'MODEL (description "Test model dim_orders.", materialized table);\n\nSELECT id, name FROM __ref("stg_orders")' ), "tests/unit/test_stg_orders.sql": _FAILING_TEST_SQL, diff --git a/tests/integration/src/sqlbuild/executor/build/test_measurement_audit_execution.py b/tests/integration/src/sqlbuild/executor/build/test_measurement_audit_execution.py index 657dee4e29..df288e05b5 100644 --- a/tests/integration/src/sqlbuild/executor/build/test_measurement_audit_execution.py +++ b/tests/integration/src/sqlbuild/executor/build/test_measurement_audit_execution.py @@ -92,9 +92,9 @@ def test_given_measurement_outcomes_when_building_then_gates_and_persists_canoni project_dir=tmp_path, project_files={ "sqlbuild_project.toml": 'name = "measurement_build"\nadapter = "duckdb"\n', - "models/orders.sql": model_sql, - "audits/generic/configured_rate.sql": audit_sql, - "audits/generic/empty_rate.sql": """ + "sql/models/orders.sql": model_sql, + "sql/audits/generic/configured_rate.sql": audit_sql, + "sql/audits/generic/empty_rate.sql": """ AUDIT ( evaluation measurement, value measured_value, diff --git a/tests/integration/src/sqlbuild/executor/build/test_snapshot_execution.py b/tests/integration/src/sqlbuild/executor/build/test_snapshot_execution.py index ab6df50036..d191d34180 100644 --- a/tests/integration/src/sqlbuild/executor/build/test_snapshot_execution.py +++ b/tests/integration/src/sqlbuild/executor/build/test_snapshot_execution.py @@ -62,10 +62,10 @@ model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -111,13 +111,13 @@ model_name="customer_region_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_regions\n description: Test source raw_customer_regions.\n" " schema: main\n" " table: raw_customer_regions\n" ), - "models/customer_region_snapshot.sql": ( + "sql/models/customer_region_snapshot.sql": ( "MODEL (description 'Test model customer_region_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id, region],\n" @@ -174,10 +174,10 @@ model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -328,13 +328,13 @@ def test_given_current_state_timestamp_snapshot_when_building_then_tracks_histor model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_extracts\n description: Test source raw_customer_extracts.\n" " schema: main\n" " table: raw_customer_extracts\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -392,13 +392,13 @@ def test_given_current_state_timestamp_snapshot_when_building_then_tracks_histor model_name="customer_region_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_region_extracts\n description: Test source raw_customer_region_extracts.\n" " schema: main\n" " table: raw_customer_region_extracts\n" ), - "models/customer_region_snapshot.sql": ( + "sql/models/customer_region_snapshot.sql": ( "MODEL (description 'Test model customer_region_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id, region],\n" @@ -453,13 +453,13 @@ def test_given_current_state_timestamp_snapshot_when_building_then_tracks_histor model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_extracts\n description: Test source raw_customer_extracts.\n" " schema: main\n" " table: raw_customer_extracts\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -503,13 +503,13 @@ def test_given_current_state_timestamp_snapshot_when_building_then_tracks_histor model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_changes\n description: Test source raw_customer_changes.\n" " schema: main\n" " table: raw_customer_changes\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -571,13 +571,13 @@ def test_given_current_state_timestamp_snapshot_when_building_then_tracks_histor model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_region_changes\n description: Test source raw_customer_region_changes.\n" " schema: main\n" " table: raw_customer_region_changes\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id, region],\n" @@ -635,13 +635,13 @@ def test_given_current_state_timestamp_snapshot_when_building_then_tracks_histor model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_extracts\n description: Test source raw_customer_extracts.\n" " schema: main\n" " table: raw_customer_extracts\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -756,10 +756,10 @@ def test_given_historical_timestamp_snapshot_when_building_then_uses_updated_his model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -785,10 +785,10 @@ def test_given_historical_timestamp_snapshot_when_building_then_uses_updated_his model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -810,10 +810,10 @@ def test_given_historical_timestamp_snapshot_when_building_then_uses_updated_his model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -837,10 +837,10 @@ def test_given_historical_timestamp_snapshot_when_building_then_uses_updated_his model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -864,13 +864,13 @@ def test_given_historical_timestamp_snapshot_when_building_then_uses_updated_his model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_extracts\n description: Test source raw_customer_extracts.\n" " schema: main\n" " table: raw_customer_extracts\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -901,13 +901,13 @@ def test_given_historical_timestamp_snapshot_when_building_then_uses_updated_his model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_changes\n description: Test source raw_customer_changes.\n" " schema: main\n" " table: raw_customer_changes\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -988,10 +988,10 @@ def test_given_invalid_timestamp_snapshot_source_when_building_then_fails_before model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1032,13 +1032,13 @@ def test_given_invalid_timestamp_snapshot_source_when_building_then_fails_before model_name="customer_region_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_regions\n description: Test source raw_customer_regions.\n" " schema: main\n" " table: raw_customer_regions\n" ), - "models/customer_region_snapshot.sql": ( + "sql/models/customer_region_snapshot.sql": ( "MODEL (description 'Test model customer_region_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id, region],\n" @@ -1092,10 +1092,10 @@ def test_given_invalid_timestamp_snapshot_source_when_building_then_fails_before model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1135,10 +1135,10 @@ def test_given_invalid_timestamp_snapshot_source_when_building_then_fails_before model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1178,10 +1178,10 @@ def test_given_invalid_timestamp_snapshot_source_when_building_then_fails_before model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1220,13 +1220,13 @@ def test_given_invalid_timestamp_snapshot_source_when_building_then_fails_before model_name="customer_region_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_regions\n description: Test source raw_customer_regions.\n" " schema: main\n" " table: raw_customer_regions\n" ), - "models/customer_region_snapshot.sql": ( + "sql/models/customer_region_snapshot.sql": ( "MODEL (description 'Test model customer_region_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id, region],\n" @@ -1286,10 +1286,10 @@ def test_given_invalid_timestamp_snapshot_source_when_building_then_fails_before model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1417,13 +1417,13 @@ def test_given_current_state_check_snapshot_when_building_then_tracks_checked_ch model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_daily\n description: Test source raw_customer_daily.\n" " schema: main\n" " table: raw_customer_daily\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1475,13 +1475,13 @@ def test_given_current_state_check_snapshot_when_building_then_tracks_checked_ch model_name="customer_region_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_region_daily\n description: Test source raw_customer_region_daily.\n" " schema: main\n" " table: raw_customer_region_daily\n" ), - "models/customer_region_snapshot.sql": ( + "sql/models/customer_region_snapshot.sql": ( "MODEL (description 'Test model customer_region_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id, region],\n" @@ -1534,13 +1534,13 @@ def test_given_current_state_check_snapshot_when_building_then_tracks_checked_ch model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_daily\n description: Test source raw_customer_daily.\n" " schema: main\n" " table: raw_customer_daily\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1579,13 +1579,13 @@ def test_given_current_state_check_snapshot_when_building_then_tracks_checked_ch model_name="customer_region_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_region_daily\n description: Test source raw_customer_region_daily.\n" " schema: main\n" " table: raw_customer_region_daily\n" ), - "models/customer_region_snapshot.sql": ( + "sql/models/customer_region_snapshot.sql": ( "MODEL (description 'Test model customer_region_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id, region],\n" @@ -1691,10 +1691,10 @@ def test_given_historical_check_snapshot_when_building_then_tracks_observed_hist model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1718,13 +1718,13 @@ def test_given_historical_check_snapshot_when_building_then_tracks_observed_hist model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_daily\n description: Test source raw_customer_daily.\n" " schema: main\n" " table: raw_customer_daily\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1752,10 +1752,10 @@ def test_given_historical_check_snapshot_when_building_then_tracks_observed_hist model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1776,10 +1776,10 @@ def test_given_historical_check_snapshot_when_building_then_tracks_observed_hist model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1799,10 +1799,10 @@ def test_given_historical_check_snapshot_when_building_then_tracks_observed_hist model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1873,10 +1873,10 @@ def test_given_invalid_check_snapshot_source_when_building_then_fails_before_tar model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1918,10 +1918,10 @@ def test_given_invalid_check_snapshot_source_when_building_then_fails_before_tar model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1959,10 +1959,10 @@ def test_given_invalid_check_snapshot_source_when_building_then_fails_before_tar model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -1996,10 +1996,10 @@ def test_given_invalid_check_snapshot_source_when_building_then_fails_before_tar model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2034,10 +2034,10 @@ def test_given_invalid_check_snapshot_source_when_building_then_fails_before_tar model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2074,13 +2074,13 @@ def test_given_invalid_check_snapshot_source_when_building_then_fails_before_tar model_name="customer_region_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customer_regions\n description: Test source raw_customer_regions.\n" " schema: main\n" " table: raw_customer_regions\n" ), - "models/customer_region_snapshot.sql": ( + "sql/models/customer_region_snapshot.sql": ( "MODEL (description 'Test model customer_region_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id, region],\n" @@ -2171,11 +2171,11 @@ def test_given_current_state_snapshot_when_source_row_disappears_then_hard_delet description="timestamp snapshot appends new source column", initial_project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2187,11 +2187,11 @@ def test_given_current_state_snapshot_when_source_row_disappears_then_hard_delet }, changed_project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2276,11 +2276,11 @@ def test_given_snapshot_source_adds_column_when_building_then_appends_target_col description="contract snapshot requires confirmation for declared new column", initial_project_files={ "sqlbuild_project.toml": _PROJECT_YML_CONFIRM_SCHEMA_CHANGE, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " contract enforced,\n" @@ -2298,11 +2298,11 @@ def test_given_snapshot_source_adds_column_when_building_then_appends_target_col }, changed_project_files={ "sqlbuild_project.toml": _PROJECT_YML_CONFIRM_SCHEMA_CHANGE, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " contract enforced,\n" @@ -2394,11 +2394,11 @@ def test_given_contract_snapshot_adds_declared_column_when_building_then_require description="confirmed contract snapshot appends declared new column", initial_project_files={ "sqlbuild_project.toml": _PROJECT_YML_CONFIRM_SCHEMA_CHANGE, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " contract enforced,\n" @@ -2416,11 +2416,11 @@ def test_given_contract_snapshot_adds_declared_column_when_building_then_require }, changed_project_files={ "sqlbuild_project.toml": _PROJECT_YML_CONFIRM_SCHEMA_CHANGE, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " contract enforced,\n" @@ -2513,11 +2513,11 @@ def test_given_confirmed_contract_snapshot_adds_declared_column_when_building_th description="wildcard check snapshot requires schema-change confirmation", initial_project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2529,11 +2529,11 @@ def test_given_confirmed_contract_snapshot_adds_declared_column_when_building_th }, changed_project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2609,11 +2609,11 @@ def test_given_wildcard_check_snapshot_source_adds_column_when_building_then_req description="confirmed wildcard check snapshot appends new source column", initial_project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2625,11 +2625,11 @@ def test_given_wildcard_check_snapshot_source_adds_column_when_building_then_req }, changed_project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_customers\n description: Test source raw_customers.\n schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2712,13 +2712,13 @@ def test_given_confirmed_wildcard_schema_change_when_building_then_appends_targe model_name="customer_snapshot", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2806,13 +2806,13 @@ def test_given_hard_delete_snapshot_when_duplicate_keys_fail_then_target_history description="check snapshot initial_valid_from can use updated_at", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2874,13 +2874,13 @@ def test_given_check_snapshot_with_initial_valid_from_when_building_then_uses_co description="timestamp snapshot initial_valid_from can explicitly use updated_at", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -2940,13 +2940,13 @@ def test_given_timestamp_snapshot_with_updated_at_initial_validity_when_building description="timestamp snapshot initial_valid_from can use execution time", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -3006,13 +3006,13 @@ def test_given_timestamp_snapshot_with_execution_initial_validity_when_building_ description="check snapshot explicitly accepts execution-time initial validity", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -3074,13 +3074,13 @@ def test_given_check_snapshot_with_execution_initial_validity_when_building_then description="planner carries initial_valid_from into snapshot plan entries", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -3132,13 +3132,13 @@ def test_given_snapshot_initial_validity_config_when_planning_then_plan_entry_pr description="check snapshot runs final column audits", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -3148,7 +3148,7 @@ def test_given_snapshot_initial_validity_config_when_planning_then_plan_entry_pr ");\n\n" 'SELECT customer_id, status FROM __source("raw_customers")' ), - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, setup_sql=( "CREATE TABLE main.raw_customers AS SELECT 1 AS customer_id, 'active' AS status", @@ -3205,13 +3205,13 @@ def test_given_check_snapshot_with_final_audit_when_building_then_runs_audit( description="check snapshot final audit failure fails after target update", project_files={ "sqlbuild_project.toml": _PROJECT_YML, - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_customers\n description: Test source raw_customers.\n" " schema: main\n" " table: raw_customers\n" ), - "models/customer_snapshot.sql": ( + "sql/models/customer_snapshot.sql": ( "MODEL (description 'Test model customer_snapshot.',\n" " materialized snapshot,\n" " unique_key [customer_id],\n" @@ -3221,7 +3221,7 @@ def test_given_check_snapshot_with_final_audit_when_building_then_runs_audit( ");\n\n" 'SELECT customer_id, status FROM __source("raw_customers")' ), - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, setup_sql=( "CREATE TABLE main.raw_customers AS " diff --git a/tests/integration/src/sqlbuild/executor/build/test_table_type_routing.py b/tests/integration/src/sqlbuild/executor/build/test_table_type_routing.py index 15a8a68b07..bbe92a09c7 100644 --- a/tests/integration/src/sqlbuild/executor/build/test_table_type_routing.py +++ b/tests/integration/src/sqlbuild/executor/build/test_table_type_routing.py @@ -23,11 +23,11 @@ "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[connection]\ndatabase = "demo.duckdb"\n' ), - "models/customer_totals.sql": ( + "sql/models/customer_totals.sql": ( "MODEL (description 'Test model customer_totals.', materialized table);\n\n" "SELECT customer_id, SUM(amount) AS total FROM raw_orders GROUP BY customer_id" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\n" " materialized incremental,\n" " incremental_strategy append,\n" @@ -37,7 +37,7 @@ ");\n\n" 'SELECT id, customer_id, amount, updated_at FROM __source("raw_orders")' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), diff --git a/tests/integration/src/sqlbuild/executor/run/dynamic/helpers.py b/tests/integration/src/sqlbuild/executor/run/dynamic/helpers.py index 146f816ebe..e9b06ac01d 100644 --- a/tests/integration/src/sqlbuild/executor/run/dynamic/helpers.py +++ b/tests/integration/src/sqlbuild/executor/run/dynamic/helpers.py @@ -84,7 +84,7 @@ def dynamic_context( entry: ModelPlanEntry = ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="daily_totals"), name="daily_totals", - relative_path=Path("models/daily_totals.sql"), + relative_path=Path("sql/models/daily_totals.sql"), materialization_type=MaterializationType.DYNAMIC, action=action, reason=PlanReason.FIRST_RUN, diff --git a/tests/integration/src/sqlbuild/executor/run/helpers.py b/tests/integration/src/sqlbuild/executor/run/helpers.py index 0f7145c2df..801c24d29a 100644 --- a/tests/integration/src/sqlbuild/executor/run/helpers.py +++ b/tests/integration/src/sqlbuild/executor/run/helpers.py @@ -79,7 +79,7 @@ def build_table_plan_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.TABLE, action=PlanAction.CREATE_TABLE, reason=PlanReason.FIRST_RUN, diff --git a/tests/integration/src/sqlbuild/executor/run/incremental/helpers.py b/tests/integration/src/sqlbuild/executor/run/incremental/helpers.py index e87555169d..de5d95f716 100644 --- a/tests/integration/src/sqlbuild/executor/run/incremental/helpers.py +++ b/tests/integration/src/sqlbuild/executor/run/incremental/helpers.py @@ -99,7 +99,7 @@ def build_incremental_plan_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.INCREMENTAL, action=action, reason=PlanReason.NORMAL_INCREMENTAL, diff --git a/tests/integration/src/sqlbuild/executor/run/incremental/test_incremental_execution.py b/tests/integration/src/sqlbuild/executor/run/incremental/test_incremental_execution.py index 1ba5edc877..3feeb8a5c4 100644 --- a/tests/integration/src/sqlbuild/executor/run/incremental/test_incremental_execution.py +++ b/tests/integration/src/sqlbuild/executor/run/incremental/test_incremental_execution.py @@ -436,7 +436,7 @@ def supports_zero_copy_clone(self) -> bool: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/incremental.py"), + relative_path=Path("sql/hooks/python/incremental.py"), name="insert_hook_log", function=insert_incremental_hook_log, ), @@ -776,7 +776,7 @@ def test_given_existing_table_when_running_incremental_then_succeeds( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/incremental.py"), + relative_path=Path("sql/hooks/python/incremental.py"), name="fail_hook", function=fail_incremental_hook, ), @@ -815,7 +815,7 @@ def test_given_existing_table_when_running_incremental_then_succeeds( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/incremental.py"), + relative_path=Path("sql/hooks/python/incremental.py"), name="fail_hook", function=fail_incremental_hook, ), diff --git a/tests/integration/src/sqlbuild/executor/run/microbatch/helpers.py b/tests/integration/src/sqlbuild/executor/run/microbatch/helpers.py index ce1b74633e..9af51d1d6e 100644 --- a/tests/integration/src/sqlbuild/executor/run/microbatch/helpers.py +++ b/tests/integration/src/sqlbuild/executor/run/microbatch/helpers.py @@ -168,7 +168,7 @@ def build_microbatch_plan_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), materialization_type=MaterializationType.INCREMENTAL, action=action, reason=reason, @@ -207,7 +207,7 @@ def build_integer_reconciliation_plan_entry() -> ModelPlanEntry: return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), materialization_type=MaterializationType.INCREMENTAL, action=PlanAction.INCREMENTAL_DELETE_INSERT, reason=PlanReason.NORMAL_INCREMENTAL, diff --git a/tests/integration/src/sqlbuild/executor/run/microbatch/test_microbatch_execution.py b/tests/integration/src/sqlbuild/executor/run/microbatch/test_microbatch_execution.py index 78215eeda5..018376f02a 100644 --- a/tests/integration/src/sqlbuild/executor/run/microbatch/test_microbatch_execution.py +++ b/tests/integration/src/sqlbuild/executor/run/microbatch/test_microbatch_execution.py @@ -392,7 +392,7 @@ hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/microbatch.py"), + relative_path=Path("sql/hooks/python/microbatch.py"), name="insert_hook_log", function=insert_microbatch_hook_log, ), @@ -705,7 +705,7 @@ def test_given_warn_limit_when_pre_hook_fails_then_execution_metadata_is_preserv hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/microbatch.py"), + relative_path=Path("sql/hooks/python/microbatch.py"), name="skip_hook", function=skip_microbatch_hook, ), @@ -990,7 +990,7 @@ def test_given_reconciliation_reduces_work_when_enforcing_limit_then_final_set_e hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/microbatch.py"), + relative_path=Path("sql/hooks/python/microbatch.py"), name="fail_hook", function=fail_microbatch_hook, ), @@ -1098,7 +1098,7 @@ def test_given_reconciliation_reduces_work_when_enforcing_limit_then_final_set_e hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/microbatch.py"), + relative_path=Path("sql/hooks/python/microbatch.py"), name="fail_hook", function=fail_microbatch_hook, ), diff --git a/tests/integration/src/sqlbuild/executor/run/test_table_execution.py b/tests/integration/src/sqlbuild/executor/run/test_table_execution.py index 67e7fd9677..56b8b42a30 100644 --- a/tests/integration/src/sqlbuild/executor/run/test_table_execution.py +++ b/tests/integration/src/sqlbuild/executor/run/test_table_execution.py @@ -331,7 +331,7 @@ def test_given_immediate_table_when_executing_then_fails( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/table.py"), + relative_path=Path("sql/hooks/python/table.py"), name="create_data", function=create_python_hook_data, ), @@ -360,7 +360,7 @@ def test_given_immediate_table_when_executing_then_fails( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/table.py"), + relative_path=Path("sql/hooks/python/table.py"), name="insert_hook_log", function=insert_table_hook_log, ), @@ -427,7 +427,7 @@ def test_given_hook_config_when_executing_table_then_succeeds( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/table.py"), + relative_path=Path("sql/hooks/python/table.py"), name="fail_hook", function=fail_table_hook, ), diff --git a/tests/integration/src/sqlbuild/executor/run/view/helpers.py b/tests/integration/src/sqlbuild/executor/run/view/helpers.py index 93cb7d9726..0f521ddd3d 100644 --- a/tests/integration/src/sqlbuild/executor/run/view/helpers.py +++ b/tests/integration/src/sqlbuild/executor/run/view/helpers.py @@ -76,7 +76,7 @@ def build_view_plan_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.VIEW, action=PlanAction.CREATE_VIEW, reason=PlanReason.FIRST_RUN, diff --git a/tests/integration/src/sqlbuild/executor/run/view/test_view_execution.py b/tests/integration/src/sqlbuild/executor/run/view/test_view_execution.py index 20f5475d59..ba1a7e58eb 100644 --- a/tests/integration/src/sqlbuild/executor/run/view/test_view_execution.py +++ b/tests/integration/src/sqlbuild/executor/run/view/test_view_execution.py @@ -88,7 +88,7 @@ hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/view.py"), + relative_path=Path("sql/hooks/python/view.py"), name="create_view_data", function=create_python_view_hook_data, ), @@ -121,7 +121,7 @@ hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/view.py"), + relative_path=Path("sql/hooks/python/view.py"), name="create_order_step", function=create_python_view_order_step, ), @@ -216,7 +216,7 @@ def test_given_view_when_executing_then_succeeds( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/view.py"), + relative_path=Path("sql/hooks/python/view.py"), name="fail_hook", function=fail_python_view_hook, ), @@ -244,7 +244,7 @@ def test_given_view_when_executing_then_succeeds( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/view.py"), + relative_path=Path("sql/hooks/python/view.py"), name="fail_hook", function=fail_python_view_hook, ), diff --git a/tests/integration/src/sqlbuild/executor/scenario/helpers.py b/tests/integration/src/sqlbuild/executor/scenario/helpers.py index 9944e9cf00..b9ed95a2df 100644 --- a/tests/integration/src/sqlbuild/executor/scenario/helpers.py +++ b/tests/integration/src/sqlbuild/executor/scenario/helpers.py @@ -320,7 +320,7 @@ def _model_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.TABLE, action=PlanAction.CREATE_TABLE, reason=PlanReason.FIRST_RUN, @@ -344,12 +344,12 @@ def write_partial_fixture_snowflake_project( 'user = "example"\ndatabase = "analytics"\nschema = "marts"\n\n' '[defaults]\ndatabase = "analytics"\nschema = "marts"\nmaterialized = "table"\n' ), - "models/upstream.sql": ( + "sql/models/upstream.sql": ( "MODEL (description 'Upstream.', contract enforced,\n" " columns (id (type INT), label (type VARCHAR)));\n" "SELECT 1 AS id, CAST('a' AS VARCHAR) AS label\n" ), - "models/downstream.sql": ( + "sql/models/downstream.sql": ( "MODEL (description 'Downstream.');\n" 'SELECT u.id, u.label FROM __ref("upstream") AS u\n' ), diff --git a/tests/integration/src/sqlbuild/executor/scenario/test_fixture_lifecycle.py b/tests/integration/src/sqlbuild/executor/scenario/test_fixture_lifecycle.py index 997653f119..ea641392f7 100644 --- a/tests/integration/src/sqlbuild/executor/scenario/test_fixture_lifecycle.py +++ b/tests/integration/src/sqlbuild/executor/scenario/test_fixture_lifecycle.py @@ -248,7 +248,7 @@ def test_given_scenario_plan_when_executing_models_then_builds_model_relations( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/scenario.py"), + relative_path=Path("sql/hooks/python/scenario.py"), name="insert_scenario_hook_log", function=insert_scenario_hook_log, ), diff --git a/tests/integration/src/sqlbuild/executor/testing/helpers.py b/tests/integration/src/sqlbuild/executor/testing/helpers.py index e896068c20..10c047a49e 100644 --- a/tests/integration/src/sqlbuild/executor/testing/helpers.py +++ b/tests/integration/src/sqlbuild/executor/testing/helpers.py @@ -171,11 +171,11 @@ def build_authored_cte_project_files() -> dict[str, str]: "[settings]\n" "sql_analysis = true\n" ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Test model stg_orders.', materialized table);\n\n" "WITH base AS (\n" " -- a comment with an unmatched ) parenthesis\n" @@ -185,7 +185,7 @@ def build_authored_cte_project_files() -> dict[str, str]: "tagged AS (SELECT order_id, amount, note, $$a ) b$$ AS tag FROM base)\n" "SELECT order_id, amount, note, tag FROM tagged\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table);\n\n" "WITH totals AS (\n" ' WITH ranked AS (SELECT order_id, amount, tag FROM __ref("stg_orders"))\n' @@ -256,16 +256,16 @@ def build_terminated_model_project_files() -> dict[str, str]: 'name = "terminated"\nadapter = "duckdb"\n\n[connection]\n' 'database = "terminated.duckdb"\n\n[settings]\nsql_analysis = true\n' ), - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" ), - "models/m.sql": ( + "sql/models/m.sql": ( "MODEL (description 'Test model m.', materialized table);\n\n" 'WITH a AS (SELECT id FROM __source("raw_orders"))\n' "SELECT id FROM a;\n" ), - "models/m_next.sql": ( + "sql/models/m_next.sql": ( "MODEL (description 'Test model m_next.', materialized table);\n\n" 'SELECT id + 1 AS id FROM __ref("m")\n' ), diff --git a/tests/integration/src/sqlbuild/integrations/dbt/conftest.py b/tests/integration/src/sqlbuild/integrations/dbt/conftest.py index f68b5fcc31..a61cb93b72 100644 --- a/tests/integration/src/sqlbuild/integrations/dbt/conftest.py +++ b/tests/integration/src/sqlbuild/integrations/dbt/conftest.py @@ -26,7 +26,7 @@ def dbt_project_dir(tmp_path: Path) -> Path: """Create a tiny dbt DuckDB project.""" project_dir: Path = tmp_path / "dbt_project" - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" models_dir.mkdir(parents=True) project_dir.joinpath("dbt_project.yml").write_text( "\n".join( @@ -58,7 +58,7 @@ def dbt_profiles_dir(tmp_path: Path) -> Path: """Create a dbt profiles directory for DuckDB.""" profiles_dir: Path = tmp_path / "profiles" - profiles_dir.mkdir() + profiles_dir.mkdir(parents=True) profiles_dir.joinpath("profiles.yml").write_text( "\n".join( ( diff --git a/tests/integration/src/sqlbuild/integrations/dbt/helpers.py b/tests/integration/src/sqlbuild/integrations/dbt/helpers.py index e5c1c421ef..a4112344aa 100644 --- a/tests/integration/src/sqlbuild/integrations/dbt/helpers.py +++ b/tests/integration/src/sqlbuild/integrations/dbt/helpers.py @@ -25,15 +25,15 @@ def build_sqlbuild_project_with_manifest( """Create a tiny SQLBuild project with a copied dbt manifest.""" project_dir: Path = tmp_path / "sqlbuild_project" - project_dir.joinpath("models").mkdir(parents=True) - project_dir.joinpath("target").mkdir() + project_dir.joinpath("sql", "models").mkdir(parents=True) + project_dir.joinpath("target").mkdir(parents=True) project_dir.joinpath("sqlbuild_project.toml").write_text( 'name = "demo"\nadapter = "duckdb"\n', encoding="utf-8" ) model_name: str sql: str for model_name, sql in model_sql_by_name.items(): - project_dir.joinpath(f"models/{model_name}.sql").write_text( + project_dir.joinpath(f"sql/models/{model_name}.sql").write_text( f"MODEL (description 'Test model.');\n\n{sql}\n", encoding="utf-8" ) project_dir.joinpath("target/manifest.json").write_text( @@ -64,7 +64,7 @@ def build_sqlbuild_project_with_dbt_config( """Create a tiny SQLBuild project configured for real dbt interop planning.""" project_dir: Path = tmp_path / "sqlbuild_plan_project" - project_dir.joinpath("models").mkdir(parents=True) + project_dir.joinpath("sql", "models").mkdir(parents=True) project_dir.joinpath("sqlbuild_project.toml").write_text( "\n".join( ( @@ -85,7 +85,7 @@ def build_sqlbuild_project_with_dbt_config( relative_path: str contents: str for relative_path, contents in model_contents_by_relative_path.items(): - model_path: Path = project_dir / "models" / relative_path + model_path: Path = project_dir / "sql" / "models" / relative_path model_path.parent.mkdir(parents=True, exist_ok=True) model_path.write_text(contents, encoding="utf-8") return project_dir diff --git a/tests/integration/src/sqlbuild/integrations/dbt/test_manifest.py b/tests/integration/src/sqlbuild/integrations/dbt/test_manifest.py index d7e800f628..9a20691dfb 100644 --- a/tests/integration/src/sqlbuild/integrations/dbt/test_manifest.py +++ b/tests/integration/src/sqlbuild/integrations/dbt/test_manifest.py @@ -56,12 +56,12 @@ def test_given_real_dbt_manifest_when_compiling_sqlbuild_then_preserves_dbt_ref( assert compile_result.returncode == 0, compile_result.stderr or compile_result.stdout sqlbuild_project_dir: Path = tmp_path / "sqlbuild_project" - sqlbuild_project_dir.joinpath("models").mkdir(parents=True) - sqlbuild_project_dir.joinpath("target").mkdir() + sqlbuild_project_dir.joinpath("sql", "models").mkdir(parents=True) + sqlbuild_project_dir.joinpath("target").mkdir(parents=True) sqlbuild_project_dir.joinpath("sqlbuild_project.toml").write_text( 'name = "demo"\nadapter = "duckdb"\n', encoding="utf-8" ) - sqlbuild_project_dir.joinpath("models/downstream_orders.sql").write_text( + sqlbuild_project_dir.joinpath("sql/models/downstream_orders.sql").write_text( test_case.sqlbuild_model_sql, encoding="utf-8" ) sqlbuild_project_dir.joinpath("target/manifest.json").write_text( diff --git a/tests/integration/src/sqlbuild/integrations/dbt/test_plan.py b/tests/integration/src/sqlbuild/integrations/dbt/test_plan.py index 380f6eafb4..1c27f38582 100644 --- a/tests/integration/src/sqlbuild/integrations/dbt/test_plan.py +++ b/tests/integration/src/sqlbuild/integrations/dbt/test_plan.py @@ -242,7 +242,7 @@ ), RealDbtInteropPlanTestCase( description="routes explicit model path selector for real SQLBuild project", - args=("--select", "path:models/marts"), + args=("--select", "path:sql/models/marts"), sqlbuild_model_contents_by_relative_path={ "marts/mart_orders.sql": "MODEL (description 'Test model mart_orders.');\n\nselect 1 as order_id\n", }, @@ -275,7 +275,7 @@ expected_dbt_anchor_unique_ids_by_term={}, expected_dbt_skip_reason=DbtInteropSkipReason.NO_DBT_WORK, expected_sqlbuild_skip_reason=None, - expected_path_translations=(("path:models\\marts", "path:models/marts"),), + expected_path_translations=(("path:models\\marts", "path:sql/models/marts"),), ), RealDbtInteropPlanTestCase( description="preserves routed SQLBuild cursor args in real plan argv", diff --git a/tests/integration/src/sqlbuild/lint/main/helpers.py b/tests/integration/src/sqlbuild/lint/main/helpers.py index 78e74f1825..4a802a99eb 100644 --- a/tests/integration/src/sqlbuild/lint/main/helpers.py +++ b/tests/integration/src/sqlbuild/lint/main/helpers.py @@ -23,9 +23,9 @@ def compile_models( """Write and compile the models.""" (project_dir / "sqlbuild_project.toml").write_text(_PROJECT_TOML, encoding="utf-8") - (project_dir / "models").mkdir(exist_ok=True) + (project_dir / "sql" / "models").mkdir(parents=True, exist_ok=True) for name, sql in models: - (project_dir / "models" / name).write_text(sql, encoding="utf-8") + (project_dir / "sql" / "models" / name).write_text(sql, encoding="utf-8") return build_compiled_project( discovered_inputs=discover_project_inputs(project_dir=project_dir), adapter=DuckDbAdapter(), diff --git a/tests/integration/src/sqlbuild/lint/main/test_fix_verdict.py b/tests/integration/src/sqlbuild/lint/main/test_fix_verdict.py index abc54e7244..04dcfc5576 100644 --- a/tests/integration/src/sqlbuild/lint/main/test_fix_verdict.py +++ b/tests/integration/src/sqlbuild/lint/main/test_fix_verdict.py @@ -107,8 +107,8 @@ def test_given_baseline_and_fixed_compiles_when_comparing_then_failures_belong_t ) -> None: before_dir: Path = tmp_path / "before" after_dir: Path = tmp_path / "after" - before_dir.mkdir() - after_dir.mkdir() + before_dir.mkdir(parents=True) + after_dir.mkdir(parents=True) before: CompiledProjectView = compile_models( project_dir=before_dir, models=test_case.before_models ) @@ -119,7 +119,9 @@ def test_given_baseline_and_fixed_compiles_when_comparing_then_failures_belong_t verdict: FixVerdict = fix_verdict( before=compile_facts(project=before, project_dir=before_dir), after=compile_facts(project=after, project_dir=before_dir), - edited=frozenset((before_dir / "models" / name).resolve() for name in test_case.edited), + edited=frozenset( + (before_dir / "sql" / "models" / name).resolve() for name in test_case.edited + ), ) assert {path.name: reason for path, reason in verdict.failing.items()} == dict( @@ -150,8 +152,8 @@ def test_given_lineage_unavailable_on_both_sides_when_comparing_then_matching_co ) -> None: before_dir: Path = tmp_path / "before" after_dir: Path = tmp_path / "after" - before_dir.mkdir() - after_dir.mkdir() + before_dir.mkdir(parents=True) + after_dir.mkdir(parents=True) before: CompiledProjectView = without_lineage( compile_models(project_dir=before_dir, models=test_case.before_models) ) @@ -162,7 +164,9 @@ def test_given_lineage_unavailable_on_both_sides_when_comparing_then_matching_co verdict: FixVerdict = fix_verdict( before=compile_facts(project=before, project_dir=before_dir), after=compile_facts(project=after, project_dir=before_dir), - edited=frozenset((before_dir / "models" / name).resolve() for name in test_case.edited), + edited=frozenset( + (before_dir / "sql" / "models" / name).resolve() for name in test_case.edited + ), ) assert {path.name: reason for path, reason in verdict.failing.items()} == dict( diff --git a/tests/integration/src/sqlbuild/rule_engine/fact_digests/helpers.py b/tests/integration/src/sqlbuild/rule_engine/fact_digests/helpers.py index 80f6d565e0..5b0f82c1af 100644 --- a/tests/integration/src/sqlbuild/rule_engine/fact_digests/helpers.py +++ b/tests/integration/src/sqlbuild/rule_engine/fact_digests/helpers.py @@ -9,28 +9,28 @@ from sqlbuild.compiler.compile.types import CompiledProjectView PROJECT_FILES: dict[str, str] = { - "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "sources/raw.yml": ( + "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\nextra_paths = ["config"]\n', + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Raw orders.\n" ' expression: "(SELECT 1 AS id, 2 AS customer_id)"\n' ), - "seeds/regions.csv": "region_id,name\n1,north\n", - "seeds/regions.yml": ( + "sql/seeds/regions.csv": "region_id,name\n1,north\n", + "sql/seeds/regions.yml": ( "seeds:\n - name: regions\n description: Regions.\n columns:\n" " - name: region_id\n type: INTEGER\n" " - name: name\n type: VARCHAR\n" ), - "constants/policy.sql": "CONSTANT (name minimum_amount, value 7);\n", - "enums/order_status.sql": "ENUM (name order_status, members [PAID, OPEN]);\n", - "functions/sql/is_paid.sql": ( + "sql/constants/policy.sql": "CONSTANT (name minimum_amount, value 7);\n", + "sql/enums/order_status.sql": "ENUM (name order_status, members [PAID, OPEN]);\n", + "sql/functions/sql/is_paid.sql": ( "FUNCTION (\n arguments (status STRING),\n returns BOOLEAN,\n);\n\nstatus = 'PAID'\n" ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( "MODEL (\n columns (\n order_id (type INTEGER, audits [not_null]),\n ),\n);\n\n" 'SELECT CAST(id AS INTEGER) AS order_id FROM __source("raw_orders")\n' ), - "models/marts/order_totals.sql": ( + "sql/models/marts/order_totals.sql": ( 'MODEL (description "Order totals");\n\nSELECT o.order_id FROM __ref("stg_orders") AS o\n' ), "tests/unit/test_order_totals.sql": ( diff --git a/tests/integration/src/sqlbuild/rule_engine/fact_digests/test_fact_digests.py b/tests/integration/src/sqlbuild/rule_engine/fact_digests/test_fact_digests.py index 57e900dc41..57d85f1eaa 100644 --- a/tests/integration/src/sqlbuild/rule_engine/fact_digests/test_fact_digests.py +++ b/tests/integration/src/sqlbuild/rule_engine/fact_digests/test_fact_digests.py @@ -13,10 +13,10 @@ write_files, ) -_STG: str = "models/staging/stg_orders.sql" -_TOTALS: str = "models/marts/order_totals.sql" +_STG: str = "sql/models/staging/stg_orders.sql" +_TOTALS: str = "sql/models/marts/order_totals.sql" _NEW_MODEL: dict[str, str] = { - "models/marts/order_counts.sql": "MODEL ();\n\nSELECT 1 AS order_count\n" + "sql/models/marts/order_counts.sql": "MODEL ();\n\nSELECT 1 AS order_count\n" } _TOTALS_WITH_COLUMN: dict[str, str] = { _TOTALS: 'MODEL ();\n\nSELECT o.order_id, 1 AS amount FROM __ref("stg_orders") AS o\n' @@ -75,46 +75,52 @@ FactDigestEditTestCase( "project sources", ("project.sources",), - {"sources/raw.yml": PROJECT_FILES["sources/raw.yml"].replace("Raw", "All")}, + {"sql/sources/raw.yml": PROJECT_FILES["sql/sources/raw.yml"].replace("Raw", "All")}, ), FactDigestEditTestCase( "project seeds", ("project.seeds",), - {"seeds/regions.yml": PROJECT_FILES["seeds/regions.yml"].replace("Regions", "Areas")}, + { + "sql/seeds/regions.yml": PROJECT_FILES["sql/seeds/regions.yml"].replace( + "Regions", "Areas" + ) + }, ), FactDigestEditTestCase( "project functions", ("project.functions",), { - "functions/sql/is_paid.sql": PROJECT_FILES["functions/sql/is_paid.sql"].replace( - "'PAID'", "'OPEN'" - ) + "sql/functions/sql/is_paid.sql": PROJECT_FILES[ + "sql/functions/sql/is_paid.sql" + ].replace("'PAID'", "'OPEN'") }, ), FactDigestEditTestCase("project tests", ("project.tests",), _TEST_EDITED), FactDigestEditTestCase("all tests", ("tests.all",), _TEST_EDITED), FactDigestEditTestCase("project audits", ("project.audits",), _STG_AUDITED), FactDigestEditTestCase("all audits", ("audits.all",), _STG_AUDITED), - FactDigestEditTestCase("tree paths", ("tree.paths",), {"docs/notes.yaml": "a: 1\n"}), + FactDigestEditTestCase("tree paths", ("tree.paths",), {"config/notes.yaml": "a: 1\n"}), FactDigestEditTestCase( "public enums", ("declarations.public_enums",), - {"enums/order_status.sql": "ENUM (name order_status, members [PAID, OPEN, VOID]);\n"}, + { + "sql/enums/order_status.sql": "ENUM (name order_status, members [PAID, OPEN, VOID]);\n" + }, ), FactDigestEditTestCase( "all enums", ("declarations.enums",), - {"enums/order_status.sql": "ENUM (name order_status, members [PAID]);\n"}, + {"sql/enums/order_status.sql": "ENUM (name order_status, members [PAID]);\n"}, ), FactDigestEditTestCase( "public constants", ("declarations.public_constants",), - {"constants/policy.sql": "CONSTANT (name minimum_amount, value 8);\n"}, + {"sql/constants/policy.sql": "CONSTANT (name minimum_amount, value 8);\n"}, ), FactDigestEditTestCase( "all constants", ("declarations.constants",), - {"constants/policy.sql": "CONSTANT (name minimum_amount, value 9);\n"}, + {"sql/constants/policy.sql": "CONSTANT (name minimum_amount, value 9);\n"}, ), FactDigestEditTestCase("model SQL", ("sql.for_model", _TOTALS), _TOTALS_WITH_COLUMN), FactDigestEditTestCase( @@ -141,17 +147,19 @@ _STG_ACCEPTED_STRINGS, base_files=_STG_ACCEPTED_INTEGERS, ), - FactDigestEditTestCase("tree children", ("tree.children", "models/marts"), _NEW_MODEL), - FactDigestEditTestCase("tree descendants", ("tree.descendants", "models"), _NEW_MODEL), - FactDigestEditTestCase("tree glob", ("tree.glob", "models/**/*.sql"), _NEW_MODEL), + FactDigestEditTestCase("tree children", ("tree.children", "sql/models/marts"), _NEW_MODEL), + FactDigestEditTestCase("tree descendants", ("tree.descendants", "sql/models"), _NEW_MODEL), + FactDigestEditTestCase("tree glob", ("tree.glob", "sql/models/**/*.sql"), _NEW_MODEL), FactDigestEditTestCase( - "resources under", ("tree.resources_under", "models/marts"), _NEW_MODEL + "resources under", ("tree.resources_under", "sql/models/marts"), _NEW_MODEL ), FactDigestEditTestCase( "read text", ("tree.read_text", "config/owners.yaml"), {"config/owners.yaml": "a: 2\n"} ), FactDigestEditTestCase( - "missing model appears", ("sql.for_model", "models/marts/order_counts.sql"), _NEW_MODEL + "missing model appears", + ("sql.for_model", "sql/models/marts/order_counts.sql"), + _NEW_MODEL, ), ), ids=lambda case: case.description, diff --git a/tests/integration/src/sqlbuild/rule_engine/host_payload/test_host_payload_facts.py b/tests/integration/src/sqlbuild/rule_engine/host_payload/test_host_payload_facts.py index f153d147fc..c01978d010 100644 --- a/tests/integration/src/sqlbuild/rule_engine/host_payload/test_host_payload_facts.py +++ b/tests/integration/src/sqlbuild/rule_engine/host_payload/test_host_payload_facts.py @@ -23,7 +23,7 @@ _PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n', - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_orders\n description: Raw orders.\n" ' expression: "(SELECT 1 AS id, CAST(10.5 AS DOUBLE) AS amount)"\n' @@ -31,22 +31,22 @@ " - name: raw_customers\n description: Raw customers.\n" ' expression: "(SELECT 1 AS customer_id)"\n' ), - "seeds/regions.csv": "region_id,name\n1,north\n", - "seeds/regions.yml": ( + "sql/seeds/regions.csv": "region_id,name\n1,north\n", + "sql/seeds/regions.yml": ( "seeds:\n - name: regions\n description: Regions.\n columns:\n" " - name: region_id\n type: INTEGER\n" " - name: name\n type: VARCHAR\n" ), - "functions/sql/is_paid.sql": ( + "sql/functions/sql/is_paid.sql": ( "FUNCTION (\n description 'Paid status.',\n arguments (status STRING),\n" " returns BOOLEAN,\n);\n\nstatus = 'PAID'\n" ), - "constants/policy.sql": "CONSTANT (name minimum_amount, value 7);\n", - "enums/order_status.sql": "ENUM (name order_status, members [PAID, OPEN]);\n", - "models/marts/_sqlbuild/_macros/python/amounts.py": ( + "sql/constants/policy.sql": "CONSTANT (name minimum_amount, value 7);\n", + "sql/enums/order_status.sql": "ENUM (name order_status, members [PAID, OPEN]);\n", + "sql/models/marts/_sqlbuild/_macros/python/amounts.py": ( 'def doubled(amount: str) -> str:\n return f"({amount}) * 2"\n' ), - "models/staging/stg_orders.sql": ( + "sql/models/staging/stg_orders.sql": ( "MODEL (description 'Staged orders.',\n contract enforced,\n" " columns (\n" " order_id (type INTEGER, nullable false, description 'Order key',\n" @@ -55,16 +55,16 @@ "SELECT CAST(id AS INTEGER) AS order_id, amount, 'PAID' AS status\n" 'FROM __source("raw_orders")\n' ), - "models/marts/order_totals.sql": ( + "sql/models/marts/order_totals.sql": ( 'MODEL (description "Order totals", materialized table);\n\n' 'SELECT o.order_id, @py.doubled("o.amount") AS doubled_amount, o.status\n' 'FROM __ref("stg_orders") AS o WHERE o.amount > 7\n' ), - "models/marts/order_flags.sql": ( + "sql/models/marts/order_flags.sql": ( 'MODEL (description "Order flags");\n\n' 'SELECT o.order_id, o.missing_flag AS flag FROM __ref("stg_orders") AS o\n' ), - "models/marts/flag_counts.sql": ( + "sql/models/marts/flag_counts.sql": ( 'MODEL (description "Flag counts");\n\nSELECT f.flag FROM __ref("order_flags") AS f\n' ), "tests/unit/test_order_totals.sql": ( @@ -77,7 +77,7 @@ } -_STAGING: str = "models/staging/stg_orders.sql" +_STAGING: str = "sql/models/staging/stg_orders.sql" _POPULATED_FACTS: tuple[str, ...] = ( "project.sources", "project.seeds", @@ -90,8 +90,8 @@ f"columns.inferred:{_STAGING}", f"columns.enum_types:{_STAGING}", f"audits.for_model:{_STAGING}", - "tests.for_model:models/marts/order_totals.sql", - "graph.dependents:models/marts/order_flags.sql", + "tests.for_model:sql/models/marts/order_totals.sql", + "graph.dependents:sql/models/marts/order_flags.sql", ) diff --git a/tests/integration/src/sqlbuild/rule_engine/native_rows/helpers.py b/tests/integration/src/sqlbuild/rule_engine/native_rows/helpers.py index 1316664de7..c8b1aa5a83 100644 --- a/tests/integration/src/sqlbuild/rule_engine/native_rows/helpers.py +++ b/tests/integration/src/sqlbuild/rule_engine/native_rows/helpers.py @@ -9,7 +9,7 @@ RULES_FIXTURE: Path = Path("tests/e2e/fixtures/waffle_shop") RULES_CONFIG: str = '\n[rules]\nselect = ["SQBR", "SQLCLEAN"]\n' -EDITED_MODEL: str = "models/staging/stg_orders.sql" +EDITED_MODEL: str = "sql/models/staging/stg_orders.sql" type FindingKey = tuple[str, str, int | None, int | None, str] @@ -48,14 +48,14 @@ def struct_passthrough_files(*, declared_type: str) -> dict[str, str]: 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQBRCONTRACT105"]\n\n' '[defaults]\ncontract = "enforced"\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.',\n" " columns (order_id (type INTEGER), detail (type 'STRUCT(\"café\" INTEGER)')),\n" ");\n\n" "SELECT CAST(1 AS INTEGER) AS order_id,\n" " CAST({'café': 1} AS STRUCT(\"café\" INTEGER)) AS detail\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Typed orders.',\n" f" columns (order_id (type INTEGER), detail (type '{declared_type}')),\n" ");\n\n" @@ -87,13 +87,13 @@ def edit_model(*, project_dir: Path) -> None: 'name = "orders"\nadapter = "duckdb"\n\n[rules]\nselect = ["SQBRCONTRACT105"]\n\n' '[defaults]\ncontract = "enforced"\n' ), - "models/stg_orders.sql": ( + "sql/models/stg_orders.sql": ( "MODEL (description 'Staged orders.',\n" " columns (order_id (type INTEGER), amount (type INTEGER)),\n" ");\n\n" "SELECT CAST(1 AS INTEGER) AS order_id, CAST(5 AS INTEGER) AS amount\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Typed orders.',\n" " columns (order_id (type INTEGER), amount (type BIGINT)),\n" ");\n\n" diff --git a/tests/integration/src/sqlbuild/rule_engine/native_rows/test_native_rules_request.py b/tests/integration/src/sqlbuild/rule_engine/native_rows/test_native_rules_request.py index 5e6a0297a7..92268c49cc 100644 --- a/tests/integration/src/sqlbuild/rule_engine/native_rows/test_native_rules_request.py +++ b/tests/integration/src/sqlbuild/rule_engine/native_rows/test_native_rules_request.py @@ -23,14 +23,14 @@ _TYPE_PROOF_FINDINGS: tuple[FindingKey, ...] = ( ( "K002", - "models/orders.sql", + "sql/models/orders.sql", 2, 37, "column 'amount' inferred as INTEGER but declared type is BIGINT", ), ( "SQBRCONTRACT105", - "models/orders.sql", + "sql/models/orders.sql", 5, 18, 'output "amount" is a passthrough whose type is not proven against the declared ' diff --git a/tests/integration/src/sqlbuild/rule_engine/native_rows/test_sql_rule_cache_publication.py b/tests/integration/src/sqlbuild/rule_engine/native_rows/test_sql_rule_cache_publication.py index 4f9c1d8253..8f3d0c7d00 100644 --- a/tests/integration/src/sqlbuild/rule_engine/native_rows/test_sql_rule_cache_publication.py +++ b/tests/integration/src/sqlbuild/rule_engine/native_rows/test_sql_rule_cache_publication.py @@ -29,9 +29,9 @@ def test_given_increasing_findings_when_publishing_cache_then_findings_are_store started: float = monotonic() for size in test_case.sizes: project_dir: Path = tmp_path / str(size) - (project_dir / "models").mkdir(parents=True) + (project_dir / "sql" / "models").mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text(_PROJECT_TOML, encoding="utf-8") - paths: list[Path] = [Path(f"models/orders_{index}.sql") for index in range(size)] + paths: list[Path] = [Path(f"sql/models/orders_{index}.sql") for index in range(size)] for index, path in enumerate(paths[:-1]): (project_dir / path).write_text( f'MODEL (description "Orders {index}");\n' diff --git a/tests/integration/src/sqlbuild/rule_engine/native_rows/test_sql_rule_compile_vars.py b/tests/integration/src/sqlbuild/rule_engine/native_rows/test_sql_rule_compile_vars.py index 5ee168dde0..72507d2626 100644 --- a/tests/integration/src/sqlbuild/rule_engine/native_rows/test_sql_rule_compile_vars.py +++ b/tests/integration/src/sqlbuild/rule_engine/native_rows/test_sql_rule_compile_vars.py @@ -16,7 +16,7 @@ 'name = "orders"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' '[vars]\nprobe = "1"\n\n[targets.dev]\n\n[targets.prod.vars]\nprobe = "NULL"\n' ) -_MODEL_PATH: Path = Path("models/orders.sql") +_MODEL_PATH: Path = Path("sql/models/orders.sql") _MODEL_SQL: str = ( 'MODEL (description "Orders");\nSELECT o.order_id FROM orders AS o WHERE o.order_id = @@probe\n' ) @@ -35,7 +35,7 @@ def test_given_no_early_lint_when_running_sql_rules_then_compile_vars_are_expanded( test_case: SqlRuleCompileVarsTestCase, tmp_path: Path ) -> None: - (tmp_path / "models").mkdir() + (tmp_path / "sql" / "models").mkdir(parents=True) (tmp_path / "sqlbuild_project.toml").write_text(_PROJECT_TOML, encoding="utf-8") (tmp_path / _MODEL_PATH).write_text(_MODEL_SQL, encoding="utf-8") model: SimpleNamespace = SimpleNamespace( diff --git a/tests/integration/src/sqlbuild/rule_engine/project_rule_tests/test_project_rule_tests.py b/tests/integration/src/sqlbuild/rule_engine/project_rule_tests/test_project_rule_tests.py index 6434a95ede..417652439d 100644 --- a/tests/integration/src/sqlbuild/rule_engine/project_rule_tests/test_project_rule_tests.py +++ b/tests/integration/src/sqlbuild/rule_engine/project_rule_tests/test_project_rule_tests.py @@ -40,7 +40,7 @@ " test_case=RuleCase(\n" ' description="unprefixed orders model",\n' " source='MODEL (description \"Orders\");\\nSELECT 1 AS order_id\\n',\n" - ' path="models/orders.sql",\n' + ' path="sql/models/orders.sql",\n' " expected_finding_count=1,\n" " ),\n" " )\n" @@ -51,7 +51,7 @@ " test_case=RuleCase(\n" ' description="staged orders model",\n' " source='MODEL (description \"Orders\");\\nSELECT 1 AS order_id\\n',\n" - ' path="models/stg_orders.sql",\n' + ' path="sql/models/stg_orders.sql",\n' " expected_finding_count=0,\n" " ),\n" " )\n" diff --git a/tests/unit/scripts/compile_performance_ratio/_helpers/helpers.py b/tests/unit/scripts/compile_performance_ratio/_helpers/helpers.py index dd8b933e74..5ba4a90516 100644 --- a/tests/unit/scripts/compile_performance_ratio/_helpers/helpers.py +++ b/tests/unit/scripts/compile_performance_ratio/_helpers/helpers.py @@ -43,7 +43,7 @@ def read_model_files(*, project_dir: Path) -> dict[str, str]: return { path.relative_to(project_dir).as_posix(): path.read_text(encoding="utf-8") - for path in sorted((project_dir / "models").rglob("*.sql")) + for path in sorted(project_dir.rglob("*.sql")) } diff --git a/tests/unit/scripts/compile_performance_ratio/_helpers/test_edit.py b/tests/unit/scripts/compile_performance_ratio/_helpers/test_edit.py index dc5c217b60..6d758f4347 100644 --- a/tests/unit/scripts/compile_performance_ratio/_helpers/test_edit.py +++ b/tests/unit/scripts/compile_performance_ratio/_helpers/test_edit.py @@ -25,28 +25,37 @@ OneModelEditTestCase( description="the middle model by path gets a comment before its query", model_files={ - "models/a/orders_a.sql": _HEADER + "SELECT 1 AS id\n", - "models/b/orders_b.sql": _HEADER + _WITH_QUERY, - "models/c/orders_c.sql": _HEADER + "SELECT 3 AS id\n", + "sql/models/a/orders_a.sql": _HEADER + "SELECT 1 AS id\n", + "sql/models/b/orders_b.sql": _HEADER + _WITH_QUERY, + "sql/models/c/orders_c.sql": _HEADER + "SELECT 3 AS id\n", }, revisions=1, - expected_paths=("models/b/orders_b.sql",), + expected_paths=("sql/models/b/orders_b.sql",), expected_files={ - "models/a/orders_a.sql": _HEADER + "SELECT 1 AS id\n", - "models/b/orders_b.sql": _HEADER + "-- Benchmark edit 0.\n" + _WITH_QUERY, - "models/c/orders_c.sql": _HEADER + "SELECT 3 AS id\n", + "sql/models/a/orders_a.sql": _HEADER + "SELECT 1 AS id\n", + "sql/models/b/orders_b.sql": _HEADER + "-- Benchmark edit 0.\n" + _WITH_QUERY, + "sql/models/c/orders_c.sql": _HEADER + "SELECT 3 AS id\n", }, ), OneModelEditTestCase( description="each revision adds a distinct comment so every run is a new edit", - model_files={"models/orders.sql": _HEADER + "SELECT 1 AS id\n"}, + model_files={"sql/models/orders.sql": _HEADER + "SELECT 1 AS id\n"}, revisions=2, - expected_paths=("models/orders.sql", "models/orders.sql"), + expected_paths=("sql/models/orders.sql", "sql/models/orders.sql"), expected_files={ - "models/orders.sql": _HEADER + "sql/models/orders.sql": _HEADER + "-- Benchmark edit 0.\n-- Benchmark edit 1.\nSELECT 1 AS id\n" }, ), + OneModelEditTestCase( + description="a base checkout's project from before the sql/ layout keeps models/", + model_files={"models/orders.sql": _HEADER + "SELECT 1 AS id\n"}, + revisions=1, + expected_paths=("models/orders.sql",), + expected_files={ + "models/orders.sql": _HEADER + "-- Benchmark edit 0.\nSELECT 1 AS id\n" + }, + ), ), ids=lambda case: case.description, ) @@ -76,7 +85,7 @@ def test_given_benchmark_project_when_editing_one_model_then_changes_only_the_mi ), OneModelEditErrorTestCase( description="a model without a query start is reported", - model_files={"models/orders.sql": _HEADER + " select 1 as id\n"}, + model_files={"sql/models/orders.sql": _HEADER + " select 1 as id\n"}, expected_message="has no line starting a WITH or SELECT query to edit", ), ), diff --git a/tests/unit/scripts/compile_performance_ratio/_helpers/test_measure.py b/tests/unit/scripts/compile_performance_ratio/_helpers/test_measure.py index 1a3c470cb6..d670e2ef77 100644 --- a/tests/unit/scripts/compile_performance_ratio/_helpers/test_measure.py +++ b/tests/unit/scripts/compile_performance_ratio/_helpers/test_measure.py @@ -218,8 +218,8 @@ def test_given_unobserved_cache_use_when_checking_then_rejects_the_run( description="an edit the uncached compile reproduces", incremental_report='{"models": 2}', uncached_report='{"models": 2}', - incremental_files={"target/compiled/models/orders.sql": "SELECT 1"}, - uncached_files={"target/compiled/models/orders.sql": "SELECT 1"}, + incremental_files={"target/compiled/sql/models/orders.sql": "SELECT 1"}, + uncached_files={"target/compiled/sql/models/orders.sql": "SELECT 1"}, ), ), ids=lambda case: case.description, @@ -244,17 +244,17 @@ def test_given_an_edit_the_uncached_compile_reproduces_when_checking_then_accept description="a stale report", incremental_report='{"models": 2}', uncached_report='{"models": 3}', - incremental_files={"target/compiled/models/orders.sql": "SELECT 1"}, - uncached_files={"target/compiled/models/orders.sql": "SELECT 1"}, + incremental_files={"target/compiled/sql/models/orders.sql": "SELECT 1"}, + uncached_files={"target/compiled/sql/models/orders.sql": "SELECT 1"}, expected_message="report differs", ), UncachedMatchTestCase( description="a stale compiled artifact", incremental_report='{"models": 2}', uncached_report='{"models": 2}', - incremental_files={"target/compiled/models/orders.sql": "SELECT 1"}, - uncached_files={"target/compiled/models/orders.sql": "SELECT 2"}, - expected_message="models/orders.sql", + incremental_files={"target/compiled/sql/models/orders.sql": "SELECT 1"}, + uncached_files={"target/compiled/sql/models/orders.sql": "SELECT 2"}, + expected_message="sql/models/orders.sql", ), ), ids=lambda case: case.description, diff --git a/tests/unit/scripts/compiler_differential/_helpers/comparing/test_compare.py b/tests/unit/scripts/compiler_differential/_helpers/comparing/test_compare.py index 05d6252ab5..0a1989f59f 100644 --- a/tests/unit/scripts/compiler_differential/_helpers/comparing/test_compare.py +++ b/tests/unit/scripts/compiler_differential/_helpers/comparing/test_compare.py @@ -47,8 +47,8 @@ ), JsonDifferenceTestCase( description="key_order", - left={"name": "orders", "path": "models/orders.sql"}, - right={"path": "models/orders.sql", "name": "orders"}, + left={"name": "orders", "path": "sql/models/orders.sql"}, + right={"path": "sql/models/orders.sql", "name": "orders"}, expected_location="/ (key order)", ), JsonDifferenceTestCase( @@ -59,9 +59,9 @@ ), JsonDifferenceTestCase( description="escaped_pointer_token", - left={"models/orders.sql": {"a~b": 1}}, - right={"models/orders.sql": {"a~b": 2}}, - expected_location="/models~1orders.sql/a~0b", + left={"sql/models/orders.sql": {"a~b": 1}}, + right={"sql/models/orders.sql": {"a~b": 2}}, + expected_location="/sql~1models~1orders.sql/a~0b", ), ], ids=lambda case: case.description, diff --git a/tests/unit/scripts/compiler_differential/_helpers/coverage/helpers.py b/tests/unit/scripts/compiler_differential/_helpers/coverage/helpers.py index 6507e94d9c..9dec81106f 100644 --- a/tests/unit/scripts/compiler_differential/_helpers/coverage/helpers.py +++ b/tests/unit/scripts/compiler_differential/_helpers/coverage/helpers.py @@ -106,7 +106,7 @@ def audit_input(*, definition: str, template: str, rendered: str) -> dict[str, o """Return one captured generic audit attached to column `amount` of model `orders`.""" return { - "audit_file": {"relative_path": {"__path__": f"audits/generic/{definition}.sql"}}, + "audit_file": {"relative_path": {"__path__": f"sql/audits/generic/{definition}.sql"}}, "audit_block": {"sql_body": template}, "sql_body": rendered, "attached_target_kind": {"__enum__": f"{_AUDIT_TARGET}.MODEL"}, diff --git a/tests/unit/scripts/compiler_differential/_helpers/coverage/test_discovery.py b/tests/unit/scripts/compiler_differential/_helpers/coverage/test_discovery.py index 8e5baa0f0f..5b98be1d9c 100644 --- a/tests/unit/scripts/compiler_differential/_helpers/coverage/test_discovery.py +++ b/tests/unit/scripts/compiler_differential/_helpers/coverage/test_discovery.py @@ -62,7 +62,7 @@ {"header_values": {"materialized": "copy_table"}, "contents": "-- café\n"}, ], "materialization_files": [{"name": "copy_table"}], - "adapter_file": {"relative_path": {"__path__": "adapter.py"}}, + "adapter_file": {"relative_path": {"__path__": "python/adapter.py"}}, }, expected_present=frozenset( { @@ -107,7 +107,7 @@ ], "enum_files": [{"declarations": [{"members": [{"name": "LOW", "value": 1}]}]}], "macro_files": [ - {"contents": "from macros.python.rounding import round_amount\n"}, + {"contents": "from sql.macros.python.rounding import round_amount\n"}, ], "test_files": [ { @@ -210,23 +210,23 @@ def test_given_encoded_inputs_when_classifying_then_encoded_empty_values_prove_n [ AuthoredByteKindsTestCase( description="crlf_in_discovered_model", - files={"models/orders.sql": b"MODEL ();\r\nSELECT 1\r\n"}, - read_paths=("models/orders.sql",), + files={"sql/models/orders.sql": b"MODEL ();\r\nSELECT 1\r\n"}, + read_paths=("sql/models/orders.sql",), expected_crlf=True, ), AuthoredByteKindsTestCase( description="lf_only", - files={"models/orders.sql": b"MODEL ();\nSELECT 1\n"}, - read_paths=("models/orders.sql",), + files={"sql/models/orders.sql": b"MODEL ();\nSELECT 1\n"}, + read_paths=("sql/models/orders.sql",), expected_crlf=False, ), AuthoredByteKindsTestCase( description="crlf_only_in_a_file_discovery_did_not_read", files={ - "models/orders.sql": b"MODEL ();\nSELECT 1\n", + "sql/models/orders.sql": b"MODEL ();\nSELECT 1\n", "notes/readme.txt": b"orders\r\n", }, - read_paths=("models/orders.sql",), + read_paths=("sql/models/orders.sql",), expected_crlf=False, ), ], @@ -240,7 +240,7 @@ def test_given_authored_bytes_when_classifying_then_crlf_counts_only_for_discove path.parent.mkdir(parents=True, exist_ok=True) _ = path.write_bytes(contents) capture: Path = tmp_path / "captures" / "001-discovered_project_inputs.json" - capture.parent.mkdir() + capture.parent.mkdir(parents=True) _ = capture.write_text( json.dumps( empty_inputs_capture( @@ -282,7 +282,9 @@ def test_given_discovered_project_inputs_when_listing_required_kinds_then_collec CaptureProblemsTestCase( description="sound_capture", capture=empty_inputs_capture( - asset_functions=[{"function": {"__callable__": "python.assets.orders:export"}}] + asset_functions=[ + {"function": {"__callable__": "python.nodes.assets.orders:export"}} + ] ), expected_problem_count=0, ), diff --git a/tests/unit/scripts/fensu_policy/rules/test_execution_observability.py b/tests/unit/scripts/fensu_policy/rules/test_execution_observability.py index 78eed591cb..e0f3e87b3c 100644 --- a/tests/unit/scripts/fensu_policy/rules/test_execution_observability.py +++ b/tests/unit/scripts/fensu_policy/rules/test_execution_observability.py @@ -518,9 +518,9 @@ def test_given_event_usage_when_checking_event_owner_then_matches_contract( [ CustomRuleTestCase( description="recursive project exporter declaration passes", - path="sinks/private/audit.py", + path="python/event_sinks/private/audit.py", source=( - "from sqlbuild.sinks import lifecycle_event_sink as exporter\n" + "from sqlbuild.event_sinks import lifecycle_event_sink as exporter\n" "@exporter\n" "def audit(event): ...\n" ), @@ -531,7 +531,7 @@ def test_given_event_usage_when_checking_event_owner_then_matches_contract( description="misplaced project exporter declaration faults", path="plugins/audit.py", source=( - "from sqlbuild.sinks import lifecycle_event_sink\n" + "from sqlbuild.event_sinks import lifecycle_event_sink\n" "@lifecycle_event_sink(name='audit')\n" "def audit(event): ...\n" ), @@ -542,7 +542,7 @@ def test_given_event_usage_when_checking_event_owner_then_matches_contract( description="qualified misplaced exporter declaration faults", path="plugins/audit.py", source=( - "import sqlbuild.sinks as exporters\n" + "import sqlbuild.event_sinks as exporters\n" "@exporters.lifecycle_event_sink\n" "def audit(event): ...\n" ), @@ -553,7 +553,7 @@ def test_given_event_usage_when_checking_event_owner_then_matches_contract( description="from package exporter module alias faults", path="plugins/audit.py", source=( - "from sqlbuild import sinks as ex\n" + "from sqlbuild import event_sinks as ex\n" "@ex.lifecycle_event_sink\n" "def audit(event): ...\n" ), @@ -564,8 +564,8 @@ def test_given_event_usage_when_checking_event_owner_then_matches_contract( description="fully qualified exporter decorator faults", path="plugins/audit.py", source=( - "import sqlbuild.sinks\n" - "@sqlbuild.sinks.lifecycle_event_sink\n" + "import sqlbuild.event_sinks\n" + "@sqlbuild.event_sinks.lifecycle_event_sink\n" "def audit(event): ...\n" ), expected_fault_count=1, @@ -584,7 +584,7 @@ def test_given_event_usage_when_checking_event_owner_then_matches_contract( ), CustomRuleTestCase( description="core public exporter facade passes", - path="src/sqlbuild/sinks.py", + path="src/sqlbuild/event_sinks.py", source=( "from sqlbuild.runtime.event_exporting.models import LifecycleEventSinkDefinition\n" ), @@ -629,7 +629,7 @@ def test_given_event_usage_when_checking_event_owner_then_matches_contract( CustomRuleTestCase( description="public exporter types remain consumable", path="src/sqlbuild/example/main/work.py", - source="from sqlbuild.sinks import LifecycleEventSinkDefinition\n", + source="from sqlbuild.event_sinks import LifecycleEventSinkDefinition\n", expected_fault_count=0, ), ], diff --git a/tests/unit/src/sqlbuild/adapter/discovery/main/test_discover.py b/tests/unit/src/sqlbuild/adapter/discovery/main/test_discover.py index abdaf8e1b4..c748e927c3 100644 --- a/tests/unit/src/sqlbuild/adapter/discovery/main/test_discover.py +++ b/tests/unit/src/sqlbuild/adapter/discovery/main/test_discover.py @@ -35,18 +35,18 @@ class NestedDuckDbAdapter(DuckDbAdapter): ProjectAdapterDiscoveryTestCase( description="loads public adapter files recursively", files={ - "adapters/duckdb_plus.py": VALID_DUCKDB_ADAPTER, - "adapters/warehouse/nested.py": NESTED_DUCKDB_ADAPTER, + "python/adapters/duckdb_plus.py": VALID_DUCKDB_ADAPTER, + "python/adapters/warehouse/nested.py": NESTED_DUCKDB_ADAPTER, }, expected_adapter_names=("duckdb_plus", "nested_duckdb"), ), ProjectAdapterDiscoveryTestCase( description="skips private files init files and private directories", files={ - "adapters/duckdb_plus.py": VALID_DUCKDB_ADAPTER, - "adapters/__init__.py": NESTED_DUCKDB_ADAPTER, - "adapters/_private.py": NESTED_DUCKDB_ADAPTER, - "adapters/_shared/nested.py": NESTED_DUCKDB_ADAPTER, + "python/adapters/duckdb_plus.py": VALID_DUCKDB_ADAPTER, + "python/adapters/__init__.py": NESTED_DUCKDB_ADAPTER, + "python/adapters/_private.py": NESTED_DUCKDB_ADAPTER, + "python/adapters/_shared/nested.py": NESTED_DUCKDB_ADAPTER, }, expected_adapter_names=("duckdb_plus",), ), @@ -73,15 +73,15 @@ def test_given_project_adapter_files_when_discovering_then_returns_expected_adap ProjectAdapterDiscoveryErrorTestCase( description="rejects duplicate adapter names", files={ - "adapters/one.py": VALID_DUCKDB_ADAPTER, - "adapters/two.py": VALID_DUCKDB_ADAPTER, + "python/adapters/one.py": VALID_DUCKDB_ADAPTER, + "python/adapters/two.py": VALID_DUCKDB_ADAPTER, }, expected_error_fragment="Duplicate project-local adapter_name 'duckdb_plus'", ), ProjectAdapterDiscoveryErrorTestCase( description="rejects built in adapter shadowing", files={ - "adapters/duckdb.py": VALID_DUCKDB_ADAPTER.replace("duckdb_plus", "duckdb"), + "python/adapters/duckdb.py": VALID_DUCKDB_ADAPTER.replace("duckdb_plus", "duckdb"), }, reserved_names=frozenset({"duckdb"}), expected_error_fragment="shadows a built-in adapter name", @@ -89,7 +89,7 @@ def test_given_project_adapter_files_when_discovering_then_returns_expected_adap ProjectAdapterDiscoveryErrorTestCase( description="rejects adapter subclass without adapter name", files={ - "adapters/missing_name.py": """ + "python/adapters/missing_name.py": """ from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter @@ -102,7 +102,7 @@ class MissingNameAdapter(DuckDbAdapter): ProjectAdapterDiscoveryErrorTestCase( description="rejects non adapter class with adapter name", files={ - "adapters/not_adapter.py": """ + "python/adapters/not_adapter.py": """ class NotAdapter: adapter_name = "not_adapter" """, @@ -111,7 +111,7 @@ class NotAdapter: ), ProjectAdapterDiscoveryErrorTestCase( description="reports import errors with file path", - files={"adapters/broken.py": "raise RuntimeError('boom')\n"}, + files={"python/adapters/broken.py": "raise RuntimeError('boom')\n"}, expected_error_fragment="Error importing project-local adapter module", ), ], diff --git a/tests/unit/src/sqlbuild/adapters/snowflake/_test_types.py b/tests/unit/src/sqlbuild/adapters/snowflake/_test_types.py index 8c9041d17c..45a7ff4f7c 100644 --- a/tests/unit/src/sqlbuild/adapters/snowflake/_test_types.py +++ b/tests/unit/src/sqlbuild/adapters/snowflake/_test_types.py @@ -521,3 +521,39 @@ class SnowflakeChangeTrackingTestCase: description: str config: dict[str, object] expected_sql: str + + +@dataclass +class CreditPriceTestCase: + """A credit price lookup: the account's rows, or the error its rate sheet raises.""" + + description: str + account_row: tuple[object, ...] | None + rate_sheet_row: tuple[object, ...] | None + rate_sheet_error: bool + expected_price: str + expected_source: str + + +@dataclass +class ListPriceTestCase: + description: str + region: str | None + edition: str + expected_price: str + + +@dataclass +class CreditPriceCacheTestCase: + description: str + first_rate: str + second_rate: str + expected_price: str + + +@dataclass +class AddedCostColumnsTestCase: + description: str + database: str | None + schema: str + expected_statements: list[str] diff --git a/tests/unit/src/sqlbuild/adapters/snowflake/helpers.py b/tests/unit/src/sqlbuild/adapters/snowflake/helpers.py index 48438a7f1f..d8d15e1730 100644 --- a/tests/unit/src/sqlbuild/adapters/snowflake/helpers.py +++ b/tests/unit/src/sqlbuild/adapters/snowflake/helpers.py @@ -13,6 +13,7 @@ import pandas import pytest +from snowflake.connector.errors import ProgrammingError from sqlbuild._native import FunctionArgument, FunctionReturnColumn, NativeProgressProjector from sqlbuild.adapter.contract.models import ( @@ -27,6 +28,7 @@ ) from sqlbuild.adapters.snowflake.classes.snowflake_adapter import SnowflakeAdapter from sqlbuild.adapters.snowflake.classes.snowflake_connection import _SnowflakeConnection +from sqlbuild.adapters.snowflake.constants import ACCOUNT_SQL, RATE_SHEET_SQL from sqlbuild.compiler.compile.types import FunctionLanguage from sqlbuild.observability import ( EventDispatcher, @@ -757,3 +759,49 @@ def pandas_order_totals_statement() -> str: entry_point="result", dataframe="pandas", )[0] + + +class FakeCostAccount: + """A Snowflake account answering the credit-price reads, optionally refusing its rate sheet.""" + + def __init__( + self, + *, + account_row: tuple[object, ...] | None, + rate_sheet_row: tuple[object, ...] | None, + rate_sheet_error: bool, + ) -> None: + self.answers: dict[str, tuple[object, ...] | None] = { + ACCOUNT_SQL: account_row, + RATE_SHEET_SQL: rate_sheet_row, + } + refusal: ProgrammingError = ProgrammingError( + msg="Object 'SNOWFLAKE.ORGANIZATION_USAGE.RATE_SHEET_DAILY' does not exist " + "or not authorized.", + errno=2003, + ) + self.refusals: dict[str, tuple[ProgrammingError, ...]] = { + RATE_SHEET_SQL: (refusal,) * int(rate_sheet_error) + } + self.statements: list[str] = [] + + def cursor(self) -> FakeCostCursor: + return FakeCostCursor(account=self) + + +class FakeCostCursor: + def __init__(self, *, account: FakeCostAccount) -> None: + self.account: FakeCostAccount = account + self.row: tuple[object, ...] | None = None + + def execute(self, sql: str) -> None: + self.account.statements.append(sql) + for refusal in self.account.refusals.get(sql, ()): + raise refusal + self.row = self.account.answers.get(sql) + + def fetchone(self) -> tuple[object, ...] | None: + return self.row + + def close(self) -> None: + return None diff --git a/tests/unit/src/sqlbuild/adapters/snowflake/inspection/_test_types.py b/tests/unit/src/sqlbuild/adapters/snowflake/inspection/_test_types.py index c95c119fb6..52b8b1c475 100644 --- a/tests/unit/src/sqlbuild/adapters/snowflake/inspection/_test_types.py +++ b/tests/unit/src/sqlbuild/adapters/snowflake/inspection/_test_types.py @@ -160,6 +160,7 @@ class MissingSchemaTestCase: forbidden_schemas: frozenset[str] expected_error_fragment: str expected_schema_checks: int + expected_failed_reads: int @dataclass(frozen=True) diff --git a/tests/unit/src/sqlbuild/adapters/snowflake/inspection/helpers.py b/tests/unit/src/sqlbuild/adapters/snowflake/inspection/helpers.py index 70ab1ce838..352409d446 100644 --- a/tests/unit/src/sqlbuild/adapters/snowflake/inspection/helpers.py +++ b/tests/unit/src/sqlbuild/adapters/snowflake/inspection/helpers.py @@ -863,12 +863,12 @@ def write_synthetic_snowflake_project( ) -> SyntheticSnowflakeProject: """Write a synthetic orders project and the matching warehouse relation set.""" - (project_dir / "models").mkdir(parents=True, exist_ok=True) - (project_dir / "sources").mkdir(parents=True, exist_ok=True) + (project_dir / "sql" / "models").mkdir(parents=True, exist_ok=True) + (project_dir / "sql" / "sources").mkdir(parents=True, exist_ok=True) (project_dir / "sqlbuild_project.toml").write_text( _project_toml(database=database, model_schemas=model_schemas), encoding="utf-8" ) - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources" / "raw.yml").write_text( _sources_yml(database=database, source_schema=source_schema, sources=sources), encoding="utf-8", ) @@ -886,7 +886,7 @@ def write_synthetic_snowflake_project( schema_index: int schema: str for schema_index, schema in enumerate(model_schemas): - (project_dir / "models" / schema).mkdir(parents=True, exist_ok=True) + (project_dir / "sql" / "models" / schema).mkdir(parents=True, exist_ok=True) model_index: int for model_index in range(models_per_schema): name: str = f"{schema}_orders_{model_index}" @@ -896,7 +896,7 @@ def write_synthetic_snowflake_project( )[schema_index == 0] incremental: bool = model_index % incremental_every == 0 header: str = (_TABLE_MODEL_HEADER, _INCREMENTAL_MODEL_HEADER)[incremental] - (project_dir / "models" / schema / f"{name}.sql").write_text( + (project_dir / "sql" / "models" / schema / f"{name}.sql").write_text( f"{header}SELECT order_id, ordered_at FROM {upstream}\n", encoding="utf-8" ) names_by_schema[name] = schema diff --git a/tests/unit/src/sqlbuild/adapters/snowflake/inspection/test_inspection_catalog.py b/tests/unit/src/sqlbuild/adapters/snowflake/inspection/test_inspection_catalog.py index 092fadcfbb..af98c7567b 100644 --- a/tests/unit/src/sqlbuild/adapters/snowflake/inspection/test_inspection_catalog.py +++ b/tests/unit/src/sqlbuild/adapters/snowflake/inspection/test_inspection_catalog.py @@ -17,8 +17,9 @@ from sqlbuild.adapter.contract.types import TableFreshnessStatus from sqlbuild.adapter.relations.classes.inspection_catalog import InspectionCatalog from sqlbuild.adapter.relations.constants import INSPECTION_IN_LIST_LIMIT +from sqlbuild.adapter.relations.main.inspection_query_sink import inspection_query_sink from sqlbuild.adapter.relations.main.open_inspection_catalog import open_inspection_catalog -from sqlbuild.adapter.relations.models import SchemaColumnListing +from sqlbuild.adapter.relations.models import InspectionQueryRecord, SchemaColumnListing from sqlbuild.adapters.snowflake.classes.snowflake_connection import _SnowflakeConnection from tests.unit.src.sqlbuild.adapters.snowflake.inspection._test_types import ( CappedColumnFallbackTestCase, @@ -578,6 +579,7 @@ def test_given_cap_sized_column_listing_when_reading_then_only_needed_relations_ forbidden_schemas=frozenset(), expected_error_fragment="", expected_schema_checks=1, + expected_failed_reads=0, ) ], ids=lambda case: case.description, @@ -588,8 +590,12 @@ def test_given_missing_schema_when_listing_then_relations_and_columns_are_empty( adapter, connection, warehouse = build_offline_snowflake( relations=build_inspection_catalog_relations() ) + reads: list[InspectionQueryRecord] = [] - with open_inspection_catalog(adapter=adapter, connection=connection) as catalog: + with ( + inspection_query_sink(reads.append), + open_inspection_catalog(adapter=adapter, connection=connection) as catalog, + ): relations: tuple[RelationInfo, ...] = catalog.list_relations( database="analytics", schemas=(test_case.schema,) ) @@ -603,6 +609,7 @@ def test_given_missing_schema_when_listing_then_relations_and_columns_are_empty( assert relations == () assert listing.columns_by_stored_name == {} assert len(warehouse.queries_of_kind("show_schemas")) == test_case.expected_schema_checks + assert sum(read.error is not None for read in reads) == test_case.expected_failed_reads @pytest.mark.parametrize( @@ -614,6 +621,7 @@ def test_given_missing_schema_when_listing_then_relations_and_columns_are_empty( forbidden_schemas=frozenset({"STAGING"}), expected_error_fragment="Object does not exist, or operation cannot be performed", expected_schema_checks=1, + expected_failed_reads=1, ) ], ids=lambda case: case.description, @@ -627,14 +635,17 @@ def test_given_existing_schema_when_show_reports_missing_then_original_error_is_ ) adapter: OfflineSnowflakeAdapter = OfflineSnowflakeAdapter(warehouse=warehouse) connection: _SnowflakeConnection = adapter.connect({}) + reads: list[InspectionQueryRecord] = [] with ( + inspection_query_sink(reads.append), open_inspection_catalog(adapter=adapter, connection=connection) as catalog, pytest.raises(RuntimeError, match=test_case.expected_error_fragment), ): _ = catalog.list_relations(database="analytics", schemas=(test_case.schema,)) assert len(warehouse.queries_of_kind("show_schemas")) == test_case.expected_schema_checks + assert sum(read.error is not None for read in reads) >= test_case.expected_failed_reads @pytest.mark.parametrize( diff --git a/tests/unit/src/sqlbuild/adapters/snowflake/test_cost_collection.py b/tests/unit/src/sqlbuild/adapters/snowflake/test_cost_collection.py index aa63188772..03bedb4f8e 100644 --- a/tests/unit/src/sqlbuild/adapters/snowflake/test_cost_collection.py +++ b/tests/unit/src/sqlbuild/adapters/snowflake/test_cost_collection.py @@ -6,6 +6,7 @@ from typing import Any import pytest +from snowflake.connector.errors import ProgrammingError from sqlbuild.adapters.snowflake.classes.snowflake_adapter import SnowflakeAdapter from sqlbuild.cost.models import RunCostSummary @@ -23,10 +24,23 @@ ) +class _RefusingCursor: + """A role that may read neither the account nor its rate sheet: the list price is used.""" + + def execute(self, sql: str) -> None: + raise ProgrammingError(msg=f"not authorized: {sql}", errno=2003) + + def close(self) -> None: + return None + + class _CostConnection: def __init__(self, *, close_error: bool) -> None: self.close_error: bool = close_error + def cursor(self) -> _RefusingCursor: + return _RefusingCursor() + def close(self) -> None: if self.close_error: raise OSError("close failed") diff --git a/tests/unit/src/sqlbuild/adapters/snowflake/test_credit_price.py b/tests/unit/src/sqlbuild/adapters/snowflake/test_credit_price.py new file mode 100644 index 0000000000..1ba6db3e71 --- /dev/null +++ b/tests/unit/src/sqlbuild/adapters/snowflake/test_credit_price.py @@ -0,0 +1,254 @@ +from __future__ import annotations + +from collections import Counter +from datetime import UTC, datetime +from decimal import Decimal +from pathlib import Path + +import duckdb +import pytest + +from sqlbuild.adapters.snowflake._helpers.cost import list_price, resolve_credit_price +from sqlbuild.adapters.snowflake.classes.snowflake_adapter import SnowflakeAdapter +from sqlbuild.adapters.snowflake.constants import RATE_SHEET_SQL +from sqlbuild.adapters.snowflake.models import CreditPrice +from tests.unit.src.sqlbuild.adapters.snowflake._test_types import ( + AddedCostColumnsTestCase, + CreditPriceCacheTestCase, + CreditPriceTestCase, + ListPriceTestCase, +) +from tests.unit.src.sqlbuild.adapters.snowflake.helpers import FakeCostAccount + +_DAY: datetime = datetime(2026, 11, 24, 9, tzinfo=UTC) + + +@pytest.mark.parametrize( + "test_case", + [ + CreditPriceTestCase( + description="the rate sheet's price, when the role can read it", + account_row=("ORDERS01", "AWS_EU_CENTRAL_1"), + rate_sheet_row=(Decimal("2.73"), "USD"), + rate_sheet_error=False, + expected_price="2.73", + expected_source="rate_sheet", + ), + CreditPriceTestCase( + description="no permission on the rate sheet falls through to the region's list price", + account_row=("ORDERS02", "PUBLIC.AWS_EU_CENTRAL_1"), + rate_sheet_row=None, + rate_sheet_error=True, + expected_price="3.90", + expected_source="list_price", + ), + CreditPriceTestCase( + description="a rate sheet in another currency isn't used", + account_row=("ORDERS03", "AWS_US_WEST_2"), + rate_sheet_row=(Decimal("2.10"), "EUR"), + rate_sheet_error=False, + expected_price="3.00", + expected_source="list_price", + ), + CreditPriceTestCase( + description="a region missing from the table is priced as US East", + account_row=("ORDERS04", "AWS_ME_CENTRAL_1"), + rate_sheet_row=None, + rate_sheet_error=False, + expected_price="3.00", + expected_source="list_price", + ), + CreditPriceTestCase( + description="an account that can't be read gets the US East list price", + account_row=None, + rate_sheet_row=None, + rate_sheet_error=True, + expected_price="3.00", + expected_source="list_price", + ), + ], + ids=lambda case: case.description, +) +def test_given_account_when_pricing_a_credit_then_rate_sheet_then_list_price( + test_case: CreditPriceTestCase, tmp_path: Path +) -> None: + account: FakeCostAccount = FakeCostAccount( + account_row=test_case.account_row, + rate_sheet_row=test_case.rate_sheet_row, + rate_sheet_error=test_case.rate_sheet_error, + ) + + price: CreditPrice = resolve_credit_price(connection=account, cache_dir=tmp_path, today=_DAY) + + assert (price.usd_per_credit, price.source) == ( + Decimal(test_case.expected_price), + test_case.expected_source, + ) + + +@pytest.mark.parametrize( + "test_case", + [ + ListPriceTestCase( + description="Enterprise in London", + region="AWS_EU_WEST_2", + edition="ENTERPRISE", + expected_price="4.00", + ), + ListPriceTestCase( + description="Standard in Tokyo", + region="AWS_AP_NORTHEAST_1", + edition="STANDARD", + expected_price="2.85", + ), + ListPriceTestCase( + description="Business Critical on Azure West Europe", + region="AZURE_WESTEUROPE", + edition="BUSINESS_CRITICAL", + expected_price="5.20", + ), + ListPriceTestCase( + description="an unknown edition reads as Enterprise", + region="GCP_US_CENTRAL1", + edition="VPS", + expected_price="3.00", + ), + ], + ids=lambda case: case.description, +) +def test_given_region_and_edition_when_reading_the_list_price_then_matches_the_table( + test_case: ListPriceTestCase, +) -> None: + price: CreditPrice = list_price(region=test_case.region, edition=test_case.edition) + + assert (price.usd_per_credit, price.source) == (Decimal(test_case.expected_price), "list_price") + + +@pytest.mark.parametrize( + "test_case", + [ + CreditPriceCacheTestCase( + description="a second lookup the same day reuses the first price", + first_rate="2.40", + second_rate="9.99", + expected_price="2.40", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_price_kept_for_the_day_when_pricing_again_then_the_rate_sheet_is_not_read( + test_case: CreditPriceCacheTestCase, tmp_path: Path +) -> None: + first: FakeCostAccount = FakeCostAccount( + account_row=("ORDERS05", "AWS_US_EAST_1"), + rate_sheet_row=(Decimal(test_case.first_rate), "USD"), + rate_sheet_error=False, + ) + again: FakeCostAccount = FakeCostAccount( + account_row=("ORDERS05", "AWS_US_EAST_1"), + rate_sheet_row=(Decimal(test_case.second_rate), "USD"), + rate_sheet_error=False, + ) + _ = resolve_credit_price(connection=first, cache_dir=tmp_path, today=_DAY) + + price: CreditPrice = resolve_credit_price(connection=again, cache_dir=tmp_path, today=_DAY) + + assert price.usd_per_credit == Decimal(test_case.expected_price) + assert RATE_SHEET_SQL not in again.statements + + +@pytest.mark.parametrize( + "test_case", + [ + AddedCostColumnsTestCase( + description="one ALTER ... ADD COLUMN IF NOT EXISTS per price column", + database="analytics", + schema="marts", + expected_statements=[ + "ALTER TABLE analytics.marts._sqlbuild_resource_costs " + "ADD COLUMN IF NOT EXISTS usd_per_credit VARCHAR", + "ALTER TABLE analytics.marts._sqlbuild_resource_costs " + "ADD COLUMN IF NOT EXISTS usd_per_credit_source VARCHAR", + ], + ), + ], + ids=lambda case: case.description, +) +def test_given_snowflake_when_rendering_added_cost_columns_then_one_alter_each( + test_case: AddedCostColumnsTestCase, +) -> None: + statements: list[str] = SnowflakeAdapter().render_add_resource_costs_columns_sql( + database=test_case.database, schema=test_case.schema + ) + + assert statements == test_case.expected_statements + + +@pytest.mark.parametrize( + "test_case", + [ + AddedCostColumnsTestCase( + description="a new table is created with both price columns", + database="analytics", + schema="marts", + expected_statements=[ + "estimated_usd VARCHAR, usd_per_credit VARCHAR, usd_per_credit_source VARCHAR, " + "status VARCHAR NOT NULL" + ], + ), + ], + ids=lambda case: case.description, +) +def test_given_new_table_when_creating_resource_costs_then_it_has_the_price_columns( + test_case: AddedCostColumnsTestCase, +) -> None: + sql: str = SnowflakeAdapter().render_create_resource_costs_table_sql( + database=test_case.database, schema=test_case.schema + ) + + assert test_case.expected_statements[0] in sql + + +@pytest.mark.parametrize( + "test_case", + [ + AddedCostColumnsTestCase( + description="an older table gains both columns once, however often they are added", + database=None, + schema="main", + expected_statements=["usd_per_credit", "usd_per_credit_source"], + ), + ], + ids=lambda case: case.description, +) +def test_given_table_from_before_prices_when_adding_columns_twice_then_both_exist_once( + test_case: AddedCostColumnsTestCase, +) -> None: + adapter: SnowflakeAdapter = SnowflakeAdapter() + create: str = adapter.render_create_resource_costs_table_sql( + database=test_case.database, schema=test_case.schema + ) + older: str = create.replace(" usd_per_credit VARCHAR,", "").replace( + " usd_per_credit_source VARCHAR,", "" + ) + connection: duckdb.DuckDBPyConnection = duckdb.connect() + _ = connection.execute(f"CREATE SCHEMA IF NOT EXISTS {test_case.schema}") + _ = connection.execute(older.split(") DATA_RETENTION")[0] + ")") + statements: list[str] = adapter.render_add_resource_costs_columns_sql( + database=test_case.database, schema=test_case.schema + ) + + for statement in statements + statements: + _ = connection.execute(statement) + + described: list[tuple[object, ...]] = connection.execute( + f"DESCRIBE {test_case.schema}._sqlbuild_resource_costs" + ).fetchall() + names: Counter[str] = Counter(str(row[0]) for row in described) + assert {column: names[column] for column in test_case.expected_statements} == dict.fromkeys( + test_case.expected_statements, 1 + ) + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/unit/src/sqlbuild/cli/commands/_helpers/build_planning/helpers.py b/tests/unit/src/sqlbuild/cli/commands/_helpers/build_planning/helpers.py index c79c282750..94ac70a94d 100644 --- a/tests/unit/src/sqlbuild/cli/commands/_helpers/build_planning/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/_helpers/build_planning/helpers.py @@ -29,7 +29,7 @@ def build_snapshot_full_refresh_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.SNAPSHOT, action=PlanAction.SNAPSHOT, reason=PlanReason.FULL_REFRESH, diff --git a/tests/unit/src/sqlbuild/cli/commands/_helpers/helpers.py b/tests/unit/src/sqlbuild/cli/commands/_helpers/helpers.py index d31b9ea6c7..8a26501420 100644 --- a/tests/unit/src/sqlbuild/cli/commands/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/_helpers/helpers.py @@ -97,7 +97,7 @@ def model_entry(name: str) -> ModelPlanEntry: return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.TABLE, action=PlanAction.CREATE_TABLE, reason=PlanReason.NO_CHANGE, diff --git a/tests/unit/src/sqlbuild/cli/commands/_helpers/lineage/test_cache.py b/tests/unit/src/sqlbuild/cli/commands/_helpers/lineage/test_cache.py index 9b81e4ef91..d1a1204aeb 100644 --- a/tests/unit/src/sqlbuild/cli/commands/_helpers/lineage/test_cache.py +++ b/tests/unit/src/sqlbuild/cli/commands/_helpers/lineage/test_cache.py @@ -22,14 +22,14 @@ _LAYOUT_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\nschema = "${ENV:ORDERS_SCHEMA}"\n', - "models/a/b.sql": "SELECT 1 AS order_id\n", - "models/a-c.sql": "SELECT '${ENV: ORDERS_REGION}' AS region\n", - "models/a.sql": "SELECT 2 AS order_id\n", - "models/Z.SQL": "SELECT 3 AS order_id\n", - "models/é.sql": "SELECT 'café' AS label\n", - "seeds/customers.csv": "customer_id\n1\n", - "sources/raw.YML": "sources: []\n", - "macros/python/helpers.py": "def total():\n return 1\n", + "sql/models/a/b.sql": "SELECT 1 AS order_id\n", + "sql/models/a-c.sql": "SELECT '${ENV: ORDERS_REGION}' AS region\n", + "sql/models/a.sql": "SELECT 2 AS order_id\n", + "sql/models/Z.SQL": "SELECT 3 AS order_id\n", + "sql/models/é.sql": "SELECT 'café' AS label\n", + "sql/seeds/customers.csv": "customer_id\n1\n", + "sql/sources/raw.YML": "sources: []\n", + "sql/macros/python/helpers.py": "def total():\n return 1\n", ".hidden/notes.yaml": "a: 1\n", ".gitignore": "target/\n", "nested/.sqlbuildignore": "*.tmp\n", @@ -38,30 +38,30 @@ "noext": "ENV:\n", "target/ignored.sql": "ENV:\n", ".venv/ignored.py": "ENV:\n", - "models/__pycache__/ignored.py": "ENV:\n", + "sql/models/__pycache__/ignored.py": "ENV:\n", "nested/target/kept.sql": "SELECT 4 AS order_id\n", } _LAYOUT_LINKS: dict[str, str] = { - "models/linked.sql": "models/a.sql", + "sql/models/linked.sql": "sql/models/a.sql", "linked_dir": "models", - "models/broken.sql": "models/missing.sql", + "sql/models/broken.sql": "sql/models/missing.sql", } _LAYOUT_UNLINKED_HASHED_FILES: tuple[str, ...] = ( ".gitignore", ".hidden/notes.yaml", - "macros/python/helpers.py", - "models/Z.SQL", - "models/a/b.sql", - "models/a-c.sql", - "models/a.sql", - "models/é.sql", + "sql/macros/python/helpers.py", + "sql/models/Z.SQL", + "sql/models/a/b.sql", + "sql/models/a-c.sql", + "sql/models/a.sql", + "sql/models/é.sql", "nested/.sqlbuildignore", "nested/target/kept.sql", - "seeds/customers.csv", - "sources/raw.YML", + "sql/seeds/customers.csv", + "sql/sources/raw.YML", "sqlbuild_project.toml", ) -_LAYOUT_HASHED_FILES: tuple[str, ...] = (*_LAYOUT_UNLINKED_HASHED_FILES, "models/linked.sql") +_LAYOUT_HASHED_FILES: tuple[str, ...] = (*_LAYOUT_UNLINKED_HASHED_FILES, "sql/models/linked.sql") _LAYOUT_ENVIRONMENT_NAMES: tuple[str, ...] = ("ORDERS_REGION", "ORDERS_SCHEMA") @@ -120,7 +120,7 @@ def test_given_referenced_environment_change_when_fingerprinting_then_invalidate ), LineageFingerprintAvailabilityTestCase( description="SQL output context preserves structural cache availability", - relative_path="models/orders.sql", + relative_path="sql/models/orders.sql", config=( "MODEL (description 'Test model orders.', materialized view);\n\n" "SELECT '${CTX:run_id}' AS invocation_id, 1 AS order_id\n" @@ -158,21 +158,21 @@ def test_given_dynamic_invocation_context_when_fingerprinting_then_disables_cach ), FingerprintedFilesTestCase( description="chmod permissions follow the platform directory semantics", - files={**_LAYOUT_FILES, "models/locked/hidden.sql": "SELECT 5 AS order_id\n"}, + files={**_LAYOUT_FILES, "sql/models/locked/hidden.sql": "SELECT 5 AS order_id\n"}, links={}, - unreadable_directories=("models/locked",), + unreadable_directories=("sql/models/locked",), environment={"ORDERS_SCHEMA": "orders_dev"}, cli_vars={}, expected_hashed_files=_LAYOUT_UNLINKED_HASHED_FILES - + (("models/locked/hidden.sql",) if sys.platform == "win32" else ()), + + (("sql/models/locked/hidden.sql",) if sys.platform == "win32" else ()), expected_environment_names=_LAYOUT_ENVIRONMENT_NAMES, ), FingerprintedFilesTestCase( description="undecodable names that are never hashed", files={ **_LAYOUT_FILES, - "models/notes_\udcff.md": "ENV:\n", - "models/\udcfe_dir/readme.txt": "ENV:\n", + "sql/models/notes_\udcff.md": "ENV:\n", + "sql/models/\udcfe_dir/readme.txt": "ENV:\n", }, links={}, unreadable_directories=(), @@ -230,32 +230,35 @@ def test_given_authored_files_when_fingerprinting_then_hashes_exactly_the_expect ( UncacheableFingerprintTestCase( description="an environment marker without a name", - files={**_LAYOUT_FILES, "models/bad.sql": "SELECT 'ENV: ' AS broken\n"}, + files={**_LAYOUT_FILES, "sql/models/bad.sql": "SELECT 'ENV: ' AS broken\n"}, expected_fingerprint=None, ), UncacheableFingerprintTestCase( description="an environment name followed by a non-ASCII byte", - files={"models/bad.sql": "SELECT '${ENV:ORDERSÉ}' AS broken\n"}, + files={"sql/models/bad.sql": "SELECT '${ENV:ORDERSÉ}' AS broken\n"}, expected_fingerprint=None, ), UncacheableFingerprintTestCase( description="overlapping markers inside one matched name", - files={"models/bad.sql": "SELECT 'ENV: ENV:X' AS broken\n"}, + files={"sql/models/bad.sql": "SELECT 'ENV: ENV:X' AS broken\n"}, expected_fingerprint=None, ), UncacheableFingerprintTestCase( description="dynamic context in Python source", - files={"macros/python/run.py": "RUN = 'CTX:run_id'\n", "models/a.sql": "SELECT 1\n"}, + files={ + "sql/macros/python/run.py": "RUN = 'CTX:run_id'\n", + "sql/models/a.sql": "SELECT 1\n", + }, expected_fingerprint=None, ), UncacheableFingerprintTestCase( description="an undecodable hashed file name", - files={**_LAYOUT_FILES, "models/orders_\udcff.sql": "SELECT 6 AS order_id\n"}, + files={**_LAYOUT_FILES, "sql/models/orders_\udcff.sql": "SELECT 6 AS order_id\n"}, expected_fingerprint=None, ), UncacheableFingerprintTestCase( description="a hashed file below an undecodable directory", - files={**_LAYOUT_FILES, "models/\udcfe_dir/orders.sql": "SELECT 7 AS order_id\n"}, + files={**_LAYOUT_FILES, "sql/models/\udcfe_dir/orders.sql": "SELECT 7 AS order_id\n"}, expected_fingerprint=None, ), ), @@ -279,8 +282,8 @@ def test_given_unhashable_inputs_when_fingerprinting_then_the_cache_is_disabled( ( InterruptedListingFingerprintTestCase( description="a hashed directory whose listing fails mid-way", - files={"sqlbuild_project.toml": 'name = "orders"\n', "models/a.sql": "SELECT 1\n"}, - interrupted_directory="models", + files={"sqlbuild_project.toml": 'name = "orders"\n', "sql/models/a.sql": "SELECT 1\n"}, + interrupted_directory="sql/models", expected_uncacheable_before=(3, 13), ), ), diff --git a/tests/unit/src/sqlbuild/cli/commands/_helpers/load_selection/helpers.py b/tests/unit/src/sqlbuild/cli/commands/_helpers/load_selection/helpers.py index d17591c683..d50a0bdb4c 100644 --- a/tests/unit/src/sqlbuild/cli/commands/_helpers/load_selection/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/_helpers/load_selection/helpers.py @@ -34,28 +34,28 @@ def build_load_selection_inputs() -> DiscoveredProjectInputs: local_config=LocalConfig(), source_files=( DiscoveredSourceFile( - file_path=Path("sources/raw.yml"), - relative_path=Path("sources/raw.yml"), + file_path=Path("sql/sources/raw.yml"), + relative_path=Path("sql/sources/raw.yml"), contents="", source_entries=(SourceEntry(name="raw_orders", loader="load_raw_orders"),), ), ), loader_functions=( DiscoveredLoaderFunction( - file_path=Path("python/loaders/loaders.py"), - relative_path=Path("python/loaders/loaders.py"), + file_path=Path("python/nodes/loaders/loaders.py"), + relative_path=Path("python/nodes/loaders/loaders.py"), name="fetch_orders", function=fetch_orders, ), DiscoveredLoaderFunction( - file_path=Path("python/loaders/loaders.py"), - relative_path=Path("python/loaders/loaders.py"), + file_path=Path("python/nodes/loaders/loaders.py"), + relative_path=Path("python/nodes/loaders/loaders.py"), name="refresh_orders", function=refresh_orders, ), DiscoveredLoaderFunction( - file_path=Path("python/loaders/loaders.py"), - relative_path=Path("python/loaders/loaders.py"), + file_path=Path("python/nodes/loaders/loaders.py"), + relative_path=Path("python/nodes/loaders/loaders.py"), name="load_raw_orders", function=load_raw_orders, depends_on=(fetch_orders,), diff --git a/tests/unit/src/sqlbuild/cli/commands/_helpers/runtime/helpers.py b/tests/unit/src/sqlbuild/cli/commands/_helpers/runtime/helpers.py index 6e4fc81e4e..be66e3b8ce 100644 --- a/tests/unit/src/sqlbuild/cli/commands/_helpers/runtime/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/_helpers/runtime/helpers.py @@ -47,8 +47,8 @@ def build_warehouse_discovered_inputs( def write_case_adapter_file(*, project_dir: Path, contents: str) -> None: """Write the case's project-local adapter module, which may be empty.""" - (project_dir / "adapters").mkdir(exist_ok=True) - (project_dir / "adapters" / "custom.py").write_text(contents, encoding="utf-8") + (project_dir / "python" / "adapters").mkdir(parents=True, exist_ok=True) + (project_dir / "python" / "adapters" / "custom.py").write_text(contents, encoding="utf-8") def write_dbt_profile(profiles_dir: Path, *, profile: str, output: dict[str, object]) -> None: diff --git a/tests/unit/src/sqlbuild/cli/commands/_helpers/scope/helpers.py b/tests/unit/src/sqlbuild/cli/commands/_helpers/scope/helpers.py index 6d9d48d82c..2511b6dd60 100644 --- a/tests/unit/src/sqlbuild/cli/commands/_helpers/scope/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/_helpers/scope/helpers.py @@ -21,14 +21,14 @@ def orders_move_report() -> ScopeReport: - """Return the orders report with a move preview into models/marts.""" + """Return the orders report with a move preview into sql/models/marts.""" lookup: ScopeLookup = report_scope_lookup() report: ScopeReport = query_scope_report( lookup=lookup, target="model:orders", at=None, directory=False, filters=ScopeReportFilters() ) move, diagnostics = preview_scope_move( - lookup=lookup, resource="model:orders", destination="models/marts/orders.sql" + lookup=lookup, resource="model:orders", destination="sql/models/marts/orders.sql" ) return replace(report, move_preview=move, diagnostics=(*report.diagnostics, *diagnostics)) @@ -40,18 +40,18 @@ def bare_target_scope_lookup() -> ScopeLookup: extra: tuple[ResourceRecord, ...] = ( ResourceRecord( ResourceIdentity(ResourceKind.SOURCE, "raw__orders"), - "sources/raw.yml", + "sql/sources/raw.yml", OwnershipRoot("sources", resource_kind=ResourceKind.SOURCE), ), ResourceRecord( ResourceIdentity(ResourceKind.SEED, "waffle_types"), - "seeds/waffle_types.csv", + "sql/seeds/waffle_types.csv", OwnershipRoot("seeds", resource_kind=ResourceKind.SEED), ), ResourceRecord( ResourceIdentity(ResourceKind.FUNCTION, "udf__is_completed_order"), - "functions/sql/udf__is_completed_order.sql", - OwnershipRoot("functions/sql", resource_kind=ResourceKind.FUNCTION), + "sql/functions/sql/udf__is_completed_order.sql", + OwnershipRoot("sql/functions/sql", resource_kind=ResourceKind.FUNCTION), ), ResourceRecord( ResourceIdentity(ResourceKind.TEST, "orders_are_unique"), @@ -60,7 +60,7 @@ def bare_target_scope_lookup() -> ScopeLookup: ), ResourceRecord( ResourceIdentity(ResourceKind.MODEL, "normalize"), - "models/staging/normalize.sql", + "sql/models/staging/normalize.sql", OwnershipRoot("models", resource_kind=ResourceKind.MODEL), ), ) diff --git a/tests/unit/src/sqlbuild/cli/commands/_helpers/scope/test_output.py b/tests/unit/src/sqlbuild/cli/commands/_helpers/scope/test_output.py index 1742d43409..7403c988e6 100644 --- a/tests/unit/src/sqlbuild/cli/commands/_helpers/scope/test_output.py +++ b/tests/unit/src/sqlbuild/cli/commands/_helpers/scope/test_output.py @@ -31,10 +31,10 @@ verbose=False, expected_fragments=( " Status: 1 match\n", - " ├─ ● enum:mart_status models/marts/_enums/mart_status.sql:1\n", + " ├─ ● enum:mart_status sql/models/marts/_enums/mart_status.sql:1\n", " … 1 global collapsed; run sqb scope model:orders " - "--as-path models/marts/orders.sql --globals all\n", - " Lost (1)\n └─ ● enum:order_status models/staging/enums/order_status.sql:1\n", + "--as-path sql/models/marts/orders.sql --globals all\n", + " Lost (1)\n └─ ● enum:order_status sql/models/staging/enums/order_status.sql:1\n", " Invalidated usages (1)\n - enum:order_status\n", "● used by this resource ○ not used by this resource --verbose for scope details\n", "Completeness: complete\n", @@ -54,8 +54,8 @@ expected_fragments=( " Status: 1 match\n", " ├─ ● enum:mart_status [enum; exact-owner-private; expected_model through " - "model:expected_orders; role models/marts/_enums] " - "models/marts/_enums/mart_status.sql:1:1\n", + "model:expected_orders; role sql/models/marts/_enums] " + "sql/models/marts/_enums/mart_status.sql:1:1\n", "Nearby unavailable (1 of 1)\n (none)\n", " Private retained (0)\n (none)\n", "Diagnostics (0)\n (none)\nCompleteness: complete\n", @@ -73,7 +73,7 @@ def test_given_move_preview_when_rendering_then_detail_level_follows_verbose( exit_code: int = run_scope_command( request=ScopeCommandRequest( target="model:orders", - as_path="models/marts/orders.sql", + as_path="sql/models/marts/orders.sql", verbose=test_case.verbose, ), load_scope_index=lambda **_kwargs: report_scope_lookup().index, @@ -97,7 +97,7 @@ def test_given_move_preview_when_rendering_then_detail_level_follows_verbose( f"{_BOLD}Scope{_RESET}\n {_DIM}Target:{_RESET} model:orders\n", f"{_BOLD}Used{_RESET} {_DIM}(3){_RESET}\n", f" {_DIM}├─{_RESET} {_GREEN}●{_RESET} enum:mart_status " - f"{_DIM}models/marts/_enums/mart_status.sql:1{_RESET}\n", + f"{_DIM}sql/models/marts/_enums/mart_status.sql:1{_RESET}\n", f"{_BOLD}Available{_RESET} {_DIM}(2 of 3, 1 collapsed){_RESET}\n", f" {_DIM}├─{_RESET} {_DIM}○{_RESET} constant:warehouse_password", f" {_DIM}└─{_RESET} {_GREEN}●{_RESET} {_GREEN}enum:mart_status{_RESET}", @@ -127,7 +127,7 @@ def test_given_colour_setting_when_rendering_move_preview_then_applies_colour_ro ) -> None: rendered: str = render_scope_result( result=orders_move_report(), - request=ScopeCommandRequest(target="model:orders", as_path="models/marts/orders.sql"), + request=ScopeCommandRequest(target="model:orders", as_path="sql/models/marts/orders.sql"), use_color=test_case.use_color, ) diff --git a/tests/unit/src/sqlbuild/cli/commands/main/build/test_defer_clone.py b/tests/unit/src/sqlbuild/cli/commands/main/build/test_defer_clone.py index e0a17839fc..990830aa94 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/build/test_defer_clone.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/build/test_defer_clone.py @@ -136,7 +136,7 @@ def test_given_disabled_model_in_defer_clone_scope_when_counting_then_only_enabl key=keys_by_name[name], deps=(), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), query_sql="SELECT 1 AS id", config=CompileModelConfig(values={"enabled": enabled}), destination=CompiledRelationLocation( diff --git a/tests/unit/src/sqlbuild/cli/commands/main/compile/helpers.py b/tests/unit/src/sqlbuild/cli/commands/main/compile/helpers.py index 3247a1906a..2764b1048d 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/compile/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/compile/helpers.py @@ -93,7 +93,7 @@ def prepare_static_compile_project(root: Path) -> Path: """Create a minimal local project for offline compile command tests.""" project_dir: Path = root / "project" - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" models_dir.mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( "\n".join( @@ -196,7 +196,7 @@ def build_target_writer_plan_output() -> PlanOutput: key=seed_key, name="country_codes", destination=target, - file_path=Path("seeds/country_codes.csv"), + file_path=Path("sql/seeds/country_codes.csv"), columns=(), csv_settings=SeedCsvSettings(), ), @@ -205,7 +205,7 @@ def build_target_writer_plan_output() -> PlanOutput: FunctionPlanEntry( key=function_key, name="is_completed_order", - relative_path=Path("functions/sql/is_completed_order.sql"), + relative_path=Path("sql/functions/sql/is_completed_order.sql"), destination=CompiledRelationLocation( database=None, schema="analytics", @@ -226,7 +226,7 @@ def build_target_writer_plan_output() -> PlanOutput: FunctionPlanEntry( key=python_function_key, name="is_completed_order_py", - relative_path=Path("functions/python/is_completed_order_py.py"), + relative_path=Path("sql/functions/python/is_completed_order_py.py"), destination=CompiledRelationLocation( database=None, schema="analytics", @@ -335,7 +335,7 @@ def build_static_target_writer_project() -> CompiledProjectView: key=function_key, deps=(), name="is_completed_order", - relative_path=Path("functions/sql/is_completed_order.sql"), + relative_path=Path("sql/functions/sql/is_completed_order.sql"), arguments=(FunctionArgument(name="order_status", type="VARCHAR"),), returns="BOOLEAN", body_sql="order_status = 'completed'", @@ -417,7 +417,7 @@ def build_compile_output_graph(*, model_names: tuple[str, ...]) -> ProjectGraph: key=key, deps=(), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), query_sql="SELECT 1 AS id", config=CompileModelConfig(values={}), destination=CompiledRelationLocation( @@ -553,8 +553,8 @@ def prepare_rule_gated_compile_project(root: Path, *, test_header: str) -> Path: project_dir: Path = prepare_static_compile_project(root) with (project_dir / "sqlbuild_project.toml").open("a", encoding="utf-8") as config: config.write('\n[rules]\nselect = ["SQBRMODEL102"]\n') - (project_dir / "sources").mkdir() - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources").mkdir(parents=True) + (project_dir / "sql" / "sources" / "raw.yml").write_text( "sources:\n" " - name: raw_orders\n description: Test source raw_orders.\n" " schema: main\n table: raw_orders\n" @@ -562,13 +562,13 @@ def prepare_rule_gated_compile_project(root: Path, *, test_header: str) -> Path: " schema: main\n table: raw_refunds\n", encoding="utf-8", ) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( "MODEL (description 'Test model orders.', materialized view);\n\n" 'SELECT o.order_id, r.refund_id FROM __source("raw_orders") AS o\n' 'LEFT JOIN __source("raw_refunds") AS r ON r.order_id = o.order_id\n', encoding="utf-8", ) - (project_dir / "models" / "bad_star.sql").write_text( + (project_dir / "sql" / "models" / "bad_star.sql").write_text( 'MODEL (description "Test model bad_star.", ' 'materialized view);\n\nSELECT * FROM __source("raw_orders")\n', encoding="utf-8", @@ -662,6 +662,6 @@ class BlockedModelStaging(StagingEveryProject): def create_staging_directory(self, staging_dir: Path) -> None: super().create_staging_directory(staging_dir) - blocker: Path = staging_dir / "compiled" / "models" / "staging" + blocker: Path = staging_dir / "compiled" / "sql" / "models" / "staging" blocker.parent.mkdir(parents=True) _ = blocker.write_text("not a directory\n", encoding="utf-8") diff --git a/tests/unit/src/sqlbuild/cli/commands/main/compile/test_compile_command.py b/tests/unit/src/sqlbuild/cli/commands/main/compile/test_compile_command.py index 4c3e972d42..88afcde2e4 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/compile/test_compile_command.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/compile/test_compile_command.py @@ -73,7 +73,7 @@ def test_given_local_project_when_running_compile_then_it_does_not_connect( assert exit_code == test_case.expected_exit_code for fragment in test_case.expected_stdout_fragments: assert fragment in rendered_stdout - assert (project_dir / "target" / "compiled" / "models" / "orders.sql").exists() + assert (project_dir / "target" / "compiled" / "sql" / "models" / "orders.sql").exists() assert not (project_dir / "target" / "manifest.json").exists() @@ -244,7 +244,7 @@ def test_given_python_project_dag_flag_when_running_compile_then_writes_python_d "orders FAIL 1 columns", "error[K001]: declared column 'customer_id' was not found in statically inferred output", " model: orders", - " --> models/orders.sql:5:5", + " --> sql/models/orders.sql:5:5", " 5 | customer_id (),", " | ^^^^^^^^^^^", "settings.check_declared_columns is true (the default)", @@ -269,11 +269,11 @@ def test_given_python_project_dag_flag_when_running_compile_then_writes_python_d expected_exit_code=1, expected_stdout_fragments=( "error[K002]: column 'amount_cents' inferred as VARCHAR but declared type is INTEGER", - " --> models/orders.sql:4:5", + " --> sql/models/orders.sql:4:5", " 4 | amount_cents (type INTEGER),", " | ^^^^^^^^^^^^", " output:", - " --> models/orders.sql:9:3", + " --> sql/models/orders.sql:9:3", " 9 | CAST('1' AS VARCHAR) AS amount_cents", "inferred VARCHAR", " = help: change the declared type or cast the expression explicitly", @@ -294,7 +294,7 @@ def test_given_python_project_dag_flag_when_running_compile_then_writes_python_d expected_exit_code=1, expected_stdout_fragments=( "error[K005]: column 'customer_id' is not declared in enforced contract", - " --> models/orders.sql:11:3", + " --> sql/models/orders.sql:11:3", " 11 | 2 AS customer_id", " | ^^^^^^^^^^^^^^^^", " = help: add the column to MODEL(columns) or remove it from the SELECT list", @@ -323,7 +323,7 @@ def test_given_contract_errors_when_running_compile_then_reports_diagnostics( ) -> None: project_dir: Path = prepare_static_compile_project(tmp_path) assert test_case.model_sql is not None - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( test_case.model_sql, encoding="utf-8", ) @@ -339,7 +339,7 @@ def test_given_contract_errors_when_running_compile_then_reports_diagnostics( assert exit_code == test_case.expected_exit_code for fragment in test_case.expected_stdout_fragments: assert fragment in rendered_stdout - assert (project_dir / "target" / "compiled" / "models" / "orders.sql").exists() + assert (project_dir / "target" / "compiled" / "sql" / "models" / "orders.sql").exists() assert not (project_dir / "target" / "manifest.json").exists() @@ -378,7 +378,7 @@ def test_given_contract_errors_when_running_compile_json_then_serializes_diagnos capsys: pytest.CaptureFixture[str], ) -> None: project_dir: Path = prepare_static_compile_project(tmp_path) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( test_case.model_sql, encoding="utf-8", ) @@ -403,11 +403,11 @@ def test_given_contract_errors_when_running_compile_json_then_serializes_diagnos assert diagnostics[0]["code"] == test_case.expected_code assert diagnostics[0]["severity"] == test_case.expected_severity assert diagnostics[0]["message"] == test_case.expected_message - assert diagnostics[0]["path"] == "models/orders.sql" + assert diagnostics[0]["path"] == "sql/models/orders.sql" assert diagnostics[0]["line"] == test_case.expected_line assert diagnostics[0]["column"] == test_case.expected_column assert diagnostics[0]["location"] == { - "path": "models/orders.sql", + "path": "sql/models/orders.sql", "line": test_case.expected_line, "column": test_case.expected_column, "end_line": test_case.expected_line, @@ -454,7 +454,7 @@ def test_given_unchecked_declared_columns_when_compiling_column_audit_then_audit + f"\n[settings]\n{test_case.settings_toml}\n", encoding="utf-8", ) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( "MODEL (description 'Test model orders.',\n" " materialized view,\n" " columns (\n" @@ -654,4 +654,4 @@ def observed_adapter(*args: Any, **kwargs: Any) -> NoConnectDuckDbAdapter: assert exit_code == 0 assert enabled_during == [test_case.expected_enabled_during] assert enabled_after is test_case.expected_enabled_after - assert (project_dir / "target" / "compiled" / "models" / "orders.sql").exists() + assert (project_dir / "target" / "compiled" / "sql" / "models" / "orders.sql").exists() diff --git a/tests/unit/src/sqlbuild/cli/commands/main/compile/test_compile_target_writer.py b/tests/unit/src/sqlbuild/cli/commands/main/compile/test_compile_target_writer.py index e2321f4467..44f40ec6cc 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/compile/test_compile_target_writer.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/compile/test_compile_target_writer.py @@ -58,17 +58,17 @@ TargetWriterTestCase( description="writes compiled SQL, manifest, audits, and chain tests", expected_files={ - "compiled/models/staging/orders.sql": "SELECT 1 AS order_id\n", - "compiled/functions/sql/is_completed_order.sql": ( + "compiled/sql/models/staging/orders.sql": "SELECT 1 AS order_id\n", + "compiled/sql/functions/sql/is_completed_order.sql": ( "CREATE OR REPLACE MACRO analytics.is_completed_order(order_status) AS (\n" "order_status = 'completed'\n" ")\n" ), - "compiled/functions/python/is_completed_order_py.sql": ( + "compiled/sql/functions/python/is_completed_order_py.sql": ( "REGISTER PYTHON FUNCTION analytics.is_completed_order_py" "(VARCHAR) RETURNS BOOLEAN\n" ), - "compiled/audits/generic/orders/not_null__order_id.sql": ( + "compiled/sql/audits/generic/orders/not_null__order_id.sql": ( "SELECT order_id FROM analytics.orders WHERE order_id IS NULL\n" ), }, @@ -208,8 +208,8 @@ def test_given_parameterized_test_entries_when_writing_target_then_case_artifact TargetWriterTestCase( description="writes offline compiled SQL without manifest by default", expected_files={ - "compiled/models/staging/orders.sql": "SELECT 2 AS order_id\n", - "compiled/functions/sql/is_completed_order.sql": ( + "compiled/sql/models/staging/orders.sql": "SELECT 2 AS order_id\n", + "compiled/sql/functions/sql/is_completed_order.sql": ( "CREATE OR REPLACE MACRO analytics.is_completed_order(order_status) AS (\n" "order_status = 'completed'\n" ")\n" @@ -225,7 +225,7 @@ def test_given_compiled_project_when_writing_static_target_then_expected_files_a ) -> None: project: CompiledProjectView = build_static_target_writer_project() target_dir: Path = tmp_path / "target" - stale_path: Path = target_dir / "compiled" / "models" / "deleted.sql" + stale_path: Path = target_dir / "compiled" / "sql" / "models" / "deleted.sql" stale_path.parent.mkdir(parents=True) stale_path.write_text("SELECT 'stale'\n", encoding="utf-8") @@ -234,7 +234,7 @@ def test_given_compiled_project_when_writing_static_target_then_expected_files_a adapter=DuckDbAdapter(), project=project, ) - model_path: Path = target_dir / "compiled" / "models" / "staging" / "orders.sql" + model_path: Path = target_dir / "compiled" / "sql" / "models" / "staging" / "orders.sql" unchanged_mtime_ns: int = 1_000_000_000 os.utime(model_path, ns=(unchanged_mtime_ns, unchanged_mtime_ns)) _ = write_static_compile_target( @@ -295,7 +295,7 @@ def test_given_unicode_sql_when_writing_static_target_twice_then_bytes_remain_un adapter=DuckDbAdapter(), project=project, ) - model_path: Path = target_dir / "compiled" / "models" / "staging" / "orders.sql" + model_path: Path = target_dir / "compiled" / "sql" / "models" / "staging" / "orders.sql" unchanged_mtime_ns: int = 1_000_000_000 os.utime(model_path, ns=(unchanged_mtime_ns, unchanged_mtime_ns)) _ = write_static_compile_target( @@ -328,7 +328,7 @@ def test_given_invalid_utf8_artifact_when_writing_again_then_existing_decode_err adapter=DuckDbAdapter(), project=project, ) - model_path: Path = target_dir / "compiled" / "models" / "staging" / "orders.sql" + model_path: Path = target_dir / "compiled" / "sql" / "models" / "staging" / "orders.sql" model_path.write_bytes(b"\xff") with pytest.raises(UnicodeDecodeError, match=test_case.expected_message): @@ -354,7 +354,7 @@ def test_given_unwritable_model_artifact_when_writing_static_target_then_later_g ) -> None: project: CompiledProjectView = build_static_target_writer_project() target_dir: Path = tmp_path / "target" - blocker: Path = target_dir / "compiled" / "models" / "staging" + blocker: Path = target_dir / "compiled" / "sql" / "models" / "staging" blocker.parent.mkdir(parents=True) blocker.write_text("not a directory\n", encoding="utf-8") @@ -366,8 +366,8 @@ def test_given_unwritable_model_artifact_when_writing_static_target_then_later_g ) assert blocker.read_text(encoding="utf-8") == "not a directory\n" - assert not (target_dir / "compiled" / "functions").exists() - assert not (target_dir / "compiled" / "audits").exists() + assert not (target_dir / "compiled" / "sql" / "functions").exists() + assert not (target_dir / "compiled" / "sql" / "audits").exists() assert not (target_dir / "compiled" / "tests").exists() @@ -386,7 +386,7 @@ def test_given_model_write_failure_and_later_error_when_writing_static_target_th test_case: ExpectedMessageTestCase, ) -> None: target_dir: Path = tmp_path / "target" - blocker: Path = target_dir / "compiled" / "models" / "staging" + blocker: Path = target_dir / "compiled" / "sql" / "models" / "staging" blocker.parent.mkdir(parents=True) blocker.write_text("not a directory\n", encoding="utf-8") @@ -397,14 +397,14 @@ def test_given_model_write_failure_and_later_error_when_writing_static_target_th project=build_static_target_writer_project(), ) - assert not (target_dir / "compiled" / "functions").exists() + assert not (target_dir / "compiled" / "sql" / "functions").exists() @pytest.mark.parametrize( "test_case", [ ExpectedMessageTestCase( - description="interrupt after the model group", expected_message="compiled/functions" + description="interrupt after the model group", expected_message="compiled/sql/functions" ) ], ids=lambda case: case.description, @@ -425,7 +425,7 @@ def test_given_interrupt_after_model_group_when_writing_static_target_then_later assert time.monotonic() - started < INTERRUPT_RETURN_SECONDS assert not (target_dir / test_case.expected_message).exists() - assert not (target_dir / "compiled" / "audits").exists() + assert not (target_dir / "compiled" / "sql" / "audits").exists() assert not (target_dir / "compiled" / "tests").exists() @@ -434,7 +434,7 @@ def test_given_interrupt_after_model_group_when_writing_static_target_then_later [ ExpectedMessageTestCase( description="staged model write failure falls back despite a later error", - expected_message="compiled/models/staging/orders.sql", + expected_message="compiled/sql/models/staging/orders.sql", ) ], ids=lambda case: case.description, @@ -640,7 +640,7 @@ def test_given_changed_unrelated_model_when_writing_then_reuses_test_artifact( compiled_model_record(project.models[0]), key=replace(project.models[0].key, name="unrelated"), name="unrelated", - relative_path=Path("models/unrelated.sql"), + relative_path=Path("sql/models/unrelated.sql"), query_sql="SELECT 9 AS unrelated_id", ) changed_project: CompiledProjectView = project_with( diff --git a/tests/unit/src/sqlbuild/cli/commands/main/compile/test_staged_artifact_publication.py b/tests/unit/src/sqlbuild/cli/commands/main/compile/test_staged_artifact_publication.py index b7d34af1d4..4af25121f7 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/compile/test_staged_artifact_publication.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/compile/test_staged_artifact_publication.py @@ -26,8 +26,8 @@ write_relative_files, ) -_MODEL_FILE: str = "compiled/models/staging/orders.sql" -_FUNCTION_FILE: str = "compiled/functions/sql/is_completed_order.sql" +_MODEL_FILE: str = "compiled/sql/models/staging/orders.sql" +_FUNCTION_FILE: str = "compiled/sql/functions/sql/is_completed_order.sql" _PUBLISHED_FILES: dict[str, str] = { _MODEL_FILE: "SELECT 2 AS order_id\n", _FUNCTION_FILE: ( @@ -43,9 +43,9 @@ [ StagedPublishTestCase( description="new files join an existing tree and replace its stale files", - existing_files={"compiled/models/obsolete.sql": "SELECT 0\n"}, + existing_files={"compiled/sql/models/obsolete.sql": "SELECT 0\n"}, expected_files=_PUBLISHED_FILES, - expected_removed=("compiled/models/obsolete.sql",), + expected_removed=("compiled/sql/models/obsolete.sql",), ), StagedPublishTestCase( description="a cold tree is published whole", @@ -77,9 +77,9 @@ def test_given_staged_artifacts_when_publishing_then_target_holds_exactly_the_st [ TamperedStagedPublishTestCase( description="a staged file deleted after preparation", - existing_files={"compiled/models/obsolete.sql": "SELECT 0\n"}, + existing_files={"compiled/sql/models/obsolete.sql": "SELECT 0\n"}, removed_staged_files=(_MODEL_FILE,), - expected_kept_files={"compiled/models/obsolete.sql": "SELECT 0\n"}, + expected_kept_files={"compiled/sql/models/obsolete.sql": "SELECT 0\n"}, ) ], ids=lambda case: case.description, @@ -110,8 +110,8 @@ def remove_staged(root: Path) -> None: StagingInterleavingTestCase( description="cleanup during staging creation keeps the live compile's tree", existing_files={ - ".sqlbuild-staging-abandoned/compiled/models/orders.sql": "SELECT 0\n", - "compiled/models/obsolete.sql": "SELECT 0\n", + ".sqlbuild-staging-abandoned/compiled/sql/models/orders.sql": "SELECT 0\n", + "compiled/sql/models/obsolete.sql": "SELECT 0\n", }, expected_files=_PUBLISHED_FILES, ) @@ -154,7 +154,7 @@ def remove_while_locked(path: Any, *args: Any, **kwargs: Any) -> None: assert survived == [True] assert written is not None assert read_target_files(target, test_case.expected_files) == test_case.expected_files - assert not (target / "compiled" / "models" / "obsolete.sql").exists() + assert not (target / "compiled" / "sql" / "models" / "obsolete.sql").exists() assert sorted(path.name for path in target.glob(".sqlbuild-staging-*")) == [] @@ -163,9 +163,9 @@ def remove_while_locked(path: Any, *args: Any, **kwargs: Any) -> None: [ TamperedStagedPublishTestCase( description="the owner marker removed from a live staging tree", - existing_files={"compiled/models/obsolete.sql": "SELECT 0\n"}, + existing_files={"compiled/sql/models/obsolete.sql": "SELECT 0\n"}, removed_staged_files=(".owner",), - expected_kept_files={"compiled/models/obsolete.sql": "SELECT 0\n"}, + expected_kept_files={"compiled/sql/models/obsolete.sql": "SELECT 0\n"}, ) ], ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/cli/commands/main/dag/helpers.py b/tests/unit/src/sqlbuild/cli/commands/main/dag/helpers.py index 2cc2cf31a5..d7f00251b5 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/dag/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/dag/helpers.py @@ -31,7 +31,7 @@ def prepare_static_dag_project(root: Path) -> Path: """Create a minimal local project for dag command tests.""" project_dir: Path = root / "project" - models_dir: Path = project_dir / "models" + models_dir: Path = project_dir / "sql" / "models" models_dir.mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( "\n".join( @@ -63,10 +63,10 @@ def prepare_advisory_placement_dag_project(root: Path) -> Path: config_path.read_text(encoding="utf-8") + "\n[scopes]\nenforce_placement = false\n", encoding="utf-8", ) - constants_dir: Path = project_dir / "constants" - constants_dir.mkdir() + constants_dir: Path = project_dir / "sql" / "constants" + constants_dir.mkdir(parents=True) (constants_dir / "value.sql").write_text("CONSTANT (name value, value 1);\n", encoding="utf-8") - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( 'MODEL (description "Test model orders.", ' 'materialized table);\n\nSELECT @const("value") AS order_id\n', encoding="utf-8", @@ -78,15 +78,19 @@ def prepare_python_dag_project(root: Path) -> Path: """Create a local project with Python assets and checks.""" project_dir: Path = prepare_static_dag_project(root) - tasks_dir: Path = project_dir / "python" / "tasks" - assets_dir: Path = project_dir / "python" / "assets" - loaders_dir: Path = project_dir / "python" / "loaders" - checks_dir: Path = project_dir / "python" / "checks" - tasks_dir.mkdir(parents=True) - assets_dir.mkdir(parents=True) - loaders_dir.mkdir(parents=True) - checks_dir.mkdir(parents=True) - (tasks_dir / "prepare_orders.py").write_text( + tasks_dir: Path = project_dir / "python" / "nodes" / "tasks" + assets_dir: Path = project_dir / "python" / "nodes" / "assets" + loaders_dir: Path = project_dir / "python" / "nodes" / "loaders" + checks_dir: Path = project_dir / "python" / "nodes" / "checks" + for unit in ( + tasks_dir / "prepare_orders", + loaders_dir / "warehouse_export", + assets_dir / "orders_export", + checks_dir / "check_orders_export", + checks_dir / "check_loader_export", + ): + unit.mkdir(parents=True) + (tasks_dir / "prepare_orders" / "asset.py").write_text( "\n".join( ( "from sqlbuild.assets import asset", @@ -106,11 +110,11 @@ def prepare_python_dag_project(root: Path) -> Path: + "\n", encoding="utf-8", ) - (loaders_dir / "warehouse_export.py").write_text( + (loaders_dir / "warehouse_export" / "loader.py").write_text( "\n".join( ( "from sqlbuild.loaders import loader", - "from python.tasks.prepare_orders import prepare_orders", + "from python.nodes.tasks.prepare_orders.asset import prepare_orders", "", "@loader(", " depends_on=(prepare_orders,),", @@ -124,12 +128,12 @@ def prepare_python_dag_project(root: Path) -> Path: + "\n", encoding="utf-8", ) - (assets_dir / "orders_export.py").write_text( + (assets_dir / "orders_export" / "asset.py").write_text( "\n".join( ( "from sqlbuild.assets import asset", - "from python.loaders.warehouse_export import warehouse_export", - "from python.tasks.prepare_orders import prepare_orders", + "from python.nodes.loaders.warehouse_export.loader import warehouse_export", + "from python.nodes.tasks.prepare_orders.asset import prepare_orders", "", "@asset(", " depends_on=(prepare_orders, warehouse_export),", @@ -149,13 +153,13 @@ def prepare_python_dag_project(root: Path) -> Path: + "\n", encoding="utf-8", ) - (checks_dir / "check_orders_export.py").write_text( + (checks_dir / "check_orders_export" / "checks.py").write_text( "\n".join( ( "from sqlbuild.checks import check", - "from python.assets.orders_export import orders_export", - "from python.loaders.warehouse_export import warehouse_export", - "from python.tasks.prepare_orders import prepare_orders", + "from python.nodes.assets.orders_export.asset import orders_export", + "from python.nodes.loaders.warehouse_export.loader import warehouse_export", + "from python.nodes.tasks.prepare_orders.asset import prepare_orders", "", "@check(", " depends_on=(orders_export, prepare_orders, warehouse_export),", @@ -171,11 +175,11 @@ def prepare_python_dag_project(root: Path) -> Path: + "\n", encoding="utf-8", ) - (checks_dir / "check_loader_export.py").write_text( + (checks_dir / "check_loader_export" / "checks.py").write_text( "\n".join( ( "from sqlbuild.checks import check", - "from python.loaders.warehouse_export import warehouse_export", + "from python.nodes.loaders.warehouse_export.loader import warehouse_export", "", "@check(depends_on=warehouse_export, tags=['loader'])", "def check_loader_export(ctx):", diff --git a/tests/unit/src/sqlbuild/cli/commands/main/dag/test_dag_command.py b/tests/unit/src/sqlbuild/cli/commands/main/dag/test_dag_command.py index 20f420cf25..4adf362720 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/dag/test_dag_command.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/dag/test_dag_command.py @@ -141,7 +141,7 @@ def test_given_local_project_when_running_dag_json_then_outputs_static_graph_wit "asset:prepare_orders", "loader:warehouse_export", ], - "path": "python/checks/check_orders_export.py", + "path": "python/nodes/checks/check_orders_export/checks.py", "description": "Orders export is present", "severity": "error", "tags": ["daily"], @@ -155,7 +155,7 @@ def test_given_local_project_when_running_dag_json_then_outputs_static_graph_wit "name": "check_loader_export", "checked_asset_ids": ["loader:warehouse_export"], "description": "Test check check_loader_export.", - "path": "python/checks/check_loader_export.py", + "path": "python/nodes/checks/check_loader_export/checks.py", "severity": "error", "tags": ["loader"], }, diff --git a/tests/unit/src/sqlbuild/cli/commands/main/dbt/helpers.py b/tests/unit/src/sqlbuild/cli/commands/main/dbt/helpers.py index a2c6148d42..499f75d42e 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/dbt/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/dbt/helpers.py @@ -74,6 +74,8 @@ def write_duckdb_sqlbuild_project(project_dir: Path) -> None: """Write a SQLBuild project config with an inline DuckDB connection.""" (project_dir / "sqlbuild_project.toml").write_text( - 'name = "demo"\nadapter = "duckdb"\n\n[connection]\npath = "warehouse.duckdb"\n', + 'name = "demo"\nadapter = "duckdb"\n' + 'extra_paths = ["dbt_project", "fake_dbt", "dbt_args.json"]\n\n' + '[connection]\npath = "warehouse.duckdb"\n', encoding="utf-8", ) diff --git a/tests/unit/src/sqlbuild/cli/commands/main/entry/test_main.py b/tests/unit/src/sqlbuild/cli/commands/main/entry/test_main.py index 1d2445a75f..88b27cdd89 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/entry/test_main.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/entry/test_main.py @@ -207,7 +207,7 @@ def test_given_compile_command_arguments_when_running_with_dependencies_then_it_ "plan", "--json", "--select", - "path:models/marts", + "path:sql/models/marts", "--project-dir", "dbt_project", "--start-cursor-int", @@ -219,7 +219,7 @@ def test_given_compile_command_arguments_when_running_with_dependencies_then_it_ expected_dbt_args=( "--json", "--select", - "path:models/marts", + "path:sql/models/marts", "--project-dir", "dbt_project", "--start-cursor-int", diff --git a/tests/unit/src/sqlbuild/cli/commands/main/entry/test_observability_cleanup.py b/tests/unit/src/sqlbuild/cli/commands/main/entry/test_observability_cleanup.py index ea4175c20a..ccc754d26f 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/entry/test_observability_cleanup.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/entry/test_observability_cleanup.py @@ -66,13 +66,13 @@ def test_given_no_public_sink_when_observability_runs_then_provider_import_is_sk write_repo_files( tmp_path, { - "providers/exploding.py": ( + "python/providers/exploding.py": ( "from pathlib import Path\n" f"Path({str(marker_path)!r}).write_text('imported', encoding='utf-8')\n" "raise RuntimeError('provider must not import')\n" ), - "sinks/_private.py": "raise RuntimeError('private sink imported')\n", - "sinks/helpers.py": ( + "python/event_sinks/_private.py": "raise RuntimeError('private sink imported')\n", + "python/event_sinks/helpers.py": ( "from pathlib import Path\n" f"Path({str(helper_marker_path)!r}).write_text('imported', encoding='utf-8')\n" "def encode(value):\n return value\n" diff --git a/tests/unit/src/sqlbuild/cli/commands/main/entry/test_scope.py b/tests/unit/src/sqlbuild/cli/commands/main/entry/test_scope.py index 577d080ba3..1ea840250c 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/entry/test_scope.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/entry/test_scope.py @@ -35,9 +35,9 @@ def record(request: ScopeCommandRequest) -> int: "scope", "model:orders", "--as-path", - "models/marts/orders.sql", + "sql/models/marts/orders.sql", "--defined-under", - "macros/shared/", + "sql/macros/shared/", "--kind", "macro", "--kind", @@ -71,8 +71,8 @@ def record(request: ScopeCommandRequest) -> int: assert received == [ ScopeCommandRequest( target="model:orders", - as_path="models/marts/orders.sql", - defined_under="macros/shared/", + as_path="sql/models/marts/orders.sql", + defined_under="sql/macros/shared/", kinds=("macro", "enum"), match="normal*", used_only=True, @@ -98,10 +98,10 @@ def record(request: ScopeCommandRequest) -> int: "test_case", ( ScopeArgumentMisuseCase("missing_target", ("scope",)), - ScopeArgumentMisuseCase("target_and_at", ("scope", "model:x", "--at", "models/x.sql")), + ScopeArgumentMisuseCase("target_and_at", ("scope", "model:x", "--at", "sql/models/x.sql")), ScopeArgumentMisuseCase( "move_without_target", - ("scope", "--at", "models/x.sql", "--as-path", "models/y.sql"), + ("scope", "--at", "sql/models/x.sql", "--as-path", "sql/models/y.sql"), ), ScopeArgumentMisuseCase("zero_page", ("scope", "model:x", "--page-size", "0")), ScopeArgumentMisuseCase("negative_depth", ("scope", "model:x", "--nearby-depth", "-1")), diff --git a/tests/unit/src/sqlbuild/cli/commands/main/entrypoint/helpers.py b/tests/unit/src/sqlbuild/cli/commands/main/entrypoint/helpers.py index 7447f03a7b..35b4b6d78d 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/entrypoint/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/entrypoint/helpers.py @@ -3,11 +3,11 @@ from __future__ import annotations from sqlbuild._native import EventExporterCommandScope, EventExporterDispatcher +from sqlbuild.event_sinks import CommandOutputStream from sqlbuild.runtime.output_capture.models import ( BoundCommandOutputSink, CommandOutputRecord, ) -from sqlbuild.sinks import CommandOutputStream def make_event_exporter_scope(*, records: list[CommandOutputRecord]) -> EventExporterCommandScope: diff --git a/tests/unit/src/sqlbuild/cli/commands/main/entrypoint/test_dispatch_with_output_capture.py b/tests/unit/src/sqlbuild/cli/commands/main/entrypoint/test_dispatch_with_output_capture.py index 882ecb69f3..01a5c50638 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/entrypoint/test_dispatch_with_output_capture.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/entrypoint/test_dispatch_with_output_capture.py @@ -8,15 +8,15 @@ import pytest from sqlbuild._native import INVOCATION_CONTEXT_ENV, EventExporterCommandScope -from sqlbuild.observability import ExecutionIdentity -from sqlbuild.runtime.output_capture.main.configured_output_capture_scope import ( - configured_output_capture_scope, -) -from sqlbuild.sinks import ( +from sqlbuild.event_sinks import ( CommandOutputRecord, CommandOutputValidationError, command_output_context, ) +from sqlbuild.observability import ExecutionIdentity +from sqlbuild.runtime.output_capture.main.configured_output_capture_scope import ( + configured_output_capture_scope, +) from tests.unit.src.sqlbuild.cli.commands.main.entrypoint._test_types import ( OutputCaptureWiringTestCase, ) diff --git a/tests/unit/src/sqlbuild/cli/commands/main/execution/helpers.py b/tests/unit/src/sqlbuild/cli/commands/main/execution/helpers.py index b969aa9ef6..5e3ab7c251 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/execution/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/execution/helpers.py @@ -18,7 +18,7 @@ def fail_build_discovery( ) -> Mock: """Make project discovery fail in a provider module and record debug resource reporting.""" - providers: Path = project_dir / "providers" + providers: Path = project_dir / "python" / "providers" providers.mkdir(parents=True) _ = (project_dir / "sqlbuild_project.toml").write_text( 'name = "shop"\nadapter = "duckdb"\n', encoding="utf-8" @@ -75,8 +75,8 @@ def configure_native_scenario_command( files: dict[str, str] = { "sqlbuild_project.toml": _SCENARIO_PROJECT_TOML, - "sources/raw.yml": _SCENARIO_SOURCES_YAML, - "models/orders.sql": _SCENARIO_MODEL_SQL, + "sql/sources/raw.yml": _SCENARIO_SOURCES_YAML, + "sql/models/orders.sql": _SCENARIO_MODEL_SQL, "tests/scenarios/orders_paid.sql": scenario_sql, } for relative_path, contents in files.items(): diff --git a/tests/unit/src/sqlbuild/cli/commands/main/execution/test_scenario_command.py b/tests/unit/src/sqlbuild/cli/commands/main/execution/test_scenario_command.py index 4db2347d6e..f7b1c665e1 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/execution/test_scenario_command.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/execution/test_scenario_command.py @@ -74,8 +74,9 @@ def test_given_scenario_compile_when_running_then_presentation_has_one_owner( assert test_case.expected_fragment in stream.getvalue() assert test_case.unexpected_fragment not in stream.getvalue() assert "PASS=0 FAIL=0 TOTAL=0" in stream.getvalue() - assert tuple(event.event_type for event in events[-2:]) == ( + assert tuple(event.event_type for event in events[-3:]) == ( "operation_started", + "invocation_phase", test_case.expected_terminal, ) diff --git a/tests/unit/src/sqlbuild/cli/commands/main/init/test_run.py b/tests/unit/src/sqlbuild/cli/commands/main/init/test_run.py index 61c8678a8b..b5e14be943 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/init/test_run.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/init/test_run.py @@ -18,40 +18,40 @@ description="creates blank project directories for all resource types", project_dir_name="demo-project", expected_directories=( - "models/staging", - "models/marts", - "schemas", - "sources", - "seeds", + "sql/models/staging", + "sql/models/marts", + "sql/schemas", + "sql/sources", + "sql/seeds", "python", - "hooks/sql", - "hooks/python", + "sql/hooks/sql", + "sql/hooks/python", "tests/unit", "tests/scenarios", - "functions/sql", - "functions/python", - "macros/sql", - "macros/python", - "audits/generic", - "audits/singular", + "sql/functions/sql", + "sql/functions/python", + "sql/macros/sql", + "sql/macros/python", + "sql/audits/generic", + "sql/audits/singular", ), expected_gitkeep_files=( - "models/staging/.gitkeep", - "models/marts/.gitkeep", - "schemas/.gitkeep", - "sources/.gitkeep", - "seeds/.gitkeep", - "python/.gitkeep", - "hooks/sql/.gitkeep", - "hooks/python/.gitkeep", + "sql/models/staging/.gitkeep", + "sql/models/marts/.gitkeep", + "sql/schemas/.gitkeep", + "sql/sources/.gitkeep", + "sql/seeds/.gitkeep", + "python/nodes/.gitkeep", + "sql/hooks/sql/.gitkeep", + "sql/hooks/python/.gitkeep", "tests/unit/.gitkeep", "tests/scenarios/.gitkeep", - "functions/sql/.gitkeep", - "functions/python/.gitkeep", - "macros/sql/.gitkeep", - "macros/python/.gitkeep", - "audits/generic/.gitkeep", - "audits/singular/.gitkeep", + "sql/functions/sql/.gitkeep", + "sql/functions/python/.gitkeep", + "sql/macros/sql/.gitkeep", + "sql/macros/python/.gitkeep", + "sql/audits/generic/.gitkeep", + "sql/audits/singular/.gitkeep", ), expected_config_fragment=( '[connections.developer]\ndatabase = "demo_project.duckdb"\n\n[settings]' @@ -61,12 +61,12 @@ "Project: demo_project", "Config: sqlbuild_project.toml", "Next steps:", - "1. Add sources to sources/", - "2. Add seeds to seeds/", - "3. Add Python loaders, assets, checks, and factories to python/", - "4. Add SQL hooks to hooks/sql/, Python hooks to hooks/python/", - "reusable audits to audits/generic/", - "standalone audits to audits/singular/", + "1. Add sources to sql/sources/", + "2. Add seeds to sql/seeds/", + "3. Add Python loaders, assets, checks, and factories to python/nodes/", + "4. Add SQL hooks to sql/hooks/sql/, Python hooks to sql/hooks/python/", + "reusable audits to sql/audits/generic/", + "standalone audits to sql/audits/singular/", "7. sqb compile", "8. sqb build", ), @@ -87,7 +87,7 @@ def test_given_empty_directory_when_running_init_then_scaffolds_project_director capsys: pytest.CaptureFixture[str], ) -> None: project_dir: Path = tmp_path / test_case.project_dir_name - project_dir.mkdir() + project_dir.mkdir(parents=True) monkeypatch.setattr(native_module, "update_sqlbuild_skills", lambda *, project_dir: None) use_plain_terminal(monkeypatch) @@ -131,7 +131,7 @@ def test_given_color_terminal_when_running_init_then_it_styles_heading( capsys: pytest.CaptureFixture[str], ) -> None: project_dir: Path = tmp_path / test_case.project_dir_name - project_dir.mkdir() + project_dir.mkdir(parents=True) monkeypatch.setattr(native_module, "update_sqlbuild_skills", lambda *, project_dir: None) use_color_terminal(monkeypatch) diff --git a/tests/unit/src/sqlbuild/cli/commands/main/playground/test_playground.py b/tests/unit/src/sqlbuild/cli/commands/main/playground/test_playground.py index dc319aaa8b..9d1a78f14d 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/playground/test_playground.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/playground/test_playground.py @@ -29,26 +29,26 @@ expected_files=( Path("README.md"), Path("sqlbuild_project.toml"), - Path("models/staging/stg_orders.sql"), - Path("models/marts/fact_orders.sql"), - Path("seeds/waffle_types.csv"), - Path("sources/raw.yml"), + Path("sql/models/staging/stg_orders.sql"), + Path("sql/models/marts/fact_orders.sql"), + Path("sql/seeds/waffle_types.csv"), + Path("sql/sources/raw.yml"), Path("tests/unit/test_daily_revenue_chain.sql"), - Path("models/marts/_sqlbuild/_audits/generic/expression_is_true.sql"), - Path("functions/sql/udf__is_completed_order.sql"), - Path("functions/sql/table_fn__customer_orders.sql"), - Path("python/loaders/waffle_sources.py"), - Path("macros/python/currency.py"), - Path("models/marts/_sqlbuild/_macros/python/currency.py"), - Path("models/marts/_sqlbuild/_macros/python/datetime.py"), - Path("materializations/partition_tracked.py"), + Path("sql/models/marts/_sqlbuild/_audits/generic/expression_is_true.sql"), + Path("sql/functions/sql/udf__is_completed_order.sql"), + Path("sql/functions/sql/table_fn__customer_orders.sql"), + Path("python/nodes/loaders/waffle_sources/loaders.py"), + Path("sql/macros/python/currency.py"), + Path("sql/models/marts/_sqlbuild/_macros/python/currency.py"), + Path("sql/models/marts/_sqlbuild/_macros/python/datetime.py"), + Path("python/materializations/partition_tracked.py"), ), unexpected_paths=( Path("target"), Path("sqlbuild_local.toml"), Path("waffle_shop_control.duckdb"), - Path("macros/__pycache__"), - Path("models/marts/_macros"), + Path("sql/macros/__pycache__"), + Path("sql/models/marts/_macros"), ), expected_file_fragments=( ( @@ -56,7 +56,7 @@ ("[connections.developer]", 'connection = "developer"'), ), ( - Path("materializations/partition_tracked.py"), + Path("python/materializations/partition_tracked.py"), ("from sqlbuild.adapter.contract.types import FrameworkType",), ), ), @@ -70,9 +70,9 @@ Path("definitions.py"), Path("waffle_shop/README.md"), Path("waffle_shop/sqlbuild_project.toml"), - Path("waffle_shop/models/marts/fact_orders.sql"), - Path("waffle_shop/sources/raw.yml"), - Path("waffle_shop/python/loaders/waffle_sources.py"), + Path("waffle_shop/sql/models/marts/fact_orders.sql"), + Path("waffle_shop/sql/sources/raw.yml"), + Path("waffle_shop/python/nodes/loaders/waffle_sources/loaders.py"), ), unexpected_paths=( Path("target"), @@ -84,11 +84,11 @@ expected_file_fragments=( (Path("waffle_shop/sqlbuild_project.toml"), ('default_target = "dev"',)), ( - Path("waffle_shop/sources/raw.yml"), + Path("waffle_shop/sql/sources/raw.yml"), ("managed: true",), ), ( - Path("waffle_shop/python/loaders/waffle_sources.py"), + Path("waffle_shop/python/nodes/loaders/waffle_sources/loaders.py"), ("def raw__customers(ctx", "def raw__orders(ctx"), ), ( @@ -106,9 +106,9 @@ Path("README.md"), Path("definitions.py"), Path("waffle_shop/sqlbuild_project.toml"), - Path("waffle_shop/models/marts/fact_orders.sql"), - Path("waffle_shop/sources/raw.yml"), - Path("waffle_shop/python/loaders/waffle_sources.py"), + Path("waffle_shop/sql/models/marts/fact_orders.sql"), + Path("waffle_shop/sql/sources/raw.yml"), + Path("waffle_shop/python/nodes/loaders/waffle_sources/loaders.py"), ), unexpected_paths=( Path("target"), @@ -142,10 +142,10 @@ expected_files=( Path("README.md"), Path("sqlbuild_project.toml"), - Path("models/fact_waffle_orders.sql"), - Path("models/customer_revenue.sql"), - Path("sources/raw.yml"), - Path("python/loaders/waffle_loaders.py"), + Path("sql/models/fact_waffle_orders.sql"), + Path("sql/models/customer_revenue.sql"), + Path("sql/sources/raw.yml"), + Path("python/nodes/loaders/waffle_loaders/loaders.py"), ), unexpected_paths=(Path("target"), Path("sqlbuild_local.toml")), expected_file_fragments=( @@ -153,16 +153,16 @@ Path("sqlbuild_project.toml"), ("[connections.developer]", 'connection = "developer"'), ), - (Path("sources/raw.yml"), ("managed: true",)), + (Path("sql/sources/raw.yml"), ("managed: true",)), ( - Path("python/loaders/waffle_loaders.py"), + Path("python/nodes/loaders/waffle_loaders/loaders.py"), ("def raw_orders(ctx):", "def raw_customers(ctx):"), ), ), unexpected_file_fragments=( - (Path("sources/raw.yml"), ("loader:",)), + (Path("sql/sources/raw.yml"), ("loader:",)), ( - Path("python/loaders/waffle_loaders.py"), + Path("python/nodes/loaders/waffle_loaders/loaders.py"), ("def load_raw_orders(ctx):", "def load_raw_customers(ctx):"), ), ), @@ -174,12 +174,14 @@ expected_files=( Path("README.md"), Path("sqlbuild_project.toml"), - Path("sources/raw.yml"), - Path("models/fact_orders.sql"), - Path("python/assets/orders_inputs.py"), - Path("python/loaders/orders.py"), - Path("python/assets/orders_export.py"), - Path("python/checks/orders_export.py"), + Path("sql/sources/raw.yml"), + Path("sql/models/fact_orders.sql"), + Path("python/nodes/assets/prepare_raw_orders/asset.py"), + Path("python/nodes/assets/optional_partner_feed/asset.py"), + Path("python/nodes/assets/export_window/asset.py"), + Path("python/nodes/loaders/orders/loader.py"), + Path("python/nodes/assets/orders_export/asset.py"), + Path("python/nodes/checks/orders_export/checks.py"), ), unexpected_paths=(Path("target"), Path("sqlbuild_local.toml")), expected_file_fragments=( @@ -188,20 +190,20 @@ ("[connections.developer]", 'connection = "developer"'), ), ( - Path("python/assets/orders_inputs.py"), - ( - "from sqlbuild.assets import SkipMode, asset", - "def prepare_raw_orders", - "SkipMode.SOFT", - "def export_window", - ), + Path("python/nodes/assets/prepare_raw_orders/asset.py"), + ("def prepare_raw_orders",), + ), + ( + Path("python/nodes/assets/optional_partner_feed/asset.py"), + ("from sqlbuild.assets import SkipMode, asset", "SkipMode.SOFT"), ), + (Path("python/nodes/assets/export_window/asset.py"), ("def export_window",)), ( - Path("python/loaders/orders.py"), + Path("python/nodes/loaders/orders/loader.py"), ("@loader(depends_on=(prepare_raw_orders,))", "def raw_orders"), ), ( - Path("python/assets/orders_export.py"), + Path("python/nodes/assets/orders_export/asset.py"), ( 'ctx.relation(model("fact_orders"))', "materialized=False", @@ -209,7 +211,7 @@ ), ), ( - Path("python/checks/orders_export.py"), + Path("python/nodes/checks/orders_export/checks.py"), ( "@check(depends_on=orders_export", "ctx.result_of(node_function=orders_export)", @@ -217,7 +219,7 @@ ), ), unexpected_file_fragments=( - (Path("python/assets/orders_inputs.py"), ("sqlbuild.compiler",)), + (Path("python/nodes/assets/prepare_raw_orders/asset.py"), ("sqlbuild.compiler",)), ), ), ], @@ -277,7 +279,7 @@ def test_given_existing_target_when_creating_playground_then_it_raises_user_erro tmp_path: Path, ) -> None: target_dir: Path = tmp_path / test_case.target_relative_path - target_dir.mkdir() + target_dir.mkdir(parents=True) with pytest.raises(CliUserError) as exc_info: _ = run_playground_command( diff --git a/tests/unit/src/sqlbuild/cli/commands/main/scope/test_scope.py b/tests/unit/src/sqlbuild/cli/commands/main/scope/test_scope.py index 17608c3ab7..64b211325a 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/scope/test_scope.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/scope/test_scope.py @@ -76,7 +76,7 @@ def test_given_verbose_flag_when_rendering_json_then_bytes_match_default_json( exit_code: int = run_scope_command( request=ScopeCommandRequest( target="model:orders", - as_path="models/marts/orders.sql", + as_path="sql/models/marts/orders.sql", json_output=True, verbose=verbose, ), @@ -120,14 +120,14 @@ def test_given_incomplete_index_when_running_then_prints_useful_payload_and_exit index: ScopeIndex = ScopeIndex(completeness=ScopeCompleteness(discovery=False)) stream: StringIO = StringIO() exit_code: int = run_scope_command( - request=ScopeCommandRequest(at="models/new.sql", json_output=True), + request=ScopeCommandRequest(at="sql/models/new.sql", json_output=True), load_scope_index=lambda **_kwargs: index, output_stream=stream, ) payload: dict[str, object] = json.loads(stream.getvalue()) resource: dict[str, object] = payload["resource"] assert exit_code == test_case.expected_exit_code - assert resource["path"] == "models/new.sql" + assert resource["path"] == "sql/models/new.sql" assert payload["complete"] is False @@ -140,14 +140,14 @@ def test_given_prospective_directory_with_trailing_slash_when_running_then_prese index: ScopeIndex = report_scope_lookup().index stream: StringIO = StringIO() exit_code: int = run_scope_command( - request=ScopeCommandRequest(at="models/staging/", json_output=True), + request=ScopeCommandRequest(at="sql/models/staging/", json_output=True), load_scope_index=lambda **_kwargs: index, output_stream=stream, ) payload: dict[str, object] = json.loads(stream.getvalue()) resource: dict[str, object] = payload["resource"] assert exit_code == test_case.expected_exit_code - assert resource["target"] == "models/staging/" + assert resource["target"] == "sql/models/staging/" assert resource["directory"] is True @@ -159,7 +159,7 @@ def test_given_existing_target_and_destination_when_running_then_text_has_move_s ) -> None: stream: StringIO = StringIO() exit_code: int = run_scope_command( - request=ScopeCommandRequest(target="model:orders", as_path="models/marts/orders.sql"), + request=ScopeCommandRequest(target="model:orders", as_path="sql/models/marts/orders.sql"), load_scope_index=lambda **_kwargs: report_scope_lookup().index, output_stream=stream, ) diff --git a/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/helpers.py b/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/helpers.py index 6c7eb7748f..c7979e2874 100644 --- a/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/helpers.py @@ -68,7 +68,7 @@ def build_progress_snapshot_plan_output( entry: ModelPlanEntry = ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.SNAPSHOT, action=PlanAction.SNAPSHOT, reason=PlanReason.FIRST_RUN, diff --git a/tests/unit/src/sqlbuild/cli/output/main/plan/helpers.py b/tests/unit/src/sqlbuild/cli/output/main/plan/helpers.py index 2e8c8438a8..dc7643b5fa 100644 --- a/tests/unit/src/sqlbuild/cli/output/main/plan/helpers.py +++ b/tests/unit/src/sqlbuild/cli/output/main/plan/helpers.py @@ -79,7 +79,7 @@ def build_model_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=materialization_type, action=action, reason=reason, @@ -179,7 +179,7 @@ def build_plan_provider_usage( consumer_name: str = "raw_orders", parameter_name: str = "marker_provider", annotation_class_name: str | None = "MarkerProvider", - annotation_module: str | None = "providers.marker", + annotation_module: str | None = "python.providers.marker", ) -> PlanProviderUsage: return PlanProviderUsage( provider_name=provider_name, @@ -196,7 +196,7 @@ def build_discovered_provider_usage( provider_name: str = "marker_provider", parameter_name: str = "marker_provider", annotation_class_name: str | None = "MarkerProvider", - annotation_module: str | None = "providers.marker", + annotation_module: str | None = "python.providers.marker", ) -> DiscoveredProviderUsage: return DiscoveredProviderUsage( provider_name=provider_name, @@ -237,7 +237,7 @@ def build_seed_entry(*, name: str, reason: PlanReason = PlanReason.FIRST_RUN) -> destination=CompiledRelationLocation( database=None, schema="main", name=name, qualified_name=f"main.{name}" ), - file_path=Path(f"seeds/{name}.csv"), + file_path=Path(f"sql/seeds/{name}.csv"), columns=(), csv_settings=SeedCsvSettings(), reason=reason, @@ -256,7 +256,7 @@ def build_function_entry( return FunctionPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.UDF, name=name), name=name, - relative_path=Path(f"functions/{language.value}/{name}.sql"), + relative_path=Path(f"sql/functions/{language.value}/{name}.sql"), destination=CompiledRelationLocation( database=None, schema="main", name=name, qualified_name=f"main.{name}" ), diff --git a/tests/unit/src/sqlbuild/cli/output/main/plan/test_plan_text.py b/tests/unit/src/sqlbuild/cli/output/main/plan/test_plan_text.py index 4cffc3d982..49783efbb9 100644 --- a/tests/unit/src/sqlbuild/cli/output/main/plan/test_plan_text.py +++ b/tests/unit/src/sqlbuild/cli/output/main/plan/test_plan_text.py @@ -695,9 +695,9 @@ { "dependencies": [ { - "module": "python.tasks.helpers", + "module": "python.nodes.tasks.helpers", "qualname": "order_label", - "source_path": "python/tasks/helpers.py", + "source_path": "python/nodes/tasks/helpers.py", "source_text": "def order_label():\n return 'old'\n", } ] @@ -708,9 +708,9 @@ { "dependencies": [ { - "module": "python.tasks.helpers", + "module": "python.nodes.tasks.helpers", "qualname": "order_label", - "source_path": "python/tasks/helpers.py", + "source_path": "python/nodes/tasks/helpers.py", "source_text": "def order_label():\n return 'new'\n", } ] @@ -728,7 +728,7 @@ "dependency diff:", "- return 1", "+ return 2", - "python/tasks/helpers.py :: python.tasks.helpers :: order_label", + "python/nodes/tasks/helpers.py :: python.nodes.tasks.helpers :: order_label", "- return 'old'", "+ return 'new'", ), @@ -1441,9 +1441,9 @@ def test_given_plan_output_when_formatting_then_contains_expected_fragments( { "dependencies": [ { - "module": "python.tasks.helpers", + "module": "python.nodes.tasks.helpers", "qualname": "order_label", - "source_path": "python/tasks/helpers.py", + "source_path": "python/nodes/tasks/helpers.py", "source_text": "def order_label():\n return 'old'\n", } ] @@ -1454,9 +1454,9 @@ def test_given_plan_output_when_formatting_then_contains_expected_fragments( { "dependencies": [ { - "module": "python.tasks.helpers", + "module": "python.nodes.tasks.helpers", "qualname": "order_label", - "source_path": "python/tasks/helpers.py", + "source_path": "python/nodes/tasks/helpers.py", "source_text": "def order_label():\n return 'new'\n", } ] @@ -1466,7 +1466,7 @@ def test_given_plan_output_when_formatting_then_contains_expected_fragments( ), ), expected_fragments=( - "\033[2m # python/tasks/helpers.py :: python.tasks.helpers :: order_label\033[0m", + "\033[2m # python/nodes/tasks/helpers.py :: python.nodes.tasks.helpers :: order_label\033[0m", "\033[38;5;167m - return 'old'\033[0m", "\033[32m + return 'new'\033[0m", ), diff --git a/tests/unit/src/sqlbuild/cli/output/main/plan_json/test_plan_json.py b/tests/unit/src/sqlbuild/cli/output/main/plan_json/test_plan_json.py index f0aa36e0e6..6b8d47b325 100644 --- a/tests/unit/src/sqlbuild/cli/output/main/plan_json/test_plan_json.py +++ b/tests/unit/src/sqlbuild/cli/output/main/plan_json/test_plan_json.py @@ -592,7 +592,7 @@ def test_given_direct_diagnostics_policy_when_formatting_plan_json_then_evidence { "module": "tasks.helpers", "qualname": "order_label", - "source_path": "python/tasks/helpers.py", + "source_path": "python/nodes/tasks/helpers.py", "source_text": "def order_label():\n return 'old'\n", } ] @@ -605,7 +605,7 @@ def test_given_direct_diagnostics_policy_when_formatting_plan_json_then_evidence { "module": "tasks.helpers", "qualname": "order_label", - "source_path": "python/tasks/helpers.py", + "source_path": "python/nodes/tasks/helpers.py", "source_text": "def order_label():\n return 'new'\n", } ] @@ -621,7 +621,7 @@ def test_given_direct_diagnostics_policy_when_formatting_plan_json_then_evidence '"dependency_diff"', '"- return 1"', '"+ return 2"', - "python/tasks/helpers.py :: tasks.helpers :: order_label", + "python/nodes/tasks/helpers.py :: tasks.helpers :: order_label", "\"- return 'old'\"", "\"+ return 'new'\"", ), @@ -656,7 +656,7 @@ def test_given_direct_diagnostics_policy_when_formatting_plan_json_then_evidence '"name": "publish_orders"', '"parameter": "marker_provider"', '"class_name": "MarkerProvider"', - '"module": "providers.marker"', + '"module": "python.providers.marker"', ), ), ], diff --git a/tests/unit/src/sqlbuild/cli/target_artifacts/main/write_runtime_target/test_runtime_target_writer.py b/tests/unit/src/sqlbuild/cli/target_artifacts/main/write_runtime_target/test_runtime_target_writer.py index e11cecf15f..f8756ddbcd 100644 --- a/tests/unit/src/sqlbuild/cli/target_artifacts/main/write_runtime_target/test_runtime_target_writer.py +++ b/tests/unit/src/sqlbuild/cli/target_artifacts/main/write_runtime_target/test_runtime_target_writer.py @@ -22,15 +22,15 @@ TargetWriterTestCase( description="writes runtime SQL from executed statements", expected_files={ - "run/models/staging/orders.sql": ( + "run/sql/models/staging/orders.sql": ( "DROP TABLE IF EXISTS analytics.orders__staging;\n\n" "CREATE OR REPLACE TABLE analytics.orders__staging AS SELECT 1 AS order_id;\n" ), - "run/functions/sql/is_completed_order.sql": ( + "run/sql/functions/sql/is_completed_order.sql": ( "CREATE OR REPLACE FUNCTION analytics.is_completed_order" "(order_status VARCHAR) RETURNS BOOLEAN;\n" ), - "run/functions/python/is_completed_order_py.sql": ( + "run/sql/functions/python/is_completed_order_py.sql": ( "REGISTER PYTHON FUNCTION analytics.is_completed_order_py" "(VARCHAR) RETURNS BOOLEAN;\n" ), @@ -39,19 +39,19 @@ TargetWriterTestCase( description="preserves existing runtime files outside current result scope", initial_files={ - "run/models/marts/fact_orders.sql": "SELECT 1;\n", + "run/sql/models/marts/fact_orders.sql": "SELECT 1;\n", }, expected_files={ - "run/models/marts/fact_orders.sql": "SELECT 1;\n", - "run/models/staging/orders.sql": ( + "run/sql/models/marts/fact_orders.sql": "SELECT 1;\n", + "run/sql/models/staging/orders.sql": ( "DROP TABLE IF EXISTS analytics.orders__staging;\n\n" "CREATE OR REPLACE TABLE analytics.orders__staging AS SELECT 1 AS order_id;\n" ), - "run/functions/sql/is_completed_order.sql": ( + "run/sql/functions/sql/is_completed_order.sql": ( "CREATE OR REPLACE FUNCTION analytics.is_completed_order" "(order_status VARCHAR) RETURNS BOOLEAN;\n" ), - "run/functions/python/is_completed_order_py.sql": ( + "run/sql/functions/python/is_completed_order_py.sql": ( "REGISTER PYTHON FUNCTION analytics.is_completed_order_py" "(VARCHAR) RETURNS BOOLEAN;\n" ), diff --git a/tests/unit/src/sqlbuild/compiler/auditing/main/test_parse_audit_instance.py b/tests/unit/src/sqlbuild/compiler/auditing/main/test_parse_audit_instance.py index c0c373ac63..5af3d9d5df 100644 --- a/tests/unit/src/sqlbuild/compiler/auditing/main/test_parse_audit_instance.py +++ b/tests/unit/src/sqlbuild/compiler/auditing/main/test_parse_audit_instance.py @@ -39,7 +39,7 @@ def test_given_audit_mapping_when_parsing_then_always_run_is_reserved_option( ) -> None: result: SchemaAuditInstance = parse_audit_instance( raw_audit=test_case.raw_audit, - file_path=Path("models/orders.sql"), + file_path=Path("sql/models/orders.sql"), label="model orders", error_class=ValueError, ) @@ -84,7 +84,7 @@ def test_given_invalid_audit_option_when_parsing_then_raises_clear_error( with pytest.raises(ValueError) as error_info: parse_audit_instance( raw_audit=test_case.raw_audit, - file_path=Path("models/orders.sql"), + file_path=Path("sql/models/orders.sql"), label="model orders", error_class=ValueError, ) @@ -112,19 +112,19 @@ def test_given_all_directional_thresholds_when_parsing_then_typed_policies_are_r "evidence_limit": 7, } }, - file_path=Path("models/orders.sql"), + file_path=Path("sql/models/orders.sql"), label="model orders", error_class=ValueError, ) above: SchemaAuditInstance = parse_audit_instance( raw_audit={"rate": {"thresholds": {"error": {"above": 10.5}}}}, - file_path=Path("models/orders.sql"), + file_path=Path("sql/models/orders.sql"), label="model orders", error_class=ValueError, ) outside: SchemaAuditInstance = parse_audit_instance( raw_audit={"rate": {"thresholds": {"warn": {"outside": (90, 110)}}}}, - file_path=Path("models/orders.sql"), + file_path=Path("sql/models/orders.sql"), label="model orders", error_class=ValueError, ) @@ -164,14 +164,14 @@ def test_given_invalid_measurement_policy_options_when_parsing_then_clear_errors with pytest.raises(ValueError, match=test_case.expected_error_fragment): parse_audit_instance( raw_audit=test_case.raw_audit, - file_path=Path("models/orders.sql"), + file_path=Path("sql/models/orders.sql"), label="model orders", error_class=ValueError, ) with pytest.raises(ValueError, match="outside threshold requires two numeric values"): parse_audit_instance( raw_audit={"rate": {"thresholds": {"warn": {"outside": (90,)}}}}, - file_path=Path("models/orders.sql"), + file_path=Path("sql/models/orders.sql"), label="model orders", error_class=ValueError, ) @@ -200,7 +200,7 @@ def test_given_audit_meta_when_parsing_then_meta_is_not_an_argument( ) -> None: result: SchemaAuditInstance = parse_audit_instance( raw_audit=test_case.raw_audit, - file_path=Path("models/orders.sql"), + file_path=Path("sql/models/orders.sql"), label="model orders", error_class=ValueError, ) @@ -232,7 +232,7 @@ def test_given_invalid_audit_meta_when_parsing_then_compile_error_names_the_valu with pytest.raises(ValueError, match=test_case.expected_error_fragment): parse_audit_instance( raw_audit=test_case.raw_audit, - file_path=Path("models/orders.sql"), + file_path=Path("sql/models/orders.sql"), label="model orders", error_class=ValueError, ) diff --git a/tests/unit/src/sqlbuild/compiler/auditing/main/test_parse_audit_instances.py b/tests/unit/src/sqlbuild/compiler/auditing/main/test_parse_audit_instances.py index 3466972905..7c1ed589b7 100644 --- a/tests/unit/src/sqlbuild/compiler/auditing/main/test_parse_audit_instances.py +++ b/tests/unit/src/sqlbuild/compiler/auditing/main/test_parse_audit_instances.py @@ -40,7 +40,7 @@ def test_given_audit_list_when_parsing_then_returns_audit_instances( ) -> None: result: tuple[SchemaAuditInstance, ...] = parse_audit_instances( raw_audits=test_case.raw_audits, - file_path=Path("models/orders.yml"), + file_path=Path("sql/models/orders.yml"), label="model orders", error_class=ValueError, null_as_empty=test_case.null_as_empty, @@ -56,13 +56,13 @@ def test_given_audit_list_when_parsing_then_returns_audit_instances( description="rejects null when null is not empty", raw_audits=None, null_as_empty=False, - expected_message="models/orders.yml model orders audits must be a list", + expected_message="sql/models/orders.yml model orders audits must be a list", ), ParseAuditInstancesErrorTestCase( description="rejects a mapping", raw_audits={"not_null": {}}, null_as_empty=True, - expected_message="models/orders.yml model orders audits must be a list", + expected_message="sql/models/orders.yml model orders audits must be a list", ), ], ids=lambda case: case.description, @@ -73,7 +73,7 @@ def test_given_invalid_audit_list_when_parsing_then_raises_injected_error( with pytest.raises(ValueError) as error: parse_audit_instances( raw_audits=test_case.raw_audits, - file_path=Path("models/orders.yml"), + file_path=Path("sql/models/orders.yml"), label="model orders", error_class=ValueError, null_as_empty=test_case.null_as_empty, diff --git a/tests/unit/src/sqlbuild/compiler/authored_values/main/helpers.py b/tests/unit/src/sqlbuild/compiler/authored_values/main/helpers.py index d755484b8b..babfdd6cc5 100644 --- a/tests/unit/src/sqlbuild/compiler/authored_values/main/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/authored_values/main/helpers.py @@ -4,7 +4,7 @@ from sqlbuild._native import optional_named_bool, optional_named_string -AUTHORED_VALUES_FILE_PATH: Path = Path("models/orders.yml") +AUTHORED_VALUES_FILE_PATH: Path = Path("sql/models/orders.yml") AUTHORED_VALUES_LABEL: str = "model 'orders'" diff --git a/tests/unit/src/sqlbuild/compiler/authored_values/main/test_authored_values.py b/tests/unit/src/sqlbuild/compiler/authored_values/main/test_authored_values.py index 7537c2bc08..a6e43c4dba 100644 --- a/tests/unit/src/sqlbuild/compiler/authored_values/main/test_authored_values.py +++ b/tests/unit/src/sqlbuild/compiler/authored_values/main/test_authored_values.py @@ -57,13 +57,13 @@ def test_given_authored_value_when_parsing_then_returns_expected_value( description="named string rejects non-string value", parse=parse_named_string, raw_value=3, - expected_message="models/orders.yml model 'orders' 'setting' must be a non-empty string", + expected_message="sql/models/orders.yml model 'orders' 'setting' must be a non-empty string", ), AuthoredValueErrorTestCase( description="named bool rejects integer value", parse=parse_named_bool_default_false, raw_value=1, - expected_message="models/orders.yml model 'orders' 'setting' must be a boolean", + expected_message="sql/models/orders.yml model 'orders' 'setting' must be a boolean", ), ], ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/config/helpers.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/config/helpers.py index e22b83aaab..69f2cbd3c8 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/config/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/config/helpers.py @@ -78,7 +78,7 @@ def validate_natively( # noqa: PLR0913 ) outcome: int | _native.NativeConfigError | None = validator.validate( config.values, - (model_name, query_sql, f"models/{model_name}.sql"), + (model_name, query_sql, f"sql/models/{model_name}.sql"), ( [("ref", name, False) for name in names], declared_columns, diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/config/test_model_config_reuse.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/config/test_model_config_reuse.py index ca5b50acae..383429634c 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/config/test_model_config_reuse.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/config/test_model_config_reuse.py @@ -55,7 +55,7 @@ def test_given_static_column_contracts_when_attaching_then_values_are_not_aliase time_travel_retention = "14d" """.strip() + "\n", - "models/customers.sql": """ + "sql/models/customers.sql": """ MODEL (description "Test model customers.", columns (customer_id (type INTEGER, nullable false, description "Customer id")), ); @@ -63,7 +63,7 @@ def test_given_static_column_contracts_when_attaching_then_values_are_not_aliase SELECT 1 AS customer_id """.strip() + "\n", - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", columns (order_id (type BIGINT, nullable true, description "Order id")), ); @@ -127,7 +127,7 @@ def test_given_templated_columns_when_attaching_then_resolves_each_model_context identifier_type = "INTEGER" """.strip() + "\n", - "models/customers.sql": """ + "sql/models/customers.sql": """ MODEL (description "Test model customers.", columns ( customer_id ( @@ -140,7 +140,7 @@ def test_given_templated_columns_when_attaching_then_resolves_each_model_context SELECT 1 AS customer_id """.strip() + "\n", - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", columns ( order_id ( diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/helpers.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/helpers.py index 0ae5d088b6..c8f9f9ca80 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/helpers.py @@ -155,7 +155,7 @@ def macro(*, _output: str = output) -> str: resources=( ResourceRecord( model_identity, - "models/marts/finance/orders.sql", + "sql/models/marts/finance/orders.sql", OwnershipRoot("models", resource_kind=ResourceKind.MODEL), ), ), @@ -171,7 +171,7 @@ def macro(*, _output: str = output) -> str: def build_loaded_macros(tmp_path: Path, macro_file_contents: str) -> dict[str, LoadedMacro]: - macros_dir: Path = tmp_path / "macros" / "python" + macros_dir: Path = tmp_path / "sql" / "macros" / "python" macros_dir.mkdir(parents=True, exist_ok=True) macro_file_path: Path = macros_dir / "common.py" macro_file_path.write_text(macro_file_contents, encoding="utf-8") @@ -179,7 +179,7 @@ def build_loaded_macros(tmp_path: Path, macro_file_contents: str) -> dict[str, L ( DiscoveredMacroFile( file_path=macro_file_path, - relative_path=Path("macros/python/common.py"), + relative_path=Path("sql/macros/python/common.py"), contents=macro_file_contents, ), ) @@ -253,7 +253,7 @@ def _compiled_direct_tested_names(payload: object) -> tuple[str, ...]: def singular_audit_files(*, base: dict[str, str], sql: str) -> dict[str, str]: """Return project files with one top-level singular audit over the given SQL.""" - return base | {"audits/singular/check.sql": f"AUDIT ();\n{sql}"} + return base | {"sql/audits/singular/check.sql": f"AUDIT ();\n{sql}"} def model_header(*, key: str, value: str) -> str: @@ -318,7 +318,7 @@ def expand_typed_macro_sql( loaded_macros: dict[str, LoadedMacro] = build_loaded_macros(tmp_path, macro_file_contents) return expand_sql_macros( sql=sql, - file_path=tmp_path / "models" / "order_summary.sql", + file_path=tmp_path / "sql" / "models" / "order_summary.sql", loaded_macros=loaded_macros, macro_context=MacroContext( adapter_name="duckdb", @@ -393,19 +393,29 @@ def python_check_source(*, depends_on: str, body: str) -> str: ) -def python_loader_source(*, depends_on: str, body: str) -> str: - """Return loaders ``raw_regions`` and ``raw_customers``; the latter runs ``body``.""" +RAW_REGIONS_LOADER_PATH: str = "python/nodes/loaders/raw_regions/loader.py" +RAW_CUSTOMERS_LOADER_PATH: str = "python/nodes/loaders/raw_customers/loader.py" - return ( - "from sqlbuild.loaders import loader\n\n\n" - "@loader\n" - "def raw_regions(ctx):\n" - " '''Test loader raw_regions.'''\n return [{'id': 1}]\n\n\n" - f"@loader(depends_on=[{depends_on}])\n" - "def raw_customers(ctx):\n" - f"{body}" - " return [{'id': 1}]\n" - ) + +def python_loader_files(*, depends_on: str, body: str) -> dict[str, str]: + """Return loaders ``raw_regions`` and ``raw_customers``, each in its unit folder.""" + + return { + RAW_REGIONS_LOADER_PATH: ( + "from sqlbuild.loaders import loader\n\n\n" + "@loader\n" + "def raw_regions(ctx):\n" + " '''Test loader raw_regions.'''\n return [{'id': 1}]\n" + ), + RAW_CUSTOMERS_LOADER_PATH: ( + "from sqlbuild.loaders import loader\n\n" + "from python.nodes.loaders.raw_regions.loader import raw_regions\n\n\n" + f"@loader(depends_on=[{depends_on}])\n" + "def raw_customers(ctx):\n" + f"{body}" + " return [{'id': 1}]\n" + ), + } def collect_typed_macro_violations( @@ -434,14 +444,14 @@ def write_scoped_macro_orders_project(project_dir: Path) -> None: (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model: Path = project_dir / "models" / "orders.sql" + model: Path = project_dir / "sql" / "models" / "orders.sql" model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\nSELECT 1 AS order_id WHERE @py.order_filter("1")\n', encoding="utf-8", ) - (project_dir / "macros" / "python").mkdir(parents=True) - (project_dir / "macros" / "python" / "order_filter.py").write_text( + (project_dir / "sql" / "macros" / "python").mkdir(parents=True) + (project_dir / "sql" / "macros" / "python" / "order_filter.py").write_text( 'def order_filter(column: str) -> str:\n return f"{column} > 0"\n', encoding="utf-8" ) tests_dir: Path = project_dir / "tests" / "unit" diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_assembly.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_assembly.py index 05602f383f..244bd6e040 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_assembly.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_assembly.py @@ -38,6 +38,7 @@ from tests.unit.src.sqlbuild.compiler.compile._test_helpers import ( base_repo_files, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files if TYPE_CHECKING: from sqlbuild._native import CompileInputsView @@ -62,7 +63,7 @@ schema = "analytics" """.strip() + "\n", - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", columns ( order_id (type VARCHAR), @@ -73,7 +74,7 @@ select * from __source("raw_orders") """.strip() + "\n", - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -81,7 +82,7 @@ table: orders """.strip() + "\n", - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: country_codes description: Test seed country_codes. @@ -90,8 +91,8 @@ type: VARCHAR """.strip() + "\n", - "seeds/country_codes.csv": "code\nUS\n", - "models/staging/_sqlbuild/_audits/generic/not_null.sql": "AUDIT ();\n\n" + "sql/seeds/country_codes.csv": "code\nUS\n", + "sql/models/staging/_sqlbuild/_audits/generic/not_null.sql": "AUDIT ();\n\n" 'SELECT @column FROM __ref("@model") WHERE @column IS NULL\n', "tests/unit/orders_test.sql": """ TEST (); @@ -139,8 +140,8 @@ repo_files=base_repo_files() | { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS order_id\n", - "seeds/schema.yml": """ + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS order_id\n", + "sql/seeds/schema.yml": """ seeds: - name: order_codes description: Test seed order_codes. @@ -149,8 +150,8 @@ type: INTEGER """.strip() + "\n", - "seeds/order_codes.csv": "order_id\n1\n", - "audits/singular/orders.sql": """ + "sql/seeds/order_codes.csv": "order_id\n1\n", + "sql/audits/singular/orders.sql": """ AUDIT (always_run true); SELECT order_id FROM __ref("orders") @@ -214,7 +215,7 @@ database = "${ENV:LOCAL_TARGET_DB}_${project}" """.strip() + "\n", - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: country_codes description: Test seed country_codes. @@ -223,7 +224,7 @@ type: VARCHAR """.strip() + "\n", - "seeds/country_codes.csv": "code\nUS\n", + "sql/seeds/country_codes.csv": "code\nUS\n", }, expected_model_names=(), expected_model_deps=(), @@ -268,7 +269,7 @@ schema = "env_schema" """.strip() + "\n", - "seeds/lookups.yml": """ + "sql/seeds/lookups.yml": """ seeds: - name: country_codes description: Test seed country_codes. @@ -279,7 +280,7 @@ type: VARCHAR """.strip() + "\n", - "seeds/country_codes.csv": "code\nUS\n", + "sql/seeds/country_codes.csv": "code\nUS\n", }, expected_model_names=(), expected_model_deps=(), @@ -306,13 +307,13 @@ repo_files=base_repo_files() | { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "macros/python/status.py": ( + "sql/macros/python/status.py": ( 'def normalize_status(value):\n return f"LOWER(TRIM({value}))"\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\nSELECT @py.normalize_status(\"' PAID '\") AS status\n" ), - "models/customers.sql": "MODEL (description 'Test model customers.');\n\nSELECT 'active' AS status\n", + "sql/models/customers.sql": "MODEL (description 'Test model customers.');\n\nSELECT 'active' AS status\n", "tests/unit/test_normalize_status.sql": """ TEST (mode macro, name "normalizes_status"); @@ -361,7 +362,7 @@ suffix = "dev" """.strip() + "\n", - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -369,7 +370,9 @@ write_strategy: table """.strip() + "\n", - "python/loaders/raw_orders.py": """ + **node_module_files( + "python/nodes/loaders/raw_orders.py", + """ from sqlbuild.loaders import loader @loader @@ -377,7 +380,8 @@ def raw_orders(ctx): '''Test loader raw_orders.''' return [{"id": 1}] """.strip() - + "\n", + + "\n", + ), }, expected_model_names=(), expected_model_deps=(), @@ -398,7 +402,7 @@ def raw_orders(ctx): repo_files=base_repo_files() | { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "functions/sql/format_cents.sql": """ + "sql/functions/sql/format_cents.sql": """ FUNCTION (description "Test function format_cents.", arguments (amount_cents INTEGER), returns VARCHAR, @@ -407,10 +411,10 @@ def raw_orders(ctx): '$' || CAST(amount_cents / 100 AS VARCHAR) """.strip() + "\n", - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\nSELECT __udf("format_cents")(1250) AS formatted\n' ), - "models/customers.sql": "MODEL (description 'Test model customers.');\n\nSELECT 'active' AS status\n", + "sql/models/customers.sql": "MODEL (description 'Test model customers.');\n\nSELECT 'active' AS status\n", "tests/unit/test_format_cents.sql": """ TEST (mode udf, name "formats_cents"); @@ -449,7 +453,7 @@ def raw_orders(ctx): repo_files=base_repo_files() | { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "functions/sql/customer_orders.sql": """ + "sql/functions/sql/customer_orders.sql": """ FUNCTION (description "Test function customer_orders.", arguments (p_customer_id INTEGER), returns table ( @@ -461,7 +465,7 @@ def raw_orders(ctx): SELECT p_customer_id AS customer_id, 1 AS order_id """.strip() + "\n", - "models/customer_order_summary.sql": ( + "sql/models/customer_order_summary.sql": ( "MODEL (description 'Test model customer_order_summary.');\n\nSELECT customer_id, order_id " 'FROM __table_fn("customer_orders")(42)\n' ), @@ -604,7 +608,7 @@ def test_given_named_generic_audit_instances_when_assembling_then_each_name_is_p tmp_path, base_repo_files() | { - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", audits [ expression_is_true (name "positive_revenue", expression "revenue > 0"), @@ -615,7 +619,7 @@ def test_given_named_generic_audit_instances_when_assembling_then_each_name_is_p SELECT 1 AS revenue """.strip() + "\n", - "audits/generic/expression_is_true.sql": """ + "sql/audits/generic/expression_is_true.sql": """ AUDIT (); SELECT * FROM @relation WHERE NOT (@expression) @@ -675,7 +679,7 @@ def test_given_preserved_target_when_assembling_seed_then_declaration_remains_ph schema = "physical_schema" """.strip() + "\n", - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: country_codes description: Test seed country_codes. @@ -691,8 +695,8 @@ def test_given_preserved_target_when_assembling_seed_then_declaration_remains_ph type: VARCHAR """.strip() + "\n", - "seeds/country_codes.csv": "code\nUS\n", - "seeds/currencies.csv": "code\nUSD\n", + "sql/seeds/country_codes.csv": "code\nUS\n", + "sql/seeds/currencies.csv": "code\nUSD\n", }, ) discovered: DiscoveredProjectInputs = discover_project_inputs(project_dir=tmp_path) @@ -965,8 +969,8 @@ def test_given_sql_hooks_when_assembling_then_applies_adapter_aware_validation( tmp_path, { "sqlbuild_project.toml": 'name = "demo"\nadapter = "sqlserver"\n', - "models/orders.sql": test_case.model_sql, - "hooks/sql/vendor_hook.sql": test_case.named_hook_sql, + "sql/models/orders.sql": test_case.model_sql, + "sql/hooks/sql/vendor_hook.sql": test_case.named_hook_sql, }, ) discovered: DiscoveredProjectInputs = discover_project_inputs(project_dir=tmp_path) diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_attached_audit_gates.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_attached_audit_gates.py index 64a06f3b1f..81fe2b2f67 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_attached_audit_gates.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_attached_audit_gates.py @@ -44,42 +44,48 @@ AttachedAuditGateTestCase( "model audit reading a sibling model makes the model wait for it", { - "audits/generic/code_check.sql": gate_audit(read='__ref("allowed")'), - "models/allowed.sql": gate_model(sql="SELECT 'A' AS code"), - "models/orders.sql": gate_model(sql="SELECT 'A' AS code", header=_AUDITED_HEADER), + "sql/audits/generic/code_check.sql": gate_audit(read='__ref("allowed")'), + "sql/models/allowed.sql": gate_model(sql="SELECT 'A' AS code"), + "sql/models/orders.sql": gate_model( + sql="SELECT 'A' AS code", header=_AUDITED_HEADER + ), }, (("orders", "allowed"),), ), AttachedAuditGateTestCase( "source audit reading an unrelated model makes the source's dependants wait", { - "audits/generic/code_check.sql": gate_audit(read='__ref("allowed")'), - "sources/raw.yml": _SOURCES_WITH_AUDIT, - "models/allowed.sql": gate_model(sql="SELECT 'A' AS code"), - "models/staged_orders.sql": gate_model(sql='SELECT * FROM __source("raw_orders")'), - "models/other_orders.sql": gate_model(sql='SELECT * FROM __source("raw_orders")'), + "sql/audits/generic/code_check.sql": gate_audit(read='__ref("allowed")'), + "sql/sources/raw.yml": _SOURCES_WITH_AUDIT, + "sql/models/allowed.sql": gate_model(sql="SELECT 'A' AS code"), + "sql/models/staged_orders.sql": gate_model( + sql='SELECT * FROM __source("raw_orders")' + ), + "sql/models/other_orders.sql": gate_model( + sql='SELECT * FROM __source("raw_orders")' + ), }, (("other_orders", "allowed"), ("staged_orders", "allowed")), ), AttachedAuditGateTestCase( "seed audit reading another seed makes the seed wait for it", { - "audits/generic/code_check.sql": gate_audit(read='__seed("allowed_codes")'), - "seeds/order_codes.yml": _SEED_WITH_AUDIT, - "seeds/order_codes.csv": "code\nA\n", - "seeds/allowed_codes.yml": _ALLOWED_SEED, - "seeds/allowed_codes.csv": "code\nA\n", + "sql/audits/generic/code_check.sql": gate_audit(read='__seed("allowed_codes")'), + "sql/seeds/order_codes.yml": _SEED_WITH_AUDIT, + "sql/seeds/order_codes.csv": "code\nA\n", + "sql/seeds/allowed_codes.yml": _ALLOWED_SEED, + "sql/seeds/allowed_codes.csv": "code\nA\n", }, (("order_codes", "allowed_codes"),), ), AttachedAuditGateTestCase( "source audit triggered by another audit's read gates that triggering model", { - "audits/generic/code_check.sql": gate_audit(read='__ref("valid_codes")'), - "audits/generic/order_check.sql": gate_audit(read='__source("raw_orders")'), - "sources/raw.yml": _SOURCES_WITH_AUDIT, - "models/valid_codes.sql": gate_model(sql="SELECT 'A' AS code"), - "models/orders.sql": gate_model( + "sql/audits/generic/code_check.sql": gate_audit(read='__ref("valid_codes")'), + "sql/audits/generic/order_check.sql": gate_audit(read='__source("raw_orders")'), + "sql/sources/raw.yml": _SOURCES_WITH_AUDIT, + "sql/models/valid_codes.sql": gate_model(sql="SELECT 'A' AS code"), + "sql/models/orders.sql": gate_model( sql="SELECT 'A' AS code", header=_ORDER_CHECK_HEADER ), }, @@ -106,9 +112,11 @@ def test_given_attached_audit_reading_another_resource_when_compiling_then_it_ad AttachedAuditGateCycleTestCase( "model audit reading a model built from its target", { - "audits/generic/code_check.sql": gate_audit(read='__ref("orders_mart")'), - "models/orders.sql": gate_model(sql="SELECT 'A' AS code", header=_AUDITED_HEADER), - "models/orders_mart.sql": gate_model(sql='SELECT * FROM __ref("orders")'), + "sql/audits/generic/code_check.sql": gate_audit(read='__ref("orders_mart")'), + "sql/models/orders.sql": gate_model( + sql="SELECT 'A' AS code", header=_AUDITED_HEADER + ), + "sql/models/orders_mart.sql": gate_model(sql='SELECT * FROM __ref("orders")'), }, ( "[P005]", @@ -119,9 +127,11 @@ def test_given_attached_audit_reading_another_resource_when_compiling_then_it_ad AttachedAuditGateCycleTestCase( "source audit reading a model built from the source", { - "audits/generic/code_check.sql": gate_audit(read='__ref("staged_orders")'), - "sources/raw.yml": _SOURCES_WITH_AUDIT, - "models/staged_orders.sql": gate_model(sql='SELECT * FROM __source("raw_orders")'), + "sql/audits/generic/code_check.sql": gate_audit(read='__ref("staged_orders")'), + "sql/sources/raw.yml": _SOURCES_WITH_AUDIT, + "sql/models/staged_orders.sql": gate_model( + sql='SELECT * FROM __source("raw_orders")' + ), }, ( "[P005]", @@ -132,10 +142,12 @@ def test_given_attached_audit_reading_another_resource_when_compiling_then_it_ad AttachedAuditGateCycleTestCase( "seed audit reading a model built from the seed", { - "audits/generic/code_check.sql": gate_audit(read='__ref("coded_orders")'), - "seeds/order_codes.yml": _SEED_WITH_AUDIT, - "seeds/order_codes.csv": "code\nA\n", - "models/coded_orders.sql": gate_model(sql='SELECT * FROM __seed("order_codes")'), + "sql/audits/generic/code_check.sql": gate_audit(read='__ref("coded_orders")'), + "sql/seeds/order_codes.yml": _SEED_WITH_AUDIT, + "sql/seeds/order_codes.csv": "code\nA\n", + "sql/models/coded_orders.sql": gate_model( + sql='SELECT * FROM __seed("order_codes")' + ), }, ( "[P005]", @@ -146,10 +158,12 @@ def test_given_attached_audit_reading_another_resource_when_compiling_then_it_ad AttachedAuditGateCycleTestCase( "two model audits that each read the other's target", { - "audits/generic/code_check.sql": gate_audit(read='__ref("customers")'), - "audits/generic/order_check.sql": gate_audit(read='__ref("orders")'), - "models/orders.sql": gate_model(sql="SELECT 'A' AS code", header=_AUDITED_HEADER), - "models/customers.sql": gate_model( + "sql/audits/generic/code_check.sql": gate_audit(read='__ref("customers")'), + "sql/audits/generic/order_check.sql": gate_audit(read='__ref("orders")'), + "sql/models/orders.sql": gate_model( + sql="SELECT 'A' AS code", header=_AUDITED_HEADER + ), + "sql/models/customers.sql": gate_model( sql="SELECT 'A' AS code", header=_ORDER_CHECK_HEADER ), }, @@ -158,13 +172,13 @@ def test_given_attached_audit_reading_another_resource_when_compiling_then_it_ad AttachedAuditGateCycleTestCase( "source audit triggered by an audit read that reads its triggering model's dependant", { - "audits/generic/code_check.sql": gate_audit(read='__ref("order_summary")'), - "audits/generic/order_check.sql": gate_audit(read='__source("raw_orders")'), - "sources/raw.yml": _SOURCES_WITH_AUDIT, - "models/orders.sql": gate_model( + "sql/audits/generic/code_check.sql": gate_audit(read='__ref("order_summary")'), + "sql/audits/generic/order_check.sql": gate_audit(read='__source("raw_orders")'), + "sql/sources/raw.yml": _SOURCES_WITH_AUDIT, + "sql/models/orders.sql": gate_model( sql="SELECT 'A' AS code", header=_ORDER_CHECK_HEADER ), - "models/order_summary.sql": gate_model(sql='SELECT * FROM __ref("orders")'), + "sql/models/order_summary.sql": gate_model(sql='SELECT * FROM __ref("orders")'), }, ( "[P005]", diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_audit_factories.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_audit_factories.py index 8f541715e3..853ebe7b84 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_audit_factories.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_audit_factories.py @@ -21,6 +21,7 @@ from tests.unit.src.sqlbuild.compiler.compile._helpers.helpers import ( DUCKDB_COMPILE_ADAPTER_CONTEXT, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files if TYPE_CHECKING: from sqlbuild._native import CompileInputsView @@ -51,9 +52,9 @@ def test_given_factory_attachment_when_building_inputs_then_cases_append_with_pr tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "models/orders.sql": f"MODEL (description 'Test model orders.', {test_case.model_header}); SELECT 1 AS amount", - "audits/generic/expression_is_true.sql": _AUDIT_FILE, - "python/factories/quality.py": """ + "sql/models/orders.sql": f"MODEL (description 'Test model orders.', {test_case.model_header}); SELECT 1 AS amount", + "sql/audits/generic/expression_is_true.sql": _AUDIT_FILE, + "python/nodes/factories/quality.py": """ from sqlbuild.audits import AuditCase, AuditSeverity, audit_factory @audit_factory @@ -78,7 +79,7 @@ def unused_quality(): assert tuple(audit.name for audit in schema_entry.audits) == test_case.expected_audit_names location: SourceLocation | None = schema_entry.audits[0].location assert location is not None - assert location.path == Path("python/factories/quality.py") + assert location.path == Path("python/nodes/factories/quality.py") assert location.line > 0 assert "audit_factories" not in inputs.model_inputs[0].config.values assert test_case.expected_warning_code in tuple( @@ -119,14 +120,17 @@ def test_given_invalid_factory_attachment_when_building_inputs_then_compile_erro tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "models/orders.sql": f"MODEL (description 'Test model orders.', {test_case.model_header}); SELECT 1 AS amount", - "python/factories/quality.py": f""" + "sql/models/orders.sql": f"MODEL (description 'Test model orders.', {test_case.model_header}); SELECT 1 AS amount", + **node_module_files( + "python/nodes/factories/quality.py", + f""" from sqlbuild.audits import AuditCase, audit_factory @audit_factory def quality(): {test_case.factory_cases} """, + ), }, ) diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_declaration_scopes.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_declaration_scopes.py index 248b232a37..52f7d4a4d9 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_declaration_scopes.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_declaration_scopes.py @@ -75,12 +75,12 @@ def test_given_models_in_one_folder_when_compiling_then_folder_visibility_is_reb tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "models/domain/_enums/status.sql": "ENUM (name status, members [OPEN, SHIPPED]);", - "models/domain/customers.sql": ( + "sql/models/domain/_enums/status.sql": "ENUM (name status, members [OPEN, SHIPPED]);", + "sql/models/domain/customers.sql": ( 'MODEL (description "Test model customers.");\n' 'SELECT @enum("status").OPEN AS status\n' ), - "models/domain/orders.sql": ( + "sql/models/domain/orders.sql": ( 'MODEL (description "Test model orders.");\n' 'SELECT @enum("status").SHIPPED AS status\n' ), @@ -106,27 +106,27 @@ def test_given_models_in_one_folder_when_compiling_then_folder_visibility_is_reb ( ScopedDeclarationCompileTestCase( "global declaration", - {"constants/value.sql": "CONSTANT (name value, value 1);"}, - "models/domain/child/orders.sql", + {"sql/constants/value.sql": "CONSTANT (name value, value 1);"}, + "sql/models/domain/child/orders.sql", 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value\n', "SELECT 1 AS value", ), ScopedDeclarationCompileTestCase( "inherited declaration", - {"models/domain/constants/value.sql": "CONSTANT (name value, value 2);"}, - "models/domain/child/orders.sql", + {"sql/models/domain/constants/value.sql": "CONSTANT (name value, value 2);"}, + "sql/models/domain/child/orders.sql", 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value\n', "SELECT 2 AS value", ), ScopedDeclarationCompileTestCase( "all ancestor declarations", { - "models/domain/constants/parent.sql": "CONSTANT (name parent_value, value 2);", - "models/domain/child/constants/child.sql": ( + "sql/models/domain/constants/parent.sql": "CONSTANT (name parent_value, value 2);", + "sql/models/domain/child/constants/child.sql": ( "CONSTANT (name child_value, value 3);" ), }, - "models/domain/child/grandchild/orders.sql", + "sql/models/domain/child/grandchild/orders.sql", ( 'MODEL (description "Test model orders.");\nSELECT @const("parent_value") + @const("child_value") AS value\n' ), @@ -134,15 +134,15 @@ def test_given_models_in_one_folder_when_compiling_then_folder_visibility_is_reb ), ScopedDeclarationCompileTestCase( "local declaration", - {"models/domain/_constants/value.sql": "CONSTANT (name value, value 4);"}, - "models/domain/orders.sql", + {"sql/models/domain/_constants/value.sql": "CONSTANT (name value, value 4);"}, + "sql/models/domain/orders.sql", 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value\n', "SELECT 4 AS value", ), ScopedDeclarationCompileTestCase( "private declaration", {}, - "models/domain/orders.sql", + "sql/models/domain/orders.sql", 'MODEL (description "Test model orders.", constants (_value 5));\nSELECT @const("_value") AS value\n', "SELECT 5 AS value", ), @@ -173,63 +173,67 @@ def test_given_scoped_declaration_when_compiling_model_then_only_lexically_visib ScopedDeclarationErrorTestCase( "sibling declaration", { - "models/one/_constants/value.sql": "CONSTANT (name value, value 1);", - "models/two/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/models/one/_constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/two/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', }, - ("known but inaccessible", "models/one/_constants/value.sql", "models/two/orders.sql"), + ( + "known but inaccessible", + "sql/models/one/_constants/value.sql", + "sql/models/two/orders.sql", + ), ), ScopedDeclarationErrorTestCase( "descendant declaration", { - "models/domain/child/_constants/value.sql": "CONSTANT (name value, value 1);", - "models/domain/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/models/domain/child/_constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/domain/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', }, - ("known but inaccessible", "models/domain/child/_constants/value.sql"), + ("known but inaccessible", "sql/models/domain/child/_constants/value.sql"), ), ScopedDeclarationErrorTestCase( "unknown declaration", { - "models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("missing") AS value' + "sql/models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("missing") AS value' }, ("Unknown constant 'missing'", "Visible constants: none"), ), ScopedDeclarationErrorTestCase( "model private does not export to test", { - "models/orders.sql": "MODEL (description 'Test model orders.', constants (_value 1));\nSELECT 1 AS value", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', constants (_value 1));\nSELECT 1 AS value", "tests/unit/orders_test.sql": ( 'TEST ();\nWITH __expected__orders AS (SELECT @const("_value") AS value) ' "SELECT 1" ), }, - ("known but inaccessible", "models/orders.sql", "tests/unit/orders_test.sql"), + ("known but inaccessible", "sql/models/orders.sql", "tests/unit/orders_test.sql"), ), ScopedDeclarationErrorTestCase( "filename resemblance without expected relationship", { - "models/domain/_constants/value.sql": "CONSTANT (name model_value, value 9);", - "models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", + "sql/models/domain/_constants/value.sql": "CONSTANT (name model_value, value 9);", + "sql/models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", "tests/unit/orders_test.sql": ( "TEST ();\nWITH __ref__orders AS (SELECT 1 AS value), " "__assert__valid AS (SELECT @const('model_value') WHERE FALSE) SELECT 1" ), }, - ("known but inaccessible", "models/domain/_constants/value.sql"), + ("known but inaccessible", "sql/models/domain/_constants/value.sql"), ), ScopedDeclarationErrorTestCase( "unrelated production scope is not granted", { - "models/orders/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", - "models/customers/_constants/value.sql": ( + "sql/models/orders/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", + "sql/models/customers/_constants/value.sql": ( "CONSTANT (name customer_value, value 10);" ), - "models/customers/customers.sql": "MODEL (description 'Test model customers.');\nSELECT 1 AS value", + "sql/models/customers/customers.sql": "MODEL (description 'Test model customers.');\nSELECT 1 AS value", "tests/unit/check.sql": ( "TEST ();\nWITH __ref__orders AS (SELECT 1 AS value), " "__expected__orders AS (SELECT @const('customer_value') AS value) SELECT 1" ), }, - ("known but inaccessible", "models/customers/_constants/value.sql"), + ("known but inaccessible", "sql/models/customers/_constants/value.sql"), ), ), ids=lambda case: case.description, @@ -254,8 +258,8 @@ def test_given_inaccessible_or_unknown_declaration_when_compiling_then_diagnosti ScopedDeclarationSurfaceTestCase( "inline model hook", { - "models/domain/_constants/value.sql": "CONSTANT (name value, value 11);", - "models/domain/orders.sql": ( + "sql/models/domain/_constants/value.sql": "CONSTANT (name value, value 11);", + "sql/models/domain/orders.sql": ( "MODEL (description 'Test model orders.', pre_hooks [inline_sql(\"SELECT @const('value')\")]);\nSELECT 1" ), }, @@ -269,9 +273,9 @@ def test_given_inaccessible_or_unknown_declaration_when_compiling_then_diagnosti ScopedDeclarationSurfaceTestCase( "named hook definition path", { - "models/domain/_sqlbuild/_constants/value.sql": "CONSTANT (name value, value 12);", - "models/domain/_sqlbuild/_hooks/sql/typed.sql": 'HOOK (description "Test hook typed.");\nSELECT @const("value")', - "models/domain/orders.sql": 'MODEL (description "Test model orders.", post_hooks [sql("typed")]);\nSELECT 1', + "sql/models/domain/_sqlbuild/_constants/value.sql": "CONSTANT (name value, value 12);", + "sql/models/domain/_sqlbuild/_hooks/sql/typed.sql": 'HOOK (description "Test hook typed.");\nSELECT @const("value")', + "sql/models/domain/orders.sql": 'MODEL (description "Test model orders.", post_hooks [sql("typed")]);\nSELECT 1', }, lambda inputs: ( cast(list[SqlHookEntry], inputs.model_inputs[0].config.values["post_hooks"])[ @@ -283,11 +287,11 @@ def test_given_inaccessible_or_unknown_declaration_when_compiling_then_diagnosti ScopedDeclarationSurfaceTestCase( "function definition path", { - "functions/sql/domain/_constants/value.sql": "CONSTANT (name value, value 13);", - "functions/sql/domain/value.sql": ( + "sql/functions/sql/domain/_constants/value.sql": "CONSTANT (name value, value 13);", + "sql/functions/sql/domain/value.sql": ( 'FUNCTION (description "Test function value.", returns INTEGER);\n@const("value")' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1", }, lambda inputs: inputs.sql_function_inputs[0].body_sql, "13", @@ -295,13 +299,13 @@ def test_given_inaccessible_or_unknown_declaration_when_compiling_then_diagnosti ScopedDeclarationSurfaceTestCase( "standalone audit definition path", { - "models/domain/_sqlbuild/_constants/value.sql": "CONSTANT (name value, value 15);", - "models/domain/_sqlbuild/audits/singular/check.sql": ( + "sql/models/domain/_sqlbuild/_constants/value.sql": "CONSTANT (name value, value 15);", + "sql/models/domain/_sqlbuild/audits/singular/check.sql": ( 'AUDIT ();\nSELECT @const("value") FROM __ref("orders") ' 'JOIN __ref("customers") ON TRUE' ), - "models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1", - "models/domain/customers.sql": "MODEL (description 'Test model customers.');\nSELECT 1", + "sql/models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1", + "sql/models/domain/customers.sql": "MODEL (description 'Test model customers.');\nSELECT 1", }, lambda inputs: inputs.audit_inputs[0].sql_body, 'SELECT 15 FROM __ref("orders") JOIN __ref("customers") ON TRUE', @@ -309,13 +313,13 @@ def test_given_inaccessible_or_unknown_declaration_when_compiling_then_diagnosti ScopedDeclarationSurfaceTestCase( "generic audit definition path", { - "models/domain/_sqlbuild/_constants/value.sql": ( + "sql/models/domain/_sqlbuild/_constants/value.sql": ( "CONSTANT (name value, value 18);" ), - "models/domain/_sqlbuild/_audits/generic/scoped.sql": ( + "sql/models/domain/_sqlbuild/_audits/generic/scoped.sql": ( 'AUDIT ();\nSELECT * FROM __ref("@model") WHERE @const("value") = 18' ), - "models/domain/orders.sql": "MODEL (description 'Test model orders.', audits [scoped]);\nSELECT 1", + "sql/models/domain/orders.sql": "MODEL (description 'Test model orders.', audits [scoped]);\nSELECT 1", }, lambda inputs: inputs.audit_inputs[0].sql_body, 'SELECT * FROM __ref("orders") WHERE 18 = 18', @@ -328,7 +332,7 @@ def test_given_inaccessible_or_unknown_declaration_when_compiling_then_diagnosti "TEST ();\nWITH __ref__orders AS (SELECT 1 AS value), " '__expected__orders AS (SELECT @const("value") AS value) SELECT 1' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", }, lambda inputs: inputs.test_inputs[0].sql_body, "WITH __ref__orders AS (SELECT 1 AS value), " @@ -342,7 +346,7 @@ def test_given_inaccessible_or_unknown_declaration_when_compiling_then_diagnosti "SCENARIO (description 'Test scenario orders.');\nWITH __ref__orders AS (SELECT 1 AS value), " '__expected__orders AS (SELECT @const("value") AS value) SELECT 1' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", }, lambda inputs: inputs.scenario_inputs[0].sql_body, "WITH __ref__orders AS (SELECT 1 AS value), " @@ -370,12 +374,12 @@ def test_given_scoped_declaration_when_compiling_sql_surface_then_uses_authored_ ExpectedModelDeclarationGrantTestCase( description="single model inherited local constant and enum", files={ - "models/domain/_constants/inherited.sql": ( + "sql/models/domain/_constants/inherited.sql": ( "CONSTANT (name inherited_value, value 2);" ), - "models/domain/_constants/local.sql": ("CONSTANT (name local_value, value 3);"), - "models/domain/_enums/state.sql": "ENUM (name state, members [OPEN, CLOSED]);", - "models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value, 'OPEN' AS state", + "sql/models/domain/_constants/local.sql": ("CONSTANT (name local_value, value 3);"), + "sql/models/domain/_enums/state.sql": "ENUM (name state, members [OPEN, CLOSED]);", + "sql/models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value, 'OPEN' AS state", "tests/unit/check.sql": ( "TEST ();\nWITH __ref__orders AS (SELECT 1 AS value), " "__expected__orders AS (SELECT @const('inherited_value') + " @@ -392,10 +396,10 @@ def test_given_scoped_declaration_when_compiling_sql_surface_then_uses_authored_ ExpectedModelDeclarationGrantTestCase( description="multiple expected models deterministic union", files={ - "models/a/_constants/a.sql": "CONSTANT (name a_value, value 4);", - "models/a/a.sql": "MODEL (description 'Test model a.');\nSELECT 4 AS value", - "models/b/_constants/b.sql": "CONSTANT (name b_value, value 5);", - "models/b/b.sql": "MODEL (description 'Test model b.');\nSELECT 5 AS value", + "sql/models/a/_constants/a.sql": "CONSTANT (name a_value, value 4);", + "sql/models/a/a.sql": "MODEL (description 'Test model a.');\nSELECT 4 AS value", + "sql/models/b/_constants/b.sql": "CONSTANT (name b_value, value 5);", + "sql/models/b/b.sql": "MODEL (description 'Test model b.');\nSELECT 5 AS value", "tests/unit/check.sql": ( "TEST ();\nWITH __ref__a AS (SELECT 1 AS value), " "__expected__b AS (SELECT @const('b_value') AS value), " @@ -411,8 +415,8 @@ def test_given_scoped_declaration_when_compiling_sql_surface_then_uses_authored_ ExpectedModelDeclarationGrantTestCase( description="test path visibility remains separate from model grant", files={ - "models/domain/_constants/model.sql": "CONSTANT (name model_value, value 6);", - "models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", + "sql/models/domain/_constants/model.sql": "CONSTANT (name model_value, value 6);", + "sql/models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", "tests/unit/_constants/test.sql": "CONSTANT (name test_value, value 7);", "tests/unit/check.sql": ( "TEST ();\nWITH __ref__orders AS (SELECT 1 AS value), " @@ -426,13 +430,13 @@ def test_given_scoped_declaration_when_compiling_sql_surface_then_uses_authored_ ExpectedModelDeclarationGrantTestCase( description="only macros called by the test are granted", files={ - "models/domain/_sqlbuild/_macros/python/discount.py": ( + "sql/models/domain/_sqlbuild/_macros/python/discount.py": ( 'def discount(expression: str) -> str:\n return f"({expression} - 1)"\n' ), - "models/domain/_sqlbuild/_macros/python/surcharge.py": ( + "sql/models/domain/_sqlbuild/_macros/python/surcharge.py": ( 'def surcharge(expression: str) -> str:\n return f"({expression} + 1)"\n' ), - "models/domain/orders.sql": ( + "sql/models/domain/orders.sql": ( "MODEL (description 'Test model orders.');\nSELECT @py.discount('10') AS value, @py.surcharge('10') AS fee" ), "tests/unit/check.sql": ( @@ -446,13 +450,13 @@ def test_given_scoped_declaration_when_compiling_sql_surface_then_uses_authored_ ExpectedModelDeclarationGrantTestCase( description="macros called inside macro arguments are granted", files={ - "models/domain/_sqlbuild/_macros/python/discount.py": ( + "sql/models/domain/_sqlbuild/_macros/python/discount.py": ( 'def discount(expression: str) -> str:\n return f"({expression} - 1)"\n' ), - "models/domain/_sqlbuild/_macros/python/surcharge.py": ( + "sql/models/domain/_sqlbuild/_macros/python/surcharge.py": ( 'def surcharge(expression: str) -> str:\n return f"({expression} + 1)"\n' ), - "models/domain/orders.sql": ( + "sql/models/domain/orders.sql": ( "MODEL (description 'Test model orders.');\nSELECT @py.discount('10') AS value, @py.surcharge('10') AS fee" ), "tests/unit/check.sql": ( @@ -469,7 +473,7 @@ def test_given_scoped_declaration_when_compiling_sql_surface_then_uses_authored_ ExpectedModelDeclarationGrantTestCase( description="model private declaration is not granted", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', constants (_private 8));\nSELECT @const('_private') AS value" ), "tests/unit/check.sql": ( @@ -483,10 +487,10 @@ def test_given_scoped_declaration_when_compiling_sql_surface_then_uses_authored_ ExpectedModelDeclarationGrantTestCase( description="filename resemblance and no expected model grant nothing", files={ - "models/domain/customers.sql": ( + "sql/models/domain/customers.sql": ( "MODEL (description 'Test model customers.');\nSELECT 1 AS value" ), - "models/domain/orders.sql": ( + "sql/models/domain/orders.sql": ( "MODEL (description 'Test model orders.');\n" 'SELECT value FROM __ref("customers")' ), @@ -501,8 +505,8 @@ def test_given_scoped_declaration_when_compiling_sql_surface_then_uses_authored_ ExpectedModelDeclarationGrantTestCase( description="scenario expected model grant", files={ - "models/domain/_constants/value.sql": "CONSTANT (name scenario_value, value 10);", - "models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", + "sql/models/domain/_constants/value.sql": "CONSTANT (name scenario_value, value 10);", + "sql/models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", "tests/scenarios/check.sql": ( "SCENARIO (description 'Test scenario check.');\nWITH __ref__orders AS (SELECT 1 AS value), " "__expected__orders AS (SELECT @const('scenario_value') AS value) SELECT 1" @@ -553,8 +557,8 @@ def test_given_expected_models_when_compiling_then_public_declarations_are_grant RelationshipUsageTestCase( description="expected model provenance is retained", files={ - "models/domain/_constants/value.sql": ("CONSTANT (name model_value, value 6);"), - "models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", + "sql/models/domain/_constants/value.sql": ("CONSTANT (name model_value, value 6);"), + "sql/models/domain/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", "tests/unit/check.sql": ( "TEST ();\nWITH __ref__orders AS (SELECT 1 AS value), " "__expected__orders AS " @@ -593,16 +597,16 @@ def test_given_relationship_granted_reference_when_compiling_then_usage_retains_ ScopePlacementCompileTestCase( description="exact local placement is accepted", files={ - "models/domain/_constants/value.sql": ("CONSTANT (name value, value 1);"), - "models/domain/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/models/domain/_constants/value.sql": ("CONSTANT (name value, value 1);"), + "sql/models/domain/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', }, ), ScopePlacementCompileTestCase( description="inherited lowest common ancestor is accepted", files={ - "models/domain/constants/value.sql": "CONSTANT (name value, value 1);", - "models/domain/a/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', - "models/domain/b/customers.sql": 'MODEL (description "Test model customers.");\nSELECT @const("value") AS value', + "sql/models/domain/constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/domain/a/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/models/domain/b/customers.sql": 'MODEL (description "Test model customers.");\nSELECT @const("value") AS value', }, ), ), @@ -645,9 +649,9 @@ def test_given_models_in_same_directory_when_reusing_visibility_then_usage_consu tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "models/domain/area/_constants/value.sql": "CONSTANT (name value, value 1);", - "models/domain/area/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', - "models/domain/area/customers.sql": 'MODEL (description "Test model customers.");\nSELECT @const("value") AS value', + "sql/models/domain/area/_constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/domain/area/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/models/domain/area/customers.sql": 'MODEL (description "Test model customers.");\nSELECT @const("value") AS value', }, ) @@ -666,23 +670,23 @@ def test_given_models_in_same_directory_when_reusing_visibility_then_usage_consu ScopePlacementCompileTestCase( description="used global with one owner is rejected as over broad", files={ - "constants/value.sql": "CONSTANT (name value, value 1);", - "models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', }, - expected_fragment="required exact-owner-private at 'models'", + expected_fragment="required exact-owner-private at 'sql/models'", ), ScopePlacementCompileTestCase( description="unused global is rejected", files={ - "constants/value.sql": "CONSTANT (name value, value 1);", - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", + "sql/constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", }, expected_fragment="Unused global declaration 'constant:value'", ), ScopePlacementCompileTestCase( description="unused private is rejected", files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', constants (_value 1));\nSELECT 1 AS value" ), }, @@ -691,10 +695,10 @@ def test_given_models_in_same_directory_when_reusing_visibility_then_usage_consu ScopePlacementCompileTestCase( description="inherited declaration used in one directory must be local", files={ - "models/domain/constants/value.sql": "CONSTANT (name value, value 1);", - "models/domain/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/models/domain/constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/domain/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', }, - expected_fragment="required exact-owner-private at 'models/domain'", + expected_fragment="required exact-owner-private at 'sql/models/domain'", ), ), ids=lambda case: case.description, @@ -724,8 +728,8 @@ def test_given_invalid_declaration_placement_when_assembling_then_it_reports_an_ ScopePlacementCompileTestCase( description="over broad global is advisory when placement enforcement is disabled", files={ - "constants/value.sql": "CONSTANT (name value, value 1);", - "models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', }, expected_model_names=("orders",), expected_diagnostics=(("S024", "warning"),), @@ -762,8 +766,10 @@ def test_given_disabled_placement_enforcement_when_assembling_then_project_and_w ( ScopedDeclarationCompileTestCase( description="inherited enum contract", - files={"models/domain/enums/state.sql": "ENUM (name state, members [OPEN, CLOSED]);"}, - model_path="models/domain/child/orders.sql", + files={ + "sql/models/domain/enums/state.sql": "ENUM (name state, members [OPEN, CLOSED]);" + }, + model_path="sql/models/domain/child/orders.sql", model_sql=( "MODEL (description 'Test model orders.', contract enforced, columns (state (type state)));\n" 'SELECT @enum("state").OPEN AS state' @@ -801,10 +807,10 @@ def test_given_inherited_enum_when_compiling_contract_then_resolves_from_model_p ScopedDeclarationCompileTestCase( description="source authored path", files={ - "sources/domain/_constants/value.sql": "CONSTANT (name value, value 14);", - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1", + "sql/sources/domain/_constants/value.sql": "CONSTANT (name value, value 14);", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1", }, - model_path="sources/domain/source.yml", + model_path="sql/sources/domain/source.yml", model_sql='SELECT @const("value")', expected_sql="SELECT 14", ), @@ -856,13 +862,13 @@ def test_given_sources_in_same_file_when_reusing_visibility_then_usage_consumers tmp_path: Path, write_repo_files: Callable[[Path, dict[str, str]], None], ) -> None: - source_path: Path = tmp_path / "sources/domain/source.yml" + source_path: Path = tmp_path / "sql/sources/domain/source.yml" write_repo_files( tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "sources/domain/_constants/value.sql": "CONSTANT (name value, value 14);", - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1", + "sql/sources/domain/_constants/value.sql": "CONSTANT (name value, value 14);", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1", }, ) discovered: DiscoveredProjectInputs = discover_project_inputs(project_dir=tmp_path) @@ -871,7 +877,7 @@ def test_given_sources_in_same_file_when_reusing_visibility_then_usage_consumers source_files=( DiscoveredSourceFile( file_path=source_path, - relative_path=Path("sources/domain/source.yml"), + relative_path=Path("sql/sources/domain/source.yml"), contents="", source_entries=( SourceEntry(name="customer_orders", expression='SELECT @const("value")'), @@ -920,7 +926,7 @@ def test_given_tests_in_same_directory_when_reusing_visibility_then_usage_consum tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value", "tests/unit/domain/_constants/value.sql": "CONSTANT (name value, value 16);", "tests/unit/domain/customer_orders.sql": test_sql, "tests/unit/domain/inventory_orders.sql": test_sql, diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_declarations.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_declarations.py index c5000b10f7..3d84aa4fdf 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_declarations.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_declarations.py @@ -69,17 +69,17 @@ def test_given_public_and_private_declarations_when_compiling_then_resolves_scop tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "models/_enums/market.sql": """ + "sql/models/_enums/market.sql": """ ENUM (name fulfillment_method, members [DELIVERY, PICKUP]); ENUM (name priority, members (LOW 1, HIGH 3)); """, - "constants/market/thresholds.sql": """ + "sql/constants/market/thresholds.sql": """ CONSTANT (name min_items, value 7); """, - "models/_constants/thresholds.sql": """ + "sql/models/_constants/thresholds.sql": """ CONSTANT (name source_name, value "O'Brien"); """, - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", contract enforced, pre_hooks [inline_sql('SELECT @const("min_items") + @const("_offset")')], @@ -105,7 +105,7 @@ def test_given_public_and_private_declarations_when_compiling_then_resolves_scop @const("min_items") + @const("_offset") AS threshold, @const("source_name") AS source_name """, - "functions/sql/add_threshold.sql": """ + "sql/functions/sql/add_threshold.sql": """ FUNCTION (description "Test function add_threshold.", arguments (value INTEGER), returns INTEGER, @@ -113,7 +113,7 @@ def test_given_public_and_private_declarations_when_compiling_then_resolves_scop value + @const("min_items") """, - "sources/inline.yml": """ + "sql/sources/inline.yml": """ sources: - name: inline_values description: Test source inline_values. @@ -142,7 +142,7 @@ def test_given_public_and_private_declarations_when_compiling_then_resolves_scop ) SELECT 1 """, - "audits/singular/orders.sql": """ + "sql/audits/singular/orders.sql": """ AUDIT (); SELECT * FROM __ref("orders") WHERE threshold < @const("min_items") @@ -309,7 +309,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ "sqlbuild_project.toml": ( _PROJECT_FILE + '\n[constants]\ncollection_rendering = "array"\n' ), - "constants/typed.sql": """ + "sql/constants/typed.sql": """ CONSTANT (name enabled, value true); CONSTANT (name ratio, value 0.75); CONSTANT (name rate, type decimal, value "2.4700"); @@ -320,7 +320,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ CONSTANT (name country_array, value ["GB", "FR"], render_as array); CONSTANT (name labels, value (GB "Great Britain", FR "France")); """, - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", pre_hooks [inline_sql("SELECT 'GB' IN @const('countries')")], post_hooks [sql("typed_hook")], @@ -337,15 +337,15 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ @const("labels") AS labels, @const("_local_values") AS local_values """, - "functions/sql/is_supported.sql": """ + "sql/functions/sql/is_supported.sql": """ FUNCTION (description "Test function is_supported.", arguments (value VARCHAR), returns BOOLEAN); value IN @const("countries") """, - "hooks/sql/typed_hook.sql": """ + "sql/hooks/sql/typed_hook.sql": """ HOOK (description "Typed constant hook"); SELECT 'FR' IN @const("countries") """, - "sources/inline.yml": """ + "sql/sources/inline.yml": """ sources: - name: supported_entries description: Test source supported_entries. @@ -364,12 +364,12 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ __expected__orders AS (SELECT @const("country_array") AS countries) SELECT 1 """, - "audits/singular/orders.sql": """ + "sql/audits/singular/orders.sql": """ AUDIT (); SELECT * FROM __ref("orders") JOIN __source("supported_entries") USING (country) WHERE country NOT IN @const("unique_countries") """, - "audits/generic/typed_audit.sql": """ + "sql/audits/generic/typed_audit.sql": """ AUDIT (); SELECT * FROM __ref("@model") WHERE country NOT IN @const("countries") """, @@ -403,7 +403,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ [ DeclarationFingerprintTestCase( description="constant value changes rendered query identity", - declaration_path="models/_constants/threshold.sql", + declaration_path="sql/models/_constants/threshold.sql", initial_declaration="CONSTANT (name threshold, value 7);\n", changed_declaration="CONSTANT (name threshold, value 8);\n", model_sql='MODEL (description "Test model threshold.");\nSELECT @const("threshold") AS threshold\n', @@ -412,7 +412,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ ), DeclarationFingerprintTestCase( description="list order changes rendered query identity", - declaration_path="models/_constants/countries.sql", + declaration_path="sql/models/_constants/countries.sql", initial_declaration='CONSTANT (name countries, value ["GB", "FR"]);\n', changed_declaration='CONSTANT (name countries, value ["FR", "GB"]);\n', model_sql='MODEL (description "Test model countries.");\nSELECT @const("countries") AS countries\n', @@ -421,7 +421,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ ), DeclarationFingerprintTestCase( description="list duplicate changes rendered query identity", - declaration_path="models/_constants/countries.sql", + declaration_path="sql/models/_constants/countries.sql", initial_declaration='CONSTANT (name countries, value ["GB", "FR"]);\n', changed_declaration='CONSTANT (name countries, value ["GB", "FR", "FR"]);\n', model_sql='MODEL (description "Test model countries.");\nSELECT @const("countries") AS countries\n', @@ -430,7 +430,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ ), DeclarationFingerprintTestCase( description="set order does not change rendered query identity", - declaration_path="models/_constants/countries.sql", + declaration_path="sql/models/_constants/countries.sql", initial_declaration='CONSTANT (name countries, value {"GB", "FR"});\n', changed_declaration='CONSTANT (name countries, value {"FR", "GB"});\n', model_sql='MODEL (description "Test model countries.");\nSELECT @const("countries") AS countries\n', @@ -439,7 +439,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ ), DeclarationFingerprintTestCase( description="object key order does not change rendered query identity", - declaration_path="models/_constants/labels.sql", + declaration_path="sql/models/_constants/labels.sql", initial_declaration=( 'CONSTANT (name labels, value (GB "Great Britain", FR "France"));\n' ), @@ -452,7 +452,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ ), DeclarationFingerprintTestCase( description="set membership changes rendered query identity", - declaration_path="models/_constants/countries.sql", + declaration_path="sql/models/_constants/countries.sql", initial_declaration='CONSTANT (name countries, value {"GB", "FR"});\n', changed_declaration='CONSTANT (name countries, value {"GB", "HK"});\n', model_sql='MODEL (description "Test model countries.");\nSELECT @const("countries") AS countries\n', @@ -461,7 +461,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ ), DeclarationFingerprintTestCase( description="object value changes rendered query identity", - declaration_path="models/_constants/labels.sql", + declaration_path="sql/models/_constants/labels.sql", initial_declaration='CONSTANT (name labels, value (GB "Great Britain"));\n', changed_declaration='CONSTANT (name labels, value (GB "Britain"));\n', model_sql='MODEL (description "Test model labels.");\nSELECT @const("labels") AS labels\n', @@ -470,7 +470,7 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ ), DeclarationFingerprintTestCase( description="collection render mode changes rendered query identity", - declaration_path="models/_constants/countries.sql", + declaration_path="sql/models/_constants/countries.sql", initial_declaration='CONSTANT (name countries, value ["GB", "FR"]);\n', changed_declaration=( 'CONSTANT (name countries, value ["GB", "FR"], render_as array);\n' @@ -481,21 +481,21 @@ def test_given_typed_constants_when_compiling_then_all_sql_surfaces_use_adapter_ ), DeclarationFingerprintTestCase( description="declaration used by another model does not alter model identity", - declaration_path="models/_constants/countries.sql", + declaration_path="sql/models/_constants/countries.sql", initial_declaration='CONSTANT (name countries, value ["GB", "FR"]);\n', changed_declaration='CONSTANT (name countries, value ["GB", "HK"]);\n', model_sql="MODEL (description 'Test model countries.');\nSELECT 1 AS value\n", expected_query_hash_changed=False, expected_metadata_changed=False, additional_files={ - "models/z_consumer.sql": ( + "sql/models/z_consumer.sql": ( 'MODEL (description "Test model z_consumer.");\nSELECT @const("countries") AS countries\n' ) }, ), DeclarationFingerprintTestCase( description="enum members change enforced contract identity", - declaration_path="models/_enums/state.sql", + declaration_path="sql/models/_enums/state.sql", initial_declaration="ENUM (name state, members [OPEN]);\n", changed_declaration="ENUM (name state, members [OPEN, CLOSED]);\n", model_sql=""" @@ -521,7 +521,7 @@ def test_given_declaration_change_when_compiling_then_updates_dependent_identity { "sqlbuild_project.toml": _PROJECT_FILE, test_case.declaration_path: test_case.initial_declaration, - "models/orders.sql": test_case.model_sql, + "sql/models/orders.sql": test_case.model_sql, } | test_case.additional_files, ) @@ -549,8 +549,8 @@ def test_given_declaration_change_when_compiling_then_updates_dependent_identity CompileDeclarationsErrorTestCase( description="unknown enum member", repo_files={ - "enums/state.sql": "ENUM (name state, members [OPEN, CLOSED]);", - "models/orders.sql": ( + "sql/enums/state.sql": "ENUM (name state, members [OPEN, CLOSED]);", + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\nSELECT @enum("state").MISSING AS state\n' ), }, @@ -559,8 +559,8 @@ def test_given_declaration_change_when_compiling_then_updates_dependent_identity CompileDeclarationsErrorTestCase( description="lowercase enum member access", repo_files={ - "enums/state.sql": 'ENUM (name state, members (DELIVERY "active"));', - "models/orders.sql": ( + "sql/enums/state.sql": 'ENUM (name state, members (DELIVERY "active"));', + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\nSELECT @enum("state").active AS state\n' ), }, @@ -569,22 +569,22 @@ def test_given_declaration_change_when_compiling_then_updates_dependent_identity CompileDeclarationsErrorTestCase( description="unknown constant", repo_files={ - "models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("missing") AS value\n', + "sql/models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("missing") AS value\n', }, expected_error_fragment="Unknown constant 'missing'", ), CompileDeclarationsErrorTestCase( description="foreign private constant", repo_files={ - "models/a.sql": "MODEL (description 'Test model a.', constants (_limit 7));\nSELECT 1 AS value\n", - "models/b.sql": 'MODEL (description "Test model b.");\nSELECT @const("_limit") AS value\n', + "sql/models/a.sql": "MODEL (description 'Test model a.', constants (_limit 7));\nSELECT 1 AS value\n", + "sql/models/b.sql": 'MODEL (description "Test model b.");\nSELECT @const("_limit") AS value\n', }, expected_error_fragment="Constant '_limit' is known but inaccessible", ), CompileDeclarationsErrorTestCase( description="non-private model constant name", repo_files={ - "models/orders.sql": "MODEL (description 'Test model orders.', constants (limit 7));\nSELECT 1 AS value\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', constants (limit 7));\nSELECT 1 AS value\n", }, expected_error_fragment=( "Invalid model-local constant identity 'limit'.*use snake_case '_limit'" @@ -593,29 +593,29 @@ def test_given_declaration_change_when_compiling_then_updates_dependent_identity CompileDeclarationsErrorTestCase( description="duplicate public enum name", repo_files={ - "enums/one.sql": "ENUM (name state, members [OPEN]);", - "enums/nested/two.sql": "ENUM (name state, members [CLOSED]);", - "models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value\n", + "sql/enums/one.sql": "ENUM (name state, members [OPEN]);", + "sql/enums/nested/two.sql": "ENUM (name state, members [CLOSED]);", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\nSELECT 1 AS value\n", }, expected_error_fragment="Duplicate declaration 'enum:state'", ), CompileDeclarationsErrorTestCase( description="nested collection cannot render as a portable value list", repo_files={ - "constants/groups.sql": "CONSTANT (name groups, value [[1], [2]]);", - "models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("groups") AS groups\n', + "sql/constants/groups.sql": "CONSTANT (name groups, value [[1], [2]]);", + "sql/models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("groups") AS groups\n', }, expected_error_fragment=( - "constants/groups.sql constant 'groups'.*adapter 'duckdb'.*value_list" + "sql/constants/groups.sql constant 'groups'.*adapter 'duckdb'.*value_list" ), ), CompileDeclarationsErrorTestCase( description="constant rendered over the SQL value size limit", repo_files={ - "constants/big.sql": f'CONSTANT (name big, value "{"'" * 600_000}");', - "models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("big") AS big\n', + "sql/constants/big.sql": f'CONSTANT (name big, value "{"'" * 600_000}");', + "sql/models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("big") AS big\n', }, - expected_error_fragment="constants/big.sql constant 'big'.*maximum is 1000000 bytes", + expected_error_fragment="sql/constants/big.sql constant 'big'.*maximum is 1000000 bytes", ), ], ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_expansion_spans.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_expansion_spans.py index faeb53c22c..01474c6d65 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_expansion_spans.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_expansion_spans.py @@ -95,7 +95,7 @@ def test_given_expanded_offset_when_mapping_then_authored_position_matches( passes: tuple[tuple[ExpansionSpan, ...], ...] expanded_sql, passes = expand_authored_sql_with_spans( sql=test_case.sql, - file_path=tmp_path / "models" / "orders.sql", + file_path=tmp_path / "sql" / "models" / "orders.sql", effective_vars=test_case.effective_vars, loaded_macros=loaded_macros, macro_context=_MACRO_CONTEXT, diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_hook_reads.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_hook_reads.py index d0042a4519..8a577903f3 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_hook_reads.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_hook_reads.py @@ -30,7 +30,7 @@ sql_analysis = false sql_validation = false """ -_HOOK_PATH: str = "models/marts/_sqlbuild/_hooks/python/lookups.py" +_HOOK_PATH: str = "sql/models/marts/_sqlbuild/_hooks/python/lookups.py" _HOOKED_HEADER: str = ( 'MODEL (description "Test model lookups.", post_hooks [python("refresh_lookup")]);' ) @@ -38,8 +38,8 @@ _SOURCES: str = ( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n table: orders\n" ) -_SQL_HOOK_PATH: str = "models/marts/_sqlbuild/_hooks/sql/record_rows.sql" -_MACRO_PATH: str = "models/marts/_sqlbuild/_macros/python/counts.py" +_SQL_HOOK_PATH: str = "sql/models/marts/_sqlbuild/_hooks/sql/record_rows.sql" +_MACRO_PATH: str = "sql/models/marts/_sqlbuild/_macros/python/counts.py" _IGNORING_MACRO: str = "def count_rows(relation):\n return 'SELECT 1'\n" _NAMED_SQL_HOOK_HEADER: str = ( 'MODEL (description "Test model counts.", post_hooks [sql("record_rows")]);' @@ -53,8 +53,8 @@ description="hook reading a model makes the hooked model wait for it", files={ _HOOK_PATH: python_hook_source(reads='model("customers")'), - "models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), - "models/marts/orders.sql": gate_model( + "sql/models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=_HOOKED_HEADER ), }, @@ -66,10 +66,10 @@ _HOOK_PATH: python_hook_source( reads='[seed("country_codes"), source("raw_orders")]' ), - "seeds/country_codes.yml": _COUNTRY_SEED, - "seeds/country_codes.csv": "code\nGB\n", - "sources/raw.yml": _SOURCES, - "models/marts/orders.sql": gate_model( + "sql/seeds/country_codes.yml": _COUNTRY_SEED, + "sql/seeds/country_codes.csv": "code\nGB\n", + "sql/sources/raw.yml": _SOURCES, + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=_HOOKED_HEADER ), }, @@ -78,8 +78,8 @@ HookReadEdgeTestCase( description="inline SQL hook reading a model directly", files={ - "models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), - "models/marts/orders.sql": gate_model( + "sql/models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=inline_sql_hook_header('SELECT count(*) FROM __ref("customers")'), ), @@ -91,8 +91,8 @@ files={ _MACRO_PATH: _IGNORING_MACRO, _SQL_HOOK_PATH: 'HOOK (description "Test hook.");\n@py.count_rows(__ref("customers"))\n', - "models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), - "models/marts/orders.sql": gate_model( + "sql/models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=_NAMED_SQL_HOOK_HEADER ), }, @@ -101,10 +101,10 @@ HookReadEdgeTestCase( description="inline SQL hook reading a source and a seed", files={ - "seeds/country_codes.yml": _COUNTRY_SEED, - "seeds/country_codes.csv": "code\nGB\n", - "sources/raw.yml": _SOURCES, - "models/marts/orders.sql": gate_model( + "sql/seeds/country_codes.yml": _COUNTRY_SEED, + "sql/seeds/country_codes.csv": "code\nGB\n", + "sql/sources/raw.yml": _SOURCES, + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=inline_sql_hook_header( 'SELECT * FROM __source("raw_orders"), __seed("country_codes")' @@ -134,8 +134,8 @@ def test_given_hook_reads_when_compiling_then_hooked_model_runs_after_reads( HookReadEdgeTestCase( description="inline SQL hook read orders the build but is not lineage", files={ - "models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), - "models/marts/orders.sql": gate_model( + "sql/models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=inline_sql_hook_header('SELECT count(*) FROM __ref("customers")'), ), @@ -165,10 +165,10 @@ def test_given_sql_hook_read_when_compiling_then_lineage_and_selection_ignore_it description="hook reading a model built from its own model", files={ _HOOK_PATH: python_hook_source(reads='model("order_rollup")'), - "models/marts/orders.sql": gate_model( + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=_HOOKED_HEADER ), - "models/marts/order_rollup.sql": gate_model( + "sql/models/marts/order_rollup.sql": gate_model( sql='SELECT count(*) AS n FROM __ref("orders")' ), }, @@ -184,13 +184,13 @@ def test_given_sql_hook_read_when_compiling_then_lineage_and_selection_ignore_it _HOOK_PATH: python_hook_source( reads='[model("order_rollup"), model("order_count")]' ), - "models/marts/orders.sql": gate_model( + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=_HOOKED_HEADER ), - "models/marts/order_rollup.sql": gate_model( + "sql/models/marts/order_rollup.sql": gate_model( sql='SELECT count(*) AS n FROM __ref("orders")' ), - "models/marts/order_count.sql": gate_model( + "sql/models/marts/order_count.sql": gate_model( sql='SELECT count(*) AS n FROM __ref("orders")' ), }, @@ -204,17 +204,17 @@ def test_given_sql_hook_read_when_compiling_then_lineage_and_selection_ignore_it files={ _MACRO_PATH: _IGNORING_MACRO, _SQL_HOOK_PATH: 'HOOK (description "Test hook.");\n@py.count_rows(__ref("order_count"))\n', - "models/marts/orders.sql": gate_model( + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=( "MODEL (description 'Test model orders.', pre_hooks [inline_sql('SELECT * FROM __ref(\"order_rollup\")')], " 'post_hooks [sql("record_rows")]);' ), ), - "models/marts/order_rollup.sql": gate_model( + "sql/models/marts/order_rollup.sql": gate_model( sql='SELECT count(*) AS n FROM __ref("orders")' ), - "models/marts/order_count.sql": gate_model( + "sql/models/marts/order_count.sql": gate_model( sql='SELECT count(*) AS n FROM __ref("orders")' ), }, @@ -247,7 +247,7 @@ def test_given_hook_reading_its_own_dependant_when_compiling_then_it_reports_p00 description="hook reading an unknown model", files={ _HOOK_PATH: python_hook_source(reads='model("missing_customers")'), - "models/marts/orders.sql": gate_model( + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=_HOOKED_HEADER ), }, @@ -259,7 +259,7 @@ def test_given_hook_reading_its_own_dependant_when_compiling_then_it_reports_p00 HookReadErrorTestCase( description="inline SQL hook reading an unknown model", files={ - "models/marts/orders.sql": gate_model( + "sql/models/marts/orders.sql": gate_model( sql="SELECT 1 AS order_id", header=inline_sql_hook_header('SELECT * FROM __ref("missing_customers")'), ), diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_macros.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_macros.py index 8339b61cba..1724cb585b 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_macros.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_macros.py @@ -47,7 +47,7 @@ LoadProjectMacrosTestCase( description="exports only public ordinary functions owned by each macro module", macro_files={ - "macros/python/orders.py": """ + "sql/macros/python/orders.py": """ from pathlib import Path from urllib.parse import quote @@ -72,12 +72,12 @@ def order_columns() -> str: LoadProjectMacrosTestCase( description="composes absolute and relative project macro imports without re-export", macro_files={ - "macros/python/shared.py": "def shared(value: str) -> str:\n return value.upper()\n", - "macros/python/absolute.py": ( - "from macros.python.shared import shared as render_shared\n\n" + "sql/macros/python/shared.py": "def shared(value: str) -> str:\n return value.upper()\n", + "sql/macros/python/absolute.py": ( + "from sql.macros.python.shared import shared as render_shared\n\n" "def absolute_macro() -> str:\n return render_shared('absolute')\n" ), - "macros/python/relative.py": ( + "sql/macros/python/relative.py": ( "from .shared import shared\n\n" "def relative_macro() -> str:\n return shared('relative')\n" ), @@ -121,12 +121,12 @@ def test_given_macro_modules_when_loading_then_exports_only_owned_public_functio MacroDependencyTestCase( description="tracks imported macro called through a private helper but not unused import", macro_files={ - "macros/python/shared.py": ( + "sql/macros/python/shared.py": ( "def used(value: str) -> str:\n return value.upper()\n\n" "def unused() -> str:\n return 'unused'\n" ), - "macros/python/orders.py": ( - "from macros.python.shared import used as render_used, unused\n\n" + "sql/macros/python/orders.py": ( + "from sql.macros.python.shared import used as render_used, unused\n\n" "def _render(value: str) -> str:\n return render_used(value)\n\n" "def orders() -> str:\n return _render('orders')\n" ), @@ -138,7 +138,7 @@ def test_given_macro_modules_when_loading_then_exports_only_owned_public_functio MacroDependencyTestCase( description="tracks public macro called through private helper in same module", macro_files={ - "macros/python/composed.py": ( + "sql/macros/python/composed.py": ( "def base(value: str) -> str:\n return value.upper()\n\n" "def _helper(value: str) -> str:\n return base(value)\n\n" "def composed() -> str:\n return _helper('composed')\n" @@ -187,11 +187,11 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before consumer_source: str = ( "from pathlib import Path\n" "Path(__file__).parents[3].joinpath('executed').touch()\n" - "from models.sales._macros.python.shared import shared\n\n" + "from sql.models.sales._macros.python.shared import shared\n\n" "def consumer() -> str:\n return shared()\n" ) - shared_path: Path = tmp_path / "models/sales/_macros/python/shared.py" - consumer_path: Path = tmp_path / "models/finance/macros/python/consumer.py" + shared_path: Path = tmp_path / "sql/models/sales/_macros/python/shared.py" + consumer_path: Path = tmp_path / "sql/models/finance/macros/python/consumer.py" shared_path.parent.mkdir(parents=True) consumer_path.parent.mkdir(parents=True) shared_path.write_text(shared_source, encoding="utf-8") @@ -199,21 +199,21 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before macro_files: tuple[DiscoveredMacroFile, ...] = ( DiscoveredMacroFile( shared_path, - Path("models/sales/_macros/python/shared.py"), + Path("sql/models/sales/_macros/python/shared.py"), shared_source, ScopeKind.LOCAL, Path("models"), - Path("models/sales"), - Path("models/sales/_macros"), + Path("sql/models/sales"), + Path("sql/models/sales/_macros"), ), DiscoveredMacroFile( consumer_path, - Path("models/finance/macros/python/consumer.py"), + Path("sql/models/finance/macros/python/consumer.py"), consumer_source, ScopeKind.INHERITED, Path("models"), - Path("models/finance"), - Path("models/finance/macros"), + Path("sql/models/finance"), + Path("sql/models/finance/macros"), ), ) @@ -229,46 +229,46 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before LoadProjectMacrosErrorTestCase( description="rejects a relative project module import before execution", macro_files={ - "macros/python/a_consumer.py": ( + "sql/macros/python/a_consumer.py": ( "from pathlib import Path\n" "Path(__file__).parent.parent.joinpath('executed').touch()\n" "from . import shared\n" ), - "macros/python/shared.py": "def shared_macro() -> str:\n return 'shared'\n", + "sql/macros/python/shared.py": "def shared_macro() -> str:\n return 'shared'\n", }, - expected_error_fragment="imports project package 'macros.python' instead of a macro module", + expected_error_fragment="imports project package 'sql.macros.python' instead of a macro module", ), LoadProjectMacrosErrorTestCase( description="rejects an import of a package containing project macros", macro_files={ - "macros/python/a_consumer.py": "import macros\n", - "macros/python/shared.py": "def shared_macro() -> str:\n return 'shared'\n", + "sql/macros/python/a_consumer.py": "import sql.macros\n", + "sql/macros/python/shared.py": "def shared_macro() -> str:\n return 'shared'\n", }, expected_error_fragment="module imports are not supported", ), LoadProjectMacrosErrorTestCase( description="rejects missing project macro module before execution", macro_files={ - "macros/python/consumer.py": ( + "sql/macros/python/consumer.py": ( "from pathlib import Path\n" "Path(__file__).parent.parent.joinpath('executed').touch()\n" - "from macros.python.missing import missing\n\n" + "from sql.macros.python.missing import missing\n\n" "def consumer() -> str:\n return missing()\n" ) }, - expected_error_fragment="imports project package 'macros.python.missing'", + expected_error_fragment="imports project package 'sql.macros.python.missing'", ), LoadProjectMacrosErrorTestCase( description="rejects project macro import cycle before execution", macro_files={ - "macros/python/first.py": ( + "sql/macros/python/first.py": ( "from pathlib import Path\n" "Path(__file__).parent.parent.joinpath('executed').touch()\n" - "from macros.python.second import second\n\n" + "from sql.macros.python.second import second\n\n" "def first() -> str:\n return second()\n" ), - "macros/python/second.py": ( - "from macros.python.first import first\n\ndef second() -> str:\n return first()\n" + "sql/macros/python/second.py": ( + "from sql.macros.python.first import first\n\ndef second() -> str:\n return first()\n" ), }, expected_error_fragment="Macro import cycle", @@ -276,7 +276,7 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before LoadProjectMacrosErrorTestCase( description="rejects local macro call cycle before execution", macro_files={ - "macros/python/cycle.py": ( + "sql/macros/python/cycle.py": ( "from pathlib import Path\n" "Path(__file__).parent.parent.joinpath('executed').touch()\n\n" "def first() -> str:\n return second()\n\n" @@ -288,11 +288,11 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before LoadProjectMacrosErrorTestCase( description="rejects relative import escaping macro package before dependency executes", macro_files={ - "macros/python/consumer.py": ( + "sql/macros/python/consumer.py": ( "from ....macros.shared import shared\n\n" "def consumer() -> str:\n return shared()\n" ), - "macros/python/shared.py": ( + "sql/macros/python/shared.py": ( "from pathlib import Path\n" "Path(__file__).parent.parent.joinpath('executed').touch()\n\n" "def shared() -> str:\n return 'shared'\n" @@ -303,7 +303,7 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before LoadProjectMacrosErrorTestCase( description="rejects dynamic local helper alias before execution", macro_files={ - "macros/python/helpers.py": ( + "sql/macros/python/helpers.py": ( "def _helper() -> str:\n return 'helper'\n\n" "def outer() -> str:\n" " alias = _helper\n" @@ -315,9 +315,9 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before LoadProjectMacrosErrorTestCase( description="rejects module-level local helper alias before execution", macro_files={ - "macros/python/shared.py": "def shared() -> str:\n return 'shared'\n", - "macros/python/helpers.py": ( - "from macros.python.shared import shared\n\n" + "sql/macros/python/shared.py": "def shared() -> str:\n return 'shared'\n", + "sql/macros/python/helpers.py": ( + "from sql.macros.python.shared import shared\n\n" "def _helper() -> str:\n return shared()\n\n" "_alias = _helper\n\n" "def outer() -> str:\n return _alias()\n" @@ -330,9 +330,9 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before LoadProjectMacrosErrorTestCase( description="rejects local helper call in macro default before execution", macro_files={ - "macros/python/shared.py": "def shared() -> str:\n return 'shared'\n", - "macros/python/helpers.py": ( - "from macros.python.shared import shared\n\n" + "sql/macros/python/shared.py": "def shared() -> str:\n return 'shared'\n", + "sql/macros/python/helpers.py": ( + "from sql.macros.python.shared import shared\n\n" "def _helper() -> str:\n return shared()\n\n" "def outer(value=_helper()) -> str:\n return value\n" ), @@ -344,9 +344,9 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before LoadProjectMacrosErrorTestCase( description="rejects module function replacing imported macro binding", macro_files={ - "macros/python/shared.py": "def shared() -> str:\n return 'shared'\n", - "macros/python/consumer.py": ( - "from macros.python.shared import shared as _helper\n\n" + "sql/macros/python/shared.py": "def shared() -> str:\n return 'shared'\n", + "sql/macros/python/consumer.py": ( + "from sql.macros.python.shared import shared as _helper\n\n" "def _helper() -> str:\n return 'local'\n\n" "def outer() -> str:\n return _helper()\n" ), @@ -356,49 +356,49 @@ def test_given_inaccessible_scoped_macro_import_when_loading_then_rejects_before LoadProjectMacrosErrorTestCase( description="rejects normalized project macro module path collision", macro_files={ - "macros/python/a.b.py": "def dotted() -> str:\n return 'dotted'\n", - "macros/python/a/b.py": "def nested() -> str:\n return 'nested'\n", + "sql/macros/python/a.b.py": "def dotted() -> str:\n return 'dotted'\n", + "sql/macros/python/a/b.py": "def nested() -> str:\n return 'nested'\n", }, - expected_error_fragment="Macro module path collision for 'macros.python.a.b'", + expected_error_fragment="Macro module path collision for 'sql.macros.python.a.b'", ), LoadProjectMacrosErrorTestCase( description="rejects public module owned constants", - macro_files={"macros/python/orders.py": "DEFAULT_LIMIT = 10\n"}, + macro_files={"sql/macros/python/orders.py": "DEFAULT_LIMIT = 10\n"}, expected_error_fragment="declaration 'DEFAULT_LIMIT' must be underscore-private", ), LoadProjectMacrosErrorTestCase( description="rejects public module owned classes", - macro_files={"macros/python/orders.py": "class Formatter:\n pass\n"}, + macro_files={"sql/macros/python/orders.py": "class Formatter:\n pass\n"}, expected_error_fragment="declaration 'Formatter' must be underscore-private", ), LoadProjectMacrosErrorTestCase( description="reports an earlier module's declaration before a later syntax error", macro_files={ - "macros/python/a_orders.py": "DEFAULT_LIMIT = 10\n", - "macros/python/b_customers.py": "def customers(:\n", + "sql/macros/python/a_orders.py": "DEFAULT_LIMIT = 10\n", + "sql/macros/python/b_customers.py": "def customers(:\n", }, expected_error_fragment=( - "^Macro module 'macros/python/a_orders.py' declaration 'DEFAULT_LIMIT' must be " + "^Macro module 'sql/macros/python/a_orders.py' declaration 'DEFAULT_LIMIT' must be " "underscore-private$" ), ), LoadProjectMacrosErrorTestCase( description="reports a later module's syntax error after earlier modules pass", macro_files={ - "macros/python/a_orders.py": "def orders() -> str:\n return 'orders'\n", - "macros/python/b_customers.py": "def customers(:\n", + "sql/macros/python/a_orders.py": "def orders() -> str:\n return 'orders'\n", + "sql/macros/python/b_customers.py": "def customers(:\n", }, expected_error_fragment="^Failed to parse macros from '.*b_customers.py': ", ), LoadProjectMacrosErrorTestCase( description="names the shallowest module-level use of an imported macro", macro_files={ - "macros/python/shared.py": ( + "sql/macros/python/shared.py": ( "def first() -> str:\n return 'first'\n\n" "def second() -> str:\n return 'second'\n" ), - "macros/python/consumer.py": ( - "from macros.python.shared import first, second\n\n" + "sql/macros/python/consumer.py": ( + "from sql.macros.python.shared import first, second\n\n" "_PAIRS = [[first], second]\n\n" "def consumer() -> str:\n return 'consumer'\n" ), @@ -640,7 +640,7 @@ def test_given_sql_macro_variants_when_expanding_then_it_returns_expected_sql( expanded_sql: str = expand_sql_macros( sql=test_case.sql, - file_path=tmp_path / "models" / "orders.sql", + file_path=tmp_path / "sql" / "models" / "orders.sql", loaded_macros=loaded_macros, macro_overrides=test_case.macro_overrides, macro_context=_MACRO_CONTEXT, @@ -729,7 +729,7 @@ def test_given_invalid_sql_macro_usage_when_expanding_then_it_raises_clear_error with pytest.raises(ValueError, match=test_case.expected_error_fragment): expand_sql_macros( sql=test_case.sql, - file_path=tmp_path / "models" / "orders.sql", + file_path=tmp_path / "sql" / "models" / "orders.sql", loaded_macros=loaded_macros, macro_overrides=test_case.macro_overrides, macro_context=_MACRO_CONTEXT, @@ -773,15 +773,15 @@ def test_given_sql_with_at_tokens_when_finding_macro_calls_then_returns_real_uni SqlMacroInventoryTestCase( description="an invalid SQL macro keeps the valid exports and names its own file", macro_files={ - "macros/sql/a_valid.sql": ( + "sql/macros/sql/a_valid.sql": ( 'MACRO (description "Valid", arguments (v BIGINT), returns BIGINT);\n\n@v + 1\n' ), - "macros/sql/z_invalid.sql": ( + "sql/macros/sql/z_invalid.sql": ( 'MACRO (description "Invalid", returns BIGINT);\n\nWITH a AS (SELECT 1)\n' ), }, expected_exports=("a_valid",), - expected_fault_paths=("macros/sql/z_invalid.sql",), + expected_fault_paths=("sql/macros/sql/z_invalid.sql",), ) ], ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_model_schemas.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_model_schemas.py index bc73d41f34..b4df6d1efc 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_model_schemas.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_model_schemas.py @@ -78,8 +78,8 @@ def test_given_identical_contract_headers_when_attaching_then_each_model_keeps_i sql_validation = false """.strip() + "\n", - "models/customers.sql": model_sql, - "models/staging/orders.sql": model_sql, + "sql/models/customers.sql": model_sql, + "sql/models/staging/orders.sql": model_sql, }, ) @@ -100,8 +100,8 @@ def test_given_identical_contract_headers_when_attaching_then_each_model_keeps_i ) assert len(locations) == test_case.expected_count assert locations == ( - (Path("models/customers.sql"), Path("models/customers.sql")), - (Path("models/staging/orders.sql"), Path("models/staging/orders.sql")), + (Path("sql/models/customers.sql"), Path("sql/models/customers.sql")), + (Path("sql/models/staging/orders.sql"), Path("sql/models/staging/orders.sql")), ) @@ -111,9 +111,9 @@ def test_given_identical_contract_headers_when_attaching_then_each_model_keeps_i ModelSchemaCompilationTestCase( description="inherited schemas with additive local columns", expected_schema_paths=( - "schemas/orders/base.sql", - "schemas/orders/observed.sql", - "schemas/orders/sourced.sql", + "sql/schemas/orders/base.sql", + "sql/schemas/orders/observed.sql", + "sql/schemas/orders/sourced.sql", ), expected_exact_column_names=( "order_id", @@ -138,8 +138,8 @@ def test_given_identical_contract_headers_when_attaching_then_each_model_keeps_i ), expected_exact_order_audit_names=("not_null", "unique"), expected_exact_order_audit_paths=( - "schemas/orders/base.sql", - "models/exact_orders.sql", + "sql/schemas/orders/base.sql", + "sql/models/exact_orders.sql", ), expected_superset_order_audit_names=("not_null",), ) @@ -155,8 +155,8 @@ def test_given_inherited_model_schemas_when_compiling_then_attaches_resolved_con tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "enums/order_status.sql": "ENUM (name order_status, members [OPEN, CLOSED]);", - "schemas/orders/base.sql": """ + "sql/enums/order_status.sql": "ENUM (name order_status, members [OPEN, CLOSED]);", + "sql/schemas/orders/base.sql": """ SCHEMA ( name order, description "Canonical order schema", @@ -166,14 +166,14 @@ def test_given_inherited_model_schemas_when_compiling_then_attaches_resolved_con ), ); """, - "schemas/orders/sourced.sql": """ + "sql/schemas/orders/sourced.sql": """ SCHEMA ( name sourced_order, extends order, columns (source (type VARCHAR, nullable false)), ); """, - "schemas/orders/observed.sql": """ + "sql/schemas/orders/observed.sql": """ SCHEMA ( name observed_order, extends sourced_order, @@ -181,7 +181,7 @@ def test_given_inherited_model_schemas_when_compiling_then_attaches_resolved_con columns (observed_at (type TIMESTAMP)), ); """, - "models/exact_orders.sql": """ + "sql/models/exact_orders.sql": """ MODEL ( materialized view, schema staging, @@ -200,7 +200,7 @@ def test_given_inherited_model_schemas_when_compiling_then_attaches_resolved_con CURRENT_TIMESTAMP::TIMESTAMP AS observed_at, TRUE::BOOLEAN AS quality_flag """, - "models/order_superset.sql": """ + "sql/models/order_superset.sql": """ MODEL ( materialized view, schema staging, @@ -343,7 +343,7 @@ def test_given_named_schema_contract_mismatch_when_validating_then_reports_expec tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "schemas/order.sql": """ + "sql/schemas/order.sql": """ SCHEMA ( name order, columns ( @@ -352,7 +352,7 @@ def test_given_named_schema_contract_mismatch_when_validating_then_reports_expec ), ); """, - "models/orders.sql": f""" + "sql/models/orders.sql": f""" MODEL ( model_schema order, contract {test_case.contract}, @@ -401,7 +401,7 @@ def test_given_dynamic_pivot_family_when_compiling_then_preserves_closed_contrac tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "models/stg_order_amounts.sql": """ + "sql/models/stg_order_amounts.sql": """ MODEL (description "Test model stg_order_amounts.", contract enforced, columns ( @@ -415,7 +415,7 @@ def test_given_dynamic_pivot_family_when_compiling_then_preserves_closed_contrac CAST('books' AS VARCHAR) AS category, CAST(10.25 AS DECIMAL(12,2)) AS amount """, - "models/customer_category_amounts.sql": """ + "sql/models/customer_category_amounts.sql": """ MODEL (description "Test model customer_category_amounts.", contract enforced, columns (customer_id (type INTEGER)), @@ -433,7 +433,7 @@ def test_given_dynamic_pivot_family_when_compiling_then_preserves_closed_contrac USING MAX(amount) GROUP BY customer_id """, - "models/customer_category_amounts_copy.sql": """ + "sql/models/customer_category_amounts_copy.sql": """ MODEL (description "Test model customer_category_amounts_copy.", contract enforced, columns (customer_id (type INTEGER)), @@ -514,7 +514,7 @@ def test_given_partial_upstream_schema_when_compiling_dynamic_pivot_then_closure tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "models/order_amounts.sql": """ + "sql/models/order_amounts.sql": """ MODEL (description "Test model order_amounts.", contract none, columns ( @@ -529,7 +529,7 @@ def test_given_partial_upstream_schema_when_compiling_dynamic_pivot_then_closure CAST(10 AS INTEGER) AS amount, CAST(99 AS INTEGER) AS unrelated """, - "models/customer_category_amounts.sql": """ + "sql/models/customer_category_amounts.sql": """ MODEL (description "Test model customer_category_amounts.", contract enforced, columns (customer_id (type INTEGER)), @@ -586,7 +586,7 @@ def test_given_unenforced_dynamic_upstream_when_compiling_passthrough_then_closu tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "models/order_amounts.sql": """ + "sql/models/order_amounts.sql": """ MODEL (description "Test model order_amounts.", contract enforced, columns ( @@ -602,7 +602,7 @@ def test_given_unenforced_dynamic_upstream_when_compiling_passthrough_then_closu CAST(10 AS INTEGER) AS amount, CAST(99 AS INTEGER) AS unrelated """, - "models/open_category_amounts.sql": """ + "sql/models/open_category_amounts.sql": """ MODEL (description "Test model open_category_amounts.", contract none, columns (customer_id (type INTEGER)), @@ -620,7 +620,7 @@ def test_given_unenforced_dynamic_upstream_when_compiling_passthrough_then_closu USING MAX(amount) GROUP BY customer_id """, - "models/closed_category_amounts.sql": """ + "sql/models/closed_category_amounts.sql": """ MODEL (description "Test model closed_category_amounts.", contract enforced, columns (customer_id (type INTEGER)), @@ -674,11 +674,11 @@ def test_given_parent_schema_type_change_when_fingerprinting_superset_then_ident ) -> None: repo_files: dict[str, str] = { "sqlbuild_project.toml": _PROJECT_FILE, - "schemas/order.sql": f""" + "sql/schemas/order.sql": f""" SCHEMA (name order, columns (order_id (type {test_case.initial_type}))); SCHEMA (name sourced_order, extends order, columns (source (type VARCHAR))); """, - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (model_schema sourced_order, contract none); SELECT 1 AS order_id, 'feed' AS source """, @@ -690,7 +690,7 @@ def test_given_parent_schema_type_change_when_fingerprinting_superset_then_ident tmp_path, repo_files | { - "schemas/order.sql": f""" + "sql/schemas/order.sql": f""" SCHEMA (name order, columns (order_id (type {test_case.changed_type}))); SCHEMA (name sourced_order, extends order, columns (source (type VARCHAR))); """ @@ -723,8 +723,8 @@ def test_given_local_cursor_column_when_validating_named_contract_then_combined_ tmp_path, { "sqlbuild_project.toml": _PROJECT_FILE, - "schemas/event.sql": "SCHEMA (name event, columns (event_id (type INTEGER)));", - "models/events.sql": """ + "sql/schemas/event.sql": "SCHEMA (name event, columns (event_id (type INTEGER)));", + "sql/models/events.sql": """ MODEL ( materialized incremental, incremental_strategy append, @@ -755,15 +755,15 @@ def test_given_local_cursor_column_when_validating_named_contract_then_combined_ ModelSchemaErrorTestCase( description="unknown model schema", repo_files={ - "models/orders.sql": "MODEL (model_schema missing); SELECT 1 AS id", + "sql/models/orders.sql": "MODEL (model_schema missing); SELECT 1 AS id", }, expected_error_fragment="unknown model_schema 'missing'", ), ModelSchemaErrorTestCase( description="model-local inherited column type override", repo_files={ - "schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", - "models/orders.sql": """ + "sql/schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", + "sql/models/orders.sql": """ MODEL (model_schema order, columns (ID (type BIGINT))); SELECT 1 AS id """, @@ -773,8 +773,8 @@ def test_given_local_cursor_column_when_validating_named_contract_then_combined_ ModelSchemaErrorTestCase( description="model-local inherited column nullability override", repo_files={ - "schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", - "models/orders.sql": """ + "sql/schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", + "sql/models/orders.sql": """ MODEL (model_schema order, columns (id (nullable false))); SELECT 1 AS id """, @@ -784,8 +784,8 @@ def test_given_local_cursor_column_when_validating_named_contract_then_combined_ ModelSchemaErrorTestCase( description="model-local inherited column description override", repo_files={ - "schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", - "models/orders.sql": """ + "sql/schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", + "sql/models/orders.sql": """ MODEL (model_schema order, columns (id (description "Local"))); SELECT 1 AS id """, @@ -795,70 +795,70 @@ def test_given_local_cursor_column_when_validating_named_contract_then_combined_ ModelSchemaErrorTestCase( description="model-local inherited column empty augmentation", repo_files={ - "schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", - "models/orders.sql": "MODEL (model_schema order, columns (id ())); SELECT 1 AS id", + "sql/schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", + "sql/models/orders.sql": "MODEL (model_schema order, columns (id ())); SELECT 1 AS id", }, expected_error_fragment="redeclares named-schema column 'id'", ), ModelSchemaErrorTestCase( description="unknown model-local inherited column audit reports model owner", repo_files={ - "schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", - "models/orders.sql": """ + "sql/schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));", + "sql/models/orders.sql": """ MODEL (model_schema order, columns (id (audits [missing_audit]))); SELECT 1 AS id """, }, expected_error_fragment=( - "models/orders.sql references unknown generic audit 'missing_audit'" + "sql/models/orders.sql references unknown generic audit 'missing_audit'" ), ), ModelSchemaErrorTestCase( description="unknown parent", repo_files={ - "schemas/order.sql": """ + "sql/schemas/order.sql": """ SCHEMA (name order, extends missing, columns (id (type INTEGER))); """, - "models/orders.sql": "MODEL (description 'Test model orders.'); SELECT 1 AS id", + "sql/models/orders.sql": "MODEL (description 'Test model orders.'); SELECT 1 AS id", }, expected_error_fragment="extends unknown schema 'missing'", ), ModelSchemaErrorTestCase( description="transitive inheritance cycle", repo_files={ - "schemas/order.sql": """ + "sql/schemas/order.sql": """ SCHEMA (name first, extends second, columns (first_id (type INTEGER))); SCHEMA (name second, extends third, columns (second_id (type INTEGER))); SCHEMA (name third, extends first, columns (third_id (type INTEGER))); """, - "models/orders.sql": "MODEL (description 'Test model orders.'); SELECT 1 AS id", + "sql/models/orders.sql": "MODEL (description 'Test model orders.'); SELECT 1 AS id", }, expected_error_fragment="first -> second -> third -> first", ), ModelSchemaErrorTestCase( description="case insensitive inherited duplicate", repo_files={ - "schemas/order.sql": """ + "sql/schemas/order.sql": """ SCHEMA (name base, columns (order_id (type INTEGER))); SCHEMA (name child, extends base, columns (ORDER_ID (type INTEGER))); """, - "models/orders.sql": "MODEL (description 'Test model orders.'); SELECT 1 AS id", + "sql/models/orders.sql": "MODEL (description 'Test model orders.'); SELECT 1 AS id", }, expected_error_fragment="redeclares inherited column 'ORDER_ID'", ), ModelSchemaErrorTestCase( description="unknown inherited column audit reports schema owner", repo_files={ - "schemas/order.sql": """ + "sql/schemas/order.sql": """ SCHEMA (name order, columns (id (type INTEGER, audits [missing_audit]))); """, - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (model_schema order); SELECT 1 AS id """, }, expected_error_fragment=( - "schemas/order.sql references unknown generic audit 'missing_audit'" + "sql/schemas/order.sql references unknown generic audit 'missing_audit'" ), ), ], diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_parameterized_sql_tests.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_parameterized_sql_tests.py index 17fe77969d..4d6ab0df8d 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_parameterized_sql_tests.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_parameterized_sql_tests.py @@ -44,23 +44,23 @@ description="expands ordered typed model and macro test cases before macros", repo_files=base_repo_files() | { - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 'open' AS status\n", - "models/customers.sql": "MODEL (description 'Test model customers.');\n\nSELECT 1 AS customer_id\n", - "sources/raw.yml": "sources:\n - name: raw_orders\n description: Test source raw_orders.\n expression: SELECT 1 AS order_id\n", - "seeds/schema.yml": ( + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 'open' AS status\n", + "sql/models/customers.sql": "MODEL (description 'Test model customers.');\n\nSELECT 1 AS customer_id\n", + "sql/sources/raw.yml": "sources:\n - name: raw_orders\n description: Test source raw_orders.\n expression: SELECT 1 AS order_id\n", + "sql/seeds/schema.yml": ( "seeds:\n - name: country_codes\n description: Test seed country_codes.\n columns:\n" " - name: code\n type: VARCHAR\n" ), - "seeds/country_codes.csv": "code\nGB\n", - "models/_constants/offset.sql": "CONSTANT (name offset, value 2);\n", - "models/_enums/state.sql": "ENUM (name state, members [OPEN, CLOSED]);\n", - "functions/sql/add_one.sql": """ + "sql/seeds/country_codes.csv": "code\nGB\n", + "sql/models/_constants/offset.sql": "CONSTANT (name offset, value 2);\n", + "sql/models/_enums/state.sql": "ENUM (name state, members [OPEN, CLOSED]);\n", + "sql/functions/sql/add_one.sql": """ FUNCTION (description "Test function add_one.", arguments (value INTEGER), returns INTEGER); value + 1 """.strip() + "\n", - "functions/sql/by_customer.sql": """ + "sql/functions/sql/by_customer.sql": """ FUNCTION (description "Test function by_customer.", arguments (customer_id INTEGER), returns table (customer_id INTEGER) diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_python_sql_references.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_python_sql_references.py index a915dad008..383e256635 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_python_sql_references.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_python_sql_references.py @@ -17,7 +17,7 @@ gate_model, python_check_source, python_hook_source, - python_loader_source, + python_loader_files, python_task_source, render_compile_diagnostics, ) @@ -31,27 +31,26 @@ sql_validation = false """ _DISABLED_PROJECT_FILE: str = _PROJECT_FILE + "\n[references]\nenforce_explicit = false\n" -_HOOK_PATH: str = "models/marts/_sqlbuild/_hooks/python/lookups.py" -_TASK_PATH: str = "python/tasks/export.py" +_HOOK_PATH: str = "sql/models/marts/_sqlbuild/_hooks/python/lookups.py" +_TASK_PATH: str = "python/nodes/tasks/export/asset.py" _HOOKED_HEADER: str = ( 'MODEL (description "Test model export.", post_hooks [python("refresh_lookup")]);' ) _MODELS: dict[str, str] = { - "models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), - "models/marts/orders.sql": gate_model(sql="SELECT 1 AS order_id", header=_HOOKED_HEADER), + "sql/models/marts/customers.sql": gate_model(sql="SELECT 1 AS customer_id"), + "sql/models/marts/orders.sql": gate_model(sql="SELECT 1 AS order_id", header=_HOOKED_HEADER), } _COUNTRY_SEED: dict[str, str] = { - "seeds/country_codes.yml": ( + "sql/seeds/country_codes.yml": ( "seeds:\n - name: country_codes\n description: Test seed country_codes.\n columns:\n - name: code\n type: VARCHAR\n" ), - "seeds/country_codes.csv": "code\nGB\n", + "sql/seeds/country_codes.csv": "code\nGB\n", } -_CHECK_PATH: str = "python/checks/orders.py" -_LOADER_PATH: str = "python/loaders/raw.py" +_CHECK_PATH: str = "python/nodes/checks/orders/checks.py" _RAW_SOURCES: dict[str, str] = { - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw_regions\n description: Test source raw_regions.\n managed: true\n write_strategy: table\n" " columns:\n - name: id\n type: INTEGER\n" @@ -77,7 +76,7 @@ "[P008]", "asset:export_orders names model:customers as 'customers' in SQL passed to " "ctx.query()", - "python/tasks/export.py:7", + "python/nodes/tasks/export/asset.py:7", 'depends_on=model("customers")', "if 'customers' is an external table that shares the name, qualify it with its " "schema", @@ -102,13 +101,13 @@ }, expected_error_fragments=( "[P008] check:orders_present names model:customers as 'customers' in SQL passed " - "to ctx.query() --> python/checks/orders.py:7", + "to ctx.query() --> python/nodes/checks/orders/checks.py:7", "[P008] asset:export_orders names model:customers as 'customers' in SQL passed to " - "ctx.query() --> python/tasks/export.py:7", + "ctx.query() --> python/nodes/tasks/export/asset.py:7", "[P008] asset:export_orders names model:customers as 'customers' in SQL passed to " - "ctx.query() --> python/tasks/export.py:8", + "ctx.query() --> python/nodes/tasks/export/asset.py:8", "[P008] asset:export_orders names model:orders as 'orders' in SQL passed to " - "ctx.query() --> python/tasks/export.py:8", + "ctx.query() --> python/nodes/tasks/export/asset.py:8", ), ), PythonSqlReferenceErrorTestCase( @@ -122,7 +121,7 @@ }, expected_error_fragments=( "[P008] asset:export_orders names model:customers as 'customers' in SQL passed to " - "ctx.query() --> python/tasks/export.py:7", + "ctx.query() --> python/nodes/tasks/export/asset.py:7", ), ), PythonSqlReferenceErrorTestCase( @@ -182,7 +181,7 @@ "[P008]", "check:orders_present names model:customers as 'customers' in SQL passed to " "ctx.query()", - "python/checks/orders.py:7", + "python/nodes/checks/orders/checks.py:7", 'declare it with depends_on=model("customers")', ), ), @@ -192,7 +191,7 @@ **_MODELS, **_RAW_SOURCES, _HOOK_PATH: python_hook_source(), - _LOADER_PATH: python_loader_source( + **python_loader_files( depends_on="", body=' ctx.query("SELECT * FROM raw_regions")\n' ), }, @@ -207,7 +206,7 @@ **_MODELS, **_RAW_SOURCES, _HOOK_PATH: python_hook_source(), - _LOADER_PATH: python_loader_source( + **python_loader_files( depends_on="raw_regions", body=' ctx.query("SELECT * FROM raw_regions")\n' ), }, @@ -219,7 +218,7 @@ **_MODELS, **_RAW_SOURCES, _HOOK_PATH: python_hook_source(), - _LOADER_PATH: python_loader_source( + **python_loader_files( depends_on="", body=' ctx.query("SELECT * FROM customers")\n' ), }, @@ -345,7 +344,7 @@ def test_given_hard_coded_project_relation_when_compiling_then_it_reports_p008( **_MODELS, **_RAW_SOURCES, _HOOK_PATH: python_hook_source(), - _LOADER_PATH: python_loader_source( + **python_loader_files( depends_on="raw_regions", body=( " regions = ctx.loader(raw_regions)\n" diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_scoped_named_declarations.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_scoped_named_declarations.py index 0f5f16a290..c785469390 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_scoped_named_declarations.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_scoped_named_declarations.py @@ -42,12 +42,12 @@ _SQL_HOOK: str = "HOOK (description 'Test hook.');\nSELECT 1" _PYTHON_HOOK: str = "from sqlbuild.hooks import hook\n\n\n@hook\ndef mark(ctx):\n '''Test hook mark.'''\n return None\n" _SINGULAR_BASE_FILES: dict[str, str] = { - "models/orders.sql": _ORDERS, - "models/customers.sql": _CUSTOMERS, - "sources/raw.yml": _SOURCES, - "seeds/codes.yml": _SEED_YAML, - "seeds/order_codes.csv": "order_id\n1\n", - "functions/sql/order_rows.sql": _TABLE_FUNCTION, + "sql/models/orders.sql": _ORDERS, + "sql/models/customers.sql": _CUSTOMERS, + "sql/sources/raw.yml": _SOURCES, + "sql/seeds/codes.yml": _SEED_YAML, + "sql/seeds/order_codes.csv": "order_id\n1\n", + "sql/functions/sql/order_rows.sql": _TABLE_FUNCTION, } @@ -85,9 +85,9 @@ NamedDeclarationAcceptedTestCase( "top-level singular audit over a sub-folder model and a table function", { - "models/marts/orders.sql": _ORDERS, - "functions/sql/order_rows.sql": _TABLE_FUNCTION, - "audits/singular/check.sql": ( + "sql/models/marts/orders.sql": _ORDERS, + "sql/functions/sql/order_rows.sql": _TABLE_FUNCTION, + "sql/audits/singular/check.sql": ( 'AUDIT ();\nSELECT * FROM __ref("orders") ' 'JOIN __table_fn("order_rows")() USING (order_id)' ), @@ -96,9 +96,9 @@ NamedDeclarationAcceptedTestCase( "top-level singular audit over a sub-folder model and a source", { - "models/marts/orders.sql": _ORDERS, - "sources/raw.yml": _SOURCES, - "audits/singular/check.sql": ( + "sql/models/marts/orders.sql": _ORDERS, + "sql/sources/raw.yml": _SOURCES, + "sql/audits/singular/check.sql": ( 'AUDIT ();\nSELECT * FROM __ref("orders") ' 'JOIN __source("raw_orders") USING (order_id)' ), @@ -107,9 +107,9 @@ NamedDeclarationAcceptedTestCase( "top-level generic audit used across one resource tree", { - "audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/marts/orders.sql": model_header(key="audits", value="[order_check]"), - "models/staging/orders_stage.sql": model_header( + "sql/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/marts/orders.sql": model_header(key="audits", value="[order_check]"), + "sql/models/staging/orders_stage.sql": model_header( key="audits", value="[order_check]" ), }, @@ -117,16 +117,18 @@ NamedDeclarationAcceptedTestCase( "folder-only generic audit used by its folder", { - "models/marts/_sqlbuild/_audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/marts/orders.sql": model_header(key="audits", value="[order_check]"), + "sql/models/marts/_sqlbuild/_audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/marts/orders.sql": model_header(key="audits", value="[order_check]"), }, ), NamedDeclarationAcceptedTestCase( "inherited generic audit used below its owner", { - "models/marts/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/marts/daily/orders.sql": model_header(key="audits", value="[order_check]"), - "models/marts/weekly/orders_weekly.sql": model_header( + "sql/models/marts/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/marts/daily/orders.sql": model_header( + key="audits", value="[order_check]" + ), + "sql/models/marts/weekly/orders_weekly.sql": model_header( key="audits", value="[order_check]" ), }, @@ -134,9 +136,9 @@ NamedDeclarationAcceptedTestCase( "scoped singular audit references resources below its owner", { - "models/marts/orders.sql": _ORDERS, - "models/marts/customers.sql": _CUSTOMERS, - "models/marts/_sqlbuild/audits/singular/check.sql": ( + "sql/models/marts/orders.sql": _ORDERS, + "sql/models/marts/customers.sql": _CUSTOMERS, + "sql/models/marts/_sqlbuild/audits/singular/check.sql": ( 'AUDIT ();\nSELECT * FROM __ref("orders") JOIN __ref("customers") ' "USING (order_id)" ), @@ -145,11 +147,11 @@ NamedDeclarationAcceptedTestCase( "audit factory is the only consumer of a scoped generic audit", { - "models/marts/_sqlbuild/_audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/marts/orders.sql": model_header( + "sql/models/marts/_sqlbuild/_audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/marts/orders.sql": model_header( key="audit_factories", value="[order_quality]" ), - "python/factories/quality.py": ( + "python/nodes/factories/quality.py": ( "from sqlbuild.audits import AuditCase, audit_factory\n\n\n" "@audit_factory\ndef order_quality():\n" ' return [AuditCase(name="order_ok", definition="order_check")]\n' @@ -159,14 +161,14 @@ NamedDeclarationAcceptedTestCase( "scoped schema, SQL hook, and Python hook bound below their owner", { - "models/marts/_sqlbuild/schemas/order_shape.sql": _SCHEMA, - "models/marts/_sqlbuild/hooks/sql/touch.sql": _SQL_HOOK, - "models/marts/_sqlbuild/hooks/python/lifecycle.py": _PYTHON_HOOK, - "models/marts/daily/orders.sql": ( + "sql/models/marts/_sqlbuild/schemas/order_shape.sql": _SCHEMA, + "sql/models/marts/_sqlbuild/hooks/sql/touch.sql": _SQL_HOOK, + "sql/models/marts/_sqlbuild/hooks/python/lifecycle.py": _PYTHON_HOOK, + "sql/models/marts/daily/orders.sql": ( 'MODEL (model_schema order_shape, pre_hooks [sql("touch")], ' 'post_hooks [python("mark")]);\nSELECT 1 AS order_id' ), - "models/marts/weekly/orders_weekly.sql": ( + "sql/models/marts/weekly/orders_weekly.sql": ( 'MODEL (model_schema order_shape, pre_hooks [sql("touch")], ' 'post_hooks [python("mark")]);\nSELECT 1 AS order_id' ), @@ -175,16 +177,16 @@ NamedDeclarationAcceptedTestCase( "child schema extends a parent visible from the child's folder", { - "models/marts/_sqlbuild/schemas/order_shape.sql": _SCHEMA, - "models/marts/daily/_sqlbuild/_schemas/daily_shape.sql": ( + "sql/models/marts/_sqlbuild/schemas/order_shape.sql": _SCHEMA, + "sql/models/marts/daily/_sqlbuild/_schemas/daily_shape.sql": ( "SCHEMA (name daily_shape, extends order_shape, " "columns (order_date (type DATE)));" ), - "models/marts/daily/orders.sql": ( + "sql/models/marts/daily/orders.sql": ( "MODEL (model_schema daily_shape);\n" "SELECT 1 AS order_id, CURRENT_DATE AS order_date" ), - "models/marts/weekly/orders_weekly.sql": model_header( + "sql/models/marts/weekly/orders_weekly.sql": model_header( key="model_schema", value="order_shape" ), }, @@ -212,53 +214,53 @@ def test_given_valid_named_declaration_layout_when_compiling_then_project_is_acc "test_case", ( NamedDeclarationErrorTestCase( - "audit file directly under audits/", - {"models/orders.sql": _ORDERS, "audits/check.sql": _GENERIC_AUDIT}, - ("Unsupported entries in audits/", "audits/generic/ or audits/singular/"), + "audit file directly under sql/audits/", + {"sql/models/orders.sql": _ORDERS, "sql/audits/check.sql": _GENERIC_AUDIT}, + ("Unsupported entries in sql/audits/", "sql/audits/generic/ or sql/audits/singular/"), ), NamedDeclarationErrorTestCase( "audit folder other than generic or singular", - {"models/orders.sql": _ORDERS, "audits/checks/check.sql": _GENERIC_AUDIT}, - ("Unsupported entries in audits/: audits/checks",), + {"sql/models/orders.sql": _ORDERS, "sql/audits/checks/check.sql": _GENERIC_AUDIT}, + ("Unsupported entries in sql/audits/: sql/audits/checks",), ), NamedDeclarationErrorTestCase( "folder-only singular audit role", { - "models/marts/orders.sql": _ORDERS, - "models/marts/_sqlbuild/_audits/singular/check.sql": _GENERIC_AUDIT, + "sql/models/marts/orders.sql": _ORDERS, + "sql/models/marts/_sqlbuild/_audits/singular/check.sql": _GENERIC_AUDIT, }, - ("models/marts/_sqlbuild/_audits/singular/ is invalid",), + ("sql/models/marts/_sqlbuild/_audits/singular/ is invalid",), ), NamedDeclarationErrorTestCase( "_sqlbuild directly under a resource tree root", { - "models/orders.sql": model_header(key="audits", value="[order_check]"), - "models/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/orders.sql": model_header(key="audits", value="[order_check]"), + "sql/models/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, }, - ("Grouped declaration root models/_sqlbuild/ must be below a concrete owner",), + ("Grouped declaration root sql/models/_sqlbuild/ must be below a concrete owner",), ), NamedDeclarationErrorTestCase( "unsupported hook language folder", { - "models/marts/orders.sql": _ORDERS, - "models/marts/_sqlbuild/hooks/shell/touch.sql": _SQL_HOOK, + "sql/models/marts/orders.sql": _ORDERS, + "sql/models/marts/_sqlbuild/hooks/shell/touch.sql": _SQL_HOOK, }, ("hooks/ accepts only python/, sql/",), ), NamedDeclarationErrorTestCase( "scoped audit uses a constant that is not visible from the audit's folder", { - "models/staging/_sqlbuild/_constants/order_limit.sql": ( + "sql/models/staging/_sqlbuild/_constants/order_limit.sql": ( "CONSTANT (name order_limit, value 10);" ), - "models/staging/orders_stage.sql": ( + "sql/models/staging/orders_stage.sql": ( 'MODEL (description "Test model orders_stage.");\nSELECT @const("order_limit") AS order_id' ), - "models/marts/_sqlbuild/_audits/generic/order_check.sql": ( + "sql/models/marts/_sqlbuild/_audits/generic/order_check.sql": ( 'AUDIT ();\nSELECT * FROM __ref("@model") ' 'WHERE order_id > @const("order_limit")' ), - "models/marts/orders.sql": model_header(key="audits", value="[order_check]"), + "sql/models/marts/orders.sql": model_header(key="audits", value="[order_check]"), }, ("order_limit", "known but inaccessible"), ), @@ -326,176 +328,198 @@ def test_given_invalid_named_declaration_layout_when_compiling_then_error_names_ NamedDeclarationErrorTestCase( "top-level generic audit used under one folder", { - "audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/marts/orders.sql": model_header(key="audits", value="[order_check]"), + "sql/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/marts/orders.sql": model_header(key="audits", value="[order_check]"), }, - ("[S024]", "Move it to 'models/marts/_sqlbuild/_audits/generic/'"), + ("[S024]", "Move it to 'sql/models/marts/_sqlbuild/_audits/generic/'"), ), NamedDeclarationErrorTestCase( "top-level generic audit used across sibling sub-folders", { - "audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/marts/daily/orders.sql": model_header(key="audits", value="[order_check]"), - "models/marts/weekly/orders_weekly.sql": model_header( + "sql/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/marts/daily/orders.sql": model_header( + key="audits", value="[order_check]" + ), + "sql/models/marts/weekly/orders_weekly.sql": model_header( key="audits", value="[order_check]" ), }, - ("Move it to 'models/marts/_sqlbuild/audits/generic/'",), + ("Move it to 'sql/models/marts/_sqlbuild/audits/generic/'",), ), NamedDeclarationErrorTestCase( "inherited generic audit used only by its own folder", { - "models/marts/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/marts/orders.sql": model_header(key="audits", value="[order_check]"), + "sql/models/marts/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/marts/orders.sql": model_header(key="audits", value="[order_check]"), }, - ("Move it to 'models/marts/_sqlbuild/_audits/generic/'",), + ("Move it to 'sql/models/marts/_sqlbuild/_audits/generic/'",), ), NamedDeclarationErrorTestCase( "top-level singular audit referencing one folder", { - "models/marts/orders.sql": _ORDERS, - "models/marts/customers.sql": _CUSTOMERS, - "audits/singular/check.sql": ( + "sql/models/marts/orders.sql": _ORDERS, + "sql/models/marts/customers.sql": _CUSTOMERS, + "sql/audits/singular/check.sql": ( 'AUDIT ();\nSELECT * FROM __ref("orders") JOIN __ref("customers") ' "USING (order_id)" ), }, ( "References: model:customers, model:orders", - "models/marts/_sqlbuild/audits/singular/", + "sql/models/marts/_sqlbuild/audits/singular/", ), ), NamedDeclarationErrorTestCase( "top-level generic audit used only through an audit factory", { - "audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/marts/orders.sql": model_header( + "sql/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/marts/orders.sql": model_header( key="audit_factories", value="[order_quality]" ), - "python/factories/quality.py": ( + "python/nodes/factories/quality.py": ( "from sqlbuild.audits import AuditCase, audit_factory\n\n\n" "@audit_factory\ndef order_quality():\n" ' return [AuditCase(name="order_ok", definition="order_check")]\n' ), }, - ("Move it to 'models/marts/_sqlbuild/_audits/generic/'",), + ("Move it to 'sql/models/marts/_sqlbuild/_audits/generic/'",), ), NamedDeclarationErrorTestCase( "top-level schema used under one folder", { - "schemas/order_shape.sql": _SCHEMA, - "models/marts/orders.sql": model_header(key="model_schema", value="order_shape"), + "sql/schemas/order_shape.sql": _SCHEMA, + "sql/models/marts/orders.sql": model_header( + key="model_schema", value="order_shape" + ), }, - ("Move it to 'models/marts/_sqlbuild/_schemas/'",), + ("Move it to 'sql/models/marts/_sqlbuild/_schemas/'",), ), NamedDeclarationErrorTestCase( "top-level SQL hook used under one folder", { - "hooks/sql/touch.sql": _SQL_HOOK, - "models/marts/orders.sql": model_header(key="pre_hooks", value='[sql("touch")]'), + "sql/hooks/sql/touch.sql": _SQL_HOOK, + "sql/models/marts/orders.sql": model_header( + key="pre_hooks", value='[sql("touch")]' + ), }, - ("Move it to 'models/marts/_sqlbuild/_hooks/sql/'",), + ("Move it to 'sql/models/marts/_sqlbuild/_hooks/sql/'",), ), NamedDeclarationErrorTestCase( "top-level Python hook used under one folder", { - "hooks/python/lifecycle.py": _PYTHON_HOOK, - "models/marts/orders.sql": model_header(key="pre_hooks", value='[python("mark")]'), + "sql/hooks/python/lifecycle.py": _PYTHON_HOOK, + "sql/models/marts/orders.sql": model_header( + key="pre_hooks", value='[python("mark")]' + ), }, - ("Move it to 'models/marts/_sqlbuild/_hooks/python/'",), + ("Move it to 'sql/models/marts/_sqlbuild/_hooks/python/'",), ), NamedDeclarationErrorTestCase( "scoped generic audit used from a sibling folder", { - "models/marts/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/staging/orders.sql": model_header(key="audits", value="[order_check]"), + "sql/models/marts/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/staging/orders.sql": model_header(key="audits", value="[order_check]"), }, ( "[S006]", - "Generic audit 'order_check' is not visible from 'models/staging/orders.sql'", + "Generic audit 'order_check' is not visible from 'sql/models/staging/orders.sql'", ), ), NamedDeclarationErrorTestCase( "every consumer of an invisible scoped audit is reported", { - "models/marts/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/staging/orders.sql": model_header(key="audits", value="[order_check]"), - "models/staging/customers.sql": model_header(key="audits", value="[order_check]"), + "sql/models/marts/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/staging/orders.sql": model_header(key="audits", value="[order_check]"), + "sql/models/staging/customers.sql": model_header( + key="audits", value="[order_check]" + ), }, ( "[S006] Generic audit 'order_check' is not visible from " - "'models/staging/customers.sql'", - "[S006] Generic audit 'order_check' is not visible from 'models/staging/orders.sql'", + "'sql/models/staging/customers.sql'", + "[S006] Generic audit 'order_check' is not visible from 'sql/models/staging/orders.sql'", ), ), NamedDeclarationErrorTestCase( "scoped generic audit used from a parent folder", { - "models/marts/daily/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, - "models/marts/orders.sql": model_header(key="audits", value="[order_check]"), + "sql/models/marts/daily/_sqlbuild/audits/generic/order_check.sql": _GENERIC_AUDIT, + "sql/models/marts/orders.sql": model_header(key="audits", value="[order_check]"), }, - ("Generic audit 'order_check' is not visible from 'models/marts/orders.sql'",), + ("Generic audit 'order_check' is not visible from 'sql/models/marts/orders.sql'",), ), NamedDeclarationErrorTestCase( "scoped schema bound from a sibling folder", { - "models/marts/_sqlbuild/_schemas/order_shape.sql": _SCHEMA, - "models/staging/orders.sql": model_header(key="model_schema", value="order_shape"), + "sql/models/marts/_sqlbuild/_schemas/order_shape.sql": _SCHEMA, + "sql/models/staging/orders.sql": model_header( + key="model_schema", value="order_shape" + ), }, - ("Schema 'order_shape' is not visible from 'models/staging/orders.sql'",), + ("Schema 'order_shape' is not visible from 'sql/models/staging/orders.sql'",), ), NamedDeclarationErrorTestCase( "scoped schema bound from a parent folder", { - "models/marts/daily/_sqlbuild/schemas/order_shape.sql": _SCHEMA, - "models/marts/orders.sql": model_header(key="model_schema", value="order_shape"), + "sql/models/marts/daily/_sqlbuild/schemas/order_shape.sql": _SCHEMA, + "sql/models/marts/orders.sql": model_header( + key="model_schema", value="order_shape" + ), }, - ("Schema 'order_shape' is not visible from 'models/marts/orders.sql'",), + ("Schema 'order_shape' is not visible from 'sql/models/marts/orders.sql'",), ), NamedDeclarationErrorTestCase( "scoped SQL hook called from a sibling folder", { - "models/marts/_sqlbuild/_hooks/sql/touch.sql": _SQL_HOOK, - "models/staging/orders.sql": model_header(key="pre_hooks", value='[sql("touch")]'), + "sql/models/marts/_sqlbuild/_hooks/sql/touch.sql": _SQL_HOOK, + "sql/models/staging/orders.sql": model_header( + key="pre_hooks", value='[sql("touch")]' + ), }, - ("SQL hook 'touch' is not visible from 'models/staging/orders.sql'",), + ("SQL hook 'touch' is not visible from 'sql/models/staging/orders.sql'",), ), NamedDeclarationErrorTestCase( "scoped SQL hook called from a parent folder", { - "models/marts/daily/_sqlbuild/hooks/sql/touch.sql": _SQL_HOOK, - "models/marts/orders.sql": model_header(key="pre_hooks", value='[sql("touch")]'), + "sql/models/marts/daily/_sqlbuild/hooks/sql/touch.sql": _SQL_HOOK, + "sql/models/marts/orders.sql": model_header( + key="pre_hooks", value='[sql("touch")]' + ), }, - ("SQL hook 'touch' is not visible from 'models/marts/orders.sql'",), + ("SQL hook 'touch' is not visible from 'sql/models/marts/orders.sql'",), ), NamedDeclarationErrorTestCase( "scoped Python hook called from a sibling folder", { - "models/marts/_sqlbuild/_hooks/python/lifecycle.py": _PYTHON_HOOK, - "models/staging/orders.sql": model_header( + "sql/models/marts/_sqlbuild/_hooks/python/lifecycle.py": _PYTHON_HOOK, + "sql/models/staging/orders.sql": model_header( key="pre_hooks", value='[python("mark")]' ), }, - ("Python hook 'mark' is not visible from 'models/staging/orders.sql'",), + ("Python hook 'mark' is not visible from 'sql/models/staging/orders.sql'",), ), NamedDeclarationErrorTestCase( "scoped Python hook called from a parent folder", { - "models/marts/daily/_sqlbuild/hooks/python/lifecycle.py": _PYTHON_HOOK, - "models/marts/orders.sql": model_header(key="pre_hooks", value='[python("mark")]'), + "sql/models/marts/daily/_sqlbuild/hooks/python/lifecycle.py": _PYTHON_HOOK, + "sql/models/marts/orders.sql": model_header( + key="pre_hooks", value='[python("mark")]' + ), }, - ("Python hook 'mark' is not visible from 'models/marts/orders.sql'",), + ("Python hook 'mark' is not visible from 'sql/models/marts/orders.sql'",), ), NamedDeclarationErrorTestCase( "child schema extends a parent from a sibling folder", { - "models/staging/_sqlbuild/schemas/order_shape.sql": _SCHEMA, - "models/marts/_sqlbuild/_schemas/daily_shape.sql": ( + "sql/models/staging/_sqlbuild/schemas/order_shape.sql": _SCHEMA, + "sql/models/marts/_sqlbuild/_schemas/daily_shape.sql": ( "SCHEMA (name daily_shape, extends order_shape, " "columns (order_date (type DATE)));" ), - "models/marts/orders.sql": model_header(key="model_schema", value="daily_shape"), - "models/staging/orders_stage.sql": model_header( + "sql/models/marts/orders.sql": model_header( + key="model_schema", value="daily_shape" + ), + "sql/models/staging/orders_stage.sql": model_header( key="model_schema", value="order_shape" ), }, @@ -504,16 +528,16 @@ def test_given_invalid_named_declaration_layout_when_compiling_then_error_names_ NamedDeclarationErrorTestCase( "scoped schema uses an enum type that is not visible from the schema's folder", { - "models/staging/_sqlbuild/_enums/order_status.sql": ( + "sql/models/staging/_sqlbuild/_enums/order_status.sql": ( "ENUM (name order_status, members [OPEN, CLOSED]);" ), - "models/staging/orders_stage.sql": ( + "sql/models/staging/orders_stage.sql": ( 'MODEL (description "Test model orders_stage.");\nSELECT @enum("order_status").OPEN AS status' ), - "models/marts/_sqlbuild/_schemas/order_shape.sql": ( + "sql/models/marts/_sqlbuild/_schemas/order_shape.sql": ( "SCHEMA (name order_shape, columns (status (type order_status)));" ), - "models/marts/orders.sql": ( + "sql/models/marts/orders.sql": ( "MODEL (model_schema order_shape);\nSELECT 'OPEN' AS status" ), }, @@ -541,8 +565,10 @@ def test_given_invalid_named_declaration_use_when_compiling_then_diagnostics_nam NamedDeclarationWarningTestCase( "advisory placement keeps a misplaced scoped schema compiling", { - "schemas/order_shape.sql": _SCHEMA, - "models/marts/orders.sql": model_header(key="model_schema", value="order_shape"), + "sql/schemas/order_shape.sql": _SCHEMA, + "sql/models/marts/orders.sql": model_header( + key="model_schema", value="order_shape" + ), }, "S024", ), diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_sql_analysis_validation.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_sql_analysis_validation.py index 9db54e9764..7e0c1d5794 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_sql_analysis_validation.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_sql_analysis_validation.py @@ -12,7 +12,7 @@ ) _MODEL_NAME: str = "test_model" -_FILE_PATH: Path = Path("models/test_model.sql") +_FILE_PATH: Path = Path("sql/models/test_model.sql") @pytest.mark.parametrize( diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_sql_vars.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_sql_vars.py index 0dd1695407..81e8209be6 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_sql_vars.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_sql_vars.py @@ -12,7 +12,7 @@ SubstituteSqlVarsTestCase, ) -_FILE_PATH: Path = Path("models/test_model.sql") +_FILE_PATH: Path = Path("sql/models/test_model.sql") @pytest.mark.parametrize( diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_typed_macro_references.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_typed_macro_references.py index 35bcb9de2f..1cb400c2d0 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_typed_macro_references.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_typed_macro_references.py @@ -37,8 +37,8 @@ 'name = "demo"\nadapter = "duckdb"\n\n[settings]\nsql_analysis = false\n' "sql_validation = false\n" ), - "models/orders_eu.sql": "MODEL (description 'Test model orders_eu.');\nSELECT 1 AS order_id", - "models/orders_us.sql": "MODEL (description 'Test model orders_us.');\nSELECT 2 AS order_id", + "sql/models/orders_eu.sql": "MODEL (description 'Test model orders_eu.');\nSELECT 1 AS order_id", + "sql/models/orders_us.sql": "MODEL (description 'Test model orders_us.');\nSELECT 2 AS order_id", } @@ -123,7 +123,7 @@ def test_given_typed_reference_arguments_when_expanding_then_renders_call_site_r sql="@py.orders_base()", expected_error_fragments=( "model:order_summary depends on model:stg_orders through macro orders_base()", - "--> macros/python/common.py", + "--> sql/macros/python/common.py", 'pass it in: @py.orders_base(__ref("stg_orders"))', "[references]\n enforce_explicit = false", ), @@ -391,8 +391,8 @@ def test_given_typed_macro_arguments_when_compiling_then_every_argument_is_a_dep tmp_path, _DEPENDENCY_PROJECT_FILES | { - "macros/python/common.py": test_case.macro_file_contents, - "models/order_summary.sql": f"MODEL (description 'Test model order_summary.');\n{test_case.sql}", + "sql/macros/python/common.py": test_case.macro_file_contents, + "sql/models/order_summary.sql": f"MODEL (description 'Test model order_summary.');\n{test_case.sql}", }, ) diff --git a/tests/unit/src/sqlbuild/compiler/compile/_test_helpers.py b/tests/unit/src/sqlbuild/compiler/compile/_test_helpers.py index c0cc5cd6a7..78db4b69a6 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_test_helpers.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_test_helpers.py @@ -15,7 +15,8 @@ def base_repo_files() -> dict[str, str]: return { "sqlbuild_project.toml": ( - 'name = "demo"\nadapter = "duckdb"\n\n[settings]\ndefault_audit_severity = "warn"\n' + 'name = "demo"\nadapter = "duckdb"\nextra_paths = ["dbt"]\n\n' + '[settings]\ndefault_audit_severity = "warn"\n' ), } diff --git a/tests/unit/src/sqlbuild/compiler/compile/test_cursor_start.py b/tests/unit/src/sqlbuild/compiler/compile/test_cursor_start.py index 0cdc703b1f..bee1a653a8 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/test_cursor_start.py +++ b/tests/unit/src/sqlbuild/compiler/compile/test_cursor_start.py @@ -31,7 +31,7 @@ "[defaults]\ncursor_start = 10\n\n" "[path_defaults.events]\ncursor_start = 20\n" ), - "models/events/orders.sql": ( + "sql/models/events/orders.sql": ( "MODEL (description 'Test model orders.',\nmaterialized incremental\nincremental_strategy delete_insert\n" "cursor id\ncursor_type integer\ncursor_start 30\n);\n\nSELECT 1 AS id" ), @@ -74,7 +74,7 @@ def test_given_cursor_start_layers_when_building_compile_inputs_then_model_uses_ '[path_defaults.events]\ncursor_start_max_ahead = "3d"\n' 'cursor_future_max_distance = "disabled"\n' ), - "models/events/orders.sql": ( + "sql/models/events/orders.sql": ( "MODEL (description 'Test model orders.',\nmaterialized incremental\nincremental_strategy delete_insert\n" "cursor event_at\ncursor_type timestamp\ncursor_grain day\n" "cursor_start_max_ahead '0d'\ncursor_start_max_action cap\n" @@ -117,7 +117,7 @@ def test_given_cursor_safety_layers_when_compiling_then_model_fields_use_model_p description="cursor_start requires cursor", repo_files={ "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\nmaterialized incremental\nincremental_strategy merge\n" "cursor_type integer\ncursor_start 100\n);\n\nSELECT 1 AS id" ), @@ -128,7 +128,7 @@ def test_given_cursor_safety_layers_when_compiling_then_model_fields_use_model_p description="integer cursor_start rejects non whole number", repo_files={ "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.',\nmaterialized incremental\nincremental_strategy merge\ncursor id\n" "cursor_type integer\nunique_key [id]\n" "cursor_start '3.14'\n);\n\nSELECT 1 AS id" diff --git a/tests/unit/src/sqlbuild/compiler/compile/test_main.py b/tests/unit/src/sqlbuild/compiler/compile/test_main.py index 990a93bb5b..9c8ca74b7b 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/test_main.py +++ b/tests/unit/src/sqlbuild/compiler/compile/test_main.py @@ -125,7 +125,7 @@ local_only = "present" """.strip() + "\n", - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", columns ( order_id (type VARCHAR), @@ -135,7 +135,7 @@ select 1 """.strip() + "\n", - "models/staging/nested/orders_enriched.sql": """ + "sql/models/staging/nested/orders_enriched.sql": """ MODEL (description "Test model orders_enriched.", materialized incremental, incremental_strategy delete_insert, @@ -151,7 +151,7 @@ select __cursor_start ( ) as batch_start, __cursor_end() as batch_end """.strip() + "\n", - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: country_codes description: Test seed country_codes. @@ -162,8 +162,8 @@ type: VARCHAR """.strip() + "\n", - "seeds/country_codes.csv": "country_code,country_name\nUS,United States\n", - "sources/raw.yml": """ + "sql/seeds/country_codes.csv": "country_code,country_name\nUS,United States\n", + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -222,7 +222,7 @@ description="allows models with no matching schema metadata", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n" + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n" }, selected_target=None, cli_vars={}, @@ -243,7 +243,7 @@ description="validates incremental config columns against authored enforced contract", repo_files=base_repo_files() | { - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", materialized incremental, contract enforced, @@ -302,7 +302,7 @@ description="does not require snapshot generated validity columns in enforced contract", repo_files=base_repo_files() | { - "models/customer_snapshot.sql": """ + "sql/models/customer_snapshot.sql": """ MODEL (description "Test model customer_snapshot.", materialized snapshot, contract enforced, @@ -396,7 +396,7 @@ shared = "local" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target="prod", cli_vars={}, @@ -452,7 +452,7 @@ target = "dev" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, cli_vars=None, @@ -489,7 +489,7 @@ local_only = "present" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, cli_vars={"cli_only": "present"}, @@ -531,7 +531,7 @@ active = "dev" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, cli_vars=None, @@ -573,7 +573,7 @@ local_only = "present" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, cli_vars={"cli_only": "present"}, @@ -612,7 +612,7 @@ warehouse = "dev_wh" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, cli_vars=None, @@ -653,7 +653,7 @@ local_only = "present" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, cli_vars={"shared": "cli", "cli_only": "present"}, @@ -679,7 +679,7 @@ description="preserves direct model header full refresh config", repo_files=base_repo_files() | { - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized incremental, incremental_strategy append, " "full_refresh false);\n\nSELECT 1 AS id\n" ), @@ -711,12 +711,12 @@ "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[defaults]\nfull_refresh = false\n' ), - "models/a_incremental.sql": ( + "sql/models/a_incremental.sql": ( "MODEL (description 'Test model a_incremental.', materialized incremental, incremental_strategy append);" "\n\nSELECT 1 AS id\n" ), - "models/b_view.sql": "MODEL (description 'Test model b_view.', materialized view);\n\nSELECT 1 AS id\n", - "models/c_table.sql": "MODEL (description 'Test model c_table.', materialized table);\n\nSELECT 1 AS id\n", + "sql/models/b_view.sql": "MODEL (description 'Test model b_view.', materialized view);\n\nSELECT 1 AS id\n", + "sql/models/c_table.sql": "MODEL (description 'Test model c_table.', materialized table);\n\nSELECT 1 AS id\n", }, selected_target=None, cli_vars=None, @@ -754,7 +754,7 @@ '[defaults]\nmaterialized = "${model_kind}"\nfull_refresh = false\n' 'incremental_strategy = "append"\n' ), - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nSELECT 1 AS id\n", }, selected_target=None, cli_vars=None, @@ -807,7 +807,7 @@ absolute = 0.01 """.strip() + "\n", - "models/staging/orders.sql": ( + "sql/models/staging/orders.sql": ( "MODEL (description 'Test model orders.',\n unique_key [order_id]," "\n cursor event_time," "\n cursor_type timestamp," @@ -866,7 +866,7 @@ append_cursor_inclusive = false """.strip() + "\n", - "models/staging/orders.sql": ( + "sql/models/staging/orders.sql": ( "MODEL (description 'Test model orders.',\n cursor event_time," "\n cursor_type timestamp," "\n cursor_grain second," @@ -929,7 +929,7 @@ absolute = 0.01 """.strip() + "\n", - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", row_diff_exclude_columns [run_id, loaded_at], row_diff_tolerances ( @@ -1013,7 +1013,7 @@ schema = "dev_${ENV:USER}_${CTX:model.schema}" """.strip() + "\n", - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", materialized incremental, incremental_strategy append, @@ -1090,7 +1090,7 @@ schema = "schema_${CTX:run.id}" """.strip() + "\n", - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", alias 'orders_${CTX:run.target}', config ( @@ -1140,8 +1140,8 @@ schema = "${CTX:model.name}_schema" """.strip() + "\n", - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", - "models/customers.sql": "MODEL (description 'Test model customers.');\n\nselect 2\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/customers.sql": "MODEL (description 'Test model customers.');\n\nselect 2\n", }, selected_target=None, cli_vars=None, @@ -1177,7 +1177,7 @@ append_cursor_inclusive = "${if(eq(ENV:APPEND_INCLUSIVE, '0'), false, true)}" """.strip() + "\n", - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", cursor event_time, cursor_type timestamp, @@ -1242,7 +1242,7 @@ valid_order_id = "1" """.strip() + "\n", - "models/marts/orders.sql": """ + "sql/models/marts/orders.sql": """ MODEL ( schema "${model_schema}", alias "orders_${ENV:ENV_NAME}", @@ -1334,7 +1334,7 @@ schema = "preserve" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, cli_vars=None, @@ -1365,7 +1365,7 @@ description="expands macros in model query and sql interpolation in hook strings", repo_files=base_repo_files() | { - "macros/python/common.py": """ + "sql/macros/python/common.py": """ def project_columns(ctx) -> str: optional_suffix = "" if ctx.vars["optional_suffix"] is None else ctx.vars["optional_suffix"] return ( @@ -1398,7 +1398,7 @@ def grant_select(target: str) -> str: database = "analytics" """.strip() + "\n", - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", alias orders_dev, post_hooks [inline_sql('@py.grant_select("@@CTX:destination.qualified")')], @@ -1421,13 +1421,13 @@ def grant_select(target: str) -> str: SELECT 1 """.strip() + "\n", - "audits/singular/orders.sql": """ + "sql/audits/singular/orders.sql": """ AUDIT (); SELECT @py.project_columns() FROM __source("raw_orders") JOIN __ref("orders") USING (order_id) """.strip() + "\n", - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -1528,7 +1528,7 @@ def grant_select(target: str) -> str: } """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", "tests/unit/orders_test.sql": """ TEST (); @@ -1585,7 +1585,7 @@ def grant_select(target: str) -> str: description="applies sql interpolation across all authored sql text fields", repo_files=base_repo_files() | { - "macros/python/common.py": """ + "sql/macros/python/common.py": """ def source_columns() -> str: return "1 AS id" """.strip() @@ -1606,7 +1606,7 @@ def source_columns() -> str: min_amount = "100" """.strip() + "\n", - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", pre_hooks [inline_sql("insert into @@audit_schema.load_log select '@@ENV:USER_NAME'")], columns (order_id (audits [source_filter])), @@ -1618,7 +1618,7 @@ def source_columns() -> str: AND event_date >= CURRENT_DATE """.strip() + "\n", - "functions/sql/is_large_order.sql": """ + "sql/functions/sql/is_large_order.sql": """ FUNCTION (description "Test function is_large_order.", arguments (amount INTEGER), returns BOOLEAN, @@ -1640,14 +1640,14 @@ def source_columns() -> str: SELECT 1 """.strip() + "\n", - "audits/singular/orders.sql": """ + "sql/audits/singular/orders.sql": """ AUDIT (); SELECT * FROM __ref("orders") JOIN __source("raw_orders") USING (id) WHERE loaded_by = '@@ENV:USER_NAME' """.strip() + "\n", - "audits/generic/source_filter.sql": """ + "sql/audits/generic/source_filter.sql": """ AUDIT (); SELECT @column @@ -1656,7 +1656,7 @@ def source_columns() -> str: AND source_system = '@@ENV:SOURCE_SYSTEM' """.strip() + "\n", - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -1772,7 +1772,7 @@ def source_columns() -> str: database = "analytics" """.strip() + "\n", - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", alias orders_dev, post_hooks [ @@ -1785,7 +1785,7 @@ def source_columns() -> str: SELECT 1 AS id """.strip() + "\n", - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from sqlbuild.hooks import hook @@ -1841,7 +1841,7 @@ def notify(ctx, message): schema = "marts" """.strip() + "\n", - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", post_hooks [sql("record_access", role: "O'Brien")], ); @@ -1849,7 +1849,7 @@ def notify(ctx, message): SELECT 1 AS id """.strip() + "\n", - "hooks/sql/record_access.sql": """ + "sql/hooks/sql/record_access.sql": """ HOOK (description "Record model access"); SELECT @'role' AS role, '@@CTX:destination.qualified' AS relation_name @@ -1872,7 +1872,7 @@ def notify(ctx, message): "FROM analytics.marts.access_log" ), name="record_access", - relative_path=Path("hooks/sql/record_access.sql"), + relative_path=Path("sql/hooks/sql/record_access.sql"), definition_sql=( "SELECT @'role' AS role, " "'@@CTX:destination.qualified' AS relation_name\n" @@ -1898,7 +1898,7 @@ def notify(ctx, message): description="validates Python hook kwargs while allowing defaults and variadic kwargs", repo_files=base_repo_files() | { - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", pre_hooks [ python("defaulted", channel: "alerts"), @@ -1911,7 +1911,7 @@ def notify(ctx, message): SELECT 1 AS id """.strip() + "\n", - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from sqlbuild.hooks import hook @@ -1967,7 +1967,7 @@ def optional_positional_only(ctx, channel="alerts", /): description="preserves raw Python hook kwargs after discovered hook validation", repo_files=base_repo_files() | { - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", post_hooks [ python("notify", message: "@@CTX:destination.qualified", macro_text: "@py.format_message()"), @@ -1977,7 +1977,7 @@ def optional_positional_only(ctx, channel="alerts", /): SELECT 1 AS id """.strip() + "\n", - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from sqlbuild.hooks import hook @@ -2018,7 +2018,7 @@ def notify(ctx, message, macro_text): description="expands vars and macros in sql function bodies and headers", repo_files=base_repo_files() | { - "macros/python/common.py": """ + "sql/macros/python/common.py": """ def status_match(column_name: str, status: str) -> str: return f"{column_name} = '{status}'" """.strip() @@ -2043,7 +2043,7 @@ def status_match(column_name: str, status: str) -> str: schema = "default_schema" """.strip() + "\n", - "functions/sql/is_completed_order.sql": """ + "sql/functions/sql/is_completed_order.sql": """ FUNCTION (description "Test function is_completed_order.", database ${udf_database}, schema ${udf_schema}, @@ -2104,10 +2104,10 @@ def status_match(column_name: str, status: str) -> str: sql_validation = false """.strip() + "\n", - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( 'MODEL (description "Test model fact_orders.");\n\nSELECT * FROM __table_fn("customer_orders")(7)\n' ), - "functions/sql/customer_orders.sql": """ + "sql/functions/sql/customer_orders.sql": """ FUNCTION (description "Test function customer_orders.", arguments (p_customer_id INTEGER), returns table ( @@ -2161,7 +2161,7 @@ def status_match(column_name: str, status: str) -> str: repo_files=base_repo_files() | { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "functions/sql/customer_orders.sql": """ + "sql/functions/sql/customer_orders.sql": """ FUNCTION (description "Test function customer_orders.", returns table ( order_id INTEGER, @@ -2214,12 +2214,12 @@ def status_match(column_name: str, status: str) -> str: description="expands macros across multi block tests and audits", repo_files=base_repo_files() | { - "macros/python/common.py": """ + "sql/macros/python/common.py": """ def project_columns() -> str: return "order_id" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", "tests/unit/orders_test.sql": """ TEST (name "first"); @@ -2244,7 +2244,7 @@ def project_columns() -> str: SELECT 1 """.strip() + "\n", - "audits/singular/orders.sql": """ + "sql/audits/singular/orders.sql": """ AUDIT (name "first"); SELECT @py.project_columns() FROM __ref("orders") JOIN __source("raw_orders") USING (order_id); @@ -2254,7 +2254,7 @@ def project_columns() -> str: SELECT @py.project_columns() FROM __ref("orders") JOIN __source("raw_customers") USING (order_id) """.strip() + "\n", - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -2338,7 +2338,7 @@ def project_columns() -> str: schema = "default_schema" """.strip() + "\n", - "functions/python/is_completed_order.py": """ + "sql/functions/python/is_completed_order.py": """ from sqlbuild.functions import udf @udf( @@ -2396,7 +2396,7 @@ def main(order_status): description="renders attached model and source audits from generic definitions", repo_files=base_repo_files() | { - "models/marts/orders.sql": """ + "sql/models/marts/orders.sql": """ MODEL (description "Test model orders.", audits [model_not_null], columns ( @@ -2407,7 +2407,7 @@ def main(order_status): select 1 """.strip() + "\n", - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -2419,25 +2419,25 @@ def main(order_status): - source_column_not_null """.strip() + "\n", - "audits/generic/model_not_null.sql": """ + "sql/audits/generic/model_not_null.sql": """ AUDIT (); SELECT 1 FROM __ref("@model") """.strip() + "\n", - "audits/generic/column_not_null.sql": """ + "sql/audits/generic/column_not_null.sql": """ AUDIT (); SELECT @column FROM __ref("@model") WHERE @column IS NULL """.strip() + "\n", - "audits/generic/source_not_null.sql": """ + "sql/audits/generic/source_not_null.sql": """ AUDIT (); SELECT 1 FROM __source("@source") """.strip() + "\n", - "audits/generic/source_column_not_null.sql": """ + "sql/audits/generic/source_column_not_null.sql": """ AUDIT (); SELECT @column FROM __source("@source") WHERE @column IS NULL @@ -2475,7 +2475,7 @@ def main(order_status): description="renders built-in attached audits when no project generic definition exists", repo_files=base_repo_files() | { - "models/marts/orders.sql": """ + "sql/models/marts/orders.sql": """ MODEL (description "Test model orders.", columns ( order_id (nullable false, audits [not_null, unique]), @@ -2490,8 +2490,8 @@ def main(order_status): select 1 as order_id, 'placed' as status, null as customer_id """.strip() + "\n", - "models/marts/customers.sql": "MODEL (description 'Test model customers.');\n\nselect 1 as customer_id\n", - "sources/raw.yml": """ + "sql/models/marts/customers.sql": "MODEL (description 'Test model customers.');\n\nselect 1 as customer_id\n", + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -2546,8 +2546,8 @@ def main(order_status): description="skips generic audit definitions as direct executable audits", repo_files=base_repo_files() | { - "models/marts/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", - "audits/generic/custom_check.sql": """ + "sql/models/marts/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/audits/generic/custom_check.sql": """ AUDIT (); SELECT 1 @@ -2575,8 +2575,8 @@ def main(order_status): description="warns when project generic audit shadows built-in audit", repo_files=base_repo_files() | { - "models/marts/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", - "audits/generic/not_null.sql": "AUDIT ();\n\nSELECT 1\n", + "sql/models/marts/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/audits/generic/not_null.sql": "AUDIT ();\n\nSELECT 1\n", }, selected_target=None, cli_vars=None, @@ -2603,7 +2603,7 @@ def main(order_status): description="generates clickstate style run ids when none are provided", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n" + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n" }, selected_target=None, cli_vars=None, @@ -2632,7 +2632,7 @@ def main(order_status): sql_validation = false """.strip() + "\n", - "models/staging/broken.sql": "MODEL (description 'Test model broken.');\n\nSELEC id FROM (SELECT 1\n", + "sql/models/staging/broken.sql": "MODEL (description 'Test model broken.');\n\nSELEC id FROM (SELECT 1\n", }, selected_target=None, cli_vars=None, @@ -2663,7 +2663,7 @@ def main(order_status): sql_analysis = false """.strip() + "\n", - "models/staging/broken.sql": "MODEL (description 'Test model broken.');\n\nSELEC id FROM (SELECT 1\n", + "sql/models/staging/broken.sql": "MODEL (description 'Test model broken.');\n\nSELEC id FROM (SELECT 1\n", }, selected_target=None, cli_vars=None, @@ -2686,7 +2686,7 @@ def main(order_status): description="allows invalid sql when no_sql_validation flag is set", repo_files=base_repo_files() | { - "models/staging/broken.sql": "MODEL (description 'Test model broken.');\n\nSELEC id FROM (SELECT 1\n", + "sql/models/staging/broken.sql": "MODEL (description 'Test model broken.');\n\nSELEC id FROM (SELECT 1\n", }, selected_target=None, cli_vars=None, @@ -2729,7 +2729,7 @@ def main(order_status): } """.strip() + "\n", - "models/fact_orders.sql": ( + "sql/models/fact_orders.sql": ( 'MODEL (description "Test model fact_orders.");\n\nselect * from __dbt_ref("stg_orders") ' 'union all select * from __dbt_ref("stripe", "orders")\n' ), @@ -3098,11 +3098,11 @@ def test_given_preserved_target_when_building_functions_then_logical_namespaces_ schema = "physical_schema" """.strip() + "\n", - "functions/sql/defaulted.sql": ( + "sql/functions/sql/defaulted.sql": ( "FUNCTION (description 'Test function defaulted.', returns INTEGER, tags [reference, daily]);\n\n1\n" ), - "models/model_defaulted.sql": "MODEL (description 'Test model model_defaulted.');\n\nSELECT 1 AS id\n", - "functions/python/explicit.py": """ + "sql/models/model_defaulted.sql": "MODEL (description 'Test model model_defaulted.');\n\nSELECT 1 AS id\n", + "sql/functions/python/explicit.py": """ from sqlbuild.functions import udf @udf( @@ -3117,7 +3117,7 @@ def main(): return 1 """.strip() + "\n", - "functions/python/unqualified.py": """ + "sql/functions/python/unqualified.py": """ from sqlbuild.functions import udf @udf(arguments={}, returns="INTEGER", runtime_version="3.11") @@ -3258,11 +3258,11 @@ def test_given_project_and_local_environment_when_resolving_then_local_values_ov "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[settings]\nsql_validation = false\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\n' 'SELECT * FROM __table_fn("customer_orders")\n' ), - "functions/sql/customer_orders.sql": ( + "sql/functions/sql/customer_orders.sql": ( 'FUNCTION (description "Test function customer_orders.",\n' " arguments (customer_id INTEGER),\n" " returns table (order_id INTEGER)\n" @@ -3281,7 +3281,7 @@ def test_given_project_and_local_environment_when_resolving_then_local_values_ov "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[settings]\nsql_validation = false\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.');\n\n" "SELECT * FROM __table_fn('customer_orders')(1)\n" ), @@ -3334,7 +3334,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report sql_validation = false """.strip() + "\n", - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders."); SELECT * FROM __table_fn("missing_orders")(1) @@ -3350,7 +3350,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report repo_files=base_repo_files() | { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "functions/sql/customer_orders.sql": """ + "sql/functions/sql/customer_orders.sql": """ FUNCTION (description "Test function customer_orders.", arguments (customer_id INTEGER), returns table (order_id INTEGER, customer_id INTEGER) @@ -3369,10 +3369,10 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report repo_files=base_repo_files() | { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\nSELECT * FROM __table_fn("order_total")(1)\n' ), - "functions/sql/order_total.sql": """ + "sql/functions/sql/order_total.sql": """ FUNCTION (description "Test function order_total.", arguments (order_id INTEGER), returns INTEGER @@ -3393,10 +3393,10 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[settings]\nsql_validation = false\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\nSELECT * FROM __table_fn("customer_orders")(1, 2)\n' ), - "functions/sql/customer_orders.sql": """ + "sql/functions/sql/customer_orders.sql": """ FUNCTION (description "Test function customer_orders.", arguments (customer_id INTEGER), returns table (order_id INTEGER) @@ -3417,7 +3417,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[settings]\nsql_validation = false\n' ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\nSELECT * FROM __table_fn("customer_orders")(1,)\n' ), }, @@ -3430,7 +3430,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report repo_files=base_repo_files() | { "sqlbuild_project.toml": 'name = "demo"\nadapter = "duckdb"\n', - "functions/sql/customer_orders.sql": """ + "sql/functions/sql/customer_orders.sql": """ FUNCTION (description "Test function customer_orders.", arguments (customer_id INTEGER), returns table (order_id INTEGER) @@ -3459,7 +3459,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a model references an unknown source", repo_files=base_repo_files() | { - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders."); SELECT * FROM __source("missing_source") @@ -3474,7 +3474,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when authored enforced contract omits incremental cursor", repo_files=base_repo_files() | { - "models/orders.sql": """ + "sql/models/orders.sql": """ MODEL (description "Test model orders.", materialized incremental, contract enforced, @@ -3499,7 +3499,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when authored enforced contract omits snapshot check column", repo_files=base_repo_files() | { - "models/customer_snapshot.sql": """ + "sql/models/customer_snapshot.sql": """ MODEL (description "Test model customer_snapshot.", materialized snapshot, contract enforced, @@ -3524,7 +3524,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when authored enforced snapshot appends new columns", repo_files=base_repo_files() | { - "models/customer_snapshot.sql": """ + "sql/models/customer_snapshot.sql": """ MODEL (description "Test model customer_snapshot.", materialized snapshot, contract enforced, @@ -3550,7 +3550,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when an audit references an unknown source", repo_files=base_repo_files() | { - "audits/singular/orders.sql": """ + "sql/audits/singular/orders.sql": """ AUDIT (); SELECT * FROM __source("missing_source") @@ -3565,7 +3565,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a model uses dbt refs", repo_files=base_repo_files() | { - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders."); SELECT * FROM __dbt_ref("stg_orders") @@ -3575,7 +3575,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report selected_target=None, run_id=None, expected_error_fragment=( - r'Model file models/staging/orders\.sql uses __dbt_ref\("stg_orders"\) ' + r'Model file sql/models/staging/orders\.sql uses __dbt_ref\("stg_orders"\) ' "but no dbt manifest was found" ), ), @@ -3583,7 +3583,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a SQL function uses dbt refs", repo_files=base_repo_files() | { - "functions/sql/orders.sql": """ + "sql/functions/sql/orders.sql": """ FUNCTION (description "Test function orders.", returns table (order_id INTEGER) ); @@ -3595,7 +3595,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report selected_target=None, run_id=None, expected_error_fragment=( - r'SQL function file functions/sql/orders\.sql uses __dbt_ref\("stg_orders"\) ' + r'SQL function file sql/functions/sql/orders\.sql uses __dbt_ref\("stg_orders"\) ' "but dbt refs are not supported yet" ), ), @@ -3603,7 +3603,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when an audit uses dbt refs", repo_files=base_repo_files() | { - "audits/singular/orders.sql": """ + "sql/audits/singular/orders.sql": """ AUDIT (); SELECT * FROM __dbt_ref("stg_orders") @@ -3613,7 +3613,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report selected_target=None, run_id=None, expected_error_fragment=( - r'Audit file audits/singular/orders\.sql may not use __dbt_ref\("stg_orders"\); ' + r'Audit file sql/audits/singular/orders\.sql may not use __dbt_ref\("stg_orders"\); ' "audit dbt model checks belong in dbt" ), ), @@ -3621,7 +3621,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when an attached source audit overrides implicit source context", repo_files=base_repo_files() | { - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -3630,7 +3630,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report source: other_source """.strip() + "\n", - "audits/generic/source_not_null.sql": """ + "sql/audits/generic/source_not_null.sql": """ AUDIT (); SELECT 1 FROM __source("@source") @@ -3645,7 +3645,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when model column allows nulls and uses not null audit", repo_files=base_repo_files() | { - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", columns ( order_id (nullable true, audits [not_null]), @@ -3666,7 +3666,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when an attached source audit references an unknown generic definition", repo_files=base_repo_files() | { - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -3698,7 +3698,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a compiled test body lacks top level test ctes", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", "tests/unit/orders_test.sql": """ TEST (); @@ -3714,8 +3714,8 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a compiled test body lacks ceremonial select one", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", - "sources/raw.yml": """ + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -3743,7 +3743,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a compiled test body references an unknown source mock", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", "tests/unit/orders_test.sql": """ TEST (); @@ -3766,7 +3766,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a compiled test body references an unknown seed mock", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", "tests/unit/orders_test.sql": """ TEST (); @@ -3806,8 +3806,8 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report } """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", - "sources/raw.yml": """ + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/sources/raw.yml": """ sources: - name: raw__orders description: Test source raw__orders. @@ -3851,9 +3851,9 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report } """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", - "seeds/countries.csv": "country_code,country_name\nUS,United States\n", - "seeds/schema.yml": """ + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/seeds/countries.csv": "country_code,country_name\nUS,United States\n", + "sql/seeds/schema.yml": """ seeds: - name: countries description: Test seed countries. @@ -3886,8 +3886,8 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a compiled test body references an unknown macro mock", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", - "sources/raw.yml": """ + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -3918,7 +3918,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a compiled test body references an unknown expected model", repo_files=base_repo_files() | { - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -3946,8 +3946,8 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a compiled test body uses a reserved helper cte name", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", - "sources/raw.yml": """ + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/sources/raw.yml": """ sources: - name: raw_orders description: Test source raw_orders. @@ -3978,7 +3978,7 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when a compiled audit body references an unknown macro", repo_files=base_repo_files() | { - "audits/singular/orders.sql": """ + "sql/audits/singular/orders.sql": """ AUDIT (); SELECT @py.missing_macro() @@ -3993,17 +3993,17 @@ def test_given_rejected_reference_calls_when_building_compile_inputs_then_report description="raises when macro files collide during compile", repo_files=base_repo_files() | { - "macros/python/common.py": """ + "sql/macros/python/common.py": """ def project_columns() -> str: return "order_id" """.strip() + "\n", - "macros/python/nested/common.py": """ + "sql/macros/python/nested/common.py": """ def project_columns() -> str: return "customer_id" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4013,8 +4013,8 @@ def project_columns() -> str: description="raises when a macro identity is noncanonical", repo_files=base_repo_files() | { - "macros/python/orders.py": "def DailyOrders():\n return 'order_id'\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect @py.DailyOrders()\n", + "sql/macros/python/orders.py": "def DailyOrders():\n return 'order_id'\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect @py.DailyOrders()\n", }, selected_target=None, run_id=None, @@ -4027,12 +4027,12 @@ def project_columns() -> str: description="raises when model config field contains a macro call", repo_files=base_repo_files() | { - "macros/python/common.py": """ + "sql/macros/python/common.py": """ def dynamic_schema() -> str: return "marts" """.strip() + "\n", - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", schema '@py.dynamic_schema()', ); @@ -4049,7 +4049,7 @@ def dynamic_schema() -> str: description="raises when the selected target does not exist", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n" + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n" }, selected_target="missing", run_id=None, @@ -4064,7 +4064,7 @@ def dynamic_schema() -> str: target = "missing" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4081,7 +4081,7 @@ def dynamic_schema() -> str: default_target = "missing" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4100,7 +4100,7 @@ def dynamic_schema() -> str: user = "${missing}" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4118,7 +4118,7 @@ def dynamic_schema() -> str: path = "${ENV:SQLBUILD_DB_PATH}" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4135,7 +4135,7 @@ def dynamic_schema() -> str: adapter = "duckdb" """.strip() + "\n", - "models/staging/orders.sql": """ + "sql/models/staging/orders.sql": """ MODEL (description "Test model orders.", schema '${CTX:this}', ); @@ -4166,7 +4166,7 @@ def dynamic_schema() -> str: schema = "dev_${CTX:destination.missing}" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4189,7 +4189,7 @@ def dynamic_schema() -> str: database = "dev_${CTX:model.database}" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4210,7 +4210,7 @@ def dynamic_schema() -> str: second = "${first}" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4233,7 +4233,7 @@ def dynamic_schema() -> str: schema = "${SQLBUILD:user}" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4251,7 +4251,7 @@ def dynamic_schema() -> str: path = "${CTX:schema}" """.strip() + "\n", - "models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4261,7 +4261,7 @@ def dynamic_schema() -> str: description="raises when plural hooks use bare SQL strings", repo_files=base_repo_files() | { - "models/staging/broken.sql": ( + "sql/models/staging/broken.sql": ( "MODEL (description 'Test model broken.', post_hooks ['SELECT 1']);\n\nSELECT 1 AS id\n" ), }, @@ -4273,7 +4273,7 @@ def dynamic_schema() -> str: description="raises when inline hook renders an empty payload", repo_files=base_repo_files() | { - "models/staging/broken.sql": ( + "sql/models/staging/broken.sql": ( "MODEL (description 'Test model broken.', post_hooks [inline_sql('')]);\n\nSELECT 1 AS id\n" ), }, @@ -4290,10 +4290,10 @@ def dynamic_schema() -> str: "sqlbuild_project.toml": ( 'name = "demo"\nadapter = "duckdb"\n\n[settings]\nsql_validation = false\n' ), - "models/staging/broken.sql": ( + "sql/models/staging/broken.sql": ( 'MODEL (description "Test model broken.", post_hooks [sql("dynamic", statement: "")]);\n\nSELECT 1 AS id\n' ), - "hooks/sql/dynamic.sql": "HOOK (description 'Test hook dynamic.');\n\n@statement\n", + "sql/hooks/sql/dynamic.sql": "HOOK (description 'Test hook dynamic.');\n\n@statement\n", }, selected_target=None, run_id=None, @@ -4305,7 +4305,7 @@ def dynamic_schema() -> str: description="raises when hook sql uses config template syntax", repo_files=base_repo_files() | { - "models/staging/broken.sql": ( + "sql/models/staging/broken.sql": ( "MODEL (description 'Test model broken.', post_hooks [" "inline_sql('GRANT SELECT ON ${CTX:destination.qualified} TO analyst')" "]);\n\n" @@ -4323,7 +4323,7 @@ def dynamic_schema() -> str: description="raises when python hook references unknown hook name", repo_files=base_repo_files() | { - "models/staging/broken.sql": ( + "sql/models/staging/broken.sql": ( 'MODEL (description "Test model broken.", post_hooks [python("notify")]);\n\nSELECT 1 AS id\n' ), }, @@ -4337,10 +4337,10 @@ def dynamic_schema() -> str: description="raises with nonzero hook index when later python hook is invalid", repo_files=base_repo_files() | { - "models/staging/broken.sql": ( + "sql/models/staging/broken.sql": ( 'MODEL (description "Test model broken.", post_hooks [python("known"), python("missing")]);\n\nSELECT 1 AS id\n' ), - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from sqlbuild.hooks import hook @@ -4361,10 +4361,10 @@ def known(ctx): description="raises when python hook is missing required kwarg", repo_files=base_repo_files() | { - "models/staging/broken.sql": ( + "sql/models/staging/broken.sql": ( 'MODEL (description "Test model broken.", pre_hooks [python("notify")]);\n\nSELECT 1 AS id\n' ), - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from sqlbuild.hooks import hook @@ -4385,10 +4385,10 @@ def notify(ctx, channel): description="raises when python hook receives unknown kwarg", repo_files=base_repo_files() | { - "models/staging/broken.sql": ( + "sql/models/staging/broken.sql": ( 'MODEL (description "Test model broken.", post_hooks [python("notify", unknown: "value")]);\n\nSELECT 1 AS id\n' ), - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from sqlbuild.hooks import hook @@ -4409,10 +4409,10 @@ def notify(ctx): description="raises when python hook requires positional only argument", repo_files=base_repo_files() | { - "models/staging/broken.sql": ( + "sql/models/staging/broken.sql": ( 'MODEL (description "Test model broken.", post_hooks [python("notify")]);\n\nSELECT 1 AS id\n' ), - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from sqlbuild.hooks import hook @@ -4434,7 +4434,7 @@ def notify(ctx, channel, /): description="raises when model header tags is a string instead of list", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL (description 'Test model orders.', tags nightly);\n\nSELECT 1\n", + "sql/models/staging/orders.sql": "MODEL (description 'Test model orders.', tags nightly);\n\nSELECT 1\n", }, selected_target=None, run_id=None, @@ -4444,7 +4444,7 @@ def notify(ctx, channel, /): description="raises when dbt ref has no discovered manifest", repo_files=base_repo_files() | { - "models/fact_orders.sql": 'MODEL (description "Test model fact_orders.");\n\nselect * from __dbt_ref("orders")\n', + "sql/models/fact_orders.sql": 'MODEL (description "Test model fact_orders.");\n\nselect * from __dbt_ref("orders")\n', }, selected_target=None, run_id=None, @@ -4475,7 +4475,7 @@ def notify(ctx, channel, /): } """.strip() + "\n", - "models/fact_orders.sql": 'MODEL (description "Test model fact_orders.");\n\nselect * from __dbt_ref("orders")\n', + "sql/models/fact_orders.sql": 'MODEL (description "Test model fact_orders.");\n\nselect * from __dbt_ref("orders")\n', }, selected_target=None, run_id=None, @@ -4499,7 +4499,7 @@ def notify(ctx, channel, /): } """.strip() + "\n", - "models/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", + "sql/models/orders.sql": "MODEL (description 'Test model orders.');\n\nselect 1\n", }, selected_target=None, run_id=None, @@ -4542,10 +4542,10 @@ def test_given_attachment_conflicts_when_building_compile_inputs_then_it_raises_ description="Python hook validation inspects signatures without executing hooks", repo_files=base_repo_files() | { - "models/staging/orders.sql": ( + "sql/models/staging/orders.sql": ( 'MODEL (description "Test model orders.", post_hooks [python("notify", channel: "alerts")]);\n\nSELECT 1 AS id\n' ), - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from pathlib import Path from sqlbuild.hooks import hook @@ -4576,7 +4576,7 @@ def test_given_python_hook_when_building_compile_inputs_then_validation_does_not ) assert ( - tmp_path / "hooks" / "executed.marker" + tmp_path / "sql" / "hooks" / "executed.marker" ).is_file() is test_case.expected_marker_file_exists @@ -4606,13 +4606,13 @@ def test_given_typed_hook_defaults_when_building_config_then_layers_values( ) -> None: defaults: DefaultsConfig = DefaultsConfig(pre_hooks=test_case.default_hook) path_defaults: dict[str, dict[str, object]] = { - "models/marts": {"post_hooks": test_case.path_default_hook} + "sql/models/marts": {"post_hooks": test_case.path_default_hook} } config: CompileModelConfig = build_config_natively( defaults=defaults, path_defaults=path_defaults, - matched_path_default="models/marts", + matched_path_default="sql/models/marts", model_header_values={}, target_config=None, ) @@ -4723,7 +4723,7 @@ def test_given_retention_layers_when_building_model_config_then_precedence_is_re 'time_travel_retention = "14d"', ) ), - "models/orders.sql": ( + "sql/models/orders.sql": ( "MODEL (description 'Test model orders.', materialized table, time_travel_retention 30d);\n\nSELECT 1 AS id\n" ), }, @@ -4760,7 +4760,7 @@ def test_given_authored_retention_header_when_building_inputs_then_typed_policy_ description="snapshot append new columns contract conflict has code", repo_files=base_repo_files() | { - "models/customer_snapshot.sql": """ + "sql/models/customer_snapshot.sql": """ MODEL (description "Test model customer_snapshot.", materialized snapshot, contract enforced, @@ -4814,8 +4814,8 @@ def test_given_snapshot_contract_schema_change_conflict_when_building_then_error description="model referencing a seed via __seed compiles successfully", repo_files=base_repo_files() | { - "seeds/waffle_types.csv": "waffle_type_id,waffle_name\n1,Classic\n", - "seeds/schema.yml": ( + "sql/seeds/waffle_types.csv": "waffle_type_id,waffle_name\n1,Classic\n", + "sql/seeds/schema.yml": ( "seeds:\n" " - name: waffle_types\n description: Test seed waffle_types.\n" " columns:\n" @@ -4824,7 +4824,7 @@ def test_given_snapshot_contract_schema_change_conflict_when_building_then_error " - name: waffle_name\n" " type: VARCHAR\n" ), - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (description "Test model orders.");\n\nSELECT waffle_type_id FROM __seed("waffle_types")' ), }, diff --git a/tests/unit/src/sqlbuild/compiler/compile/test_resolved_connection.py b/tests/unit/src/sqlbuild/compiler/compile/test_resolved_connection.py index aacbaf32ff..98eea70591 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/test_resolved_connection.py +++ b/tests/unit/src/sqlbuild/compiler/compile/test_resolved_connection.py @@ -29,7 +29,7 @@ description="resolved connection override becomes the effective connection", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", }, resolved_connection={"database": "/abs/warehouse.duckdb", "schema": "analytics"}, expected_effective_connection={ @@ -41,7 +41,7 @@ description="without override the merged project connection is used", repo_files={ "sqlbuild_project.toml": _PROJECT_TOML, - "models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", + "sql/models/orders.sql": "MODEL (description 'Test model orders.', materialized table);\n\nSELECT 1 AS order_id", }, resolved_connection=None, expected_effective_connection={"database": "warehouse.duckdb"}, diff --git a/tests/unit/src/sqlbuild/compiler/contracts/helpers.py b/tests/unit/src/sqlbuild/compiler/contracts/helpers.py index d968d3cf38..0ed1cb43da 100644 --- a/tests/unit/src/sqlbuild/compiler/contracts/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/contracts/helpers.py @@ -57,7 +57,7 @@ def make_contract_project( key=key, deps=(), name=model_name, - relative_path=Path(f"models/{model_name}.sql"), + relative_path=Path(f"sql/models/{model_name}.sql"), query_sql="SELECT 1 AS id", config=CompileModelConfig( values=cast( @@ -134,7 +134,7 @@ def make_promotion_project( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), deps=(), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), query_sql="SELECT 1 AS id", config=CompileModelConfig(values=values), destination=CompiledRelationLocation( diff --git a/tests/unit/src/sqlbuild/compiler/contracts/test_validate.py b/tests/unit/src/sqlbuild/compiler/contracts/test_validate.py index 7a67065018..0fbdedfc50 100644 --- a/tests/unit/src/sqlbuild/compiler/contracts/test_validate.py +++ b/tests/unit/src/sqlbuild/compiler/contracts/test_validate.py @@ -293,10 +293,10 @@ def test_given_compiled_project_when_validating_contracts_then_returns_expected_ ContractLocationTestCase( description="uses declared column location", column_name="customer_id", - path=Path("models/orders.sql"), + path=Path("sql/models/orders.sql"), line=4, column=5, - expected_path=Path("models/orders.sql"), + expected_path=Path("sql/models/orders.sql"), expected_line=4, expected_column=5, ) @@ -334,10 +334,10 @@ def test_given_column_location_when_validating_contracts_then_diagnostic_uses_lo ContractLocationTestCase( description="deferred unexpected column location", column_name="amount", - path=Path("models/orders.sql"), + path=Path("sql/models/orders.sql"), line=4, column=3, - expected_path=Path("models/orders.sql"), + expected_path=Path("sql/models/orders.sql"), expected_line=4, expected_column=3, ), diff --git a/tests/unit/src/sqlbuild/compiler/dag/main/helpers.py b/tests/unit/src/sqlbuild/compiler/dag/main/helpers.py index 2dba9df49e..f4ce974ec9 100644 --- a/tests/unit/src/sqlbuild/compiler/dag/main/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/dag/main/helpers.py @@ -67,21 +67,21 @@ def raw_orders_loader() -> list[dict[str, object]]: columns=(SourceColumnEntry(name="order_id", type="INTEGER"),), ) source_file: DiscoveredSourceFile = DiscoveredSourceFile( - file_path=Path("sources/raw.yml"), - relative_path=Path("sources/raw.yml"), + file_path=Path("sql/sources/raw.yml"), + relative_path=Path("sql/sources/raw.yml"), contents="", source_entries=(source_entry,), ) schema_file: DiscoveredSchemaFile = DiscoveredSchemaFile( - file_path=Path("models/schema.yml"), - relative_path=Path("models/schema.yml"), + file_path=Path("sql/models/schema.yml"), + relative_path=Path("sql/models/schema.yml"), contents="", model_entries=(), seed_entries=(), ) seed_file: DiscoveredSeedFile = DiscoveredSeedFile( - file_path=Path("seeds/country_codes.csv"), - relative_path=Path("seeds/country_codes.csv"), + file_path=Path("sql/seeds/country_codes.csv"), + relative_path=Path("sql/seeds/country_codes.csv"), ) model_target: CompiledRelationLocation = CompiledRelationLocation( database=None, @@ -104,14 +104,14 @@ def raw_orders_loader() -> list[dict[str, object]]: effective_target_schema="raw", loader_functions=( DiscoveredLoaderFunction( - file_path=Path("python/loaders/orders.py"), - relative_path=Path("python/loaders/orders.py"), + file_path=Path("python/nodes/loaders/orders.py"), + relative_path=Path("python/nodes/loaders/orders.py"), name="shared_order_feed", function=shared_order_feed, ), DiscoveredLoaderFunction( - file_path=Path("python/loaders/orders.py"), - relative_path=Path("python/loaders/orders.py"), + file_path=Path("python/nodes/loaders/orders.py"), + relative_path=Path("python/nodes/loaders/orders.py"), name="raw_orders_loader", function=raw_orders_loader, depends_on=(shared_order_feed,), @@ -153,7 +153,7 @@ def raw_orders_loader() -> list[dict[str, object]]: key=function_key, deps=(), name="normalize_email", - relative_path=Path("functions/normalize_email.sql"), + relative_path=Path("sql/functions/normalize_email.sql"), arguments=(FunctionArgument(name="email", type="TEXT"),), returns="TEXT", body_sql="lower(email)", @@ -168,7 +168,7 @@ def raw_orders_loader() -> list[dict[str, object]]: key=model_key, deps=(source_key, seed_key, function_key), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql="SELECT 1 AS order_id", authored_sql="MODEL (materialized table);\n\nSELECT 1 AS order_id", config=CompileModelConfig(values={"materialized": "table", "tags": ["daily"]}), @@ -202,8 +202,8 @@ def raw_orders_loader() -> list[dict[str, object]]: name="orders_audit", definition_name="test_audit", audit_file=DiscoveredAuditFile( - file_path=Path("audits/orders.sql"), - relative_path=Path("audits/orders.sql"), + file_path=Path("sql/audits/orders.sql"), + relative_path=Path("sql/audits/orders.sql"), contents="", blocks=(), ), diff --git a/tests/unit/src/sqlbuild/compiler/dag/main/test_build.py b/tests/unit/src/sqlbuild/compiler/dag/main/test_build.py index d15be0ea64..00ca40b894 100644 --- a/tests/unit/src/sqlbuild/compiler/dag/main/test_build.py +++ b/tests/unit/src/sqlbuild/compiler/dag/main/test_build.py @@ -221,7 +221,7 @@ def test_given_resource_namespace_defaults_when_building_dag_then_targets_retain schema = "preserve" """.strip() + "\n", - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: country_codes columns: @@ -229,8 +229,8 @@ def test_given_resource_namespace_defaults_when_building_dag_then_targets_retain type: VARCHAR """.strip() + "\n", - "seeds/country_codes.csv": "code\nUS\n", - "functions/sql/normalize.sql": "FUNCTION (returns VARCHAR);\n\n'normalized'\n", + "sql/seeds/country_codes.csv": "code\nUS\n", + "sql/functions/sql/normalize.sql": "FUNCTION (returns VARCHAR);\n\n'normalized'\n", }, ) discovered: DiscoveredProjectInputs = discover_project_inputs(project_dir=tmp_path) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/_test_helpers.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/_test_helpers.py index 829ad3ef57..277d263aab 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/_test_helpers.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/_test_helpers.py @@ -78,17 +78,17 @@ } _SCOPED_PROJECT_FILES: dict[str, str] = { "sqlbuild_project.toml": 'name = "shop"\nadapter = "duckdb"\n', - "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", - "models/sales/daily.sql": "MODEL (description 'Daily.');\nSELECT 1 AS day_id\n", - "models/sales/schema.yml": "models: []\n", - "models/sales/enums/region.sql": "ENUM (name region, members [NORTH, SOUTH]);\n", - "models/sales/_sqlbuild/constants/limit.sql": "CONSTANT (name order_limit, value 10);\n", - "models/sales/_sqlbuild/audits/generic/positive.sql": ( + "sql/models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "sql/models/sales/daily.sql": "MODEL (description 'Daily.');\nSELECT 1 AS day_id\n", + "sql/models/sales/schema.yml": "models: []\n", + "sql/models/sales/enums/region.sql": "ENUM (name region, members [NORTH, SOUTH]);\n", + "sql/models/sales/_sqlbuild/constants/limit.sql": "CONSTANT (name order_limit, value 10);\n", + "sql/models/sales/_sqlbuild/audits/generic/positive.sql": ( "AUDIT (name positive);\nSELECT 1 WHERE FALSE\n" ), - "macros/python/money.py": "def money(value):\n return value\n", - "enums/status.sql": "ENUM (name status, members [OPEN, CLOSED]);\n", - "functions/sql/tax.sql": ( + "sql/macros/python/money.py": "def money(value):\n return value\n", + "sql/enums/status.sql": "ENUM (name status, members [OPEN, CLOSED]);\n", + "sql/functions/sql/tax.sql": ( "FUNCTION (arguments (amount DOUBLE), returns DOUBLE);\namount * 0.2\n" ), } @@ -218,7 +218,7 @@ def _random_model_file(rng: random.Random) -> str: def _add_directory(rng: random.Random, parent: Path, directories: list[Path]) -> None: path: Path = parent / rng.choice(_DIRECTORY_NAMES) - path.mkdir(exist_ok=True) + path.mkdir(parents=True, exist_ok=True) directories.append(path) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/helpers.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/helpers.py index 6349c01bd4..127f9fa009 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/helpers.py @@ -132,18 +132,17 @@ def discover_declaration_file(*, project_dir: Path, relative_path: str, contents file_path: Path = project_dir / relative_path file_path.parent.mkdir(parents=True, exist_ok=True) _ = file_path.write_text(contents, encoding="utf-8") - discovered: tuple[object, ...] = _DECLARATION_FILE_DISCOVERERS[relative_path.split("/")[0]]( - project_dir=project_dir - ) + role: str = relative_path.removeprefix("sql/").split("/")[0] + discovered: tuple[object, ...] = _DECLARATION_FILE_DISCOVERERS[role](project_dir=project_dir) return discovered[0] def discover_python_function_file( *, project_dir: Path, file_name: str, contents: str ) -> DiscoveredPythonFunctionFile: - """Write one ``functions/python`` file into a project and return its discovered record.""" + """Write one ``sql/functions/python`` file into a project and return its discovered record.""" - file_path: Path = project_dir / "functions" / "python" / file_name + file_path: Path = project_dir / "sql" / "functions" / "python" / file_name file_path.parent.mkdir(parents=True, exist_ok=True) _ = file_path.write_text(contents, encoding="utf-8") return discover_python_function_files(project_dir=project_dir)[0] @@ -152,14 +151,14 @@ def discover_python_function_file( _STATEMENT_HEADER_PARSERS: dict[str, Callable[..., object]] = { "MODEL": parse_model_sql, "AUDIT": lambda *, contents, file_path: discover_declaration_file( - project_dir=file_path.parents[2], - relative_path=file_path.relative_to(file_path.parents[2]).as_posix(), + project_dir=file_path.parents[3], + relative_path=file_path.relative_to(file_path.parents[3]).as_posix(), contents=contents, ), "TEST": parse_sql_test_file, "HOOK": lambda *, contents, file_path: discover_declaration_file( - project_dir=file_path.parents[2], - relative_path=file_path.relative_to(file_path.parents[2]).as_posix(), + project_dir=file_path.parents[3], + relative_path=file_path.relative_to(file_path.parents[3]).as_posix(), contents=contents, ), "SCENARIO": lambda *, contents, file_path: parse_sql_scenario_file( @@ -169,8 +168,8 @@ def discover_python_function_file( _STATEMENT_FILE_PATHS: dict[str, Callable[[Path], Path]] = { - "AUDIT": lambda project_dir: project_dir / "audits" / "generic" / "orders.sql", - "HOOK": lambda project_dir: project_dir / "hooks" / "sql" / "orders.sql", + "AUDIT": lambda project_dir: project_dir / "sql" / "audits" / "generic" / "orders.sql", + "HOOK": lambda project_dir: project_dir / "sql" / "hooks" / "sql" / "orders.sql", } diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_audit_factories.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_audit_factories.py index 6edbb4e71d..454fdaa566 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_audit_factories.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_audit_factories.py @@ -15,6 +15,7 @@ from tests.unit.src.sqlbuild.compiler.discovery._helpers._test_types import ( AuditFactoryDiscoveryTestCase, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -23,7 +24,7 @@ AuditFactoryDiscoveryTestCase( description="audit and node factories coexist", files={ - "python/factories/quality.py": """ + "python/nodes/factories/quality/assets.py": """ from sqlbuild.audits import AuditCase, audit_factory from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -46,7 +47,7 @@ def refresh(ctx): AuditFactoryDiscoveryTestCase( description="audit factory beside a direct task outside a factories folder", files={ - "python/quality.py": """ + "python/nodes/quality/asset.py": """ from sqlbuild.audits import AuditCase, audit_factory from sqlbuild.assets import asset @@ -111,7 +112,7 @@ def test_given_invalid_audit_factory_when_discovering_then_clear_error_is_raised write_repo_files( tmp_path, { - "python/factories/quality.py": f""" + "python/nodes/factories/quality/assets.py": f""" from sqlbuild.audits import audit_factory @audit_factory @@ -148,7 +149,10 @@ def duplicate_factory(): """ write_repo_files( tmp_path, - {"python/factories/a.py": source, "python/factories/nested/b.py": source}, + { + **node_module_files("python/nodes/factories/a.py", source), + **node_module_files("python/nodes/factories/nested/b.py", source), + }, ) with pytest.raises(PythonNodeDiscoveryError, match=test_case.expected_error_fragment): diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_command_output_sinks.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_command_output_sinks.py index e5bd1975e0..1fdd25900d 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_command_output_sinks.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_command_output_sinks.py @@ -14,7 +14,7 @@ from sqlbuild.compiler.discovery._helpers.filesystem.command_output_sinks import ( discover_command_output_sink_functions, ) -from sqlbuild.sinks import CommandOutputStream +from sqlbuild.event_sinks import CommandOutputStream from tests.unit.src.sqlbuild.compiler.discovery._helpers._test_types import ( CommandOutputSinkDiscoveryTestCase, ) @@ -33,10 +33,10 @@ def test_given_explicit_command_output_sink_when_discovering_then_returns_typed_ write_repo_files( tmp_path, { - "sinks/output.py": """ -from sqlbuild.sinks import CommandOutputRecord, command_output_sink + "python/event_sinks/output.py": """ +from sqlbuild.event_sinks import CommandOutputRecord, command_output_event_sink -@command_output_sink(streams={"stderr"}) +@command_output_event_sink(streams={"stderr"}) def publish_output(record: CommandOutputRecord) -> None: del record """, @@ -64,8 +64,8 @@ def test_given_only_lifecycle_sink_when_discovering_output_then_returns_empty( write_repo_files( tmp_path, { - "sinks/lifecycle.py": """ -from sqlbuild.sinks import lifecycle_event_sink + "python/event_sinks/lifecycle.py": """ +from sqlbuild.event_sinks import lifecycle_event_sink @lifecycle_event_sink def publish_lifecycle(event): @@ -91,17 +91,17 @@ def test_given_provider_parameter_when_discovering_output_then_records_shared_us write_repo_files( tmp_path, { - "providers/destination.py": """ + "python/providers/destination.py": """ from sqlbuild.providers import Provider class Destination(Provider): pass """, - "sinks/output.py": """ -from providers.destination import Destination -from sqlbuild.sinks import command_output_sink + "python/event_sinks/output.py": """ +from python.providers.destination import Destination +from sqlbuild.event_sinks import command_output_event_sink -@command_output_sink +@command_output_event_sink def publish_output(record, destination: Destination): del record, destination """, @@ -130,10 +130,10 @@ def test_given_wrong_first_parameter_when_discovering_output_then_rejects_signat write_repo_files( tmp_path, { - "sinks/output.py": """ -from sqlbuild.sinks import command_output_sink + "python/event_sinks/output.py": """ +from sqlbuild.event_sinks import command_output_event_sink -@command_output_sink +@command_output_event_sink def publish_output(event): del event """, diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_directory_snapshot.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_directory_snapshot.py index 859dc7fcbe..cdb03d365b 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_directory_snapshot.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_directory_snapshot.py @@ -47,7 +47,7 @@ def test_given_randomized_tree_when_listing_python_modules_then_matches_pathlib_ [ SharedSnapshotDiscoveryTestCase( "scoped_and_grouped_declarations", - expected_model_paths=("models/orders.sql", "models/sales/daily.sql"), + expected_model_paths=("sql/models/orders.sql", "sql/models/sales/daily.sql"), ) ], ids=lambda case: case.description, @@ -71,11 +71,11 @@ def test_given_shared_snapshot_when_discovering_project_then_matches_isolated_di DiscoveryPassRefreshTestCase( "added_and_removed_models", added_files={ - "models/sales/weekly.sql": "MODEL (description 'Weekly.');\nSELECT 1 AS week_id\n" + "sql/models/sales/weekly.sql": "MODEL (description 'Weekly.');\nSELECT 1 AS week_id\n" }, - removed_path="models/orders.sql", - expected_first_paths=("models/orders.sql", "models/sales/daily.sql"), - expected_second_paths=("models/sales/daily.sql", "models/sales/weekly.sql"), + removed_path="sql/models/orders.sql", + expected_first_paths=("sql/models/orders.sql", "sql/models/sales/daily.sql"), + expected_second_paths=("sql/models/sales/daily.sql", "sql/models/sales/weekly.sql"), ) ], ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_event_exporters.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_event_exporters.py index 419fe53c88..c21010de63 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_event_exporters.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_event_exporters.py @@ -30,7 +30,7 @@ def test_given_nested_and_private_files_when_discovering_then_returns_public_exp write_repo_files: Callable[[Path, dict[str, str]], None], ) -> None: declaration = """ -from sqlbuild.sinks import lifecycle_event_sink +from sqlbuild.event_sinks import lifecycle_event_sink @lifecycle_event_sink def publish(event): @@ -39,10 +39,10 @@ def publish(event): write_repo_files( tmp_path, { - "sinks/nested/public.py": declaration, - "sinks/_private.py": declaration, - "sinks/_private_dir/hidden.py": declaration, - "sinks/nested/__init__.py": declaration, + "python/event_sinks/nested/public.py": declaration, + "python/event_sinks/_private.py": declaration, + "python/event_sinks/_private_dir/hidden.py": declaration, + "python/event_sinks/nested/__init__.py": declaration, }, ) @@ -51,7 +51,7 @@ def publish(event): ) assert tuple(exporter.name for exporter in exporters) == (test_case.expected_name,) - assert exporters[0].relative_path.as_posix() == "sinks/nested/public.py" + assert exporters[0].relative_path.as_posix() == "python/event_sinks/nested/public.py" @pytest.mark.parametrize( @@ -67,15 +67,15 @@ def test_given_provider_parameter_when_discovering_then_records_usage( write_repo_files( tmp_path, { - "providers/sink.py": """ + "python/providers/sink.py": """ from sqlbuild.providers import Provider class Sink(Provider): pass """, - "sinks/publish.py": """ -from providers.sink import Sink -from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink + "python/event_sinks/publish.py": """ +from python.providers.sink import Sink +from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink @lifecycle_event_sink def publish(event: LifecycleEvent, sink: Sink) -> None: @@ -106,14 +106,14 @@ def test_given_unannotated_provider_parameter_when_discovering_then_accepts_name write_repo_files( tmp_path, { - "providers/sink.py": """ + "python/providers/sink.py": """ from sqlbuild.providers import Provider class Sink(Provider): pass """, - "sinks/publish.py": """ -from sqlbuild.sinks import lifecycle_event_sink + "python/event_sinks/publish.py": """ +from sqlbuild.event_sinks import lifecycle_event_sink @lifecycle_event_sink def publish(event, sink): @@ -160,8 +160,8 @@ def test_given_invalid_signature_when_discovering_then_rejects_before_execution( write_repo_files( tmp_path, { - "sinks/invalid.py": ( - "from sqlbuild.sinks import lifecycle_event_sink\n\n" + "python/event_sinks/invalid.py": ( + "from sqlbuild.event_sinks import lifecycle_event_sink\n\n" f"@lifecycle_event_sink\n{test_case.body}\n" ) }, @@ -182,7 +182,7 @@ def test_given_duplicate_names_when_discovering_then_rejects_deterministically( write_repo_files: Callable[[Path, dict[str, str]], None], ) -> None: declaration = """ -from sqlbuild.sinks import lifecycle_event_sink +from sqlbuild.event_sinks import lifecycle_event_sink @lifecycle_event_sink(name="duplicate") def publish(event): @@ -191,8 +191,8 @@ def publish(event): write_repo_files( tmp_path, { - "sinks/first.py": declaration, - "sinks/second.py": declaration, + "python/event_sinks/first.py": declaration, + "python/event_sinks/second.py": declaration, }, ) @@ -249,15 +249,15 @@ def test_given_invalid_typed_signature_when_discovering_then_rejects_exact_contr write_repo_files( tmp_path, { - "providers/sink.py": """ + "python/providers/sink.py": """ from sqlbuild.providers import Provider class Sink(Provider): pass """, - "sinks/invalid.py": ( - "from providers.sink import Sink\n" - "from sqlbuild.sinks import lifecycle_event_sink\n" + "python/event_sinks/invalid.py": ( + "from python.providers.sink import Sink\n" + "from sqlbuild.event_sinks import lifecycle_event_sink\n" "from sqlbuild.providers import Provider\n\n" "class Other(Provider):\n pass\n\n" f"@lifecycle_event_sink\n{test_case.declaration}\n" @@ -283,8 +283,8 @@ def test_given_decorated_function_alias_when_discovering_then_declares_exporter_ write_repo_files( tmp_path, { - "sinks/aliased.py": """ -from sqlbuild.sinks import lifecycle_event_sink + "python/event_sinks/aliased.py": """ +from sqlbuild.event_sinks import lifecycle_event_sink @lifecycle_event_sink def publish(event) -> None: @@ -300,22 +300,3 @@ def publish(event) -> None: ) assert tuple(exporter.name for exporter in exporters) == (test_case.expected_name,) - - -@pytest.mark.parametrize( - "test_case", - (EventExporterDiscoveryTestCase("legacy exporter directory", "replaced by sinks"),), - ids=lambda case: case.description, -) -def test_given_legacy_exporter_directory_when_discovering_then_reports_migration( - test_case: EventExporterDiscoveryTestCase, - tmp_path: Path, - write_repo_files: Callable[[Path, dict[str, str]], None], -) -> None: - write_repo_files( - tmp_path, - {"event_exporters/publish.py": "def publish(event):\n del event\n"}, - ) - - with pytest.raises(EventExporterDiscoveryError, match=test_case.expected_name): - discover_event_exporter_functions(project_dir=tmp_path) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_factories.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_factories.py index f184c69a81..632e3f7b82 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_factories.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_factories.py @@ -15,6 +15,7 @@ from tests.unit.src.sqlbuild.compiler.discovery._helpers._test_types import ( DiscoverPythonNodeFactoriesTestCase, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -23,7 +24,7 @@ DiscoverPythonNodeFactoriesTestCase( description="discovers mixed nodes returned by a factory", files={ - "python/factories/generated.py": """ + "python/nodes/factories/generated/factory.py": """ from sqlbuild.assets import asset from sqlbuild.checks import check from sqlbuild.factories import factory @@ -77,7 +78,7 @@ def regional_pipeline(): DiscoverPythonNodeFactoriesTestCase( description="discovers tuple nodes returned by a factory", files={ - "python/loaders/generated.py": """ + "python/nodes/loaders/generated/loaders.py": """ from sqlbuild.factories import factory from sqlbuild.loaders import loader @@ -102,7 +103,7 @@ def generated_loaders(): DiscoverPythonNodeFactoriesTestCase( description="discovers set node returned by a factory", files={ - "python/checks/generated.py": """ + "python/nodes/checks/generated/checks.py": """ from sqlbuild.checks import check from sqlbuild.factories import factory @@ -114,6 +115,7 @@ def generated_check(ctx): return True return {generated_check} """, + "python/nodes/checks/generated/__init__.py": "from .checks import generated_checks\n", }, expected_loader_names=(), expected_asset_names=(), @@ -123,7 +125,7 @@ def generated_check(ctx): DiscoverPythonNodeFactoriesTestCase( description="discovers single node returned by a factory in assets folder", files={ - "python/assets/generated.py": """ + "python/nodes/assets/generated/assets.py": """ from sqlbuild.assets import asset from sqlbuild.factories import factory @@ -144,7 +146,7 @@ def export(ctx): DiscoverPythonNodeFactoriesTestCase( description="discovers factory in loaders folder", files={ - "python/loaders/generated.py": """ + "python/nodes/loaders/generated/loaders.py": """ from sqlbuild.factories import factory from sqlbuild.loaders import loader @@ -165,7 +167,7 @@ def load(ctx): DiscoverPythonNodeFactoriesTestCase( description="discovers node kind from its decorator regardless of python subfolder", files={ - "python/checks/generated.py": """ + "python/nodes/checks/generated/asset.py": """ from sqlbuild.assets import asset @@ -173,6 +175,7 @@ def load(ctx): def export(ctx): return {} """, + "python/nodes/checks/generated/__init__.py": "from .asset import export\n", }, expected_loader_names=(), expected_asset_names=("orders_export",), @@ -182,28 +185,39 @@ def export(ctx): DiscoverPythonNodeFactoriesTestCase( description="discovers mixed-kind factory next to direct nodes using a shared helper", files={ - "python/_helpers.py": """ + "python/nodes/_helpers.py": """ REGION = "emea" """, - "python/orders/pipeline.py": """ -from python._helpers import REGION -from sqlbuild.checks import check -from sqlbuild.factories import factory -from sqlbuild.assets import asset - - -@asset(name="prepare_orders") -def prepare_orders(ctx): - return {"region": REGION} - - -@factory -def regional_checks(): - @check(name=f"orders_{REGION}_exists", depends_on=prepare_orders) - def generated_check(ctx): - return True - return generated_check -""", + "python/nodes/orders/pipeline/prepare_orders/asset.py": ( + "from python.nodes._helpers import REGION\n" + "from sqlbuild.checks import check\n" + "from sqlbuild.factories import factory\n" + "from sqlbuild.assets import asset\n" + "\n" + "\n" + '@asset(name="prepare_orders")\n' + "def prepare_orders(ctx):\n" + ' return {"region": REGION}\n' + ), + "python/nodes/orders/pipeline/regional_checks/checks.py": ( + "from python.nodes._helpers import REGION\n" + "from sqlbuild.checks import check\n" + "from sqlbuild.factories import factory\n" + "from sqlbuild.assets import asset\n" + "from python.nodes.orders.pipeline.prepare_orders.asset import prepare_orders\n" + "\n" + "\n" + "@factory\n" + "def regional_checks():\n" + ' @check(name=f"orders_{REGION}_exists", depends_on=prepare_orders)\n' + " def generated_check(ctx):\n" + " return True\n" + " return generated_check\n" + ), + "python/nodes/orders/pipeline/__init__.py": ( + "from .prepare_orders.asset import prepare_orders\n" + "from .regional_checks.checks import regional_checks\n" + ), }, expected_loader_names=(), expected_asset_names=("prepare_orders",), @@ -243,7 +257,9 @@ def test_given_factory_nodes_when_discovering_python_nodes_then_returns_generate DiscoverPythonNodeFactoriesTestCase( description="raises when factory returns invalid shape", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory @@ -251,6 +267,7 @@ def test_given_factory_nodes_when_discovering_python_nodes_then_returns_generate def broken_factory(): return "not a node" """, + ), }, expected_loader_names=(), expected_asset_names=(), @@ -260,7 +277,9 @@ def broken_factory(): DiscoverPythonNodeFactoriesTestCase( description="raises when factory returns none", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory @@ -268,6 +287,7 @@ def broken_factory(): def broken_factory(): return None """, + ), }, expected_loader_names=(), expected_asset_names=(), @@ -277,7 +297,9 @@ def broken_factory(): DiscoverPythonNodeFactoriesTestCase( description="raises when factory returns dict", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory @@ -285,6 +307,7 @@ def broken_factory(): def broken_factory(): return {"node": object()} """, + ), }, expected_loader_names=(), expected_asset_names=(), @@ -294,7 +317,9 @@ def broken_factory(): DiscoverPythonNodeFactoriesTestCase( description="raises when factory returns bytes", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory @@ -302,6 +327,7 @@ def broken_factory(): def broken_factory(): return b"not a node" """, + ), }, expected_loader_names=(), expected_asset_names=(), @@ -311,7 +337,9 @@ def broken_factory(): DiscoverPythonNodeFactoriesTestCase( description="raises when factory returns object", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory @@ -319,6 +347,7 @@ def broken_factory(): def broken_factory(): return object() """, + ), }, expected_loader_names=(), expected_asset_names=(), @@ -328,7 +357,9 @@ def broken_factory(): DiscoverPythonNodeFactoriesTestCase( description="raises when factory returns class", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory @@ -340,6 +371,7 @@ class NotANode: def broken_factory(): return NotANode """, + ), }, expected_loader_names=(), expected_asset_names=(), @@ -349,7 +381,9 @@ def broken_factory(): DiscoverPythonNodeFactoriesTestCase( description="raises when factory returns nested structures", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -363,6 +397,7 @@ def generated_task(ctx): def broken_factory(): return [[generated_task]] """, + ), }, expected_loader_names=(), expected_asset_names=(), @@ -372,7 +407,9 @@ def broken_factory(): DiscoverPythonNodeFactoriesTestCase( description="raises when factory returned item is not decorated", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory @@ -384,6 +421,7 @@ def helper(ctx): def broken_factory(): return [helper] """, + ), }, expected_loader_names=(), expected_asset_names=(), @@ -393,7 +431,9 @@ def broken_factory(): DiscoverPythonNodeFactoriesTestCase( description="raises when factory requires arguments", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory @@ -401,6 +441,7 @@ def broken_factory(): def broken_factory(region): return [] """, + ), }, expected_loader_names=(), expected_asset_names=(), @@ -410,7 +451,9 @@ def broken_factory(region): DiscoverPythonNodeFactoriesTestCase( description="raises when factory body fails", files={ - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory @@ -418,6 +461,7 @@ def broken_factory(region): def broken_factory(): raise RuntimeError("boom") """, + ), }, expected_loader_names=(), expected_asset_names=(), diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_file_faults.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_file_faults.py index fa5c970dd5..5b821fc61b 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_file_faults.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_file_faults.py @@ -56,25 +56,25 @@ description="audits fault every nested SQL file", discovery_name="audits", unreadable_files=( - "audits/singular/orders.sql", - "audits/generic/nested/_customers.sql", + "sql/audits/singular/orders.sql", + "sql/audits/generic/nested/_customers.sql", ), expected_fault_paths=( - Path("audits/generic/nested/_customers.sql"), - Path("audits/singular/orders.sql"), + Path("sql/audits/generic/nested/_customers.sql"), + Path("sql/audits/singular/orders.sql"), ), ), DiscoverFileFaultsTestCase( description="constants fault declaration files", discovery_name="constants", - unreadable_files=("constants/order_limits.sql",), - expected_fault_paths=(Path("constants/order_limits.sql"),), + unreadable_files=("sql/constants/order_limits.sql",), + expected_fault_paths=(Path("sql/constants/order_limits.sql"),), ), DiscoverFileFaultsTestCase( description="enums fault declaration files", discovery_name="enums", - unreadable_files=("enums/order_status.sql",), - expected_fault_paths=(Path("enums/order_status.sql"),), + unreadable_files=("sql/enums/order_status.sql",), + expected_fault_paths=(Path("sql/enums/order_status.sql"),), ), DiscoverFileFaultsTestCase( description="scenarios fault nested SQL files", @@ -86,27 +86,30 @@ description="sources fault only top-level YAML files", discovery_name="sources", unreadable_files=( - "sources/orders.yml", - "sources/customers.yaml", - "sources/notes.txt", - "sources/nested/products.yml", + "sql/sources/orders.yml", + "sql/sources/customers.yaml", + "sql/sources/notes.txt", + "sql/sources/nested/products.yml", + ), + expected_fault_paths=( + Path("sql/sources/customers.yaml"), + Path("sql/sources/orders.yml"), ), - expected_fault_paths=(Path("sources/customers.yaml"), Path("sources/orders.yml")), ), DiscoverFileFaultsTestCase( description="sql functions fault underscore-prefixed files", discovery_name="sql_functions", - unreadable_files=("functions/sql/_order_total.sql", "functions/sql/tax.sql"), + unreadable_files=("sql/functions/sql/_order_total.sql", "sql/functions/sql/tax.sql"), expected_fault_paths=( - Path("functions/sql/_order_total.sql"), - Path("functions/sql/tax.sql"), + Path("sql/functions/sql/_order_total.sql"), + Path("sql/functions/sql/tax.sql"), ), ), DiscoverFileFaultsTestCase( description="sql hooks skip underscore-prefixed files", discovery_name="sql_hooks", - unreadable_files=("hooks/sql/_shared.sql", "hooks/sql/grants/grant_access.sql"), - expected_fault_paths=(Path("hooks/sql/grants/grant_access.sql"),), + unreadable_files=("sql/hooks/sql/_shared.sql", "sql/hooks/sql/grants/grant_access.sql"), + expected_fault_paths=(Path("sql/hooks/sql/grants/grant_access.sql"),), ), ), ids=lambda case: case.description, @@ -134,32 +137,32 @@ def test_given_unreadable_files_when_discovering_then_faults_each_file_or_raises DiscoverModuleImportFailureTestCase( description="command output sink import failure identifies the sink file", discovery_name="command_output_sinks", - broken_file="sinks/broken_orders.py", + broken_file="python/event_sinks/broken_orders.py", expected_error_type=EventExporterDiscoveryError, - expected_error_fragment="Failed to import sink file sinks/broken_orders.py: ", + expected_error_fragment="Failed to import event sink file python/event_sinks/broken_orders.py: ", ), DiscoverModuleImportFailureTestCase( description="lifecycle sink import failure identifies the sink file", discovery_name="event_exporters", - broken_file="sinks/broken_orders.py", + broken_file="python/event_sinks/broken_orders.py", expected_error_type=EventExporterDiscoveryError, - expected_error_fragment="Failed to import sink file sinks/broken_orders.py: ", + expected_error_fragment="Failed to import event sink file python/event_sinks/broken_orders.py: ", ), DiscoverModuleImportFailureTestCase( description="materialization import failure identifies the materialization file", discovery_name="materializations", - broken_file="materializations/broken_orders.py", + broken_file="python/materializations/broken_orders.py", expected_error_type=PythonNodeDiscoveryError, expected_error_fragment=( - "Failed to import materialization file materializations/broken_orders.py: " + "Failed to import materialization file python/materializations/broken_orders.py: " ), ), DiscoverModuleImportFailureTestCase( description="provider import failure identifies the provider file", discovery_name="providers", - broken_file="providers/broken_orders.py", + broken_file="python/providers/broken_orders.py", expected_error_type=ProviderDiscoveryError, - expected_error_fragment="Failed to import provider file providers/broken_orders.py: ", + expected_error_fragment="Failed to import provider file python/providers/broken_orders.py: ", ), ), ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_hooks.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_hooks.py index 89e0f856cc..fde98bfaa6 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_hooks.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_hooks.py @@ -25,7 +25,7 @@ DiscoverHookFunctionsTestCase( description="discovers decorated hook functions", repo_files={ - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from sqlbuild.hooks import hook @@ -54,7 +54,7 @@ def undecorated(ctx): return None """.strip() + "\n", - "hooks/python/nested/catalog.py": """ + "sql/hooks/python/nested/catalog.py": """ from sqlbuild.hooks import hook @@ -72,11 +72,11 @@ def publish(ctx): "plain_call", ), expected_hook_paths=( - "hooks/python/nested/catalog.py", - "hooks/python/notifications.py", - "hooks/python/notifications.py", - "hooks/python/notifications.py", - "hooks/python/notifications.py", + "sql/hooks/python/nested/catalog.py", + "sql/hooks/python/notifications.py", + "sql/hooks/python/notifications.py", + "sql/hooks/python/notifications.py", + "sql/hooks/python/notifications.py", ), expected_hook_descriptions=( None, @@ -96,7 +96,7 @@ def publish(ctx): DiscoverHookFunctionsTestCase( description="ignores private files and init files", repo_files={ - "hooks/python/__init__.py": """ + "sql/hooks/python/__init__.py": """ from sqlbuild.hooks import hook @@ -105,7 +105,7 @@ def package_hook(ctx): return None """.strip() + "\n", - "hooks/python/_private.py": """ + "sql/hooks/python/_private.py": """ from sqlbuild.hooks import hook @@ -114,7 +114,7 @@ def private_hook(ctx): return None """.strip() + "\n", - "hooks/python/public.py": """ + "sql/hooks/python/public.py": """ from sqlbuild.hooks import hook @@ -125,14 +125,14 @@ def public_hook(ctx): + "\n", }, expected_hook_names=("public_hook",), - expected_hook_paths=("hooks/python/public.py",), + expected_hook_paths=("sql/hooks/python/public.py",), expected_hook_descriptions=(None,), expected_function_names=("public_hook",), ), DiscoverHookFunctionsTestCase( description="does not execute hook functions during discovery", repo_files={ - "hooks/python/no_execute.py": """ + "sql/hooks/python/no_execute.py": """ from pathlib import Path from sqlbuild.hooks import hook @@ -144,7 +144,7 @@ def no_execute(ctx): + "\n", }, expected_hook_names=("no_execute",), - expected_hook_paths=("hooks/python/no_execute.py",), + expected_hook_paths=("sql/hooks/python/no_execute.py",), expected_hook_descriptions=(None,), expected_function_names=("no_execute",), expected_marker_file_exists=False, @@ -152,7 +152,7 @@ def no_execute(ctx): DiscoverHookFunctionsTestCase( description="ignores imported decorated hooks", repo_files={ - "hooks/python/shared.py": """ + "sql/hooks/python/shared.py": """ from sqlbuild.hooks import hook @@ -161,9 +161,9 @@ def imported_hook(ctx): return None """.strip() + "\n", - "hooks/python/uses_import.py": """ + "sql/hooks/python/uses_import.py": """ from sqlbuild.hooks import hook -from hooks.python.shared import imported_hook +from sql.hooks.python.shared import imported_hook @hook @@ -173,7 +173,7 @@ def local_hook(ctx): + "\n", }, expected_hook_names=("imported", "local_hook"), - expected_hook_paths=("hooks/python/shared.py", "hooks/python/uses_import.py"), + expected_hook_paths=("sql/hooks/python/shared.py", "sql/hooks/python/uses_import.py"), expected_hook_descriptions=(None, None), expected_function_names=("imported_hook", "local_hook"), ), @@ -198,7 +198,7 @@ def test_given_hook_files_when_discovering_then_returns_decorated_hooks( ) assert all(callable(hook.function) for hook in hooks) assert ( - tmp_path / "hooks" / "python" / "executed.marker" + tmp_path / "sql" / "hooks" / "python" / "executed.marker" ).is_file() is test_case.expected_marker_file_exists @@ -208,7 +208,7 @@ def test_given_hook_files_when_discovering_then_returns_decorated_hooks( DiscoverHookFunctionsTestCase( description="records hook provider usage metadata", repo_files={ - "providers/marker.py": """ + "python/providers/marker.py": """ from sqlbuild.providers import Provider @@ -216,8 +216,8 @@ class MarkerProvider(Provider): pass """.strip() + "\n", - "hooks/python/marker.py": """ -from providers.marker import MarkerProvider + "sql/hooks/python/marker.py": """ +from python.providers.marker import MarkerProvider from sqlbuild.hooks import hook @@ -228,7 +228,7 @@ def mark(ctx, marker_provider: MarkerProvider): + "\n", }, expected_hook_names=("mark",), - expected_hook_paths=("hooks/python/marker.py",), + expected_hook_paths=("sql/hooks/python/marker.py",), expected_hook_descriptions=(None,), expected_function_names=("mark",), ) @@ -254,7 +254,7 @@ def test_given_hook_provider_parameter_when_discovering_then_records_provider_us assert usage.provider_name == "marker_provider" assert usage.parameter_name == "marker_provider" assert usage.annotation_class_name == "MarkerProvider" - assert usage.annotation_module == "providers.marker" + assert usage.annotation_module == "python.providers.marker" @pytest.mark.parametrize( @@ -263,7 +263,7 @@ def test_given_hook_provider_parameter_when_discovering_then_records_provider_us DiscoverHookFunctionsErrorTestCase( description="duplicate hook names fail", repo_files={ - "hooks/python/first.py": """ + "sql/hooks/python/first.py": """ from sqlbuild.hooks import hook @@ -272,7 +272,7 @@ def notify_a(ctx): return None """.strip() + "\n", - "hooks/python/second.py": """ + "sql/hooks/python/second.py": """ from sqlbuild.hooks import hook @@ -287,12 +287,12 @@ def notify_b(ctx): DiscoverHookFunctionsErrorTestCase( description="hook import failure identifies file", repo_files={ - "hooks/python/broken.py": """ + "sql/hooks/python/broken.py": """ from missing_package import missing_hook """.strip() + "\n", }, - expected_error_fragment="Failed to import Python node file hooks/python/broken.py", + expected_error_fragment="Failed to import Python node file sql/hooks/python/broken.py", ), ), ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_loaders.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_loaders.py index 735972e909..e9aaeaddea 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_loaders.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_loaders.py @@ -22,14 +22,14 @@ DiscoverLoaderFunctionsTestCase( description="discovers decorated source loaders from the python directory", files={ - "python/loaders/github.py": """ + "python/nodes/loaders/github/loader.py": """ from sqlbuild.loaders import loader @loader def github_events(ctx): return [] """, - "python/loaders/stripe.py": """ + "python/nodes/loaders/stripe/loader.py": """ from sqlbuild.loaders import loader @loader(destination="raw.customers") @@ -49,7 +49,7 @@ def stripe_customers(ctx): DiscoverLoaderFunctionsTestCase( description="discovers intermediate loader write and schema metadata", files={ - "python/loaders/events.py": """ + "python/nodes/loaders/events/loader.py": """ from sqlbuild.loaders import loader @loader( @@ -66,6 +66,7 @@ def stripe_customers(ctx): def events(ctx): return [] """, + "python/nodes/loaders/events/__init__.py": "from .loader import events\n", }, expected_names=("events",), expected_targets=("staging.events",), @@ -79,17 +80,27 @@ def events(ctx): DiscoverLoaderFunctionsTestCase( description="discovers loader dependencies from decorator metadata", files={ - "python/loaders/events.py": """ -from sqlbuild.loaders import loader - -@loader -def fetch_events(ctx): - return [] - -@loader(depends_on=[fetch_events]) -def enriched_events(ctx): - return [] -""", + "python/nodes/loaders/events/fetch_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader\n" + "def fetch_events(ctx):\n" + " return []\n" + ), + "python/nodes/loaders/events/enriched_events/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.events.fetch_events.loader import fetch_events\n" + "\n" + "\n" + "@loader(depends_on=[fetch_events])\n" + "def enriched_events(ctx):\n" + " return []\n" + ), + "python/nodes/loaders/events/__init__.py": ( + "from .fetch_events.loader import fetch_events\n" + "from .enriched_events.loader import enriched_events\n" + ), }, expected_names=("enriched_events", "fetch_events"), expected_targets=(None, None), @@ -103,17 +114,27 @@ def enriched_events(ctx): DiscoverLoaderFunctionsTestCase( description="discovers explicit loader names and dependencies", files={ - "python/loaders/events.py": """ -from sqlbuild.loaders import loader - -@loader(name="fetch_events") -def make_fetch(ctx): - return [] - -@loader(name="enriched_events", depends_on=[make_fetch]) -def make_enriched(ctx): - return [] -""", + "python/nodes/loaders/events/make_fetch/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + '@loader(name="fetch_events")\n' + "def make_fetch(ctx):\n" + " return []\n" + ), + "python/nodes/loaders/events/make_enriched/loader.py": ( + "from sqlbuild.loaders import loader\n" + "from python.nodes.loaders.events.make_fetch.loader import make_fetch\n" + "\n" + "\n" + '@loader(name="enriched_events", depends_on=[make_fetch])\n' + "def make_enriched(ctx):\n" + " return []\n" + ), + "python/nodes/loaders/events/__init__.py": ( + "from .make_fetch.loader import make_fetch\n" + "from .make_enriched.loader import make_enriched\n" + ), }, expected_names=("enriched_events", "fetch_events"), expected_targets=(None, None), @@ -139,15 +160,16 @@ def make_enriched(ctx): DiscoverLoaderFunctionsTestCase( description="ignores undecorated functions and init files", files={ - "python/loaders/__init__.py": "", - "python/loaders/helpers.py": "def helper(): return None\n", - "python/loaders/orders.py": """ + "python/nodes/loaders/__init__.py": "", + "python/nodes/loaders/helpers.py": "def helper(): return None\n", + "python/nodes/loaders/orders/loader.py": """ from sqlbuild.loaders import loader @loader def orders(ctx): return [] """, + "python/nodes/loaders/orders/__init__.py": "from .loader import orders\n", }, expected_names=("orders",), expected_targets=(None,), @@ -202,7 +224,7 @@ def test_given_project_dir_when_discovering_loaders_then_returns_expected( [ DiscoverLoaderFunctionsTestCase( description="raises clear error when loader file import fails", - files={"python/loaders/broken.py": "import missing_loader_dependency\n"}, + files={"python/nodes/loaders/broken.py": "import missing_loader_dependency\n"}, expected_names=(), expected_targets=(), expected_dependency_counts=(), @@ -211,7 +233,7 @@ def test_given_project_dir_when_discovering_loaders_then_returns_expected( expected_unique_keys=(), expected_column_names=(), expected_contracts=(), - expected_error_fragment="Failed to import Python node file python/loaders/broken.py", + expected_error_fragment="Failed to import Python node file python/nodes/loaders/broken.py", ) ], ids=lambda case: case.description, @@ -237,23 +259,37 @@ def test_given_loader_import_error_when_discovering_loaders_then_raises_clear_er DiscoverLoaderFunctionsTestCase( description="loader descriptions come from the decorator or the docstring", files={ - "python/loaders/orders.py": ''' -from sqlbuild.loaders import loader - -@loader -def raw_orders(ctx): - """Orders from the storefront export.""" - return [] - -@loader(description="Refunds from the payments export") -def raw_refunds(ctx): - """Ignored because the decorator wins.""" - return [] - -@loader -def raw_returns(ctx): - return [] -''', + "python/nodes/loaders/orders/raw_orders/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader\n" + "def raw_orders(ctx):\n" + ' """Orders from the storefront export."""\n' + " return []\n" + ), + "python/nodes/loaders/orders/raw_refunds/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + '@loader(description="Refunds from the payments export")\n' + "def raw_refunds(ctx):\n" + ' """Ignored because the decorator wins."""\n' + " return []\n" + ), + "python/nodes/loaders/orders/raw_returns/loader.py": ( + "from sqlbuild.loaders import loader\n" + "\n" + "\n" + "@loader\n" + "def raw_returns(ctx):\n" + " return []\n" + ), + "python/nodes/loaders/orders/__init__.py": ( + "from .raw_orders.loader import raw_orders\n" + "from .raw_refunds.loader import raw_refunds\n" + "from .raw_returns.loader import raw_returns\n" + ), }, expected_names=("raw_orders", "raw_refunds", "raw_returns"), expected_descriptions=( diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_macros.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_macros.py index 8b3090c2f2..23db7067d5 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_macros.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_macros.py @@ -21,12 +21,15 @@ DiscoverMacroFilesTestCase( description="discovers Python macro modules but skips package initializers", files={ - "macros/python/__init__.py": "raise RuntimeError('must not load')\n", - "macros/python/orders.py": "def order_columns(): return 'order_id'\n", - "macros/python/nested/__init__.py": "raise RuntimeError('must not load')\n", - "macros/python/nested/dates.py": "def current_date(): return 'CURRENT_DATE'\n", + "sql/macros/python/__init__.py": "raise RuntimeError('must not load')\n", + "sql/macros/python/orders.py": "def order_columns(): return 'order_id'\n", + "sql/macros/python/nested/__init__.py": "raise RuntimeError('must not load')\n", + "sql/macros/python/nested/dates.py": "def current_date(): return 'CURRENT_DATE'\n", }, - expected_relative_paths=("macros/python/nested/dates.py", "macros/python/orders.py"), + expected_relative_paths=( + "sql/macros/python/nested/dates.py", + "sql/macros/python/orders.py", + ), ), ], ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_materializations.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_materializations.py index 4943308fea..1798e07c9b 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_materializations.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_materializations.py @@ -24,8 +24,8 @@ DiscoverMaterializationFilesTestCase( description="discovers materialization files from materializations directory", files={ - "materializations/partition_tracked.py": "def materialize(ctx): pass\n", - "materializations/atomic_swap.py": "def materialize(ctx): pass\n", + "python/materializations/partition_tracked.py": "def materialize(ctx): pass\n", + "python/materializations/atomic_swap.py": "def materialize(ctx): pass\n", }, expected_names=("atomic_swap", "partition_tracked"), ), @@ -37,8 +37,8 @@ DiscoverMaterializationFilesTestCase( description="skips __init__ files in materializations directory", files={ - "materializations/__init__.py": "", - "materializations/custom_one.py": "def materialize(ctx): pass\n", + "python/materializations/__init__.py": "", + "python/materializations/custom_one.py": "def materialize(ctx): pass\n", }, expected_names=("custom_one",), ), @@ -70,7 +70,7 @@ def test_given_project_dir_when_discovering_materializations_then_returns_expect DiscoverMaterializationFilesTestCase( description="records custom materialization provider usage metadata", files={ - "providers/marker.py": """ + "python/providers/marker.py": """ from sqlbuild.providers import Provider @@ -78,8 +78,8 @@ class MarkerProvider(Provider): pass """.strip() + "\n", - "materializations/copy_table.py": """ -from providers.marker import MarkerProvider + "python/materializations/copy_table.py": """ +from python.providers.marker import MarkerProvider def materialize(ctx, marker_provider: MarkerProvider): @@ -115,4 +115,4 @@ def test_given_materialization_provider_parameter_when_discovering_then_records_ assert usage.provider_name == "marker_provider" assert usage.parameter_name == "marker_provider" assert usage.annotation_class_name == "MarkerProvider" - assert usage.annotation_module == "providers.marker" + assert usage.annotation_module == "python.providers.marker" diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_providers.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_providers.py index 9b365ec465..b5beb2135e 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_providers.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_providers.py @@ -26,7 +26,7 @@ DiscoverProviderClassesTestCase( description="discovers provider classes", repo_files={ - "providers/notifications.py": """ + "python/providers/notifications.py": """ from typing import ClassVar from sqlbuild.providers import Provider @@ -40,7 +40,7 @@ class AlertsProvider(Provider): provider_name: ClassVar[str] = "alerts" """.strip() + "\n", - "providers/nested/clock.py": """ + "python/providers/nested/clock.py": """ from sqlbuild.providers import Provider @@ -51,16 +51,16 @@ class Clock(Provider): }, expected_provider_names=("clock", "alerts", "slack_provider"), expected_provider_paths=( - "providers/nested/clock.py", - "providers/notifications.py", - "providers/notifications.py", + "python/providers/nested/clock.py", + "python/providers/notifications.py", + "python/providers/notifications.py", ), expected_provider_class_names=("Clock", "AlertsProvider", "SlackProvider"), ), DiscoverProviderClassesTestCase( description="ignores private files init files imported classes and abstract classes", repo_files={ - "providers/__init__.py": """ + "python/providers/__init__.py": """ from sqlbuild.providers import Provider @@ -68,7 +68,7 @@ class PackageProvider(Provider): pass """.strip() + "\n", - "providers/_private.py": """ + "python/providers/_private.py": """ from sqlbuild.providers import Provider @@ -76,7 +76,7 @@ class PrivateProvider(Provider): pass """.strip() + "\n", - "providers/nested/_private.py": """ + "python/providers/nested/_private.py": """ from sqlbuild.providers import Provider @@ -84,7 +84,7 @@ class NestedPrivateProvider(Provider): pass """.strip() + "\n", - "providers/shared.py": """ + "python/providers/shared.py": """ from abc import ABC, abstractmethod from sqlbuild.providers import Provider @@ -100,8 +100,8 @@ def send(self) -> None: raise NotImplementedError """.strip() + "\n", - "providers/public.py": """ -from providers.shared import AbstractProvider, ImportedProvider + "python/providers/public.py": """ +from python.providers.shared import AbstractProvider, ImportedProvider from sqlbuild.providers import Provider @@ -111,13 +111,13 @@ class PublicProvider(Provider): + "\n", }, expected_provider_names=("public_provider", "imported_provider"), - expected_provider_paths=("providers/public.py", "providers/shared.py"), + expected_provider_paths=("python/providers/public.py", "python/providers/shared.py"), expected_provider_class_names=("PublicProvider", "ImportedProvider"), ), DiscoverProviderClassesTestCase( description="skips provider base class imported into provider module", repo_files={ - "providers/base_only.py": """ + "python/providers/base_only.py": """ from sqlbuild.providers import Provider """.strip() + "\n", @@ -129,7 +129,7 @@ class PublicProvider(Provider): DiscoverProviderClassesTestCase( description="does not call setup during discovery", repo_files={ - "providers/no_setup.py": """ + "python/providers/no_setup.py": """ from pathlib import Path from sqlbuild.providers import Provider @@ -142,7 +142,7 @@ def setup(self, ctx): + "\n", }, expected_provider_names=("no_setup_provider",), - expected_provider_paths=("providers/no_setup.py",), + expected_provider_paths=("python/providers/no_setup.py",), expected_provider_class_names=("NoSetupProvider",), expected_marker_file_exists=False, ), @@ -172,7 +172,7 @@ def test_given_provider_files_when_discovering_then_returns_provider_classes( provider.provider_class for provider in providers ) assert ( - tmp_path / "providers" / "setup.marker" + tmp_path / "python" / "providers" / "setup.marker" ).is_file() is test_case.expected_marker_file_exists @@ -182,7 +182,7 @@ def test_given_provider_files_when_discovering_then_returns_provider_classes( DiscoverProviderCacheIsolationTestCase( description="isolates provider package cache between project directories", first_repo_files={ - "providers/shared.py": """ + "python/providers/shared.py": """ from sqlbuild.providers import Provider @@ -192,7 +192,7 @@ class FirstProvider(Provider): + "\n", }, second_repo_files={ - "providers/shared.py": """ + "python/providers/shared.py": """ from sqlbuild.providers import Provider @@ -200,8 +200,8 @@ class ImportedProvider(Provider): pass """.strip() + "\n", - "providers/public.py": """ -from providers.shared import ImportedProvider + "python/providers/public.py": """ +from python.providers.shared import ImportedProvider from sqlbuild.providers import Provider @@ -247,7 +247,7 @@ def test_given_previous_project_provider_package_when_discovering_then_uses_curr DiscoverProviderClassesErrorTestCase( description="duplicate provider names fail", repo_files={ - "providers/first.py": """ + "python/providers/first.py": """ from typing import ClassVar from sqlbuild.providers import Provider @@ -257,7 +257,7 @@ class FirstProvider(Provider): provider_name: ClassVar[str] = "alerts" """.strip() + "\n", - "providers/second.py": """ + "python/providers/second.py": """ from typing import ClassVar from sqlbuild.providers import Provider @@ -274,7 +274,7 @@ class SecondProvider(Provider): DiscoverProviderClassesErrorTestCase( description="duplicate provider names in same file fail", repo_files={ - "providers/duplicates.py": """ + "python/providers/duplicates.py": """ from typing import ClassVar from sqlbuild.providers import Provider @@ -289,24 +289,24 @@ class SecondProvider(Provider): """.strip() + "\n", }, - expected_error_fragment="Duplicate provider name 'alerts' found in providers/duplicates.py", + expected_error_fragment="Duplicate provider name 'alerts' found in python/providers/duplicates.py", expected_error_type=ProviderDiscoveryError, ), DiscoverProviderClassesErrorTestCase( description="provider import failure identifies file", repo_files={ - "providers/broken.py": """ + "python/providers/broken.py": """ from missing_package import missing_provider """.strip() + "\n", }, - expected_error_fragment="Failed to import provider file providers/broken.py", + expected_error_fragment="Failed to import provider file python/providers/broken.py", expected_error_type=ProviderDiscoveryError, ), DiscoverProviderClassesErrorTestCase( description="provider settings failure identifies provider", repo_files={ - "providers/slack.py": """ + "python/providers/slack.py": """ from pydantic import Field from sqlbuild.providers import Provider @@ -317,14 +317,14 @@ class SlackProvider(Provider): + "\n", }, expected_error_fragment=( - "Provider 'slack_provider' in providers/slack.py has invalid settings" + "Provider 'slack_provider' in python/providers/slack.py has invalid settings" ), expected_error_type=ProviderDiscoveryError, ), DiscoverProviderClassesErrorTestCase( description="invalid provider name identifies provider", repo_files={ - "providers/slack.py": """ + "python/providers/slack.py": """ from typing import ClassVar from sqlbuild.providers import Provider @@ -358,7 +358,7 @@ def test_given_invalid_provider_files_when_discovering_then_raises( DiscoverProviderEnvSettingsTestCase( description="env-backed settings resolve during discovery", repo_files={ - "providers/slack.py": """ + "python/providers/slack.py": """ from pydantic import Field from sqlbuild.providers import Provider @@ -402,7 +402,7 @@ def test_given_env_backed_provider_settings_when_discovering_then_instance_has_e DiscoverProviderSecretErrorTestCase( description="invalid plain env setting error redacts raw input value", repo_files={ - "providers/slack.py": """ + "python/providers/slack.py": """ from pydantic import Field from sqlbuild.providers import Provider @@ -416,7 +416,7 @@ class SlackProvider(Provider): env_name="SLACK_TOKEN", env_value="super-secret-token-value", expected_error_fragment=( - "Provider 'slack_provider' in providers/slack.py has invalid settings" + "Provider 'slack_provider' in python/providers/slack.py has invalid settings" ), unexpected_error_fragment="super-secret-token-value", ), diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_python_nodes.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_python_nodes.py index bc7cf7e81d..7852d2d333 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_python_nodes.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_python_nodes.py @@ -31,29 +31,30 @@ ) _HELPER_PACKAGE_FILES: dict[str, str] = { - "python/helpers/__init__.py": "", - "python/helpers/values.py": """ + "python/nodes/helpers/__init__.py": "", + "python/nodes/helpers/values.py": """ from pathlib import Path -Path(__file__).resolve().parents[2].joinpath("init_count.txt").open("a").write("values\\n") +Path(__file__).resolve().parents[3].joinpath("init_count.txt").open("a").write("values\\n") STATUS = "shipped" """, - "python/helpers/clean.py": """ + "python/nodes/helpers/clean.py": """ from .values import STATUS def normalize_status(value): return f"{value.strip().lower()}:{STATUS}" """, - "python/orders.py": """ -import python.helpers.clean + "python/nodes/orders/asset.py": """ +import python.nodes.helpers.clean from sqlbuild.assets import asset @asset def orders(ctx): - return python.helpers.clean.normalize_status(" Shipped ") + return python.nodes.helpers.clean.normalize_status(" Shipped ") """, + "python/nodes/orders/__init__.py": "from .asset import orders\n", } @@ -63,7 +64,7 @@ def orders(ctx): DiscoverAssetFunctionsTestCase( description="discovers decorated assets from explicit folders", files={ - "python/tasks/windows.py": """ + "python/nodes/tasks/windows/asset.py": """ from sqlbuild.assets import asset @asset(tags=("api",), group="ingestion") @@ -74,9 +75,9 @@ def fetch_window(ctx): def helper(): return None """, - "python/assets/exports.py": """ + "python/nodes/assets/exports/asset.py": """ from sqlbuild.assets import asset -from python.tasks.windows import fetch_window +from python.nodes.tasks.windows.asset import fetch_window @asset( depends_on=fetch_window, @@ -86,7 +87,7 @@ def helper(): def export_customers(ctx): return {"uri": "s3://exports/customers.parquet"} """, - "python/assets/__init__.py": """ + "python/nodes/assets/__init__.py": """ from sqlbuild.assets import asset @asset @@ -150,7 +151,7 @@ def test_given_project_dir_when_discovering_python_nodes_then_returns_expected( [ DiscoverAssetFunctionsTestCase( description="raises clear error when a node import fails", - files={"python/tasks/broken.py": "import missing_task_dependency\n"}, + files={"python/nodes/tasks/broken.py": "import missing_task_dependency\n"}, expected_asset_names=(), expected_asset_dependency_counts=(), expected_asset_tags=(), @@ -182,16 +183,16 @@ def test_given_python_node_import_error_when_discovering_then_raises_clear_error DiscoverCheckFunctionsTestCase( description="discovers decorated checks from explicit folder", files={ - "python/assets/exports.py": """ + "python/nodes/assets/exports/asset.py": """ from sqlbuild.assets import asset @asset def export_customers(ctx): return {"uri": "s3://exports/customers.parquet"} """, - "python/checks/exports.py": """ + "python/nodes/checks/exports/checks.py": """ from sqlbuild.checks import check -from python.assets.exports import export_customers +from python.nodes.assets.exports.asset import export_customers @check(depends_on=export_customers, severity="warn", tags=("exports",)) def export_customers_exists(ctx): @@ -200,9 +201,9 @@ def export_customers_exists(ctx): def helper(): return None """, - "python/checks/__init__.py": """ + "python/nodes/checks/__init__.py": """ from sqlbuild.checks import check -from python.assets.exports import export_customers +from python.nodes.assets.exports.asset import export_customers @check(depends_on=export_customers) def ignored_init_check(ctx): @@ -252,47 +253,78 @@ def test_given_project_dir_when_discovering_checks_then_returns_expected( "test_case", [ DiscoverPythonRootNodesTestCase( - description="discovers every node kind in one module directly under python", + description="discovers every node kind in one unit per node", files={ - "python/orders.py": """ -from sqlbuild.assets import asset -from sqlbuild.checks import check -from sqlbuild.loaders import loader -from sqlbuild.assets import asset - -@asset -def prepare_orders(ctx): - return None - -@loader(depends_on=[prepare_orders]) -def raw_orders(ctx): - return [] - -@asset(depends_on=prepare_orders) -def orders_export(ctx): - return None - -@check(depends_on=orders_export) -def orders_export_exists(ctx): - return True -""", + "python/nodes/orders/prepare_orders/asset.py": ( + "from sqlbuild.assets import asset\n" + "from sqlbuild.checks import check\n" + "from sqlbuild.loaders import loader\n" + "from sqlbuild.assets import asset\n" + "\n" + "\n" + "@asset\n" + "def prepare_orders(ctx):\n" + " return None\n" + ), + "python/nodes/orders/raw_orders/loader.py": ( + "from sqlbuild.assets import asset\n" + "from sqlbuild.checks import check\n" + "from sqlbuild.loaders import loader\n" + "from sqlbuild.assets import asset\n" + "from python.nodes.orders.prepare_orders.asset import prepare_orders\n" + "\n" + "\n" + "@loader(depends_on=[prepare_orders])\n" + "def raw_orders(ctx):\n" + " return []\n" + ), + "python/nodes/orders/orders_export/asset.py": ( + "from sqlbuild.assets import asset\n" + "from sqlbuild.checks import check\n" + "from sqlbuild.loaders import loader\n" + "from sqlbuild.assets import asset\n" + "from python.nodes.orders.prepare_orders.asset import prepare_orders\n" + "\n" + "\n" + "@asset(depends_on=prepare_orders)\n" + "def orders_export(ctx):\n" + " return None\n" + ), + "python/nodes/orders/checks.py": ( + "from sqlbuild.assets import asset\n" + "from sqlbuild.checks import check\n" + "from sqlbuild.loaders import loader\n" + "from sqlbuild.assets import asset\n" + "from python.nodes.orders.orders_export.asset import orders_export\n" + "\n" + "\n" + "@check(depends_on=orders_export)\n" + "def orders_export_exists(ctx):\n" + " return True\n" + ), + "python/nodes/orders/__init__.py": ( + "from .prepare_orders.asset import prepare_orders\n" + "from .raw_orders.loader import raw_orders\n" + "from .orders_export.asset import orders_export\n" + "from .checks import orders_export_exists\n" + ), }, expected_nodes=( - ("loader", "raw_orders", "python/orders.py"), - ("asset", "orders_export", "python/orders.py"), - ("asset", "prepare_orders", "python/orders.py"), - ("check", "orders_export_exists", "python/orders.py"), + ("loader", "raw_orders", "python/nodes/orders/raw_orders/loader.py"), + ("asset", "orders_export", "python/nodes/orders/orders_export/asset.py"), + ("asset", "prepare_orders", "python/nodes/orders/prepare_orders/asset.py"), + ("check", "orders_export_exists", "python/nodes/orders/checks.py"), ), ), DiscoverPythonRootNodesTestCase( description="discovers nodes in nested folders that import undecorated helpers", files={ - "python/_helpers.py": """ + "python/nodes/_helpers.py": """ def export_uri(name): return f"s3://exports/{name}.parquet" """, - "python/orders/__init__.py": "", - "python/orders/utils.py": """ + "python/nodes/orders/__init__.py": "", + "python/nodes/orders/utils.py": """ from sqlbuild.assets import asset def order_label(value): @@ -300,32 +332,32 @@ def order_label(value): LABEL = asset """, - "python/orders/ingest/loaders.py": """ + "python/nodes/orders/ingest/loader.py": """ from sqlbuild.loaders import loader @loader def raw_orders(ctx): return [] """, - "python/orders/pipeline/tasks.py": """ -from python.orders.utils import order_label + "python/nodes/orders/pipeline/tasks/asset.py": """ +from python.nodes.orders.utils import order_label from sqlbuild.assets import asset @asset def label_orders(ctx): return order_label(1) """, - "python/exports/assets.py": """ -from python._helpers import export_uri -from python.orders.pipeline.tasks import label_orders + "python/nodes/exports/orders_export/asset.py": """ +from python.nodes._helpers import export_uri +from python.nodes.orders.pipeline.tasks.asset import label_orders from sqlbuild.assets import asset @asset(depends_on=label_orders) def orders_export(ctx): return {"uri": export_uri("orders")} """, - "python/exports/deep/nested/checks.py": """ -from python.exports.assets import orders_export + "python/nodes/exports/deep/nested/checks.py": """ +from python.nodes.exports.orders_export.asset import orders_export from sqlbuild.checks import check @check(depends_on=orders_export) @@ -334,17 +366,17 @@ def orders_export_exists(ctx): """, }, expected_nodes=( - ("loader", "raw_orders", "python/orders/ingest/loaders.py"), - ("asset", "orders_export", "python/exports/assets.py"), - ("asset", "label_orders", "python/orders/pipeline/tasks.py"), - ("check", "orders_export_exists", "python/exports/deep/nested/checks.py"), + ("loader", "raw_orders", "python/nodes/orders/ingest/loader.py"), + ("asset", "orders_export", "python/nodes/exports/orders_export/asset.py"), + ("asset", "label_orders", "python/nodes/orders/pipeline/tasks/asset.py"), + ("check", "orders_export_exists", "python/nodes/exports/deep/nested/checks.py"), ), ), DiscoverPythonRootNodesTestCase( description="treats helper-only python root as having no nodes", files={ - "python/_helpers.py": "def order_label(value):\n return str(value)\n", - "python/orders/utils.py": "REGION = 'emea'\n", + "python/nodes/_helpers.py": "def order_label(value):\n return str(value)\n", + "python/nodes/orders/utils.py": "REGION = 'emea'\n", }, expected_nodes=(), ), @@ -384,13 +416,13 @@ def test_given_python_root_when_discovering_python_nodes_then_decorators_define_ DiscoverPythonRootImportTestCase( description="shares one helper module between nodes that import it absolutely", files={ - "python/_counter.py": """ + "python/nodes/_counter.py": """ from pathlib import Path -Path(__file__).resolve().parents[1].joinpath("init_count.txt").open("a").write("counter\\n") +Path(__file__).resolve().parents[2].joinpath("init_count.txt").open("a").write("counter\\n") """, - "python/tasks/first.py": """ -import python._counter + "python/nodes/tasks/first/asset.py": """ +import python.nodes._counter from sqlbuild.assets import asset @@ -398,8 +430,8 @@ def test_given_python_root_when_discovering_python_nodes_then_decorators_define_ def first_task(ctx): return None """, - "python/tasks/second.py": """ -from python import _counter + "python/nodes/tasks/second/asset.py": """ +from python.nodes import _counter from sqlbuild.assets import asset @@ -435,9 +467,9 @@ def test_given_python_root_helpers_when_discovering_then_modules_import_under_pa PythonRootProjectIsolationTestCase( description="second project imports its own python helpers", first_files={ - "python/_values.py": "STATUS = 'first'\n", - "python/orders.py": """ -from python._values import STATUS + "python/nodes/_values.py": "STATUS = 'first'\n", + "python/nodes/orders/asset.py": """ +from python.nodes._values import STATUS from sqlbuild.assets import asset @@ -445,11 +477,12 @@ def test_given_python_root_helpers_when_discovering_then_modules_import_under_pa def orders(ctx): return STATUS """, + "python/nodes/orders/__init__.py": "from .asset import orders\n", }, second_files={ - "python/_values.py": "STATUS = 'second'\n", - "python/orders.py": """ -from python._values import STATUS + "python/nodes/_values.py": "STATUS = 'second'\n", + "python/nodes/orders/asset.py": """ +from python.nodes._values import STATUS from sqlbuild.assets import asset @@ -457,6 +490,7 @@ def orders(ctx): def orders(ctx): return STATUS """, + "python/nodes/orders/__init__.py": "from .asset import orders\n", }, expected_first_result="first", expected_second_result="second", @@ -487,10 +521,10 @@ def test_given_two_projects_when_discovering_sequentially_then_python_modules_ar PythonRootHelperIdentityTestCase( description="editing a relative-import helper changes the dependent node identity", files=_HELPER_PACKAGE_FILES, - edited_path="python/helpers/clean.py", + edited_path="python/nodes/helpers/clean.py", original_text="value.strip().lower()", edited_text="value.strip().upper()", - expected_dependency_path="python/helpers/clean.py", + expected_dependency_path="python/nodes/helpers/clean.py", ), ], ids=lambda case: case.description, @@ -541,18 +575,18 @@ def test_given_python_root_helper_edit_when_rediscovering_then_node_identity_cha description="helper imported through the project package stays a dependency", unrelated_files={"site/python/__init__.py": "", "site/python/orders.py": "X = 1\n"}, project_files=_HELPER_PACKAGE_FILES, - expected_dependency_path="python/helpers/clean.py", + expected_dependency_path="python/nodes/helpers/clean.py", ), RestoredPythonPackageIdentityTestCase( description="helper called from a helper class method stays a dependency", unrelated_files={"site/python/__init__.py": "", "site/python/orders.py": "X = 1\n"}, project_files={ - "python/helpers/__init__.py": "", - "python/helpers/text.py": """ + "python/nodes/helpers/__init__.py": "", + "python/nodes/helpers/text.py": """ def strip_status(value): return value.strip().lower() """, - "python/helpers/cleaner.py": """ + "python/nodes/helpers/cleaner.py": """ from .text import strip_status @@ -560,28 +594,29 @@ class Cleaner: def run(self, value): return strip_status(value) """, - "python/orders.py": """ -import python.helpers.cleaner + "python/nodes/orders/asset.py": """ +import python.nodes.helpers.cleaner from sqlbuild.assets import asset @asset def orders(ctx): - return python.helpers.cleaner.Cleaner().run(" Shipped ") + return python.nodes.helpers.cleaner.Cleaner().run(" Shipped ") """, + "python/nodes/orders/__init__.py": "from .asset import orders\n", }, - expected_dependency_path="python/helpers/text.py", + expected_dependency_path="python/nodes/helpers/text.py", ), RestoredPythonPackageIdentityTestCase( description="a class attribute whose attribute lookup loops does not stop identity", unrelated_files={"site/python/__init__.py": "", "site/python/orders.py": "X = 1\n"}, project_files={ - "python/helpers/__init__.py": "", - "python/helpers/text.py": """ + "python/nodes/helpers/__init__.py": "", + "python/nodes/helpers/text.py": """ def strip_status(value): return value.strip().lower() """, - "python/helpers/cleaner.py": """ + "python/nodes/helpers/cleaner.py": """ from .text import strip_status @@ -596,17 +631,18 @@ class Cleaner: def run(self, value): return strip_status(value) """, - "python/orders.py": """ -import python.helpers.cleaner + "python/nodes/orders/asset.py": """ +import python.nodes.helpers.cleaner from sqlbuild.assets import asset @asset def orders(ctx): - return python.helpers.cleaner.Cleaner().run(" Shipped ") + return python.nodes.helpers.cleaner.Cleaner().run(" Shipped ") """, + "python/nodes/orders/__init__.py": "from .asset import orders\n", }, - expected_dependency_path="python/helpers/text.py", + expected_dependency_path="python/nodes/helpers/text.py", ), ], ids=lambda case: case.description, @@ -621,10 +657,12 @@ def test_given_unrelated_python_package_restored_when_building_identity_then_hel write_repo_files(tmp_path, test_case.unrelated_files) write_repo_files(project_dir, test_case.project_files) monkeypatch.delitem(sys.modules, "python", raising=False) - monkeypatch.delitem(sys.modules, "python.orders", raising=False) + monkeypatch.delitem(sys.modules, "python.nodes.orders", raising=False) monkeypatch.syspath_prepend(str(tmp_path / "site")) monkeypatch.setitem(sys.modules, "python", importlib.import_module("python")) - monkeypatch.setitem(sys.modules, "python.orders", importlib.import_module("python.orders")) + monkeypatch.setitem( + sys.modules, "python.nodes.orders", importlib.import_module("python.nodes.orders") + ) task: DiscoveredAssetFunction = discover_python_node_functions(project_dir=project_dir).assets[ 0 diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_scoped_declarations.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_scoped_declarations.py index eecb039e0c..5a46f00d63 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_scoped_declarations.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_filesystem_scoped_declarations.py @@ -50,11 +50,13 @@ class _DiscoveredFile(Protocol): @pytest.mark.parametrize( "test_case", ( - DiscoverScopedDeclarationTestCase("models", "models", "models"), + DiscoverScopedDeclarationTestCase("models", "sql/models", "sql/models"), DiscoverScopedDeclarationTestCase("unit_tests", "tests/unit", "tests/unit"), DiscoverScopedDeclarationTestCase("scenarios", "tests/scenarios", "tests/scenarios"), - DiscoverScopedDeclarationTestCase("sql_functions", "functions/sql", "functions/sql"), - DiscoverScopedDeclarationTestCase("sources", "sources", "sources"), + DiscoverScopedDeclarationTestCase( + "sql_functions", "sql/functions/sql", "sql/functions/sql" + ), + DiscoverScopedDeclarationTestCase("sources", "sql/sources", "sql/sources"), ), ids=lambda case: case.description, ) @@ -105,22 +107,22 @@ def test_given_declaration_below_authored_root_when_discovering_then_records_bou "test_case", ( DiscoverGroupedDeclarationTestCase( - "public_macro", "macro", "macros", "inherited", "models/orders" + "public_macro", "macro", "macros", "inherited", "sql/models/orders" ), DiscoverGroupedDeclarationTestCase( - "private_macro", "macro", "_macros", "local", "models/orders" + "private_macro", "macro", "_macros", "local", "sql/models/orders" ), DiscoverGroupedDeclarationTestCase( - "public_enum", "enum", "enums", "inherited", "models/orders" + "public_enum", "enum", "enums", "inherited", "sql/models/orders" ), DiscoverGroupedDeclarationTestCase( - "private_enum", "enum", "_enums", "local", "models/orders" + "private_enum", "enum", "_enums", "local", "sql/models/orders" ), DiscoverGroupedDeclarationTestCase( - "public_constant", "constant", "constants", "inherited", "models/orders" + "public_constant", "constant", "constants", "inherited", "sql/models/orders" ), DiscoverGroupedDeclarationTestCase( - "private_constant", "constant", "_constants", "local", "models/orders" + "private_constant", "constant", "_constants", "local", "sql/models/orders" ), ), ids=lambda case: case.description, @@ -130,7 +132,7 @@ def test_given_grouped_declaration_when_discovering_then_owner_is_above_sqlbuild tmp_path: Path, ) -> None: suffix, contents = declaration_contents(kind=test_case.declaration_kind) - declaration_root: Path = Path("models/orders/_sqlbuild") / test_case.directory_name + declaration_root: Path = Path("sql/models/orders/_sqlbuild") / test_case.directory_name file_name: Path = declaration_kind_folder(kind=test_case.declaration_kind) / f"policy{suffix}" file_path: Path = tmp_path / declaration_root / file_name file_path.parent.mkdir(parents=True) @@ -150,9 +152,9 @@ def test_given_grouped_declaration_when_discovering_then_owner_is_above_sqlbuild @pytest.mark.parametrize( "test_case", ( - DiscoverGlobalDeclarationTestCase("macro", "macro", "macros", "global"), - DiscoverGlobalDeclarationTestCase("enum", "enum", "enums", "global"), - DiscoverGlobalDeclarationTestCase("constant", "constant", "constants", "global"), + DiscoverGlobalDeclarationTestCase("macro", "macro", "sql/macros", "global"), + DiscoverGlobalDeclarationTestCase("enum", "enum", "sql/enums", "global"), + DiscoverGlobalDeclarationTestCase("constant", "constant", "sql/constants", "global"), ), ids=lambda case: case.description, ) @@ -191,27 +193,27 @@ def test_given_top_level_public_declarations_when_discovering_then_scope_remains ), InvalidScopedDeclarationRootTestCase( "nested_scoped_roots", - "models/macros/organization/_constants/value.sql", + "sql/models/macros/organization/_constants/value.sql", "nested inside another declaration tree", ), InvalidScopedDeclarationRootTestCase( "scoped_root_below_global_tree", - "macros/organization/_macros/python/value.py", + "sql/macros/organization/_macros/python/value.py", "nested inside another declaration tree", ), InvalidScopedDeclarationRootTestCase( "global_root_below_global_tree", - "macros/organization/constants/value.sql", + "sql/macros/organization/constants/value.sql", "nested inside another declaration tree", ), InvalidScopedDeclarationRootTestCase( "global_root_below_scoped_tree", - "models/macros/organization/enums/value.sql", + "sql/models/macros/organization/enums/value.sql", "nested inside another declaration tree", ), InvalidScopedDeclarationRootTestCase( "grouped_root_with_intermediate_folder", - "models/orders/_sqlbuild/organization/macros/python/value.py", + "sql/models/orders/_sqlbuild/organization/macros/python/value.py", "contains unsupported entries", ), InvalidScopedDeclarationRootTestCase( @@ -221,12 +223,12 @@ def test_given_top_level_public_declarations_when_discovering_then_scope_remains ), InvalidScopedDeclarationRootTestCase( "authored_root_grouped_root", - "models/_sqlbuild/macros/python/value.py", + "sql/models/_sqlbuild/macros/python/value.py", "must be below a concrete owner directory", ), InvalidScopedDeclarationRootTestCase( "grouped_root_with_unsupported_entry", - "models/orders/_sqlbuild/notes.py", + "sql/models/orders/_sqlbuild/notes.py", "contains unsupported entries", ), ), @@ -250,8 +252,8 @@ def test_given_invalid_declaration_root_when_discovering_then_raises( OrdinaryFolderTestCase( description="old local spelling is ordinary", root_relative_path="_local_constants/value.sql", - model_relative_path="models/_local_constants/orders.sql", - expected_model_relative_paths=("models/_local_constants/orders.sql",), + model_relative_path="sql/models/_local_constants/orders.sql", + expected_model_relative_paths=("sql/models/_local_constants/orders.sql",), ), ), ids=lambda case: case.description, @@ -263,7 +265,7 @@ def test_given_old_local_spelling_when_discovering_then_directory_has_no_special root_file: Path = tmp_path / test_case.root_relative_path model_file: Path = tmp_path / test_case.model_relative_path (tmp_path / "sqlbuild_project.toml").write_text( - 'name = "demo"\nadapter = "duckdb"\n', encoding="utf-8" + 'name = "demo"\nadapter = "duckdb"\nextra_paths = ["_local_constants"]\n', encoding="utf-8" ) root_file.parent.mkdir(parents=True) model_file.parent.mkdir(parents=True) @@ -295,9 +297,11 @@ def test_given_invalid_scoped_root_when_discovering_project_inputs_then_strict_d tmp_path: Path, ) -> None: config_path: Path = tmp_path / "sqlbuild_project.toml" - config_path.write_text('name = "demo"\nadapter = "duckdb"\n', encoding="utf-8") + config_path.write_text( + 'name = "demo"\nadapter = "duckdb"\nextra_paths = ["_enums"]\n', encoding="utf-8" + ) file_path: Path = tmp_path / test_case.relative_path - file_path.parent.mkdir() + file_path.parent.mkdir(parents=True) file_path.write_text(test_case.contents, encoding="utf-8") with pytest.raises(DeclarationParseError, match=test_case.expected_error_fragment): @@ -309,14 +313,14 @@ def test_given_invalid_scoped_root_when_discovering_project_inputs_then_strict_d ( OrdinaryDiscoveryExclusionTestCase( "model", - "models/domain/_constants/value.sql", + "sql/models/domain/_constants/value.sql", "CONSTANT (name scoped_value, value 1);\n", "model", (), ), OrdinaryDiscoveryExclusionTestCase( "grouped_model", - "models/domain/_sqlbuild/constants/value.sql", + "sql/models/domain/_sqlbuild/constants/value.sql", "CONSTANT (name scoped_value, value 1);\n", "model", (), @@ -337,42 +341,42 @@ def test_given_invalid_scoped_root_when_discovering_project_inputs_then_strict_d ), OrdinaryDiscoveryExclusionTestCase( "hook", - "models/domain/_sqlbuild/_constants/value.sql", + "sql/models/domain/_sqlbuild/_constants/value.sql", "CONSTANT (name scoped_value, value 1);\n", "hook", (), ), OrdinaryDiscoveryExclusionTestCase( "function", - "functions/sql/domain/_constants/value.sql", + "sql/functions/sql/domain/_constants/value.sql", "CONSTANT (name scoped_value, value 1);\n", "function", (), ), OrdinaryDiscoveryExclusionTestCase( "audit", - "models/domain/_sqlbuild/_constants/value.sql", + "sql/models/domain/_sqlbuild/_constants/value.sql", "CONSTANT (name scoped_value, value 1);\n", "audit", (), ), OrdinaryDiscoveryExclusionTestCase( "source", - "sources/domain/_constants/value.sql", + "sql/sources/domain/_constants/value.sql", "CONSTANT (name scoped_value, value 1);\n", "source", (), ), OrdinaryDiscoveryExclusionTestCase( "python_function", - "functions/sql/domain/_macros/python/value.py", + "sql/functions/sql/domain/_macros/python/value.py", "raise RuntimeError('must not import')\n", "python_function", (), ), OrdinaryDiscoveryExclusionTestCase( "python_hook", - "models/domain/_sqlbuild/_macros/python/value.py", + "sql/models/domain/_sqlbuild/_macros/python/value.py", "raise RuntimeError('must not import')\n", "python_hook", (), @@ -427,8 +431,8 @@ def test_given_file_in_declaration_role_when_discovering_resources_then_returns_ ( DiscoveryPathInventoryTestCase( "similarly_prefixed_directory", - ("models/_constants_archive/orders.sql",), - ("models/_constants_archive/orders.sql",), + ("sql/models/_constants_archive/orders.sql",), + ("sql/models/_constants_archive/orders.sql",), ), ), ids=lambda case: case.description, @@ -454,15 +458,15 @@ def test_given_similarly_prefixed_directory_when_discovering_then_treats_it_as_o DiscoveryPathInventoryTestCase( "unsorted_scoped_macros", ( - "models/z/_macros/python/z.py", - "models/a/_macros/python/z.py", - "models/a/_macros/python/a.py", - "models/a/_macros/python/__init__.py", + "sql/models/z/_macros/python/z.py", + "sql/models/a/_macros/python/z.py", + "sql/models/a/_macros/python/a.py", + "sql/models/a/_macros/python/__init__.py", ), ( - "models/a/_macros/python/a.py", - "models/a/_macros/python/z.py", - "models/z/_macros/python/z.py", + "sql/models/a/_macros/python/a.py", + "sql/models/a/_macros/python/z.py", + "sql/models/z/_macros/python/z.py", ), ), ), diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_function_header_keys.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_function_header_keys.py index c2f96bd1c5..c996081c34 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_function_header_keys.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_function_header_keys.py @@ -53,7 +53,7 @@ def test_given_supported_function_header_keys_when_parsing_then_accepts_header( DiscoveredSqlFunctionFile, discover_declaration_file( project_dir=tmp_path, - relative_path=f"functions/sql/{test_case.file_name}", + relative_path=f"sql/functions/sql/{test_case.file_name}", contents=test_case.contents, ), ).header_values @@ -91,11 +91,11 @@ def test_given_supported_function_header_keys_when_parsing_then_accepts_header( def test_given_unknown_sql_function_header_key_when_parsing_then_rejects_key_with_location( test_case: FunctionHeaderKeysTestCase, tmp_path: Path ) -> None: - file_path: Path = tmp_path / "functions" / "sql" / test_case.file_name + file_path: Path = tmp_path / "sql" / "functions" / "sql" / test_case.file_name with pytest.raises(ModelSqlParseError) as raised: discover_declaration_file( project_dir=tmp_path, - relative_path=f"functions/sql/{test_case.file_name}", + relative_path=f"sql/functions/sql/{test_case.file_name}", contents=test_case.contents, ) @@ -126,7 +126,7 @@ def test_given_unknown_sql_function_header_key_when_parsing_then_rejects_key_wit def test_given_unknown_python_udf_key_when_parsing_then_rejects_key_with_location( test_case: FunctionHeaderKeysTestCase, tmp_path: Path ) -> None: - file_path: Path = tmp_path / "functions" / "python" / test_case.file_name + file_path: Path = tmp_path / "sql" / "functions" / "python" / test_case.file_name with pytest.raises(ModelSqlParseError) as raised: discover_python_function_file( project_dir=tmp_path, file_name=test_case.file_name, contents=test_case.contents diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_resource_identities.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_resource_identities.py index 45bc37a438..7c0e16ce92 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_resource_identities.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_resource_identities.py @@ -17,7 +17,7 @@ InvalidResourceIdentityTestCase, ) -_RESOURCE_PATH: Path = Path("models/example.sql") +_RESOURCE_PATH: Path = Path("sql/models/example.sql") @pytest.mark.parametrize( @@ -120,13 +120,13 @@ def test_given_noncanonical_name_when_validating_resource_identity_then_coded_er [ DiscoveredResourceIdentityErrorTestCase( description="model filename", - project_files={"models/DailyOrders.sql": "MODEL ();\n\nSELECT 1\n"}, + project_files={"sql/models/DailyOrders.sql": "MODEL ();\n\nSELECT 1\n"}, expected_error_fragment="Invalid model identity 'DailyOrders'", ), DiscoveredResourceIdentityErrorTestCase( description="source declaration", project_files={ - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n" " - name: raw-Orders\n" " database: analytics\n" @@ -138,7 +138,9 @@ def test_given_noncanonical_name_when_validating_resource_identity_then_coded_er ), DiscoveredResourceIdentityErrorTestCase( description="SQL function filename", - project_files={"functions/sql/CalculateTax.sql": "FUNCTION (returns INTEGER);\n\n1\n"}, + project_files={ + "sql/functions/sql/CalculateTax.sql": "FUNCTION (returns INTEGER);\n\n1\n" + }, expected_error_fragment="Invalid function identity 'CalculateTax'", ), DiscoveredResourceIdentityErrorTestCase( @@ -148,13 +150,15 @@ def test_given_noncanonical_name_when_validating_resource_identity_then_coded_er ), DiscoveredResourceIdentityErrorTestCase( description="standalone audit name", - project_files={"audits/singular/orders.sql": "AUDIT (name OrderRule);\n\nSELECT 1\n"}, + project_files={ + "sql/audits/singular/orders.sql": "AUDIT (name OrderRule);\n\nSELECT 1\n" + }, expected_error_fragment="Invalid audit identity 'OrderRule'", ), DiscoveredResourceIdentityErrorTestCase( description="generic audit filename", project_files={ - "audits/generic/OrderRule.sql": ( + "sql/audits/generic/OrderRule.sql": ( "AUDIT (name valid_block_name);\n\nSELECT * FROM @relation\n" ) }, @@ -163,22 +167,22 @@ def test_given_noncanonical_name_when_validating_resource_identity_then_coded_er DiscoveredResourceIdentityErrorTestCase( description="generic audit explicit instance name", project_files={ - "audits/generic/order_rule.sql": ( + "sql/audits/generic/order_rule.sql": ( "AUDIT (name OrderRule);\n\nSELECT * FROM @relation\n" ), - "models/orders.sql": "MODEL (audits [order_rule]);\n\nSELECT 1\n", + "sql/models/orders.sql": "MODEL (audits [order_rule]);\n\nSELECT 1\n", }, expected_error_fragment="Invalid generic audit instance identity 'OrderRule'", ), DiscoveredResourceIdentityErrorTestCase( description="public declaration with private spelling", - project_files={"constants/orders.sql": "CONSTANT (name _tax_rate, value 20);\n"}, + project_files={"sql/constants/orders.sql": "CONSTANT (name _tax_rate, value 20);\n"}, expected_error_fragment="Invalid public constant identity '_tax_rate'", ), DiscoveredResourceIdentityErrorTestCase( description="private model declaration without private spelling", project_files={ - "models/orders.sql": ( + "sql/models/orders.sql": ( 'MODEL (constants (tax_rate 20));\n\nSELECT @const("tax_rate")\n' ) }, @@ -187,14 +191,14 @@ def test_given_noncanonical_name_when_validating_resource_identity_then_coded_er DiscoveredResourceIdentityErrorTestCase( description="SQL hook filename", project_files={ - "hooks/sql/GrantAccess.sql": "HOOK ();\n\nGRANT SELECT ON orders TO analyst\n" + "sql/hooks/sql/GrantAccess.sql": "HOOK ();\n\nGRANT SELECT ON orders TO analyst\n" }, expected_error_fragment="Invalid SQL hook identity 'GrantAccess'", ), DiscoveredResourceIdentityErrorTestCase( description="Python asset name", project_files={ - "python/tasks/orders.py": ( + "python/nodes/tasks/orders/asset.py": ( "from sqlbuild.assets import asset\n\n" "@asset\n" "def DailyTask(ctx):\n" diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_audits.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_audits.py index f99e1569f6..a0141d52a0 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_audits.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_audits.py @@ -101,7 +101,7 @@ def test_given_sql_audit_file_variants_when_parsing_then_it_returns_expected_raw DiscoveredAuditFile, discover_declaration_file( project_dir=tmp_path, - relative_path="audits/generic/orders.sql", + relative_path="sql/audits/generic/orders.sql", contents=test_case.contents, ), ).blocks @@ -231,7 +231,7 @@ def test_given_invalid_sql_audit_file_contents_when_parsing_then_it_raises_clear with pytest.raises(SqlAuditParseError, match=test_case.expected_error_fragment): discover_declaration_file( project_dir=tmp_path, - relative_path="audits/generic/orders.sql", + relative_path="sql/audits/generic/orders.sql", contents=test_case.contents, ) @@ -272,7 +272,7 @@ def test_given_measurement_audit_with_evidence_when_parsing_then_contract_and_qu DiscoveredAuditFile, discover_declaration_file( project_dir=tmp_path, - relative_path="audits/generic/rate.sql", + relative_path="sql/audits/generic/rate.sql", contents=test_case.contents, ), ).blocks @@ -325,6 +325,6 @@ def test_given_invalid_evaluation_grammar_when_parsing_then_clear_error_is_raise with pytest.raises(SqlAuditParseError, match=test_case.expected_error_fragment): discover_declaration_file( project_dir=tmp_path, - relative_path="audits/generic/rate.sql", + relative_path="sql/audits/generic/rate.sql", contents=test_case.contents, ) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_declarations.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_declarations.py index a4d077b83a..b4b651a5cf 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_declarations.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_declarations.py @@ -75,7 +75,7 @@ def test_given_enum_declarations_when_parsing_then_returns_typed_members( declarations: tuple[EnumDeclaration, ...] = cast( DiscoveredEnumFile, discover_declaration_file( - project_dir=tmp_path, relative_path="enums/domain.sql", contents=test_case.contents + project_dir=tmp_path, relative_path="sql/enums/domain.sql", contents=test_case.contents ), ).declarations @@ -114,7 +114,7 @@ def test_given_constant_declarations_when_parsing_then_returns_typed_values( DiscoveredConstantFile, discover_declaration_file( project_dir=tmp_path, - relative_path="constants/thresholds.sql", + relative_path="sql/constants/thresholds.sql", contents=test_case.contents, ), ).declarations @@ -159,7 +159,9 @@ def test_given_typed_public_constants_when_parsing_then_returns_normalized_value declarations: tuple[ConstantDeclaration, ...] = cast( DiscoveredConstantFile, discover_declaration_file( - project_dir=tmp_path, relative_path="constants/domain.sql", contents=test_case.contents + project_dir=tmp_path, + relative_path="sql/constants/domain.sql", + contents=test_case.contents, ), ).declarations @@ -198,7 +200,7 @@ def test_given_local_shorthand_and_wrapper_constants_when_parsing_then_honors_op declarations: tuple[ConstantDeclaration, ...] = cast( tuple[ConstantDeclaration, ...], _native.model_header_declarations( - (None, test_case.raw_value), "orders", Path("models/orders.sql") + (None, test_case.raw_value), "orders", Path("sql/models/orders.sql") )[1], ) @@ -256,7 +258,9 @@ def test_given_invalid_typed_constant_when_parsing_then_raises_contextual_error( ) -> None: with pytest.raises(DeclarationParseError, match=test_case.expected_error_fragment): discover_declaration_file( - project_dir=tmp_path, relative_path="constants/domain.sql", contents=test_case.contents + project_dir=tmp_path, + relative_path="sql/constants/domain.sql", + contents=test_case.contents, ) @@ -307,7 +311,7 @@ def test_given_invalid_enum_declaration_when_parsing_then_raises_declaration_err ) -> None: with pytest.raises(DeclarationParseError, match=test_case.expected_error_fragment): discover_declaration_file( - project_dir=tmp_path, relative_path="enums/domain.sql", contents=test_case.contents + project_dir=tmp_path, relative_path="sql/enums/domain.sql", contents=test_case.contents ) @@ -333,7 +337,7 @@ def test_given_noncanonical_declaration_identity_when_parsing_then_d016_suggests match=test_case.expected_error_fragment, ) as error_info: discover_declaration_file( - project_dir=tmp_path, relative_path="enums/domain.sql", contents=test_case.contents + project_dir=tmp_path, relative_path="sql/enums/domain.sql", contents=test_case.contents ) assert error_info.value.code == "D016" @@ -377,7 +381,9 @@ def test_given_model_schema_declarations_when_parsing_then_returns_typed_columns declarations: tuple[ModelSchemaDeclaration, ...] = cast( DiscoveredModelSchemaFile, discover_declaration_file( - project_dir=tmp_path, relative_path="schemas/orders.sql", contents=test_case.contents + project_dir=tmp_path, + relative_path="sql/schemas/orders.sql", + contents=test_case.contents, ), ).declarations @@ -390,7 +396,7 @@ def test_given_model_schema_declarations_when_parsing_then_returns_typed_columns ) assert declarations[0].columns[0].nullable is False assert declarations[0].columns[0].location is not None - assert declarations[0].columns[0].location.path == Path("schemas/orders.sql") + assert declarations[0].columns[0].location.path == Path("sql/schemas/orders.sql") assert declarations[0].columns[0].location.line == test_case.expected_base_column_line assert declarations[1].columns[0].location is not None assert declarations[1].columns[0].location.line == test_case.expected_child_column_line @@ -417,7 +423,7 @@ def test_given_empty_model_schema_when_parsing_then_raises_declaration_error( ) -> None: with pytest.raises(DeclarationParseError, match=test_case.expected_error_fragment): discover_declaration_file( - project_dir=tmp_path, relative_path="schemas/empty.sql", contents=test_case.contents + project_dir=tmp_path, relative_path="sql/schemas/empty.sql", contents=test_case.contents ) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_hooks.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_hooks.py index 13a0ef59c1..baa3bb7638 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_hooks.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_hooks.py @@ -200,7 +200,7 @@ def test_given_hook_header_and_sql_when_parsing_then_returns_named_resource( DiscoveredSqlHookFile, discover_declaration_file( project_dir=tmp_path, - relative_path="hooks/sql/grant_access.sql", + relative_path="sql/hooks/sql/grant_access.sql", contents=test_case.contents, ), ) @@ -208,7 +208,7 @@ def test_given_hook_header_and_sql_when_parsing_then_returns_named_resource( assert hook.name == test_case.expected_name assert hook.description == test_case.expected_description assert hook.sql_body == test_case.expected_sql_body - assert hook.relative_path == Path("hooks/sql/grant_access.sql") + assert hook.relative_path == Path("sql/hooks/sql/grant_access.sql") @pytest.mark.parametrize( @@ -217,12 +217,12 @@ def test_given_hook_header_and_sql_when_parsing_then_returns_named_resource( DiscoverSqlHooksTestCase( description="discovers nested public SQL hooks only", repo_files={ - "hooks/sql/admin/grant_access.sql": "HOOK ();\n\nSELECT 1\n", - "hooks/sql/_private.sql": "not a hook\n", - "hooks/python/not_sql.sql": "not a hook\n", + "sql/hooks/sql/admin/grant_access.sql": "HOOK ();\n\nSELECT 1\n", + "sql/hooks/sql/_private.sql": "not a hook\n", + "sql/hooks/python/not_sql.sql": "not a hook\n", }, expected_names=("grant_access",), - expected_paths=("hooks/sql/admin/grant_access.sql",), + expected_paths=("sql/hooks/sql/admin/grant_access.sql",), ) ], ids=lambda case: case.description, @@ -287,7 +287,9 @@ def test_given_invalid_sql_hook_when_parsing_then_raises( ) -> None: with pytest.raises(SqlHookParseError, match=test_case.expected_error_fragment): discover_declaration_file( - project_dir=tmp_path, relative_path="hooks/sql/invalid.sql", contents=test_case.contents + project_dir=tmp_path, + relative_path="sql/hooks/sql/invalid.sql", + contents=test_case.contents, ) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_models.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_models.py index 8078ba585d..9160e78c84 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_models.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_sql_models.py @@ -41,8 +41,8 @@ def test_given_unique_model_headers_when_discovering_then_header_values_and_loca tmp_path: Path, test_case: ExpectedCountTestCase, ) -> None: - models_dir: Path = tmp_path / "models" - models_dir.mkdir() + models_dir: Path = tmp_path / "sql" / "models" + models_dir.mkdir(parents=True) first_header = 'description "one", columns (café (type INTEGER))' second_header = 'description "two", columns (total (type DECIMAL(10,2)))' (models_dir / "first.sql").write_text( @@ -63,7 +63,7 @@ def test_given_unique_model_headers_when_discovering_then_header_values_and_loca }, ] assert discovered[0].header_column_locations["café"] == SourceLocation( - path=Path("models/first.sql"), line=1, column=36, end_line=1, end_column=40 + path=Path("sql/models/first.sql"), line=1, column=36, end_line=1, end_column=40 ) @@ -94,8 +94,8 @@ def test_given_multiple_invalid_model_headers_when_discovering_then_fault_order_ tmp_path: Path, test_case: ExpectedCountTestCase, ) -> None: - models_dir: Path = tmp_path / "models" - models_dir.mkdir() + models_dir: Path = tmp_path / "sql" / "models" + models_dir.mkdir(parents=True) (models_dir / "first.sql").write_text( 'MODEL (schema "unterminated); SELECT 1', encoding="utf-8" ) @@ -112,8 +112,8 @@ def test_given_multiple_invalid_model_headers_when_discovering_then_fault_order_ assert discovered == () assert len(faults) == test_case.expected_count assert [fault.path for fault in faults] == [ - Path("models/first.sql"), - Path("models/second.sql"), + Path("sql/models/first.sql"), + Path("sql/models/second.sql"), ] assert "unterminated double-quoted string at position 7" in faults[0].message assert "unterminated template value at position 7" in faults[1].message @@ -133,8 +133,8 @@ def test_given_deferred_output_locations_when_discovering_models_then_projection tmp_path: Path, test_case: DeferredModelOutputLocationTestCase, ) -> None: - models_dir: Path = tmp_path / "models" - models_dir.mkdir() + models_dir: Path = tmp_path / "sql" / "models" + models_dir.mkdir(parents=True) (models_dir / "orders.sql").write_text( "MODEL (materialized view);\n\nSELECT 1 AS order_id\n", encoding="utf-8", @@ -761,8 +761,8 @@ def test_given_invalid_sql_model_contents_when_parsing_then_it_raises_clear_erro "SELECT order_id FROM raw_orders\n" ), expected_locations={ - "order_id": (Path("models/orders.sql"), 4, 5, 4, 13), - "customer_id": (Path("models/orders.sql"), 5, 5, 5, 16), + "order_id": (Path("sql/models/orders.sql"), 4, 5, 4, 13), + "customer_id": (Path("sql/models/orders.sql"), 5, 5, 5, 16), }, ), ModelHeaderColumnLocationTestCase( @@ -779,7 +779,7 @@ def test_given_invalid_sql_model_contents_when_parsing_then_it_raises_clear_erro "SELECT status FROM raw_orders\n" ), expected_locations={ - "status": (Path("models/orders.sql"), 3, 5, 3, 11), + "status": (Path("sql/models/orders.sql"), 3, 5, 3, 11), }, ), ModelHeaderColumnLocationTestCase( @@ -789,7 +789,7 @@ def test_given_invalid_sql_model_contents_when_parsing_then_it_raises_clear_erro "columns (top (type INTEGER))); SELECT 1" ), expected_locations={ - "top": (Path("models/orders.sql"), 1, 59, 1, 62), + "top": (Path("sql/models/orders.sql"), 1, 59, 1, 62), }, ), ModelHeaderColumnLocationTestCase( @@ -805,7 +805,7 @@ def test_given_model_header_columns_when_locating_then_returns_expected_location ) -> None: locations: dict[str, SourceLocation] = model_header_column_locations( contents=test_case.contents, - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), ) assert { @@ -833,8 +833,8 @@ def test_given_model_header_columns_when_locating_then_returns_expected_location "FROM raw_orders o\n" ), expected_locations={ - "order_id": (Path("models/orders.sql"), 4, 3, 4, 13), - "amount_text": (Path("models/orders.sql"), 5, 3, 5, 43), + "order_id": (Path("sql/models/orders.sql"), 4, 3, 4, 13), + "amount_text": (Path("sql/models/orders.sql"), 5, 3, 5, 43), }, ), ModelOutputColumnLocationTestCase( @@ -847,8 +847,8 @@ def test_given_model_header_columns_when_locating_then_returns_expected_location "FROM raw_customers\n" ), expected_locations={ - "display_name": (Path("models/orders.sql"), 4, 3, 4, 61), - "customer_id": (Path("models/orders.sql"), 5, 3, 5, 14), + "display_name": (Path("sql/models/orders.sql"), 4, 3, 4, 61), + "customer_id": (Path("sql/models/orders.sql"), 5, 3, 5, 14), }, ), ModelOutputColumnLocationTestCase( @@ -864,15 +864,15 @@ def test_given_model_header_columns_when_locating_then_returns_expected_location "FROM prepared\n" ), expected_locations={ - "order_id": (Path("models/orders.sql"), 7, 3, 7, 11), - "total_cents": (Path("models/orders.sql"), 8, 3, 8, 30), + "order_id": (Path("sql/models/orders.sql"), 7, 3, 7, 11), + "total_cents": (Path("sql/models/orders.sql"), 8, 3, 8, 30), }, ), ModelOutputColumnLocationTestCase( description="locates quoted output aliases", contents=('MODEL ();\n\nSELECT\n amount_cents AS "amount cents"\nFROM raw_orders\n'), expected_locations={ - "amount cents": (Path("models/orders.sql"), 4, 3, 4, 33), + "amount cents": (Path("sql/models/orders.sql"), 4, 3, 4, 33), }, ), ModelOutputColumnLocationTestCase( @@ -884,7 +884,7 @@ def test_given_model_header_columns_when_locating_then_returns_expected_location "FROM raw_orders\n" ), expected_locations={ - "max_payment_cents": (Path("models/orders.sql"), 4, 3, 4, 68), + "max_payment_cents": (Path("sql/models/orders.sql"), 4, 3, 4, 68), }, ), ModelOutputColumnLocationTestCase( @@ -898,14 +898,14 @@ def test_given_model_header_columns_when_locating_then_returns_expected_location "MODEL ();\n\nSELECT\n CAST(amount AS VARCHAR) amount_text\nFROM raw_orders\n" ), expected_locations={ - "amount_text": (Path("models/orders.sql"), 4, 3, 4, 38), + "amount_text": (Path("sql/models/orders.sql"), 4, 3, 4, 38), }, ), ModelOutputColumnLocationTestCase( description="locates select without from using sql_analysis projection identity", contents="MODEL ();\n\nSELECT 1 AS one\n", expected_locations={ - "one": (Path("models/orders.sql"), 3, 8, 3, 16), + "one": (Path("sql/models/orders.sql"), 3, 8, 3, 16), }, ), ModelOutputColumnLocationTestCase( @@ -929,7 +929,7 @@ def test_given_model_select_outputs_when_locating_then_returns_expected_location ) -> None: locations: dict[str, SourceLocation] = model_output_column_locations( contents=test_case.contents, - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), extract_implicit_alias_columns=test_case.extract_implicit_alias_columns, ) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_target_warehouses.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_target_warehouses.py index 9b62cb5992..123b2fcbd0 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_target_warehouses.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_target_warehouses.py @@ -200,8 +200,8 @@ def test_given_invalid_target_warehouses_when_discovering_then_config_error_expl ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(test_case.project_contents, encoding="utf-8") (tmp_path / "sqlbuild_local.toml").write_text(test_case.local_contents, encoding="utf-8") - (tmp_path / "adapters").mkdir() - (tmp_path / "adapters" / "custom.py").write_text( + (tmp_path / "python" / "adapters").mkdir(parents=True) + (tmp_path / "python" / "adapters" / "custom.py").write_text( test_case.adapter_file_contents, encoding="utf-8" ) @@ -238,8 +238,8 @@ def test_given_adapter_layers_when_discovering_target_warehouses_then_config_is_ ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(test_case.project_contents, encoding="utf-8") (tmp_path / "sqlbuild_local.toml").write_text(test_case.local_contents, encoding="utf-8") - (tmp_path / "adapters").mkdir() - (tmp_path / "adapters" / "custom.py").write_text( + (tmp_path / "python" / "adapters").mkdir(parents=True) + (tmp_path / "python" / "adapters" / "custom.py").write_text( test_case.adapter_file_contents, encoding="utf-8" ) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_project.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_project.py index a6052229f4..f7d9ef1371 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_project.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_project.py @@ -106,7 +106,7 @@ def test_given_invalid_query_artifact_ttl_when_loading_project_then_error_is_act LoadProjectConfigErrorTestCase( description="audit lifecycle sink filter", project_file_contents=( - 'name = "demo"\nadapter = "duckdb"\n[sinks.lifecycle]\nevent_kinds = ["audit"]\n' + 'name = "demo"\nadapter = "duckdb"\n[event_sinks.lifecycle]\nevent_kinds = ["audit"]\n' ), expected_error_fragment="audit", ) @@ -122,7 +122,7 @@ def test_given_audit_lifecycle_sink_filter_when_loading_toml_then_kind_is_accept config: ProjectConfig = load_project_config(project_dir=tmp_path) - assert config.sinks.lifecycle.defaults.event_kinds == frozenset( + assert config.event_sinks.lifecycle.defaults.event_kinds == frozenset( {test_case.expected_error_fragment} ) assert test_case.expected_error_fragment == LifecycleEventKind.AUDIT.value @@ -1585,7 +1585,7 @@ def test_given_local_target_execution_limits_when_loading_then_limits_are_typed( name = "demo" adapter = "duckdb" -[path_defaults."models/staging"] +[path_defaults."sql/models/staging"] tags = "staging" """.strip(), expected_error_fragment="path_defaults.*tags must be a list", @@ -1596,7 +1596,7 @@ def test_given_local_target_execution_limits_when_loading_then_limits_are_typed( name = "demo" adapter = "duckdb" -[path_defaults."models/staging"] +[path_defaults."sql/models/staging"] tags = [123] """.strip(), expected_error_fragment="path_defaults.*tags.*must be strings", @@ -1629,10 +1629,10 @@ def test_given_local_target_execution_limits_when_loading_then_limits_are_typed( name = "demo" adapter = "duckdb" -[path_defaults."models/staging"] +[path_defaults."sql/models/staging"] schema = "staging" """.strip(), - expected_error_fragment="uses redundant 'models/' prefix", + expected_error_fragment="uses a redundant 'sql/models/' prefix", ), LoadProjectConfigErrorTestCase( description="raises when path defaults uses partial segment glob", @@ -2165,7 +2165,7 @@ def test_given_connection_nested_past_the_limit_when_loading_project_then_error_ ), OversizedDurationTestCase( description="lifecycle shutdown timeout", - section='[sinks.lifecycle]\nshutdown_timeout = "{digits}s"\n', + section='[event_sinks.lifecycle]\nshutdown_timeout = "{digits}s"\n', expected_error_fragment="value has 4301 digits", ), ], diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_schema.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_schema.py index 1da48302b4..6ae665472c 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_schema.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_schema.py @@ -84,7 +84,7 @@ def test_given_schema_yaml_variants_when_parsing_then_it_returns_expected_raw_me model_entries: tuple[SchemaModelEntry, ...] seed_entries: tuple[SchemaSeedEntry, ...] model_entries, seed_entries = parse_schema_yml( - contents=test_case.contents, file_path=Path("seeds/lookups.yml") + contents=test_case.contents, file_path=Path("sql/seeds/lookups.yml") ) assert tuple(entry.name for entry in model_entries) == test_case.expected_model_names @@ -179,7 +179,7 @@ def test_given_seed_csv_settings_when_parsing_then_it_returns_normalized_setting test_case: ParseSeedCsvSettingsYamlTestCase, ) -> None: _, seed_entries = parse_schema_yml( - contents=test_case.contents, file_path=Path("seeds/lookups.yml") + contents=test_case.contents, file_path=Path("sql/seeds/lookups.yml") ) assert seed_entries[0].csv_settings == SeedCsvSettings( @@ -420,7 +420,7 @@ def test_given_invalid_schema_yaml_when_parsing_then_it_raises_clear_errors( test_case: ParseSchemaYamlErrorTestCase, ) -> None: with pytest.raises(ValueError, match=test_case.expected_error_fragment): - parse_schema_yml(contents=test_case.contents, file_path=Path("seeds/lookups.yml")) + parse_schema_yml(contents=test_case.contents, file_path=Path("sql/seeds/lookups.yml")) @pytest.mark.parametrize( @@ -451,7 +451,7 @@ def test_given_seed_audits_when_parsing_then_table_and_column_audits_are_kept( ) -> None: seed_entries: tuple[SchemaSeedEntry, ...] _models, seed_entries = parse_schema_yml( - contents=test_case.contents, file_path=Path("seeds/lookups.yml") + contents=test_case.contents, file_path=Path("sql/seeds/lookups.yml") ) table_audits: tuple[str, ...] = tuple(audit.definition_name for audit in seed_entries[0].audits) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_sources.py b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_sources.py index 1be9ee29a8..55146c8d57 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_sources.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/_helpers/test_yml_sources.py @@ -383,7 +383,7 @@ def test_given_sources_yaml_variants_when_parsing_then_it_returns_expected_raw_m test_case: ParseSourcesYamlTestCase, ) -> None: source_entries: tuple[SourceEntry, ...] = parse_sources_yml( - contents=test_case.contents, file_path=Path("sources/raw.yml") + contents=test_case.contents, file_path=Path("sql/sources/raw.yml") ) assert tuple(entry.name for entry in source_entries) == test_case.expected_source_names @@ -1288,4 +1288,4 @@ def test_given_invalid_sources_yaml_when_parsing_then_it_raises_clear_errors( test_case: ParseSourcesYamlErrorTestCase, ) -> None: with pytest.raises(ValueError, match=test_case.expected_error_fragment): - parse_sources_yml(contents=test_case.contents, file_path=Path("sources/raw.yml")) + parse_sources_yml(contents=test_case.contents, file_path=Path("sql/sources/raw.yml")) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/helpers.py b/tests/unit/src/sqlbuild/compiler/discovery/helpers.py index 8655b27d50..e07e6c48bc 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/helpers.py @@ -89,13 +89,13 @@ def write_lifecycle_event_sink_project(*, project_dir: Path, exporter_config: str) -> None: - (project_dir / "sinks").mkdir() + (project_dir / "python" / "event_sinks").mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "filters"\nadapter = "duckdb"\n' + exporter_config, encoding="utf-8", ) - (project_dir / "sinks" / "publish.py").write_text( - "from sqlbuild.sinks import lifecycle_event_sink\n" + (project_dir / "python" / "event_sinks" / "publish.py").write_text( + "from sqlbuild.event_sinks import lifecycle_event_sink\n" '@lifecycle_event_sink(event_kinds={"run", "statement"}, min_severity="info")\n' "def publish(event):\n del event\n", encoding="utf-8", @@ -180,8 +180,8 @@ def parse_schema_yml( RECALL_SINK_IMPORTS: str = ( "from sqlbuild.recall import RecallWriter\n" - "from sqlbuild.sinks import (\n" - " CommandOutputRecord, LifecycleEvent, command_output_sink, lifecycle_event_sink,\n" + "from sqlbuild.event_sinks import (\n" + " CommandOutputRecord, LifecycleEvent, command_output_event_sink, lifecycle_event_sink,\n" ")\n\n" ) diff --git a/tests/unit/src/sqlbuild/compiler/discovery/main/test_serialize_hook_entries.py b/tests/unit/src/sqlbuild/compiler/discovery/main/test_serialize_hook_entries.py index 4304bec241..20ef9764a3 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/main/test_serialize_hook_entries.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/main/test_serialize_hook_entries.py @@ -21,7 +21,7 @@ _NAMED_SQL_HOOK: SqlHookEntry = SqlHookEntry( statement="INSERT INTO order_audit SELECT 'orders'", name="record_order_access", - relative_path=Path("hooks/sql/record_order_access.sql"), + relative_path=Path("sql/hooks/sql/record_order_access.sql"), definition_sql="INSERT INTO order_audit SELECT {{ table_name }}", kwargs={"table_name": "'orders'"}, description="Record order table access", @@ -41,7 +41,7 @@ "type": "sql", "statement": "INSERT INTO order_audit SELECT 'orders'", "name": "record_order_access", - "relative_path": "hooks/sql/record_order_access.sql", + "relative_path": "sql/hooks/sql/record_order_access.sql", "definition_sql": "INSERT INTO order_audit SELECT {{ table_name }}", "kwargs": {"table_name": "'orders'"}, "description": "Record order table access", diff --git a/tests/unit/src/sqlbuild/compiler/discovery/test_main.py b/tests/unit/src/sqlbuild/compiler/discovery/test_main.py index 721760acc5..d1403ee774 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/test_main.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/test_main.py @@ -10,7 +10,7 @@ DiscoveredProjectInputs, DiscoveredSqlTestBlock, ProjectConfigError, - ProjectPythonPathError, + ProjectLayoutError, discover_project_inputs, ) from sqlbuild.observability import EventDispatcher, LifecycleEvent, dispatcher_scope @@ -26,6 +26,7 @@ DiscoveryRelevantCountTestCase, ProjectPythonPathAcceptanceTestCase, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -35,9 +36,9 @@ description="discovers raw project inputs across authored project surfaces", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL ();\n\nselect 1\n", - "models/staging/schema.yml": "models: []\n", - "sources/raw.yml": """ + "sql/models/staging/orders.sql": "MODEL ();\n\nselect 1\n", + "sql/models/staging/schema.yml": "models: []\n", + "sql/sources/raw.yml": """ sources: - name: raw_orders managed: true @@ -45,8 +46,8 @@ table: orders """.strip() + "\n", - "seeds/country_codes.csv": "country_code,country_name\nUS,United States\n", - "seeds/lookups.yml": """ + "sql/seeds/country_codes.csv": "country_code,country_name\nUS,United States\n", + "sql/seeds/lookups.yml": """ seeds: - name: country_codes columns: @@ -67,63 +68,63 @@ ) SELECT 1 """, - "audits/generic/not_null.sql": "AUDIT ();\nSELECT 1\n", - "macros/python/name_helpers.py": "def slug() -> str:\n return 'slug'\n", - "python/loaders/raw_orders.py": """ + "sql/audits/generic/not_null.sql": "AUDIT ();\nSELECT 1\n", + "sql/macros/python/name_helpers.py": "def slug() -> str:\n return 'slug'\n", + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader(name="raw_orders") def fetch_orders(ctx): return [] """, - "python/tasks/windows.py": """ + "python/nodes/tasks/windows/asset.py": """ from sqlbuild.assets import asset @asset(tags=("api",), group="ingestion") def fetch_window(ctx): return {"window": "today"} """, - "python/assets/exports.py": """ + "python/nodes/assets/exports/asset.py": """ from sqlbuild.assets import asset @asset(columns=[{"name": "customer_id", "type": "string"}]) def export_customers(ctx): return {"uri": "s3://exports/customers.parquet"} """, - "python/checks/exports.py": """ + "python/nodes/checks/exports/checks.py": """ from sqlbuild.checks import check -from python.assets.exports import export_customers +from python.nodes.assets.exports.asset import export_customers @check(depends_on=export_customers, severity="warn") def export_customers_exists(ctx): return True """, - "hooks/python/notifications.py": """ + "sql/hooks/python/notifications.py": """ from sqlbuild.hooks import hook @hook(name="notify_success") def notify_success(ctx): return None """, - "providers/slack.py": """ + "python/providers/slack.py": """ from sqlbuild.providers import Provider class SlackProvider(Provider): channel: str = "#alerts" """, "target/manifest.json": '{"metadata": {"dbt_schema_version": "v12"}}\n', - "adapter.py": "class ExampleAdapter:\n pass\n", + "python/adapter.py": "class ExampleAdapter:\n pass\n", "sqlbuild_local.toml": 'target = "dev"\n', }, - expected_model_paths=("models/staging/orders.sql",), + expected_model_paths=("sql/models/staging/orders.sql",), expected_model_header_values=({},), expected_model_query_sql=("select 1",), - expected_schema_paths=("models/staging/schema.yml", "seeds/lookups.yml"), + expected_schema_paths=("sql/models/staging/schema.yml", "sql/seeds/lookups.yml"), expected_schema_model_names=((), ()), expected_schema_seed_names=((), ("country_codes",)), - expected_source_paths=("sources/raw.yml",), + expected_source_paths=("sql/sources/raw.yml",), expected_source_entry_names=(("raw_orders",),), - expected_seed_paths=("seeds/country_codes.csv",), + expected_seed_paths=("sql/seeds/country_codes.csv",), expected_test_paths=("tests/unit/orders_test.sql",), expected_test_block_indexes=(1,), expected_test_block_names=(None,), @@ -136,18 +137,18 @@ class SlackProvider(Provider): expected_scenario_sql_bodies=( "WITH\n__expected__daily_revenue AS (\n SELECT 1 AS order_id\n)\nSELECT 1", ), - expected_audit_paths=("audits/generic/not_null.sql",), + expected_audit_paths=("sql/audits/generic/not_null.sql",), expected_audit_block_indexes=(1,), expected_audit_block_names=(None,), expected_audit_block_sql_bodies=("SELECT 1",), - expected_macro_paths=("macros/python/name_helpers.py",), + expected_macro_paths=("sql/macros/python/name_helpers.py",), expected_loader_names=("raw_orders",), - expected_adapter_path="adapter.py", + expected_adapter_path="python/adapter.py", expected_asset_names=("export_customers", "fetch_window"), expected_check_names=("export_customers_exists",), expected_hook_names=("notify_success",), expected_provider_names=("slack_provider",), - expected_provider_paths=("providers/slack.py",), + expected_provider_paths=("python/providers/slack.py",), expected_provider_class_names=("SlackProvider",), ) ], @@ -341,8 +342,8 @@ def test_given_valid_sql_and_failing_python_import_when_discovering_then_phases_ tmp_path, base_repo_files() | { - "models/orders.sql": "MODEL ();\n\nSELECT 1 AS order_id\n", - "python/tasks/broken.py": "import dependency_that_does_not_exist\n", + "sql/models/orders.sql": "MODEL ();\n\nSELECT 1 AS order_id\n", + "python/nodes/tasks/broken.py": "import dependency_that_does_not_exist\n", }, ) events: list[LifecycleEvent] = [] @@ -379,7 +380,7 @@ def test_given_ignored_siblings_when_discovering_then_count_uses_relevant_collec tmp_path, base_repo_files() | { - "models/orders.sql": "MODEL ();\n\nSELECT 1 AS order_id\n", + "sql/models/orders.sql": "MODEL ();\n\nSELECT 1 AS order_id\n", ".git/objects/unrelated.sql": "not sqlbuild input\n", ".venv/cache/generated.sql": "not sqlbuild input\n", }, @@ -404,8 +405,8 @@ def test_given_ignored_siblings_when_discovering_then_count_uses_relevant_collec description="generated managed source loader matches source", repo_files=base_repo_files() | { - "sources/raw.yml": "sources:\n - name: raw_orders\n managed: true\n", - "python/loaders/generated.py": """ + "sql/sources/raw.yml": "sources:\n - name: raw_orders\n managed: true\n", + "python/nodes/loaders/generated/loaders.py": """ from sqlbuild.factories import factory from sqlbuild.loaders import loader @@ -424,7 +425,7 @@ def load(ctx): description="generated asset dependencies validate", repo_files=base_repo_files() | { - "python/factories/generated.py": """ + "python/nodes/factories/generated/assets.py": """ from sqlbuild.assets import asset from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -442,6 +443,7 @@ def export(ctx): return [prepare, export] """, + "python/nodes/factories/generated/__init__.py": "from .assets import generated_nodes\n", }, expected_asset_names=("prepare_orders", "orders_export"), ), @@ -449,7 +451,7 @@ def export(ctx): description="single-kind factory validates in factories folder", repo_files=base_repo_files() | { - "python/factories/generated_tasks.py": """ + "python/nodes/factories/generated_tasks/assets.py": """ from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -469,7 +471,9 @@ def prepare(ctx): description="factory returning its own module-level node registers it once", repo_files=base_repo_files() | { - "python/factories/orders.py": """ + **node_module_files( + "python/nodes/factories/orders.py", + """ from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -483,6 +487,7 @@ def orders(ctx): def order_nodes(): return orders """, + ), }, expected_asset_names=("orders",), ), @@ -490,7 +495,7 @@ def order_nodes(): description="factory binding its generated node to a module global registers it once", repo_files=base_repo_files() | { - "python/factories/orders.py": """ + "python/nodes/factories/orders/assets.py": """ from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -505,6 +510,7 @@ def orders(ctx): return orders """, + "python/nodes/factories/orders/__init__.py": "from .assets import order_nodes\n", }, expected_asset_names=("orders",), ), @@ -512,8 +518,8 @@ def orders(ctx): description="factory returning an imported python module node registers it once", repo_files=base_repo_files() | { - "python/a_factories/orders.py": """ -from python.tasks.orders import prepare_orders + "python/nodes/a_factories/orders/assets.py": """ +from python.nodes.tasks.orders.asset import prepare_orders from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -525,7 +531,7 @@ def publish(ctx): return None return [prepare_orders, publish] """, - "python/tasks/orders.py": """ + "python/nodes/tasks/orders/asset.py": """ from sqlbuild.assets import asset @@ -540,9 +546,9 @@ def prepare_orders(ctx): description="factory can import ordinary private helper module", repo_files=base_repo_files() | { - "python/factories/orders/_helpers.py": "TASK_NAME = 'prepare_orders'\n", - "python/factories/orders/generated.py": """ -from python.factories.orders._helpers import TASK_NAME + "python/nodes/factories/orders/_helpers.py": "TASK_NAME = 'prepare_orders'\n", + "python/nodes/factories/orders/generated/assets.py": """ +from python.nodes.factories.orders._helpers import TASK_NAME from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -562,7 +568,7 @@ def prepare(ctx): description="generated check and asset may depend on a model and a seed", repo_files=base_repo_files() | { - "python/factories/generated.py": """ + "python/nodes/factories/generated/factory.py": """ from sqlbuild.checks import check from sqlbuild.factories import factory from sqlbuild.refs import model, seed @@ -581,6 +587,7 @@ def check_orders(ctx): return [export_countries, check_orders] """, + "python/nodes/factories/generated/__init__.py": "from .factory import generated_nodes\n", }, expected_asset_names=("export_countries",), expected_check_names=("check_orders",), @@ -610,10 +617,10 @@ def test_given_generated_factory_nodes_when_discovering_inputs_then_validates_ex ProjectPythonPathAcceptanceTestCase( description="undecorated helper modules under python root", repo_files={ - "python/_helpers.py": "REGION = 'emea'\n", - "python/orders/__init__.py": "", - "python/orders/utils.py": "def order_label(value):\n return str(value)\n", - "adapter.py": "ADAPTER = None\n", + "python/nodes/_helpers.py": "REGION = 'emea'\n", + "python/nodes/orders/__init__.py": "", + "python/nodes/orders/utils.py": "def order_label(value):\n return str(value)\n", + "python/adapter.py": "ADAPTER = None\n", }, expected_project_name="demo", ), @@ -638,65 +645,69 @@ def test_given_supported_project_python_when_discovering_inputs_then_paths_are_a DiscoverProjectInputsErrorTestCase( description="raises when Python lives in removed tasks root", repo_files=base_repo_files() | {"tasks/orders.py": "VALUE = 1\n"}, - expected_error_fragment="tasks/orders.py", + expected_error_fragment="'tasks/' is not part of a SQLBuild project", ), DiscoverProjectInputsErrorTestCase( description="raises when Python lives in removed assets root", repo_files=base_repo_files() | {"assets/orders.py": "VALUE = 1\n"}, - expected_error_fragment="assets/orders.py", + expected_error_fragment="'assets/' is not part of a SQLBuild project", ), DiscoverProjectInputsErrorTestCase( description="raises when Python lives in removed checks root", repo_files=base_repo_files() | {"checks/orders.py": "VALUE = 1\n"}, - expected_error_fragment="checks/orders.py", + expected_error_fragment="'checks/' is not part of a SQLBuild project", ), DiscoverProjectInputsErrorTestCase( description="raises when Python lives in removed loaders root", repo_files=base_repo_files() | {"loaders/orders.py": "VALUE = 1\n"}, - expected_error_fragment="loaders/orders.py", + expected_error_fragment="'loaders/' is not part of a SQLBuild project", ), DiscoverProjectInputsErrorTestCase( description="raises when Python lives in removed factories root", repo_files=base_repo_files() | {"factories/orders.py": "VALUE = 1\n"}, - expected_error_fragment="factories/orders.py", + expected_error_fragment="'factories/' is not part of a SQLBuild project", ), DiscoverProjectInputsErrorTestCase( description="raises when Python lives in removed libs root", repo_files=base_repo_files() | {"libs/cleaning.py": "VALUE = 1\n"}, - expected_error_fragment="libs/cleaning.py", + expected_error_fragment="'libs/' is not part of a SQLBuild project", ), DiscoverProjectInputsErrorTestCase( description="raises when Python lives in removed dagster root", repo_files=base_repo_files() | {"dagster/definitions.py": "VALUE = 1\n"}, - expected_error_fragment="dagster/definitions.py", + expected_error_fragment="'dagster/' is not part of a SQLBuild project", ), DiscoverProjectInputsErrorTestCase( description="raises when Python lives in removed rivers_pipeline root", repo_files=base_repo_files() | {"rivers_pipeline/definitions.py": "VALUE = 1\n"}, - expected_error_fragment="rivers_pipeline/definitions.py", + expected_error_fragment="'rivers_pipeline/' is not part of a SQLBuild project", ), DiscoverProjectInputsErrorTestCase( description="raises when Python lives in removed root definitions root", repo_files=base_repo_files() | {"definitions.py": "VALUE = 1\n"}, - expected_error_fragment="definitions.py", + expected_error_fragment="'definitions.py' is not part of a SQLBuild project", + ), + DiscoverProjectInputsErrorTestCase( + description="raises when Python lives in removed event_exporters root", + repo_files=base_repo_files() + | {"event_exporters/publish.py": "def publish(event):\n del event\n"}, + expected_error_fragment="'event_exporters/' is not part of a SQLBuild project", ), ), ids=lambda case: case.description, ) -def test_given_python_in_removed_root_when_discovering_inputs_then_d016_is_raised( +def test_given_python_in_removed_root_when_discovering_inputs_then_d018_is_raised( test_case: DiscoverProjectInputsErrorTestCase, tmp_path: Path, write_repo_files: Callable[[Path, dict[str, str]], None], ) -> None: write_repo_files(tmp_path, test_case.repo_files) - with pytest.raises(ProjectPythonPathError) as error_info: + with pytest.raises(ProjectLayoutError) as error_info: discover_project_inputs(project_dir=tmp_path) - assert error_info.value.code == "D016" - assert f"Unsupported project Python path(s): {test_case.expected_error_fragment}" in str( - error_info.value - ) + assert error_info.value.code == "D018" + assert test_case.expected_error_fragment in str(error_info.value) @pytest.mark.parametrize( @@ -777,7 +788,7 @@ def test_given_non_project_with_python_when_discovering_then_missing_config_erro description="generated duplicate names fail validation", repo_files=base_repo_files() | { - "python/tasks/generated.py": """ + "python/nodes/tasks/generated/assets.py": """ from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -793,6 +804,7 @@ def profile(ctx): def generated_tasks(): return [make_task(), make_task()] """, + "python/nodes/tasks/generated/__init__.py": "from .assets import generated_tasks\n", }, expected_error_fragment="Duplicate Python node found for 'profile'", ), @@ -800,7 +812,7 @@ def generated_tasks(): description="generated name colliding with top-level node fails validation", repo_files=base_repo_files() | { - "python/tasks/top_level.py": """ + "python/nodes/tasks/top_level/asset.py": """ from sqlbuild.assets import asset @@ -808,7 +820,7 @@ def generated_tasks(): def top_level_profile(ctx): return None """, - "python/assets/generated.py": """ + "python/nodes/assets/generated/assets.py": """ from sqlbuild.assets import asset from sqlbuild.factories import factory @@ -827,23 +839,31 @@ def generated_profile(ctx): description="factory returning a distinct node named like a module node fails validation", repo_files=base_repo_files() | { - "python/factories/orders.py": """ -from sqlbuild.factories import factory -from sqlbuild.assets import asset - - -@asset -def orders(ctx): - return None - - -@factory -def order_nodes(): - @asset(name="orders") - def generated_orders(ctx): - return None - return generated_orders -""", + "python/nodes/factories/orders/orders/asset.py": ( + "from sqlbuild.factories import factory\n" + "from sqlbuild.assets import asset\n" + "\n" + "\n" + "@asset\n" + "def orders(ctx):\n" + " return None\n" + ), + "python/nodes/factories/orders/order_nodes/assets.py": ( + "from sqlbuild.factories import factory\n" + "from sqlbuild.assets import asset\n" + "\n" + "\n" + "@factory\n" + "def order_nodes():\n" + ' @asset(name="orders")\n' + " def generated_orders(ctx):\n" + " return None\n" + " return generated_orders\n" + ), + "python/nodes/factories/orders/__init__.py": ( + "from .orders.asset import orders\n" + "from .order_nodes.assets import order_nodes\n" + ), }, expected_error_fragment="Duplicate Python node found for 'orders'", ), @@ -851,7 +871,9 @@ def generated_orders(ctx): description="generated dependency cycle fails validation", repo_files=base_repo_files() | { - "python/tasks/generated.py": """ + **node_module_files( + "python/nodes/tasks/generated.py", + """ from sqlbuild.factories import factory from sqlbuild.assets import asset @@ -867,6 +889,7 @@ def second_body(ctx): first = asset(name="first", depends_on=[second])(first) return [first, second] """, + ), }, expected_error_fragment="Python node dependency cycle detected", ), @@ -874,7 +897,7 @@ def second_body(ctx): description="generated loader SQL dependency fails validation", repo_files=base_repo_files() | { - "python/loaders/generated.py": """ + "python/nodes/loaders/generated/loaders.py": """ from sqlbuild.factories import factory from sqlbuild.loaders import loader from sqlbuild.refs import model @@ -894,8 +917,8 @@ def raw_orders(ctx): description="generated managed source loader mismatch fails validation", repo_files=base_repo_files() | { - "sources/raw.yml": "sources:\n - name: raw_orders\n managed: true\n", - "python/loaders/generated.py": """ + "sql/sources/raw.yml": "sources:\n - name: raw_orders\n managed: true\n", + "python/nodes/loaders/generated/loaders.py": """ from sqlbuild.factories import factory from sqlbuild.loaders import loader @@ -908,7 +931,7 @@ def load(ctx): return load """, }, - expected_error_fragment="Managed source 'raw_orders' in sources/raw.yml requires loader", + expected_error_fragment="Managed source 'raw_orders' in sql/sources/raw.yml requires loader", ), ), ids=lambda case: case.description, @@ -931,7 +954,7 @@ def test_given_invalid_generated_factory_nodes_when_discovering_inputs_then_rais description="parameterized cases share their test's unique name", repo_files=base_repo_files() | { - "models/marts/orders.sql": "MODEL ();\n\nselect 1\n", + "sql/models/marts/orders.sql": "MODEL ();\n\nselect 1\n", "tests/unit/order_status.sql": ( "TEST (parameters (status string), cases " '(open_case (status "open"), closed_case (status "closed")));\nSELECT 1\n' @@ -963,23 +986,23 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup DiscoverProjectInputsErrorTestCase( description="raises when Python lives outside a supported project root", repo_files=base_repo_files() - | {"audit_helpers/measurements.py": "def build_cases(): return []\n"}, + | {"sql/models/measurements.py": "def build_cases(): return []\n"}, expected_error_fragment=( - "Unsupported project Python path\\(s\\): audit_helpers/measurements.py" + "Unsupported project Python path\\(s\\): sql/models/measurements.py" ), ), DiscoverProjectInputsErrorTestCase( description="raises on duplicate source names across files", repo_files=base_repo_files() | { - "sources/raw_orders.yml": """ + "sql/sources/raw_orders.yml": """ sources: - name: raw_orders schema: public table: orders """.strip() + "\n", - "sources/raw_orders_duplicate.yml": """ + "sql/sources/raw_orders_duplicate.yml": """ sources: - name: raw_orders schema: public @@ -993,7 +1016,7 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup description="raises on schema yml model metadata", repo_files=base_repo_files() | { - "models/staging/schema.yml": """ + "sql/models/staging/schema.yml": """ models: - name: stg_orders """.strip() @@ -1005,7 +1028,7 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup description="raises on duplicate schema seed names across files", repo_files=base_repo_files() | { - "seeds/a.yml": """ + "sql/seeds/a.yml": """ seeds: - name: country_codes columns: @@ -1013,7 +1036,7 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup type: VARCHAR """.strip() + "\n", - "seeds/b.yml": """ + "sql/seeds/b.yml": """ seeds: - name: country_codes columns: @@ -1028,8 +1051,8 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup description="raises on duplicate model file names across directories", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL ();\n\nselect 1\n", - "models/marts/orders.sql": "MODEL ();\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL ();\n\nselect 1\n", + "sql/models/marts/orders.sql": "MODEL ();\n\nselect 1\n", }, expected_error_fragment="Duplicate model file name found for 'orders'", ), @@ -1046,12 +1069,12 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup description="raises when a unit test and a model share a name", repo_files=base_repo_files() | { - "models/marts/orders.sql": "MODEL ();\n\nselect 1\n", + "sql/models/marts/orders.sql": "MODEL ();\n\nselect 1\n", "tests/unit/orders.sql": "TEST ();\nSELECT 1\n", }, expected_error_fragment=( "Project resource name 'orders' is declared as both model in " - "models/marts/orders.sql and unit test in tests/unit/orders.sql; .*unit test, " + "sql/models/marts/orders.sql and unit test in tests/unit/orders.sql; .*unit test, " "scenario, job, job group, sensor, and calendar names must be globally unique" ), ), @@ -1059,14 +1082,14 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup description="raises when a scenario and a source share a name", repo_files=base_repo_files() | { - "sources/raw.yml": ( + "sql/sources/raw.yml": ( "sources:\n - name: raw_orders\n schema: public\n table: orders\n" ), "tests/scenarios/raw_orders.sql": "SCENARIO ();\nSELECT 1\n", }, expected_error_fragment=( "Project resource name 'raw_orders' is declared as both source in " - "sources/raw.yml and scenario in tests/scenarios/raw_orders.sql" + "sql/sources/raw.yml and scenario in tests/scenarios/raw_orders.sql" ), ), DiscoverProjectInputsErrorTestCase( @@ -1085,8 +1108,8 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup description="raises when model and source names collide", repo_files=base_repo_files() | { - "models/staging/orders.sql": "MODEL ();\n\nselect 1\n", - "sources/raw.yml": """ + "sql/models/staging/orders.sql": "MODEL ();\n\nselect 1\n", + "sql/sources/raw.yml": """ sources: - name: orders table: orders @@ -1099,13 +1122,13 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup description="raises when source and seed names collide", repo_files=base_repo_files() | { - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: country_codes table: country_codes """.strip() + "\n", - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: country_codes columns: @@ -1120,27 +1143,27 @@ def test_given_parameterized_test_when_discovering_inputs_then_cases_are_not_dup description="raises when a source references an unknown loader", repo_files=base_repo_files() | { - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders managed: true """.strip() + "\n", }, - expected_error_fragment="Managed source 'raw_orders' in sources/raw.yml requires loader", + expected_error_fragment="Managed source 'raw_orders' in sql/sources/raw.yml requires loader", ), DiscoverProjectInputsErrorTestCase( description="raises when loader names are duplicated", repo_files=base_repo_files() | { - "python/loaders/a.py": """ + "python/nodes/loaders/a/loader.py": """ from sqlbuild.loaders import loader @loader def raw_orders(ctx): return [] """, - "python/loaders/b.py": """ + "python/nodes/loaders/b/loader.py": """ from sqlbuild.loaders import loader @loader @@ -1154,14 +1177,14 @@ def raw_orders(ctx): description="raises when explicit loader names are duplicated", repo_files=base_repo_files() | { - "python/loaders/a.py": """ + "python/nodes/loaders/a/loader.py": """ from sqlbuild.loaders import loader @loader(name="raw_orders") def load_a(ctx): return [] """, - "python/loaders/b.py": """ + "python/nodes/loaders/b/loader.py": """ from sqlbuild.loaders import loader @loader(name="raw_orders") @@ -1175,13 +1198,13 @@ def load_b(ctx): description="raises when unmanaged source name collides with loader name", repo_files=base_repo_files() | { - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: fetch_orders table: fetch_orders """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -1189,19 +1212,19 @@ def fetch_orders(ctx): return [] """, }, - expected_error_fragment="Source 'fetch_orders' in sources/raw.yml conflicts with loader", + expected_error_fragment="Source 'fetch_orders' in sql/sources/raw.yml conflicts with loader", ), DiscoverProjectInputsErrorTestCase( description="raises when unmanaged source name collides with terminal loader name", repo_files=base_repo_files() | { - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders table: raw_orders """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -1209,13 +1232,13 @@ def raw_orders(ctx): return [] """, }, - expected_error_fragment="Source 'raw_orders' in sources/raw.yml conflicts with loader", + expected_error_fragment="Source 'raw_orders' in sql/sources/raw.yml conflicts with loader", ), DiscoverProjectInputsErrorTestCase( description="raises when loader dependency is not decorated", repo_files=base_repo_files() | { - "python/loaders/events.py": """ + "python/nodes/loaders/events/loader.py": """ from sqlbuild.loaders import loader def fetch_events(ctx): @@ -1232,17 +1255,21 @@ def enriched_events(ctx): description="raises when loader dependencies contain a cycle", repo_files=base_repo_files() | { - "python/loaders/events.py": """ + "python/nodes/loaders/events/loaders.py": """ +from sqlbuild.factories import factory from sqlbuild.loaders import loader -def fetch_events(ctx): - return [] -@loader(depends_on=[fetch_events]) -def enriched_events(ctx): - return [] +@factory +def event_loaders(): + def fetch_events(ctx): + return [] -fetch_events = loader(depends_on=[enriched_events])(fetch_events) + @loader(depends_on=[fetch_events]) + def enriched_events(ctx): + return [] + + return [loader(depends_on=[enriched_events])(fetch_events), enriched_events] """, }, expected_error_fragment="Loader dependency cycle detected", @@ -1251,14 +1278,14 @@ def enriched_events(ctx): description="raises when terminal loader owns source config", repo_files=base_repo_files() | { - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: raw_orders managed: true write_strategy: table """.strip() + "\n", - "python/loaders/raw_orders.py": """ + "python/nodes/loaders/raw_orders/loader.py": """ from sqlbuild.loaders import loader @loader(write_strategy="table", columns=[{"name": "id", "type": "INTEGER"}]) @@ -1272,14 +1299,14 @@ def raw_orders(ctx): description="raises when task and asset names are duplicated", repo_files=base_repo_files() | { - "python/tasks/export_customers.py": """ + "python/nodes/tasks/export_customers/asset.py": """ from sqlbuild.assets import asset @asset def export_customers(ctx): return None """, - "python/assets/export_customers.py": """ + "python/nodes/assets/export_customers/asset.py": """ from sqlbuild.assets import asset @asset @@ -1293,16 +1320,16 @@ def export_customers(ctx): description="raises when check name collides with task name", repo_files=base_repo_files() | { - "python/tasks/export_customers.py": """ + "python/nodes/tasks/export_customers/asset.py": """ from sqlbuild.assets import asset @asset def export_customers(ctx): return None """, - "python/checks/export_customers.py": """ + "python/nodes/checks/export_customers/checks.py": """ from sqlbuild.checks import check -from python.tasks.export_customers import export_customers +from python.nodes.tasks.export_customers.asset import export_customers @check(depends_on=export_customers, name="export_customers") def export_customers_check(ctx): @@ -1315,8 +1342,8 @@ def export_customers_check(ctx): description="raises when model name collides with task name", repo_files=base_repo_files() | { - "models/marts/export_customers.sql": "MODEL ();\n\nselect 1\n", - "python/tasks/export_customers.py": """ + "sql/models/marts/export_customers.sql": "MODEL ();\n\nselect 1\n", + "python/nodes/tasks/export_customers/asset.py": """ from sqlbuild.assets import asset @asset @@ -1332,7 +1359,7 @@ def export_customers(ctx): description="raises when seed name collides with asset name", repo_files=base_repo_files() | { - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: export_customers columns: @@ -1340,8 +1367,8 @@ def export_customers(ctx): type: INTEGER """.strip() + "\n", - "seeds/export_customers.csv": "customer_id\n1\n", - "python/assets/export_customers.py": """ + "sql/seeds/export_customers.csv": "customer_id\n1\n", + "python/nodes/assets/export_customers/asset.py": """ from sqlbuild.assets import asset @asset @@ -1357,22 +1384,22 @@ def export_customers(ctx): description="raises when source name collides with check name", repo_files=base_repo_files() | { - "sources/raw.yml": """ + "sql/sources/raw.yml": """ sources: - name: export_customers_exists table: export_customers_exists """.strip() + "\n", - "python/tasks/export_customers.py": """ + "python/nodes/tasks/export_customers/asset.py": """ from sqlbuild.assets import asset @asset def export_customers(ctx): return None """, - "python/checks/export_customers.py": """ + "python/nodes/checks/export_customers/checks.py": """ from sqlbuild.checks import check -from python.tasks.export_customers import export_customers +from python.nodes.tasks.export_customers.asset import export_customers @check(depends_on=export_customers) def export_customers_exists(ctx): @@ -1387,7 +1414,7 @@ def export_customers_exists(ctx): description="raises when sql function name collides with python function name", repo_files=base_repo_files() | { - "functions/sql/is_large_order.sql": """ + "sql/functions/sql/is_large_order.sql": """ FUNCTION ( arguments (amount INTEGER), returns BOOLEAN, @@ -1396,7 +1423,7 @@ def export_customers_exists(ctx): amount > 100 """.strip() + "\n", - "functions/python/is_large_order.py": """ + "sql/functions/python/is_large_order.py": """ from sqlbuild.functions import udf @udf(arguments={"amount": "INTEGER"}, returns="BOOLEAN", runtime_version="3.11") @@ -1413,7 +1440,7 @@ def main(amount): description="raises when function name collides with loader name", repo_files=base_repo_files() | { - "functions/sql/fetch_orders.sql": """ + "sql/functions/sql/fetch_orders.sql": """ FUNCTION ( arguments (amount INTEGER), returns BOOLEAN, @@ -1422,7 +1449,7 @@ def main(amount): amount > 100 """.strip() + "\n", - "python/loaders/fetch_orders.py": """ + "python/nodes/loaders/fetch_orders/loader.py": """ from sqlbuild.loaders import loader @loader @@ -1438,25 +1465,25 @@ def fetch_orders(ctx): description="raises when SQL hook name collides with model name", repo_files=base_repo_files() | { - "models/notify.sql": "MODEL ();\n\nSELECT 1\n", - "hooks/sql/notify.sql": "HOOK ();\n\nSELECT 1\n", + "sql/models/notify.sql": "MODEL ();\n\nSELECT 1\n", + "sql/hooks/sql/notify.sql": "HOOK ();\n\nSELECT 1\n", }, expected_error_fragment=( - "Project resource name 'notify' is declared as both model in models/notify.sql " - "and sql hook in hooks/sql/notify.sql" + "Project resource name 'notify' is declared as both model in sql/models/notify.sql " + "and sql hook in sql/hooks/sql/notify.sql" ), ), DiscoverProjectInputsErrorTestCase( description="raises when Python hook name collides with provider name", repo_files=base_repo_files() | { - "providers/marker.py": """ + "python/providers/marker.py": """ from sqlbuild.providers import Provider class MarkerProvider(Provider): pass """, - "hooks/python/marker.py": """ + "sql/hooks/python/marker.py": """ from sqlbuild.hooks import hook @hook(name="marker_provider") @@ -1472,8 +1499,8 @@ def marker(ctx): description="raises when SQL and Python hook names collide", repo_files=base_repo_files() | { - "hooks/sql/notify.sql": "HOOK ();\n\nSELECT 1\n", - "hooks/python/notify.py": """ + "sql/hooks/sql/notify.sql": "HOOK ();\n\nSELECT 1\n", + "sql/hooks/python/notify.py": """ from sqlbuild.hooks import hook @hook @@ -1483,14 +1510,14 @@ def notify(ctx): }, expected_error_fragment=( "Project resource name 'notify' is declared as both sql hook in " - "hooks/sql/notify.sql and python hook in hooks/python/notify.py" + "sql/hooks/sql/notify.sql and python hook in sql/hooks/python/notify.py" ), ), DiscoverProjectInputsErrorTestCase( description="raises when task dependency is not decorated", repo_files=base_repo_files() | { - "python/tasks/windows.py": """ + "python/nodes/tasks/windows/asset.py": """ from sqlbuild.assets import asset def fetch_window(ctx): @@ -1507,17 +1534,21 @@ def export_window(ctx): description="raises when task and asset dependencies contain a cycle", repo_files=base_repo_files() | { - "python/tasks/windows.py": """ + "python/nodes/tasks/windows/assets.py": """ from sqlbuild.assets import asset +from sqlbuild.factories import factory -def fetch_window(ctx): - return None -@asset(depends_on=fetch_window) -def enrich_window(ctx): - return None +@factory +def window_assets(): + def fetch_window(ctx): + return None + + @asset(depends_on=fetch_window) + def enrich_window(ctx): + return None -fetch_window = asset(depends_on=enrich_window)(fetch_window) + return [asset(depends_on=enrich_window)(fetch_window), enrich_window] """, }, expected_error_fragment="Python node dependency cycle detected", @@ -1526,7 +1557,7 @@ def enrich_window(ctx): description="raises when check dependency is not decorated", repo_files=base_repo_files() | { - "python/checks/exports.py": """ + "python/nodes/checks/exports/checks.py": """ from sqlbuild.checks import check def export_customers(ctx): @@ -1543,7 +1574,7 @@ def export_customers_exists(ctx): description="raises when loader declares SQL model dependency", repo_files=base_repo_files() | { - "python/loaders/orders.py": """ + "python/nodes/loaders/orders/loader.py": """ from sqlbuild.loaders import loader from sqlbuild.refs import model @@ -1558,16 +1589,16 @@ def load_orders(ctx): description="raises when check depends on check", repo_files=base_repo_files() | { - "python/assets/exports.py": """ + "python/nodes/assets/exports/asset.py": """ from sqlbuild.assets import asset @asset def export_customers(ctx): return None """, - "python/checks/exports.py": """ + "python/nodes/checks/exports/checks.py": """ from sqlbuild.checks import check -from python.assets.exports import export_customers +from python.nodes.assets.exports.asset import export_customers @check(depends_on=export_customers) def export_customers_exists(ctx): @@ -1584,7 +1615,7 @@ def export_customers_recent(ctx): description="raises when seeds are declared outside seeds directory", repo_files=base_repo_files() | { - "models/schema.yml": """ + "sql/models/schema.yml": """ seeds: - name: country_codes columns: @@ -1593,13 +1624,13 @@ def export_customers_recent(ctx): """.strip() + "\n", }, - expected_error_fragment="seed declarations must live under seeds/", + expected_error_fragment="seed declarations must live under sql/seeds/", ), DiscoverProjectInputsErrorTestCase( description="raises when a seed declaration uses yaml extension", repo_files=base_repo_files() | { - "seeds/lookups.yaml": "seeds: []\n", + "sql/seeds/lookups.yaml": "seeds: []\n", }, expected_error_fragment=r"\.yaml is not supported", ), @@ -1607,9 +1638,9 @@ def export_customers_recent(ctx): description="raises when seed csv basenames are duplicated", repo_files=base_repo_files() | { - "seeds/a/country_codes.csv": "country_code\nUS\n", - "seeds/b/country_codes.csv": "country_code\nCA\n", - "seeds/lookups.yml": """ + "sql/seeds/a/country_codes.csv": "country_code\nUS\n", + "sql/seeds/b/country_codes.csv": "country_code\nCA\n", + "sql/seeds/lookups.yml": """ seeds: - name: country_codes columns: @@ -1624,7 +1655,7 @@ def export_customers_recent(ctx): description="raises when a declared seed has no matching csv file", repo_files=base_repo_files() | { - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: country_codes columns: @@ -1633,13 +1664,13 @@ def export_customers_recent(ctx): """.strip() + "\n", }, - expected_error_fragment="has no matching CSV file under seeds/", + expected_error_fragment="has no matching CSV file under sql/seeds/", ), DiscoverProjectInputsErrorTestCase( description="raises when a seed csv has no matching declaration", repo_files=base_repo_files() | { - "seeds/country_codes.csv": "country_code\nUS\n", + "sql/seeds/country_codes.csv": "country_code\nUS\n", }, expected_error_fragment="has no matching declaration for seed 'country_codes'", ), @@ -1647,7 +1678,7 @@ def export_customers_recent(ctx): description="raises when a seed csv header does not match declared columns", repo_files=base_repo_files() | { - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: country_codes columns: @@ -1657,7 +1688,7 @@ def export_customers_recent(ctx): type: VARCHAR """.strip() + "\n", - "seeds/country_codes.csv": "country_name,country_code\nUS,United States\n", + "sql/seeds/country_codes.csv": "country_name,country_code\nUS,United States\n", }, expected_error_fragment="does not match declared seed columns", ), @@ -1665,7 +1696,7 @@ def export_customers_recent(ctx): description="raises when a seed csv has duplicate header columns", repo_files=base_repo_files() | { - "seeds/schema.yml": """ + "sql/seeds/schema.yml": """ seeds: - name: country_codes columns: @@ -1675,7 +1706,7 @@ def export_customers_recent(ctx): type: VARCHAR """.strip() + "\n", - "seeds/country_codes.csv": "country_code,country_code\nUS,United States\n", + "sql/seeds/country_codes.csv": "country_code,country_code\nUS,United States\n", }, expected_error_fragment="contains duplicate CSV header column 'country_code'", ), @@ -1691,7 +1722,7 @@ def export_customers_recent(ctx): schema = "staging" """.strip() + "\n", - "models/staging/orders.sql": "MODEL ();\n\nselect 1\n", + "sql/models/staging/orders.sql": "MODEL ();\n\nselect 1\n", }, expected_error_fragment=r"path_defaults\['stagingg'\] does not match any model paths", ), diff --git a/tests/unit/src/sqlbuild/compiler/discovery/test_recall_replacement_sinks.py b/tests/unit/src/sqlbuild/compiler/discovery/test_recall_replacement_sinks.py index cad384e6aa..e6b7d38d63 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/test_recall_replacement_sinks.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/test_recall_replacement_sinks.py @@ -24,7 +24,7 @@ " history.publish_lifecycle(event)\n\n" ) OUTPUT_REPLACEMENT: str = ( - "@command_output_sink\n" + "@command_output_event_sink\n" "def redact(record: CommandOutputRecord, writer: RecallWriter) -> None:\n" " writer.publish_command_output(record)\n\n" ) @@ -32,7 +32,7 @@ "@lifecycle_event_sink\n" "def audit_log(event: LifecycleEvent) -> None:\n" " del event\n\n" - "@command_output_sink\n" + "@command_output_event_sink\n" "def output_log(record: CommandOutputRecord) -> None:\n" " del record\n" ) @@ -43,15 +43,17 @@ ( RecallSinkDiscoveryTestCase( description="no replacement keeps Recall's default for both streams", - sink_files={"sinks/logs.py": RECALL_SINK_IMPORTS + ORDINARY_SINKS}, + sink_files={"python/event_sinks/logs.py": RECALL_SINK_IMPORTS + ORDINARY_SINKS}, expected_replacements=((), ()), expected_ordinary=(("audit_log",), ("output_log",)), ), RecallSinkDiscoveryTestCase( description="one replacement per stream, by writer type under any parameter name", sink_files={ - "sinks/recall.py": RECALL_SINK_IMPORTS + LIFECYCLE_REPLACEMENT + OUTPUT_REPLACEMENT, - "sinks/logs.py": RECALL_SINK_IMPORTS + ORDINARY_SINKS, + "python/event_sinks/recall.py": RECALL_SINK_IMPORTS + + LIFECYCLE_REPLACEMENT + + OUTPUT_REPLACEMENT, + "python/event_sinks/logs.py": RECALL_SINK_IMPORTS + ORDINARY_SINKS, }, expected_replacements=((("keep_runs", "history"),), (("redact", "writer"),)), expected_ordinary=(("audit_log",), ("output_log",)), @@ -78,53 +80,53 @@ def test_given_sinks_taking_a_recall_writer_when_discovering_then_they_replace_r InvalidRecallSinkTestCase( description="two replacements for one stream are both named", project_files={ - "sinks/first.py": RECALL_SINK_IMPORTS + OUTPUT_REPLACEMENT, - "sinks/second.py": RECALL_SINK_IMPORTS + "python/event_sinks/first.py": RECALL_SINK_IMPORTS + OUTPUT_REPLACEMENT, + "python/event_sinks/second.py": RECALL_SINK_IMPORTS + OUTPUT_REPLACEMENT.replace("def redact", "def mask"), }, expected_error=EventExporterDiscoveryError, expected_code="D015", expected_message=( "Only one sink may replace Recall command-output history; found " - "sinks/first.py:redact, sinks/second.py:mask" + "python/event_sinks/first.py:redact, python/event_sinks/second.py:mask" ), ), InvalidRecallSinkTestCase( description="a sink with two writers", project_files={ - "sinks/recall.py": RECALL_SINK_IMPORTS + "@lifecycle_event_sink\n" + "python/event_sinks/recall.py": RECALL_SINK_IMPORTS + "@lifecycle_event_sink\n" "def both(event: LifecycleEvent, one: RecallWriter, two: RecallWriter) -> None:\n" " del event, one, two\n", }, expected_error=EventExporterDiscoveryError, expected_code="D015", - expected_message="sinks/recall.py:both declares more than one RecallWriter parameter", + expected_message="python/event_sinks/recall.py:both declares more than one RecallWriter parameter", ), InvalidRecallSinkTestCase( description="a replacement with a provider parameter", project_files={ - "providers/orders_api.py": "from sqlbuild.providers import Provider\n\n\n" + "python/providers/orders_api.py": "from sqlbuild.providers import Provider\n\n\n" "class OrdersApi(Provider):\n 'Order service settings.'\n\n" " region: str = 'eu'\n", - "sinks/recall.py": RECALL_SINK_IMPORTS + "@command_output_sink\n" + "python/event_sinks/recall.py": RECALL_SINK_IMPORTS + "@command_output_event_sink\n" "def redact(record: CommandOutputRecord, writer: RecallWriter, orders_api) -> None:\n" " del record, writer, orders_api\n", }, expected_error=EventExporterDiscoveryError, expected_code="D015", - expected_message="sinks/recall.py:redact must not declare provider parameters", + expected_message="python/event_sinks/recall.py:redact must not declare provider parameters", ), InvalidRecallSinkTestCase( description="a provider named recall_writer", project_files={ - "providers/recall_writer.py": "from sqlbuild.providers import Provider\n\n\n" + "python/providers/recall_writer.py": "from sqlbuild.providers import Provider\n\n\n" "class RecallWriter(Provider):\n 'Shadows the writer name.'\n\n" " region: str = 'eu'\n", - "sinks/logs.py": RECALL_SINK_IMPORTS + ORDINARY_SINKS, + "python/event_sinks/logs.py": RECALL_SINK_IMPORTS + ORDINARY_SINKS, }, expected_error=ProviderDiscoveryError, expected_code="D012", - expected_message="Provider name 'recall_writer' in providers/recall_writer.py is reserved", + expected_message="Provider name 'recall_writer' in python/providers/recall_writer.py is reserved", ), ), ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/compiler/discovery/test_runtime_event_exporter_config.py b/tests/unit/src/sqlbuild/compiler/discovery/test_runtime_event_exporter_config.py index 97cd46cb36..ba54de8dc4 100644 --- a/tests/unit/src/sqlbuild/compiler/discovery/test_runtime_event_exporter_config.py +++ b/tests/unit/src/sqlbuild/compiler/discovery/test_runtime_event_exporter_config.py @@ -21,10 +21,10 @@ ( EventExporterConfigTestCase( "global named intersection", - "[sinks.lifecycle]\n" + "[event_sinks.lifecycle]\n" 'event_kinds = ["run", "operation"]\n' 'min_severity = "warning"\n' - "[sinks.lifecycle.named.publish]\n" + "[event_sinks.lifecycle.named.publish]\n" 'event_kinds = ["run", "statement"]\n' 'min_severity = "error"\n', frozenset({"run"}), @@ -54,12 +54,14 @@ def test_given_global_and_named_filters_when_discovering_then_effective_filter_i "test_case", ( LifecycleShutdownTimeoutTestCase("default", "", None), - LifecycleShutdownTimeoutTestCase("zero", '[sinks.lifecycle]\nshutdown_timeout = "0s"\n', 0), LifecycleShutdownTimeoutTestCase( - "seconds", '[sinks.lifecycle]\nshutdown_timeout = "30s"\n', 30 + "zero", '[event_sinks.lifecycle]\nshutdown_timeout = "0s"\n', 0 ), LifecycleShutdownTimeoutTestCase( - "upper bound", '[sinks.lifecycle]\nshutdown_timeout = "10m"\n', 600 + "seconds", '[event_sinks.lifecycle]\nshutdown_timeout = "30s"\n', 30 + ), + LifecycleShutdownTimeoutTestCase( + "upper bound", '[event_sinks.lifecycle]\nshutdown_timeout = "10m"\n', 600 ), ), ids=lambda case: case.description, @@ -80,56 +82,61 @@ def test_given_lifecycle_shutdown_timeout_when_discovering_then_exposes_drain_se ( InvalidEventExporterConfigTestCase( "unknown lifecycle sink", - '[sinks.lifecycle.named.missing]\nmin_severity = "info"\n', - "unknown sink", + '[event_sinks.lifecycle.named.missing]\nmin_severity = "info"\n', + "unknown event sink", ), InvalidEventExporterConfigTestCase( - "unknown kind", '[sinks.lifecycle]\nevent_kinds = ["kafka"]\n', "unknown kind" + "unknown kind", '[event_sinks.lifecycle]\nevent_kinds = ["kafka"]\n', "unknown kind" ), InvalidEventExporterConfigTestCase( "unknown severity", - '[sinks.lifecycle]\nmin_severity = "fatal"\n', + '[event_sinks.lifecycle]\nmin_severity = "fatal"\n', "min_severity", ), InvalidEventExporterConfigTestCase( "global typo", - "[sinks.lifecycle]\nevent_kind = []\n", + "[event_sinks.lifecycle]\nevent_kind = []\n", "unknown key.*event_kind", ), InvalidEventExporterConfigTestCase( "named typo", - '[sinks.lifecycle.named.publish]\nminimum_severity = "info"\n', + '[event_sinks.lifecycle.named.publish]\nminimum_severity = "info"\n', "unknown key.*minimum_severity", ), InvalidEventExporterConfigTestCase( "negative shutdown timeout", - '[sinks.lifecycle]\nshutdown_timeout = "-1s"\n', - "sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m'", + '[event_sinks.lifecycle]\nshutdown_timeout = "-1s"\n', + "event_sinks.lifecycle.shutdown_timeout must be a fixed duration from '0s' to '10m'", ), InvalidEventExporterConfigTestCase( "numeric shutdown timeout", - "[sinks.lifecycle]\nshutdown_timeout = 5\n", - "sinks.lifecycle.shutdown_timeout must be a fixed duration", + "[event_sinks.lifecycle]\nshutdown_timeout = 5\n", + "event_sinks.lifecycle.shutdown_timeout must be a fixed duration", ), InvalidEventExporterConfigTestCase( "calendar shutdown timeout", - '[sinks.lifecycle]\nshutdown_timeout = "1mo"\n', - "sinks.lifecycle.shutdown_timeout must be a fixed duration", + '[event_sinks.lifecycle]\nshutdown_timeout = "1mo"\n', + "event_sinks.lifecycle.shutdown_timeout must be a fixed duration", ), InvalidEventExporterConfigTestCase( "shutdown timeout above upper bound", - '[sinks.lifecycle]\nshutdown_timeout = "11m"\n', - "sinks.lifecycle.shutdown_timeout must be a fixed duration", + '[event_sinks.lifecycle]\nshutdown_timeout = "11m"\n', + "event_sinks.lifecycle.shutdown_timeout must be a fixed duration", ), InvalidEventExporterConfigTestCase( "named shutdown timeout", - '[sinks.lifecycle.named.publish]\nshutdown_timeout = "5s"\n', + '[event_sinks.lifecycle.named.publish]\nshutdown_timeout = "5s"\n', "unknown key.*shutdown_timeout", ), InvalidEventExporterConfigTestCase( "legacy exporter config", '[event_exporters]\nmin_severity = "info"\n', - "replaced by sinks.lifecycle", + "event_exporters was replaced by event_sinks.lifecycle", + ), + InvalidEventExporterConfigTestCase( + "sinks config from before the rename", + '[sinks.lifecycle]\nmin_severity = "info"\n', + "sinks was renamed event_sinks", ), ), ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/compiler/frontier/helpers.py b/tests/unit/src/sqlbuild/compiler/frontier/helpers.py index 26ada14e85..8f52e348ac 100644 --- a/tests/unit/src/sqlbuild/compiler/frontier/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/frontier/helpers.py @@ -115,7 +115,7 @@ def _order_lines() -> list[dict[str, object]]: def order_line() -> OrderLine: """Return one neutral order line.""" - return OrderLine(order_id=7, status=OrderStatus.PLACED, path=PurePosixPath("models/a.sql")) + return OrderLine(order_id=7, status=OrderStatus.PLACED, path=PurePosixPath("sql/models/a.sql")) def declaration_scope_build() -> DeclarationScopeBuild: diff --git a/tests/unit/src/sqlbuild/compiler/frontier/test_stage_capture.py b/tests/unit/src/sqlbuild/compiler/frontier/test_stage_capture.py index 616cc76a25..b3e3f5afd2 100644 --- a/tests/unit/src/sqlbuild/compiler/frontier/test_stage_capture.py +++ b/tests/unit/src/sqlbuild/compiler/frontier/test_stage_capture.py @@ -51,7 +51,7 @@ "__type__": f"{HELPERS_MODULE}:OrderLine", "order_id": 7, "status": {"__enum__": f"{HELPERS_MODULE}:OrderStatus.PLACED"}, - "path": {"__path__": "models/a.sql"}, + "path": {"__path__": "sql/models/a.sql"}, }, ), StageCaptureTestCase( @@ -224,7 +224,7 @@ def test_given_reordered_value_when_rendering_capture_then_only_unordered_collec "__type__": f"{HELPERS_MODULE}:OrderLine", "order_id": 7, "status": {"__enum__": f"{HELPERS_MODULE}:OrderStatus.PLACED"}, - "path": {"__path__": "models/a.sql"}, + "path": {"__path__": "sql/models/a.sql"}, }, ), ], diff --git a/tests/unit/src/sqlbuild/compiler/lineage/helpers.py b/tests/unit/src/sqlbuild/compiler/lineage/helpers.py index 11e965d1e6..2ca3cb8df4 100644 --- a/tests/unit/src/sqlbuild/compiler/lineage/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/lineage/helpers.py @@ -54,7 +54,7 @@ def make_compiled_model( key=CompiledObjectKey(CompiledResourceType.MODEL, name), deps=(), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), query_sql=query_sql, config=CompileModelConfig(), destination=CompiledRelationLocation( @@ -76,16 +76,16 @@ def make_compiled_seed(*, name: str, columns: tuple[str, ...]) -> CompiledSeedVi deps=(), name=name, seed_file=DiscoveredSeedFile( - file_path=Path(f"seeds/{name}.csv"), - relative_path=Path(f"seeds/{name}.csv"), + file_path=Path(f"sql/seeds/{name}.csv"), + relative_path=Path(f"sql/seeds/{name}.csv"), ), schema_entry=SchemaSeedEntry( name=name, columns=tuple(SchemaColumn(column_name) for column_name in columns), ), schema_file=DiscoveredSchemaFile( - file_path=Path("seeds/schema.yml"), - relative_path=Path("seeds/schema.yml"), + file_path=Path("sql/seeds/schema.yml"), + relative_path=Path("sql/seeds/schema.yml"), contents="", model_entries=(), seed_entries=(), diff --git a/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/helpers.py b/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/helpers.py index 97be9f574a..13c06eeab0 100644 --- a/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/helpers.py @@ -54,7 +54,7 @@ def constant_declarations(value: int) -> DeclarationResolutionContext: "base_rate": ConstantDeclaration( name="base_rate", value=SqlValue(logical_type=SqlLogicalType(kind=SqlValueKind.INTEGER), value=value), - relative_path=Path("constants/base_rate.sql"), + relative_path=Path("sql/constants/base_rate.sql"), ) } ) @@ -185,13 +185,13 @@ def sqlbuild_module(_root: Path) -> object: def write_environment_project(root: Path) -> None: """Write a model and a macro for store environment checks.""" - (root / "models").mkdir() - (root / "macros" / "python").mkdir(parents=True) - _ = (root / "models/orders.sql").write_text("SELECT 1\n", encoding="utf-8") - _ = (root / "macros/python/common.py").write_text("X = 1\n", encoding="utf-8") + (root / "sql" / "models").mkdir(parents=True) + (root / "sql" / "macros" / "python").mkdir(parents=True) + _ = (root / "sql/models/orders.sql").write_text("SELECT 1\n", encoding="utf-8") + _ = (root / "sql/macros/python/common.py").write_text("X = 1\n", encoding="utf-8") -EXCLUDED_MODEL_PATHS: list[str] = ["models/orders.sql"] +EXCLUDED_MODEL_PATHS: list[str] = ["sql/models/orders.sql"] def environment_of(root: Path) -> str: diff --git a/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/test_store_environment.py b/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/test_store_environment.py index a700b9fcc8..4be44735d0 100644 --- a/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/test_store_environment.py +++ b/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/test_store_environment.py @@ -106,17 +106,17 @@ def test_given_module_digests_when_encoding_then_validation_returns_them( ), StoreEnvironmentTestCase( description="model edit", - edit=lambda root: (root / "models/orders.sql").write_text("SELECT 2\n"), + edit=lambda root: (root / "sql/models/orders.sql").write_text("SELECT 2\n"), expected_unchanged=True, ), StoreEnvironmentTestCase( description="macro edit", - edit=lambda root: (root / "macros/python/common.py").write_text("X = 2\n"), + edit=lambda root: (root / "sql/macros/python/common.py").write_text("X = 2\n"), expected_unchanged=False, ), StoreEnvironmentTestCase( description="model the caller does not exclude", - edit=lambda root: (root / "models/customers.sql").write_text("SELECT 1\n"), + edit=lambda root: (root / "sql/models/customers.sql").write_text("SELECT 1\n"), expected_unchanged=False, ), ], diff --git a/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/test_store_keys.py b/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/test_store_keys.py index d7f2000d49..eb8e062f89 100644 --- a/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/test_store_keys.py +++ b/tests/unit/src/sqlbuild/compiler/macro_bridge/_helpers/test_store_keys.py @@ -136,19 +136,19 @@ def test_given_context_value_when_naming_store_class_then_only_stable_values_are [ MacroStoreTokenTestCase( description="same file and source", - relative_path=Path("macros/python/common.py"), + relative_path=Path("sql/macros/python/common.py"), raw_source="def cents(column): ...\n", expected_equal=True, ), MacroStoreTokenTestCase( description="source edited", - relative_path=Path("macros/python/common.py"), + relative_path=Path("sql/macros/python/common.py"), raw_source="def cents(column): return column\n", expected_equal=False, ), MacroStoreTokenTestCase( description="same source in a scoped file", - relative_path=Path("models/south/_sqlbuild/_macros/python/common.py"), + relative_path=Path("sql/models/south/_sqlbuild/_macros/python/common.py"), raw_source="def cents(column): ...\n", expected_equal=False, ), @@ -160,7 +160,7 @@ def test_given_loaded_macro_change_when_naming_it_then_only_the_same_file_and_so ) -> None: original: str | None = macro_store_token( loaded=loaded_macro( - relative_path=Path("macros/python/common.py"), raw_source="def cents(column): ...\n" + relative_path=Path("sql/macros/python/common.py"), raw_source="def cents(column): ...\n" ), identity=None, ) diff --git a/tests/unit/src/sqlbuild/compiler/manifest/helpers.py b/tests/unit/src/sqlbuild/compiler/manifest/helpers.py index f25daaf0b7..1bf52192a3 100644 --- a/tests/unit/src/sqlbuild/compiler/manifest/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/manifest/helpers.py @@ -89,7 +89,7 @@ def build_test_model( *, name: str, query_sql: str = "SELECT 1", - relative_path: str = "models/test.sql", + relative_path: str = "sql/models/test.sql", database: str | None = None, schema: str | None = "public", alias: str | None = None, @@ -160,8 +160,8 @@ def build_test_source( name=name, source_entry=entry, source_file=DiscoveredSourceFile( - file_path=Path(f"sources/{name}.yml"), - relative_path=Path(f"sources/{name}.yml"), + file_path=Path(f"sql/sources/{name}.yml"), + relative_path=Path(f"sql/sources/{name}.yml"), contents="", source_entries=(entry,), ), @@ -182,13 +182,13 @@ def build_test_seed( deps=(), name=name, seed_file=DiscoveredSeedFile( - file_path=Path(f"seeds/{name}.csv"), - relative_path=Path(f"seeds/{name}.csv"), + file_path=Path(f"sql/seeds/{name}.csv"), + relative_path=Path(f"sql/seeds/{name}.csv"), ), schema_entry=SchemaSeedEntry(name=name, columns=(), tags=tags), schema_file=DiscoveredSchemaFile( - file_path=Path("seeds/schema.yml"), - relative_path=Path("seeds/schema.yml"), + file_path=Path("sql/seeds/schema.yml"), + relative_path=Path("sql/seeds/schema.yml"), contents="", model_entries=(), seed_entries=(), @@ -213,7 +213,7 @@ def build_test_plan_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.TABLE, action=PlanAction.CREATE_TABLE, reason=PlanReason.FIRST_RUN, diff --git a/tests/unit/src/sqlbuild/compiler/manifest/test_main.py b/tests/unit/src/sqlbuild/compiler/manifest/test_main.py index 9b3c970ae7..8a07e88650 100644 --- a/tests/unit/src/sqlbuild/compiler/manifest/test_main.py +++ b/tests/unit/src/sqlbuild/compiler/manifest/test_main.py @@ -73,7 +73,7 @@ _MODEL_ORDERS: CompiledModelView = build_test_model( name="orders", query_sql="SELECT * FROM raw", - relative_path="models/staging/orders.sql", + relative_path="sql/models/staging/orders.sql", schema="staging", config_values={"materialized": "table"}, description="Order records", @@ -83,13 +83,13 @@ _MODEL_ORPHAN: CompiledModelView = build_test_model( name="orphan", query_sql="SELECT 1", - relative_path="models/orphan.sql", + relative_path="sql/models/orphan.sql", schema="public", ) _MODEL_WITH_COLUMNS: CompiledModelView = build_test_model( name="typed_model", - relative_path="models/typed_model.sql", + relative_path="sql/models/typed_model.sql", description="Has columns", columns=( SchemaColumn(name="id", type="INTEGER", description="Primary key"), @@ -99,13 +99,13 @@ _MODEL_WITH_DEPS: CompiledModelView = build_test_model( name="joined", - relative_path="models/joined.sql", + relative_path="sql/models/joined.sql", deps=(model_key("orders"), source_key("raw_customers")), ) _MODEL_WITH_ALIAS: CompiledModelView = build_test_model( name="orders_aliased", - relative_path="models/marts/orders_aliased.sql", + relative_path="sql/models/marts/orders_aliased.sql", database="analytics", schema="marts", alias="fact_orders", @@ -384,7 +384,7 @@ def test_given_project_when_building_manifest_then_produces_correct_structure( SqlHookEntry( statement="SELECT 'reader'", name="record_access", - relative_path=Path("hooks/sql/record_access.sql"), + relative_path=Path("sql/hooks/sql/record_access.sql"), definition_sql="SELECT @'role'", kwargs={"role": "reader"}, description="Record access", @@ -416,7 +416,7 @@ def test_given_project_when_building_manifest_then_produces_correct_structure( "type": "sql", "statement": "SELECT 'reader'", "name": "record_access", - "relative_path": "hooks/sql/record_access.sql", + "relative_path": "sql/hooks/sql/record_access.sql", "definition_sql": "SELECT @'role'", "kwargs": {"role": "reader"}, "description": "Record access", @@ -598,19 +598,19 @@ def test_given_seed_when_building_manifest_then_produces_correct_node( FqnTestCase( description="builds fqn from nested relative path", project_name=_PROJECT, - relative_path="models/staging/orders.sql", + relative_path="sql/models/staging/orders.sql", expected_fqn=[_PROJECT, "models", "staging", "orders"], ), FqnTestCase( description="builds fqn from top-level relative path", project_name=_PROJECT, - relative_path="models/orders.sql", + relative_path="sql/models/orders.sql", expected_fqn=[_PROJECT, "models", "orders"], ), FqnTestCase( description="builds fqn from seed path", project_name=_PROJECT, - relative_path="seeds/codes.csv", + relative_path="sql/seeds/codes.csv", expected_fqn=[_PROJECT, "seeds", "codes"], ), ], @@ -702,7 +702,7 @@ def test_given_deps_when_building_manifest_then_parent_map_correct( expected_name="my_macro", expected_resource_type="macro", expected_macro_sql="def my_macro(): return 'SELECT 1'", - expected_path="macros/python/helpers.py", + expected_path="sql/macros/python/helpers.py", ), ManifestMacroNodeTestCase( description="scoped macro exposes visibility metadata", @@ -711,9 +711,9 @@ def test_given_deps_when_building_manifest_then_parent_map_correct( expected_name="my_macro", expected_resource_type="macro", expected_macro_sql="def my_macro(): return 'SELECT 1'", - expected_path="models/sales/macros/python/helpers.py", + expected_path="sql/models/sales/macros/python/helpers.py", expected_visibility="inherited", - expected_scope_path="models/sales", + expected_scope_path="sql/models/sales", expected_dependencies=("base_macro",), ), ], @@ -745,7 +745,7 @@ def test_given_macro_when_building_manifest_then_macro_node_present( dependency_records: tuple[DeclarationRecord, ...] = tuple( DeclarationRecord( identity=identity, - path=f"macros/{identity.name}.py", + path=f"sql/macros/{identity.name}.py", line=1, column=1, scope=ScopeKind.GLOBAL, @@ -759,7 +759,7 @@ def test_given_macro_when_building_manifest_then_macro_node_present( loaded_macros[dependency_name] = LoadedMacro( name=dependency_name, file_path=Path(f"/project/macros/{dependency_name}.py"), - relative_path=Path(f"macros/{dependency_name}.py"), + relative_path=Path(f"sql/macros/{dependency_name}.py"), raw_source=f"def {dependency_name}(): return 'SELECT 1'", function=lambda: "SELECT 1", ) @@ -955,7 +955,7 @@ def test_given_full_project_when_building_manifest_then_validates_against_dbt_sc model: CompiledModelView = build_test_model( name="orders", query_sql="SELECT id FROM raw", - relative_path="models/staging/orders.sql", + relative_path="sql/models/staging/orders.sql", schema="staging", config_values={"materialized": "table", "tags": ["core"]}, description="Order records", @@ -976,7 +976,7 @@ def test_given_full_project_when_building_manifest_then_validates_against_dbt_sc sql_hook_files=( DiscoveredSqlHookFile( file_path=Path("/project/hooks/sql/record_access.sql"), - relative_path=Path("hooks/sql/record_access.sql"), + relative_path=Path("sql/hooks/sql/record_access.sql"), contents="HOOK (description 'Test hook record_access.');\n\nSELECT @'role'\n", header_values={"description": "Record access"}, sql_body="SELECT @'role'", @@ -1024,7 +1024,7 @@ def test_given_full_project_when_building_manifest_then_validates_against_dbt_sc macro: LoadedMacro = LoadedMacro( name="my_macro", file_path=Path("/project/macros/python/helpers.py"), - relative_path=Path("macros/python/helpers.py"), + relative_path=Path("sql/macros/python/helpers.py"), raw_source="def my_macro(): return 'SELECT 1'", function=lambda: "SELECT 1", ) @@ -1049,7 +1049,7 @@ def test_given_full_project_when_building_manifest_then_validates_against_dbt_sc sql_hook_macro: dict[str, Any] = result["macros"][ f"macro.{_PROJECT}__sqlbuild_hooks.record_access" ] - assert sql_hook_macro["original_file_path"] == "hooks/sql/record_access.sql" + assert sql_hook_macro["original_file_path"] == "sql/hooks/sql/record_access.sql" assert sql_hook_macro["meta"] == { "sqlbuild_resource_type": "sql_hook", "sqlbuild_hook_name": "record_access", diff --git a/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/helpers.py b/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/helpers.py index b736af631c..de69c82845 100644 --- a/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/helpers.py @@ -37,7 +37,7 @@ def build_single_model_project( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="test_model"), deps=(), name="test_model", - relative_path=Path("models/test_model.sql"), + relative_path=Path("sql/models/test_model.sql"), query_sql="SELECT 1", config=CompileModelConfig(), destination=CompiledRelationLocation( @@ -78,7 +78,7 @@ def build_previous_python_identity_map( definition='{"source_text": "def prepare_orders(ctx):\\n return old_helper()\\n"}', metadata_json=( '{"dependencies": [{"module": "tasks.helpers", ' - '"qualname": "old_helper", "source_path": "python/tasks/helpers.py", ' + '"qualname": "old_helper", "source_path": "python/nodes/tasks/helpers.py", ' '"source_text": "def old_helper():\\n return 1\\n"}]}' ), ts=datetime(2026, 1, 15, 12, 0, 0), diff --git a/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/target_validation/helpers.py b/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/target_validation/helpers.py index afba121b9d..14b2a32713 100644 --- a/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/target_validation/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/target_validation/helpers.py @@ -55,7 +55,7 @@ def build_project( ), deps=(), name="stg_customers", - relative_path=Path("models/staging/stg_customers.sql"), + relative_path=Path("sql/models/staging/stg_customers.sql"), query_sql="SELECT 1", config=CompileModelConfig(values={}), destination=target, diff --git a/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/target_validation/test_main.py b/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/target_validation/test_main.py index 7dc1c10e46..b752933cad 100644 --- a/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/target_validation/test_main.py +++ b/tests/unit/src/sqlbuild/compiler/pipeline/_helpers/target_validation/test_main.py @@ -69,8 +69,8 @@ def test_given_resolved_clone_connection_when_validating_loaders_then_origin_cre local_config=LocalConfig(), source_files=( DiscoveredSourceFile( - file_path=Path("sources/managed.yml"), - relative_path=Path("sources/managed.yml"), + file_path=Path("sql/sources/managed.yml"), + relative_path=Path("sql/sources/managed.yml"), contents="", source_entries=(SourceEntry(name="managed", managed=True),), ), diff --git a/tests/unit/src/sqlbuild/compiler/pipeline/main/helpers.py b/tests/unit/src/sqlbuild/compiler/pipeline/main/helpers.py index 5b94a917f1..68c74b9078 100644 --- a/tests/unit/src/sqlbuild/compiler/pipeline/main/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/pipeline/main/helpers.py @@ -45,8 +45,8 @@ def relation_target_python_node() -> None: def build_relation_target_project() -> CompiledProjectView: source_entry: SourceEntry = SourceEntry(name="orders", schema="load_raw", table="orders") source_file: DiscoveredSourceFile = DiscoveredSourceFile( - file_path=Path("sources/raw.yml"), - relative_path=Path("sources/raw.yml"), + file_path=Path("sql/sources/raw.yml"), + relative_path=Path("sql/sources/raw.yml"), contents="", source_entries=(source_entry,), ) @@ -74,7 +74,7 @@ def build_plan_output_with_model(name: str = "orders") -> PlanOutput: entry: ModelPlanEntry = ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=MaterializationType.TABLE, action=PlanAction.CREATE_TABLE, reason=PlanReason.FIRST_RUN, diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/_test_types.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/_test_types.py index 248ce38c5d..c903e14ce5 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/_test_types.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/_test_types.py @@ -134,7 +134,7 @@ class SeedIdentityTestCase: seed_contents: str comparison_contents: str expected_same_identity: bool - seed_relative_path: Path = Path("seeds/orders.csv") + seed_relative_path: Path = Path("sql/seeds/orders.csv") @dataclass(frozen=True) diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/changes/_test_helpers.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/changes/_test_helpers.py index 9149c964a0..33ce28a809 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/changes/_test_helpers.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/changes/_test_helpers.py @@ -49,7 +49,7 @@ def build_model_from_test_case(test_case: DetectModelChangesTestCase) -> Compile key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=test_case.model_name), deps=(), name=test_case.model_name, - relative_path=Path(f"models/{test_case.model_name}.sql"), + relative_path=Path(f"sql/models/{test_case.model_name}.sql"), query_sql=test_case.query_sql, config=CompileModelConfig(values=test_case.config_values), destination=CompiledRelationLocation( @@ -71,7 +71,7 @@ def build_model_from_metadata_test_case( for dep_name in test_case.deps ), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql="SELECT 1 AS order_id", config=CompileModelConfig(values=test_case.config_values), destination=CompiledRelationLocation( @@ -147,7 +147,7 @@ def build_project_for_function_metadata_detection() -> CompiledProjectView: key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), deps=(function_key,), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql="SELECT is_large_order(amount) AS large_order FROM orders", config=CompileModelConfig(values={}), destination=CompiledRelationLocation( @@ -164,7 +164,7 @@ def build_project_for_function_metadata_detection() -> CompiledProjectView: key=function_key, deps=(), name="is_large_order", - relative_path=Path("functions/is_large_order.sql"), + relative_path=Path("sql/functions/is_large_order.sql"), arguments=(FunctionArgument(name="amount", type="INTEGER"),), returns="BOOLEAN", body_sql="amount > 100", diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/helpers.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/helpers.py index e03ad224b8..bb33504fb5 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/helpers.py @@ -106,7 +106,7 @@ def microbatch_model_with_cursor_end( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), deps=(), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql="SELECT 1", references=(), config=CompileModelConfig( @@ -181,7 +181,7 @@ def build_selection_model( key=key, deps=(), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), query_sql="SELECT 1", config=CompileModelConfig(values=values), destination=CompiledRelationLocation( @@ -228,8 +228,8 @@ def build_source_load_nodes_project() -> CompiledProjectView: name="raw_orders", source_entry=raw_orders_entry, source_file=DiscoveredSourceFile( - file_path=Path("sources/raw.yml"), - relative_path=Path("sources/raw.yml"), + file_path=Path("sql/sources/raw.yml"), + relative_path=Path("sql/sources/raw.yml"), contents="", source_entries=(raw_orders_entry,), ), @@ -237,16 +237,16 @@ def build_source_load_nodes_project() -> CompiledProjectView: ), loader_functions=( DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name="fetch_orders", function=fetch_orders, destination="staging_fetch_orders", write_strategy=SourceWriteStrategy.TABLE, ), DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name="load_orders", function=load_orders, depends_on=(fetch_orders,), @@ -306,7 +306,7 @@ def build_test_project( ) for d in dep_names ) - rel_path: str = effective_paths.get(model_name, f"models/{model_name}.sql") + rel_path: str = effective_paths.get(model_name, f"sql/models/{model_name}.sql") models.append( CompiledModel( key=model_key(model_name), @@ -334,7 +334,7 @@ def build_test_project( name=source_name, source_entry=source_entry, source_file=DiscoveredSourceFile( - file_path=Path(f"sources/{source_name}.yml"), + file_path=Path(f"sql/sources/{source_name}.yml"), relative_path=Path(source_name), contents="", source_entries=(source_entry,), @@ -351,8 +351,8 @@ def build_test_project( deps=(), name=seed_name, seed_file=DiscoveredSeedFile( - file_path=Path(f"seeds/{seed_name}.csv"), - relative_path=Path(f"seeds/{seed_name}.csv"), + file_path=Path(f"sql/seeds/{seed_name}.csv"), + relative_path=Path(f"sql/seeds/{seed_name}.csv"), ), schema_entry=SchemaSeedEntry(name=seed_name, columns=()), schema_file=_stub_schema_file(), @@ -370,7 +370,7 @@ def build_test_project( key=function_key(function_name), deps=(), name=function_name, - relative_path=Path(f"functions/sql/{function_name}.sql"), + relative_path=Path(f"sql/functions/sql/{function_name}.sql"), arguments=(), returns="BOOLEAN", body_sql="SELECT TRUE", @@ -460,8 +460,8 @@ def build_test_project( name=f"{model_name}_audit", definition_name="test_audit", audit_file=DiscoveredAuditFile( - file_path=Path("audits/generic/test.sql"), - relative_path=Path("audits/generic/test.sql"), + file_path=Path("sql/audits/generic/test.sql"), + relative_path=Path("sql/audits/generic/test.sql"), contents="", blocks=(), ), @@ -753,8 +753,8 @@ def build_test_project_with_source_entry(source_entry: SourceEntry) -> CompiledP name=source_entry.name, source_entry=source_entry, source_file=DiscoveredSourceFile( - file_path=Path("sources/raw.yml"), - relative_path=Path("sources/raw.yml"), + file_path=Path("sql/sources/raw.yml"), + relative_path=Path("sql/sources/raw.yml"), contents="", source_entries=(source_entry,), ), @@ -782,7 +782,7 @@ def build_source_cursor_input_model( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="test_model"), deps=(), name="test_model", - relative_path=Path("models/test_model.sql"), + relative_path=Path("sql/models/test_model.sql"), query_sql="SELECT 1", references=( CompileSqlReference( @@ -809,7 +809,7 @@ def build_transitive_watermark_models( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders_view"), deps=(), name="orders_view", - relative_path=Path("models/orders_view.sql"), + relative_path=Path("sql/models/orders_view.sql"), query_sql='SELECT * FROM __source("raw_orders")', references=(CompileSqlReference(ref_kind=SqlReferenceKind.SOURCE, ref_name="raw_orders"),), config=CompileModelConfig(values={"materialized": "view"}), @@ -826,7 +826,7 @@ def build_transitive_watermark_models( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="test_model"), deps=(), name="test_model", - relative_path=Path("models/test_model.sql"), + relative_path=Path("sql/models/test_model.sql"), query_sql='SELECT * FROM __ref("orders_view")', references=(CompileSqlReference(ref_kind=SqlReferenceKind.REF, ref_name="orders_view"),), config=CompileModelConfig( @@ -874,7 +874,7 @@ def build_function_transitive_watermark_models( key=CompiledObjectKey(resource_type=CompiledResourceType.TABLE_FN, name=function_name), deps=(), name=function_name, - relative_path=Path(f"functions/sql/{function_name}.sql"), + relative_path=Path(f"sql/functions/sql/{function_name}.sql"), arguments=(), returns="TABLE (order_id INTEGER)", body_sql='SELECT * FROM __ref("orders_view")', @@ -906,7 +906,7 @@ def build_cursor_input_contract_models( ), deps=(), name=test_case.reference_name, - relative_path=Path(f"models/{test_case.reference_name}.sql"), + relative_path=Path(f"sql/models/{test_case.reference_name}.sql"), query_sql="SELECT 1", config=CompileModelConfig(values={"contract": test_case.upstream_contract}), inferred_columns=test_case.compiled_inferred_columns, @@ -987,7 +987,7 @@ def build_strategy_model(test_case: ResolveModelPlanActionTestCase) -> CompiledM key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="test_model"), deps=(), name="test_model", - relative_path=Path("models/test_model.sql"), + relative_path=Path("sql/models/test_model.sql"), query_sql="SELECT 1", config=CompileModelConfig(values=config_values), destination=CompiledRelationLocation( @@ -1027,7 +1027,7 @@ def build_strategy_error_model(test_case: IncrementalStrategyErrorTestCase) -> C key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="test_model"), deps=(), name="test_model", - relative_path=Path("models/test_model.sql"), + relative_path=Path("sql/models/test_model.sql"), query_sql="SELECT 1", config=CompileModelConfig(values=config_values), destination=CompiledRelationLocation( @@ -1078,8 +1078,8 @@ def build_audit_from_test_case( scope_deps=(), name="test_audit", audit_file=DiscoveredAuditFile( - file_path=Path("audits/generic/test.sql"), - relative_path=Path("audits/generic/test.sql"), + file_path=Path("sql/audits/generic/test.sql"), + relative_path=Path("sql/audits/generic/test.sql"), contents="", blocks=(), ), @@ -1132,7 +1132,7 @@ def build_cursor_override_model(cursor_type: str | None) -> CompiledModelView: key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="test_model"), deps=(), name="test_model", - relative_path=Path("models/test_model.sql"), + relative_path=Path("sql/models/test_model.sql"), query_sql="SELECT 1", config=CompileModelConfig(values=config_values), destination=CompiledRelationLocation( @@ -1163,7 +1163,7 @@ def build_microbatch_lookback_model( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="test_model"), deps=(), name="test_model", - relative_path=Path("models/test_model.sql"), + relative_path=Path("sql/models/test_model.sql"), query_sql="SELECT 1", config=CompileModelConfig(values=config_values), destination=CompiledRelationLocation( @@ -1185,7 +1185,7 @@ def build_compiled_function(*, body_sql: str, target_schema: str = "main") -> Co ), deps=(), name="is_completed_order", - relative_path=Path("functions/sql/is_completed_order.sql"), + relative_path=Path("sql/functions/sql/is_completed_order.sql"), arguments=(FunctionArgument(name="order_status", type="STRING"),), returns="BOOLEAN", body_sql=body_sql, @@ -1225,8 +1225,8 @@ def _stub_schema_file() -> DiscoveredSchemaFile: """Return a minimal schema file stub for seed construction.""" return DiscoveredSchemaFile( - file_path=Path("seeds/schema.yml"), - relative_path=Path("seeds/schema.yml"), + file_path=Path("sql/seeds/schema.yml"), + relative_path=Path("sql/seeds/schema.yml"), contents="", model_entries=(), seed_entries=(), @@ -1242,8 +1242,8 @@ def build_scheduling_audit( """Build a minimal CompiledAudit for scheduling tests.""" stub_file: DiscoveredAuditFile = DiscoveredAuditFile( - file_path=Path("audits/singular/check.sql"), - relative_path=Path("audits/singular/check.sql"), + file_path=Path("sql/audits/singular/check.sql"), + relative_path=Path("sql/audits/singular/check.sql"), contents="", blocks=(), ) @@ -1310,11 +1310,13 @@ def build_seed_identity_compiled_seed( key=CompiledObjectKey(resource_type=CompiledResourceType.SEED, name="orders"), deps=(), name="orders", - seed_file=DiscoveredSeedFile(file_path=file_path, relative_path=Path("seeds/orders.csv")), + seed_file=DiscoveredSeedFile( + file_path=file_path, relative_path=Path("sql/seeds/orders.csv") + ), schema_entry=schema_entry, schema_file=DiscoveredSchemaFile( file_path=file_path.parent / "schema.yml", - relative_path=Path("seeds/schema.yml"), + relative_path=Path("sql/seeds/schema.yml"), contents="", model_entries=(), seed_entries=(schema_entry,), diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/migrations/test_column_migration_candidates.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/migrations/test_column_migration_candidates.py index b879b91b7d..fc84d03e51 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/migrations/test_column_migration_candidates.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/migrations/test_column_migration_candidates.py @@ -54,7 +54,7 @@ def test_given_untokenizable_tracked_model_when_planning_column_migrations_then_ key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), deps=(), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql=test_case.query_sql, config=CompileModelConfig(values=dict(BASE_CONFIG)), destination=CompiledRelationLocation( diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/planning/helpers.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/planning/helpers.py index 29ef26a7c7..6ab3ac30ec 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/planning/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/planning/helpers.py @@ -126,7 +126,7 @@ def _retention_model( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), deps=(), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), query_sql="SELECT 1 AS order_id", config=CompileModelConfig( values=config_values, @@ -153,7 +153,7 @@ def build_full_refresh_model(*, config_values: dict[str, object]) -> CompiledMod key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="order_history"), deps=(), name="order_history", - relative_path=Path("models/order_history.sql"), + relative_path=Path("sql/models/order_history.sql"), query_sql="SELECT 1 AS id", config=CompileModelConfig( values={"materialized": "incremental", "incremental_strategy": "merge", **config_values} diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/helpers.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/helpers.py index 2abbe1a717..f3a896805f 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/helpers.py @@ -24,7 +24,7 @@ def build_cursor_intrinsic_model(*, config_values: dict[str, object]) -> Compile key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="events"), deps=(), name="events", - relative_path=Path("models/events.sql"), + relative_path=Path("sql/models/events.sql"), query_sql="SELECT __cursor_start() AS batch_start, __cursor_end() AS batch_end", config=CompileModelConfig(values=config_values), destination=CompiledRelationLocation( @@ -84,7 +84,7 @@ def build_cursor_models( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), deps=(), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), query_sql="SELECT 1", config=CompileModelConfig(values=_cursor_model_config_values(cursor_type=cursor_type)), destination=CompiledRelationLocation( diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py index e636b48fa0..cea69cc114 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py @@ -291,7 +291,7 @@ def build_test_and_project( ) ), name=model_name, - relative_path=Path(f"models/{model_name}.sql"), + relative_path=Path(f"sql/models/{model_name}.sql"), query_sql=query_sql, config=CompileModelConfig(), destination=CompiledRelationLocation( @@ -315,7 +315,7 @@ def build_test_and_project( ), deps=(), name=function_name, - relative_path=Path(f"functions/sql/{function_name}.sql"), + relative_path=Path(f"sql/functions/sql/{function_name}.sql"), arguments=(), returns="BOOLEAN", body_sql="SELECT TRUE", @@ -342,7 +342,7 @@ def build_test_and_project( ), deps=(), name=function_name, - relative_path=Path(f"functions/sql/{function_name}.sql"), + relative_path=Path(f"sql/functions/sql/{function_name}.sql"), arguments=(), returns="TABLE", body_sql="SELECT 1 AS order_id", @@ -416,7 +416,7 @@ def _expand_model_query_overrides( for model_name, query_sql in test_case.model_macro_source_queries.items(): overrides[model_name] = expand_sql_macros( sql=query_sql, - file_path=Path(f"models/{model_name}.sql"), + file_path=Path(f"sql/models/{model_name}.sql"), loaded_macros=loaded_macros, macro_overrides=test_case.macro_mocks, macro_context=_MACRO_CONTEXT, @@ -446,8 +446,8 @@ def _build_loaded_macros(macro_outputs: dict[str, str]) -> dict[str, LoadedMacro for name, output in macro_outputs.items(): loaded_macros[name] = LoadedMacro( name=name, - file_path=Path("macros/python/test_macros.py"), - relative_path=Path("macros/python/test_macros.py"), + file_path=Path("sql/macros/python/test_macros.py"), + relative_path=Path("sql/macros/python/test_macros.py"), raw_source="", function=_macro_function(output), ) @@ -517,7 +517,7 @@ def build_cursor_model(*, cursor_type: str, cursor_grain: str | None) -> Compile key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="daily_orders"), deps=(), name="daily_orders", - relative_path=Path("models/daily_orders.sql"), + relative_path=Path("sql/models/daily_orders.sql"), query_sql=CURSOR_WINDOW_MODEL_SQL, config=CompileModelConfig(values=values), destination=CompiledRelationLocation( diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/test_plan_test.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/test_plan_test.py index 9fa5d39433..b20b6f11f7 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/test_plan_test.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/test_plan_test.py @@ -1052,7 +1052,7 @@ def test_given_udf_sql_test_when_planning_then_compares_resolved_actual_to_expec ), deps=(), name="format_cents", - relative_path=Path("functions/sql/format_cents.sql"), + relative_path=Path("sql/functions/sql/format_cents.sql"), arguments=(), returns="VARCHAR", body_sql="", @@ -1183,7 +1183,7 @@ def test_given_table_function_sql_test_when_planning_then_compares_resolved_actu ), deps=(), name="customer_orders", - relative_path=Path("functions/sql/customer_orders.sql"), + relative_path=Path("sql/functions/sql/customer_orders.sql"), arguments=(), returns="TABLE", body_sql="", diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_microbatch_limit.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_microbatch_limit.py index 69561d341c..4f8102f12e 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_microbatch_limit.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_microbatch_limit.py @@ -64,7 +64,7 @@ def test_given_nested_model_policy_when_applying_outer_limit_then_precedence_is_ entry: ModelPlanEntry = ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="events"), name="events", - relative_path=Path("models/events.sql"), + relative_path=Path("sql/models/events.sql"), materialization_type=MaterializationType.INCREMENTAL, action=PlanAction.INCREMENTAL_DELETE_INSERT, reason=PlanReason.NORMAL_INCREMENTAL, @@ -125,7 +125,7 @@ def test_given_coarse_effective_grain_when_applying_limit_then_authored_batch_se entry: ModelPlanEntry = ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="events"), name="events", - relative_path=Path("models/events.sql"), + relative_path=Path("sql/models/events.sql"), materialization_type=MaterializationType.INCREMENTAL, action=PlanAction.INCREMENTAL_DELETE_INSERT, reason=PlanReason.NORMAL_INCREMENTAL, @@ -251,7 +251,7 @@ def test_given_planner_owned_range_when_applying_limit_then_expected_decision_is entry: ModelPlanEntry = ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="events"), name="events", - relative_path=Path("models/events.sql"), + relative_path=Path("sql/models/events.sql"), materialization_type=MaterializationType.INCREMENTAL, action=PlanAction(test_case.plan_action), reason=PlanReason.NORMAL_INCREMENTAL, @@ -302,7 +302,7 @@ def test_given_excess_planner_owned_range_when_action_is_error_then_planning_fai entry: ModelPlanEntry = ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="events"), name="events", - relative_path=Path("models/events.sql"), + relative_path=Path("sql/models/events.sql"), materialization_type=MaterializationType.INCREMENTAL, action=PlanAction.INCREMENTAL_DELETE_INSERT, reason=PlanReason.NORMAL_INCREMENTAL, diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_plan_entry_cursor_overrides.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_plan_entry_cursor_overrides.py index 2f865bed7e..fc06953cfc 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_plan_entry_cursor_overrides.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_plan_entry_cursor_overrides.py @@ -137,7 +137,7 @@ def test_given_explicit_cursor_overrides_without_snapshot_when_planning_then_use key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), deps=(), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql="SELECT 1", references=(), config=CompileModelConfig( @@ -212,7 +212,7 @@ def test_given_runtime_owned_missing_snapshot_when_overrides_complete_then_all_r key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), deps=(), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql="SELECT 1", references=(), config=CompileModelConfig( @@ -316,7 +316,7 @@ def test_given_planner_owned_model_backed_input_when_grain_is_coarser_then_range key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="hourly_context"), deps=(), name="hourly_context", - relative_path=Path("models/hourly_context.sql"), + relative_path=Path("sql/models/hourly_context.sql"), query_sql="SELECT 1", references=(), config=CompileModelConfig( @@ -392,7 +392,7 @@ def test_given_snapshot_cursor_grain_when_planning_then_dml_bound_matches_query_ key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), deps=(), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql="SELECT 1", references=(), config=CompileModelConfig( diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_scenario_relations.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_scenario_relations.py index ebbe6f1b10..ab029f700c 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_scenario_relations.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_scenario_relations.py @@ -398,7 +398,7 @@ def notify() -> None: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/notify.py"), + relative_path=Path("sql/hooks/python/notify.py"), name="notify", function=notify, ), diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_selectors.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_selectors.py index ebb507e2dd..8c9e5240a2 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_selectors.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_selectors.py @@ -19,8 +19,8 @@ BuildPathIndexTestCase( description="strips models prefix from relative paths", model_paths={ - "stg_orders": "models/staging/stg_orders.sql", - "fact_orders": "models/marts/fact_orders.sql", + "stg_orders": "sql/models/staging/stg_orders.sql", + "fact_orders": "sql/models/marts/fact_orders.sql", }, expected_folders={ "stg_orders": "staging", @@ -30,7 +30,7 @@ BuildPathIndexTestCase( description="handles nested subdirectories", model_paths={ - "deep_model": "models/staging/raw/deep_model.sql", + "deep_model": "sql/models/staging/raw/deep_model.sql", }, expected_folders={ "deep_model": "staging/raw", @@ -39,7 +39,7 @@ BuildPathIndexTestCase( description="handles models at top level models dir", model_paths={ - "top_model": "models/top_model.sql", + "top_model": "sql/models/top_model.sql", }, expected_folders={ "top_model": "", diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_source_load_nodes.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_source_load_nodes.py index c07609435c..079d211d0b 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_source_load_nodes.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/test_source_load_nodes.py @@ -179,7 +179,7 @@ def test_given_unselected_upstream_in_closure_when_filtering_metadata_then_uses_ key=selected_key, deps=(upstream_key,), name="fact_orders", - relative_path=Path("models/fact_orders.sql"), + relative_path=Path("sql/models/fact_orders.sql"), query_sql='SELECT * FROM __ref("stg_orders")', config=CompileModelConfig(), destination=CompiledRelationLocation( @@ -193,7 +193,7 @@ def test_given_unselected_upstream_in_closure_when_filtering_metadata_then_uses_ key=upstream_key, deps=(), name="stg_orders", - relative_path=Path("models/stg_orders.sql"), + relative_path=Path("sql/models/stg_orders.sql"), query_sql="SELECT 1 AS id", config=CompileModelConfig(), destination=CompiledRelationLocation( diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/helpers.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/helpers.py index ab6f66dfcd..f146b7b6ba 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/helpers.py @@ -52,7 +52,7 @@ def check_one_source_table( source_entry=source, source_file=DiscoveredSourceFile( file_path=Path("/project/sources/raw.yml"), - relative_path=Path("sources/raw.yml"), + relative_path=Path("sql/sources/raw.yml"), contents=f"sources:\n - name: {source.name}\n", source_entries=(source,), ), diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/test_semantic_sources.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/test_semantic_sources.py index e902fa4d8d..ea4fc591fa 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/test_semantic_sources.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/test_semantic_sources.py @@ -55,8 +55,8 @@ def test_given_multiple_missing_source_schemas_when_inspecting_then_metadata_is_ tmp_path, { "sqlbuild_project.toml": 'name = "source_batch"\nadapter = "duckdb"\n', - "sources/orders.yml": "sources:\n - name: orders\n description: Test source orders.\n table: orders\n - name: customers\n description: Test source customers.\n table: customers\n", - "models/combined.sql": 'MODEL (description "Test model combined.");\nSELECT o.id FROM __source("orders") o JOIN __source("customers") c ON o.id = c.id', + "sql/sources/orders.yml": "sources:\n - name: orders\n description: Test source orders.\n table: orders\n - name: customers\n description: Test source customers.\n table: customers\n", + "sql/models/combined.sql": 'MODEL (description "Test model combined.");\nSELECT o.id FROM __source("orders") o JOIN __source("customers") c ON o.id = c.id', }, ) adapter: DuckDbAdapter = DuckDbAdapter() @@ -108,11 +108,11 @@ def test_given_source_schema_case_differs_when_inspecting_then_columns_are_found tmp_path, { "sqlbuild_project.toml": 'name = "source_case"\nadapter = "duckdb"\n', - "sources/orders.yml": ( + "sql/sources/orders.yml": ( "sources:\n - name: orders\n description: Test source orders.\n" f" schema: {test_case.declared_schema}\n table: orders\n" ), - "models/open_orders.sql": 'MODEL (description "Test model open_orders.");\nSELECT id FROM __source("orders")', + "sql/models/open_orders.sql": 'MODEL (description "Test model open_orders.");\nSELECT id FROM __source("orders")', }, ) adapter: DuckDbAdapter = DuckDbAdapter() diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/test_source_tables.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/test_source_tables.py index f2918437ce..cbce77a5f8 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/test_source_tables.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/warehouse/test_source_tables.py @@ -168,7 +168,7 @@ def test_given_source_probe_not_found_when_checking_then_raises_s405( assert raised.value.code == "S405" assert all(fragment in raised.value.message for fragment in test_case.expected_error_fragments) assert test_case.expected_help_fragment in str(raised.value.help) - assert "sources/raw.yml:2" in str(raised.value.help) + assert "sql/sources/raw.yml:2" in str(raised.value.help) assert test_case.unexpected_output_fragment not in raised.value.message + str(raised.value.help) assert tuple(connection.statements) == test_case.expected_probe_statements diff --git a/tests/unit/src/sqlbuild/compiler/planner/classes/test_sql_test_planning_exit.py b/tests/unit/src/sqlbuild/compiler/planner/classes/test_sql_test_planning_exit.py index a5be2b5415..e14a5125f9 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/classes/test_sql_test_planning_exit.py +++ b/tests/unit/src/sqlbuild/compiler/planner/classes/test_sql_test_planning_exit.py @@ -93,19 +93,19 @@ def test_given_sql_test_planning_running_when_interpreter_finalizes_then_process tmp_path: Path, ) -> None: project_dir: Path = tmp_path / "orders_project" - (project_dir / "models").mkdir(parents=True) + (project_dir / "sql" / "models").mkdir(parents=True) (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders_project"\nadapter = "duckdb"\n\n' '[connection]\ndatabase = "orders_project.duckdb"\n', encoding="utf-8", ) - (project_dir / "sources").mkdir() - (project_dir / "sources" / "raw.yml").write_text( + (project_dir / "sql" / "sources").mkdir(parents=True) + (project_dir / "sql" / "sources" / "raw.yml").write_text( "sources:\n - name: raw_orders\n description: Test source raw_orders.\n" " schema: raw\n table: orders\n", encoding="utf-8", ) - (project_dir / "models" / "orders.sql").write_text( + (project_dir / "sql" / "models" / "orders.sql").write_text( "MODEL (description 'Test model orders.', materialized table);\n\n" 'SELECT * FROM __source("raw_orders")\n', encoding="utf-8", diff --git a/tests/unit/src/sqlbuild/compiler/planner/main/execution/test_display_plan.py b/tests/unit/src/sqlbuild/compiler/planner/main/execution/test_display_plan.py index f0a04e69af..6d19da6816 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/main/execution/test_display_plan.py +++ b/tests/unit/src/sqlbuild/compiler/planner/main/execution/test_display_plan.py @@ -63,7 +63,7 @@ def test_given_incremental_override_when_building_display_plan_then_uses_effecti key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), deps=(), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql="SELECT 1 AS id", config=CompileModelConfig( values={ diff --git a/tests/unit/src/sqlbuild/compiler/planner/main/helpers.py b/tests/unit/src/sqlbuild/compiler/planner/main/helpers.py index 8f720e8ac6..b9208ad384 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/main/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/planner/main/helpers.py @@ -73,7 +73,7 @@ def build_protected_schema_replay_project() -> CompiledProjectView: key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="order_history"), deps=(), name="order_history", - relative_path=Path("models/order_history.sql"), + relative_path=Path("sql/models/order_history.sql"), query_sql="SELECT 1 AS id, 2 AS amount", config=CompileModelConfig( values={ diff --git a/tests/unit/src/sqlbuild/compiler/planner/main/identity/helpers.py b/tests/unit/src/sqlbuild/compiler/planner/main/identity/helpers.py index f00f738166..d196323318 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/main/identity/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/planner/main/identity/helpers.py @@ -102,7 +102,7 @@ def _build_model( key=key, deps=deps, name=key.name, - relative_path=Path(f"models/{key.name}.sql"), + relative_path=Path(f"sql/models/{key.name}.sql"), query_sql=query_sql, config=CompileModelConfig(), destination=CompiledRelationLocation( diff --git a/tests/unit/src/sqlbuild/compiler/planner/main/identity/test_version_identity_hooks.py b/tests/unit/src/sqlbuild/compiler/planner/main/identity/test_version_identity_hooks.py index 0b107bd78a..24f56b037a 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/main/identity/test_version_identity_hooks.py +++ b/tests/unit/src/sqlbuild/compiler/planner/main/identity/test_version_identity_hooks.py @@ -17,7 +17,7 @@ _RECORD_ACCESS: SqlHookEntry = SqlHookEntry( statement="INSERT INTO order_audit SELECT 'orders'", name="record_order_access", - relative_path=Path("hooks/sql/record_order_access.sql"), + relative_path=Path("sql/hooks/sql/record_order_access.sql"), definition_sql="INSERT INTO order_audit SELECT {{ table_name }}", kwargs={"table_name": "'orders'"}, description="Record order table access", @@ -42,7 +42,7 @@ "pre_hooks": [ replace( _RECORD_ACCESS, - relative_path=Path("hooks/sql/audit/record_order_access.sql"), + relative_path=Path("sql/hooks/sql/audit/record_order_access.sql"), ) ] }, @@ -128,7 +128,7 @@ def test_given_hook_change_when_building_model_identity_then_tracks_only_executi ), forbidden_fragments=( "Record order table access", - "hooks/sql/record_order_access.sql", + "sql/hooks/sql/record_order_access.sql", '"description"', '"relative_path"', ), diff --git a/tests/unit/src/sqlbuild/compiler/planner/main/test_execution.py b/tests/unit/src/sqlbuild/compiler/planner/main/test_execution.py index fadd90f751..7a5a095a33 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/main/test_execution.py +++ b/tests/unit/src/sqlbuild/compiler/planner/main/test_execution.py @@ -92,7 +92,7 @@ def notify() -> None: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/notify.py"), + relative_path=Path("sql/hooks/python/notify.py"), name="notify", function=notify, ), diff --git a/tests/unit/src/sqlbuild/compiler/planner/main/test_static_command_planning.py b/tests/unit/src/sqlbuild/compiler/planner/main/test_static_command_planning.py index 25c7b68d35..2cec66f0e7 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/main/test_static_command_planning.py +++ b/tests/unit/src/sqlbuild/compiler/planner/main/test_static_command_planning.py @@ -146,7 +146,7 @@ def test_given_selected_seed_when_planning_then_identity_and_reason_are_preserve project.seeds[0], seed_file=DiscoveredSeedFile( file_path=seed_path, - relative_path=Path("seeds/countries.csv"), + relative_path=Path("sql/seeds/countries.csv"), ), ), ), @@ -215,7 +215,7 @@ def test_given_selected_seed_without_state_table_when_reading_reason_then_only_s project.seeds[0], seed_file=DiscoveredSeedFile( file_path=seed_path, - relative_path=Path("seeds/countries.csv"), + relative_path=Path("sql/seeds/countries.csv"), ), destination=replace(project.seeds[0].destination, schema="analytics"), ) diff --git a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/helpers.py b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/helpers.py index 140f04c412..04d12c317a 100644 --- a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/helpers.py @@ -119,7 +119,7 @@ def build_terminal_loader_python_node_graph() -> PythonNodeGraph: loader_functions=( DiscoveredLoaderFunction( file_path=Path("/project/loaders/orders.py"), - relative_path=Path("python/loaders/orders.py"), + relative_path=Path("python/nodes/loaders/orders.py"), name="raw_orders", function=raw_orders, ), @@ -136,7 +136,7 @@ def build_orders_python_node_graph() -> PythonNodeGraph: loader_functions=( DiscoveredLoaderFunction( file_path=Path("/project/loaders/events.py"), - relative_path=Path("python/loaders/events.py"), + relative_path=Path("python/nodes/loaders/events.py"), name="load_events", function=load_events, depends_on=(prepare_orders,), @@ -145,14 +145,14 @@ def build_orders_python_node_graph() -> PythonNodeGraph: asset_functions=( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="prepare_orders", function=prepare_orders, tags=("orders", "daily"), ), DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="export_orders", function=export_orders, depends_on=(imported_prepare_orders,), @@ -166,7 +166,7 @@ def build_orders_python_node_graph() -> PythonNodeGraph: check_functions=( DiscoveredCheckFunction( file_path=Path("/project/checks/orders.py"), - relative_path=Path("python/checks/orders.py"), + relative_path=Path("python/nodes/checks/orders.py"), name="check_orders_export", function=check_orders_export, depends_on=(export_orders,), @@ -185,7 +185,7 @@ def write_python_identity_repo(*, project_dir: Path, repo_files: dict[str, str]) file_path: Path = project_dir / relative_path file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(contents, encoding="utf-8") - (project_dir / ".git").mkdir(exist_ok=True) + (project_dir / ".git").mkdir(parents=True, exist_ok=True) def load_python_identity_module( @@ -257,7 +257,7 @@ def build_sql_ref_python_node_graph(*, dependency: SqlResourceRef) -> PythonNode asset_functions=( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="profile_orders", function=prepare_orders, depends_on=(dependency,), @@ -277,14 +277,14 @@ def build_sibling_sql_ref_python_node_graph() -> PythonNodeGraph: asset_functions=( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="export_orders", function=prepare_orders, depends_on=(model_ref("orders"),), ), DiscoveredAssetFunction( file_path=Path("/project/tasks/raw.py"), - relative_path=Path("python/tasks/raw.py"), + relative_path=Path("python/nodes/tasks/raw.py"), name="export_raw_orders", function=prepare_orders, depends_on=(source_ref("raw_orders"),), @@ -302,7 +302,7 @@ def build_sql_downstream_asset_to_loader_python_node_graph() -> PythonNodeGraph: loader_functions=( DiscoveredLoaderFunction( file_path=Path("/project/loaders/orders.py"), - relative_path=Path("python/loaders/orders.py"), + relative_path=Path("python/nodes/loaders/orders.py"), name="load_events", function=load_events, depends_on=(prepare_orders,), @@ -311,7 +311,7 @@ def build_sql_downstream_asset_to_loader_python_node_graph() -> PythonNodeGraph: asset_functions=( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="prepare_orders", function=prepare_orders, depends_on=(model_ref("orders"),), @@ -370,13 +370,13 @@ def _build_loader_dependency_python_node_graph( intermediate_loaders: tuple[DiscoveredLoaderFunction, ...] = ( DiscoveredLoaderFunction( file_path=Path("/project/loaders/events.py"), - relative_path=Path("python/loaders/events.py"), + relative_path=Path("python/nodes/loaders/events.py"), name="fetch_pages", function=fetch_pages, ), DiscoveredLoaderFunction( file_path=Path("/project/loaders/events.py"), - relative_path=Path("python/loaders/events.py"), + relative_path=Path("python/nodes/loaders/events.py"), name="load_events", function=load_events, depends_on=(fetch_pages,), @@ -385,7 +385,7 @@ def _build_loader_dependency_python_node_graph( terminal_loaders: tuple[DiscoveredLoaderFunction, ...] = ( DiscoveredLoaderFunction( file_path=Path("/project/loaders/events.py"), - relative_path=Path("python/loaders/events.py"), + relative_path=Path("python/nodes/loaders/events.py"), name="raw_orders", function=raw_orders, ), @@ -398,7 +398,7 @@ def _build_loader_dependency_python_node_graph( asset_functions: tuple[DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="export_orders", function=export_orders, depends_on=(dependency_function,), @@ -407,7 +407,7 @@ def _build_loader_dependency_python_node_graph( check_functions: tuple[DiscoveredCheckFunction, ...] = ( DiscoveredCheckFunction( file_path=Path("/project/checks/orders.py"), - relative_path=Path("python/checks/orders.py"), + relative_path=Path("python/nodes/checks/orders.py"), name="check_loaded_orders", function=check_loaded_orders, depends_on=(dependency_function,), @@ -460,7 +460,7 @@ def build_orders_project_graph() -> ProjectGraph: ) source_file: DiscoveredSourceFile = DiscoveredSourceFile( file_path=Path("/project/sources/raw.yml"), - relative_path=Path("sources/raw.yml"), + relative_path=Path("sql/sources/raw.yml"), contents="sources: []\n", source_entries=(), ) @@ -475,7 +475,7 @@ def build_orders_project_graph() -> ProjectGraph: key=orders_key, deps=(raw_orders_key,), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql='select * from __source("raw_orders")', config=CompileModelConfig(values={"tags": ["daily"]}), destination=CompiledRelationLocation( @@ -555,7 +555,7 @@ def imported_identity_nodes( file_path: Path = package_dir / relative_path file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_bytes(contents) - (project_dir / ".git").mkdir() + (project_dir / ".git").mkdir(parents=True) try: with pytest.MonkeyPatch.context() as patch: patch.syspath_prepend(str(project_dir)) @@ -600,7 +600,7 @@ def identity_summary( _DOMAINS: tuple[str, ...] = ("orders", "customers", "inventory", "fulfillment", "support") _SHARED_PROJECT_FILES: dict[str, str] = { - "providers/warehouse_api/provider.py": '''"""Warehouse API client.""" + "python/providers/warehouse_api/provider.py": '''"""Warehouse API client.""" from sqlbuild.providers import Provider @@ -611,7 +611,7 @@ class WarehouseApi(Provider): def page_size(self) -> int: return 100 ''', - "python/shared/text.py": '''"""Text helpers.""" + "python/nodes/shared/text.py": '''"""Text helpers.""" def normalize_text(value: str) -> str: @@ -621,9 +621,9 @@ def normalize_text(value: str) -> str: def clean_status(value: str) -> str: return normalize_text(value).replace("-", "_") ''', - "python/shared/money.py": '''"""Money helpers.""" + "python/nodes/shared/money.py": '''"""Money helpers.""" -from python.shared.text import normalize_text +from python.nodes.shared.text import normalize_text class Money: @@ -649,8 +649,8 @@ def to_units(cents: int) -> float: def _domain_rows(domain: str) -> str: return f'''"""{domain.title()} row helpers.""" -from python.shared.money import Ledger, Money -from python.shared.text import clean_status +from python.nodes.shared.money import Ledger, Money +from python.nodes.shared.text import clean_status class RowBatch: @@ -668,13 +668,13 @@ def map_row(raw: dict[str, str]) -> dict[str, object]: def _node_files(domain: str, index: int) -> dict[str, str]: name: str = f"{domain}_sync_{index:03d}" - folder: str = f"python/{domain}/{name}" + folder: str = f"python/nodes/{domain}/{name}" return { - f"{folder}/node.py": f'''"""Sync {domain} batch {index}.""" + f"{folder}/asset.py": f'''"""Sync {domain} batch {index}.""" -from providers.warehouse_api.provider import WarehouseApi -from python.{domain}._helpers.rows import RowBatch -from python.{domain}.{name}.main import main +from python.providers.warehouse_api.provider import WarehouseApi +from python.nodes.{domain}._helpers.rows import RowBatch +from python.nodes.{domain}.{name}.main import main from sqlbuild.assets import asset @@ -685,7 +685,7 @@ def {name}(ctx, warehouse_api: WarehouseApi): ''', f"{folder}/main.py": f'''"""Sync {domain} batch {index}.""" -from python.{domain}._helpers.rows import RowBatch +from python.nodes.{domain}._helpers.rows import RowBatch def main(*, ctx, warehouse_api): @@ -701,7 +701,7 @@ def _write_shared_project( shared: dict[str, str] = dict(_SHARED_PROJECT_FILES) for domain in _DOMAINS: - shared[f"python/{domain}/_helpers/rows.py"] = _domain_rows(domain) + shared[f"python/nodes/{domain}/_helpers/rows.py"] = _domain_rows(domain) nodes: dict[str, str] = {} for index in range(node_count): nodes.update(_node_files(_DOMAINS[index % len(_DOMAINS)], index)) @@ -709,7 +709,7 @@ def _write_shared_project( file_path: Path = project_dir / relative_path file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(contents, encoding="utf-8") - (project_dir / ".git").mkdir() + (project_dir / ".git").mkdir(parents=True) return ( {str((project_dir / path).resolve()): text for path, text in shared.items()}, {str((project_dir / path).resolve()): text for path, text in nodes.items()}, diff --git a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_identity.py b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_identity.py index 2cef3e4ea4..6a6ab2dd5c 100644 --- a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_identity.py +++ b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_identity.py @@ -18,6 +18,7 @@ load_python_identity_module, write_python_identity_repo, ) +from tests.unit.src.sqlbuild.python_nodes.helpers import node_module_files @pytest.mark.parametrize( @@ -26,7 +27,9 @@ PythonNodeIdentityTestCase( description="includes same-file helper dependency", repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ def normalize_order(value): return value.strip().lower() @@ -34,12 +37,13 @@ def normalize_order(value): def build_orders(ctx): return normalize_order(" Pending ") """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=("normalize_order",), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=("def normalize_order(value):", "source_text"), @@ -47,32 +51,41 @@ def build_orders(ctx): PythonNodeIdentityTestCase( description="includes transitive imported first-party helper dependencies", repo_files={ - "python/tasks/orders.py": """ -from python.helpers.cleaning import normalize_orders + **node_module_files( + "python/nodes/tasks/orders.py", + """ +from python.nodes.helpers.cleaning import normalize_orders def build_orders(ctx): return normalize_orders(ctx) """.strip() - + "\n", - "python/helpers/cleaning.py": """ -from python.helpers.status import clean_status + + "\n", + ), + **node_module_files( + "python/nodes/helpers/cleaning.py", + """ +from python.nodes.helpers.status import clean_status def normalize_orders(ctx): return clean_status(" Pending ") """.strip() - + "\n", - "python/helpers/status.py": """ + + "\n", + ), + **node_module_files( + "python/nodes/helpers/status.py", + """ def clean_status(value): return value.strip().lower() """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=("normalize_orders", "clean_status"), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=( @@ -84,24 +97,27 @@ def clean_status(value): PythonNodeIdentityTestCase( description="excludes helpers loaded from venv under git root", repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ import vendor_helpers def build_orders(ctx): return vendor_helpers.normalize_order(" Pending ") """.strip() - + "\n", + + "\n", + ), ".venv/lib/python3.12/site-packages/vendor_helpers.py": """ def normalize_order(value): return value.strip().lower() """.strip() + "\n", }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=(), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=("dependencies",), @@ -111,24 +127,27 @@ def normalize_order(value): PythonNodeIdentityTestCase( description="excludes helpers loaded from external third-party path", repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ import external_vendor_helpers def build_orders(ctx): return external_vendor_helpers.normalize_order(" Pending ") """.strip() - + "\n", + + "\n", + ), "../third_party/external_vendor_helpers.py": """ def normalize_order(value): return value.strip().lower() """.strip() + "\n", }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=(), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=("dependencies",), @@ -138,7 +157,9 @@ def normalize_order(value): PythonNodeIdentityTestCase( description="ignores stdlib builtins and dynamic references without crashing", repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ import json @@ -151,12 +172,13 @@ def build_orders(ctx): payload = json.dumps({"count": len([" Pending "])}) return globals()[helper_name](str(payload)) """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=(), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=("dependencies",), @@ -165,15 +187,20 @@ def build_orders(ctx): PythonNodeIdentityTestCase( description="terminates cyclic helper traversal", repo_files={ - "python/tasks/orders.py": """ -from python.helpers.cycle import helper_a + **node_module_files( + "python/nodes/tasks/orders.py", + """ +from python.nodes.helpers.cycle import helper_a def build_orders(ctx): return helper_a(" Pending ") """.strip() - + "\n", - "python/helpers/cycle.py": """ + + "\n", + ), + **node_module_files( + "python/nodes/helpers/cycle.py", + """ def helper_a(value): return helper_b(value) @@ -181,12 +208,13 @@ def helper_a(value): def helper_b(value): return helper_a(value) """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=("helper_a", "helper_b"), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=("def helper_a(value):", "def helper_b(value):"), @@ -194,24 +222,30 @@ def helper_b(value): PythonNodeIdentityTestCase( description="includes first-party module attribute helper dependency", repo_files={ - "python/tasks/orders.py": """ -from python.helpers import cleaning + **node_module_files( + "python/nodes/tasks/orders.py", + """ +from python.nodes.helpers import cleaning def build_orders(ctx): return cleaning.normalize_order(" Pending ") """.strip() - + "\n", - "python/helpers/cleaning.py": """ + + "\n", + ), + **node_module_files( + "python/nodes/helpers/cleaning.py", + """ def normalize_order(value): return value.strip().lower() """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=("normalize_order",), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=("def normalize_order(value):", "source_text"), @@ -219,7 +253,9 @@ def normalize_order(value): PythonNodeIdentityTestCase( description="includes first-party class constructor dependency", repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ class Cleaner: def clean(self, value): return value.strip().lower() @@ -228,12 +264,13 @@ def clean(self, value): def build_orders(ctx): return Cleaner().clean(" Pending ") """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=("Cleaner",), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=("class Cleaner:", "source_text"), @@ -241,7 +278,9 @@ def build_orders(ctx): PythonNodeIdentityTestCase( description="includes first-party class method dependency", repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ class Cleaner: @staticmethod def clean(value): @@ -251,12 +290,13 @@ def clean(value): def build_orders(ctx): return Cleaner.clean(" Pending ") """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=("Cleaner.clean",), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=("def clean(value):", "source_text"), @@ -264,30 +304,39 @@ def build_orders(ctx): PythonNodeIdentityTestCase( description="sorts dependencies deterministically by source path and qualname", repo_files={ - "python/tasks/orders.py": """ -from python.helpers.z_helpers import z_clean -from python.helpers.a_helpers import a_clean + **node_module_files( + "python/nodes/tasks/orders.py", + """ +from python.nodes.helpers.z_helpers import z_clean +from python.nodes.helpers.a_helpers import a_clean def build_orders(ctx): return z_clean(a_clean(" Pending ")) """.strip() - + "\n", - "python/helpers/z_helpers.py": """ + + "\n", + ), + **node_module_files( + "python/nodes/helpers/z_helpers.py", + """ def z_clean(value): return value.strip() """.strip() - + "\n", - "python/helpers/a_helpers.py": """ + + "\n", + ), + **node_module_files( + "python/nodes/helpers/a_helpers.py", + """ def a_clean(value): return value.lower() """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=("a_clean", "z_clean"), expected_definition_fragments=("def build_orders(ctx):", "source_text"), expected_metadata_fragments=("def a_clean(value):", "def z_clean(value):"), @@ -295,16 +344,19 @@ def a_clean(value): PythonNodeIdentityTestCase( description="stores decorator config in definition payload", repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ def build_orders(ctx): return None """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", - expected_source_path="python/tasks/orders.py", + expected_source_path="python/nodes/tasks/orders.py", expected_dependency_qualnames=(), expected_definition_fragments=("orders", "daily", "source_text"), expected_metadata_fragments=("dependencies",), @@ -313,7 +365,7 @@ def build_orders(ctx): PythonNodeIdentityTestCase( description="includes Python hook helper dependencies", repo_files={ - "hooks/python/orders.py": """ + "sql/hooks/python/orders.py": """ from sqlbuild.hooks import hook @@ -328,10 +380,10 @@ def before_orders(ctx): """.strip() + "\n", }, - entry_module_path="hooks/python/orders.py", + entry_module_path="sql/hooks/python/orders.py", function_name="before_orders", node_type="hook", - expected_source_path="hooks/python/orders.py", + expected_source_path="sql/hooks/python/orders.py", expected_dependency_qualnames=("audit_message",), expected_definition_fragments=("def before_orders(ctx):", "source_text"), expected_metadata_fragments=("def audit_message():", "source_text"), @@ -380,26 +432,32 @@ def test_given_python_node_when_building_identity_then_includes_expected_first_p PythonNodeIdentityChangeTestCase( description="nested function source changes update body and version identity", before_repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ def build_orders(ctx): def normalize_order(value): return value.strip().lower() return normalize_order(" Pending ") """.strip() - + "\n", + + "\n", + ), }, after_repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ def build_orders(ctx): def normalize_order(value): return value.strip().upper() return normalize_order(" Pending ") """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", expected_definition_hash_changed=True, @@ -408,36 +466,48 @@ def normalize_order(value): PythonNodeIdentityChangeTestCase( description="first-party helper source changes update version identity only", before_repo_files={ - "python/tasks/orders.py": """ -from python.helpers.cleaning import normalize_order + **node_module_files( + "python/nodes/tasks/orders.py", + """ +from python.nodes.helpers.cleaning import normalize_order def build_orders(ctx): return normalize_order(" Pending ") """.strip() - + "\n", - "python/helpers/cleaning.py": """ + + "\n", + ), + **node_module_files( + "python/nodes/helpers/cleaning.py", + """ def normalize_order(value): return value.strip().lower() """.strip() - + "\n", + + "\n", + ), }, after_repo_files={ - "python/tasks/orders.py": """ -from python.helpers.cleaning import normalize_order + **node_module_files( + "python/nodes/tasks/orders.py", + """ +from python.nodes.helpers.cleaning import normalize_order def build_orders(ctx): return normalize_order(" Pending ") """.strip() - + "\n", - "python/helpers/cleaning.py": """ + + "\n", + ), + **node_module_files( + "python/nodes/helpers/cleaning.py", + """ def normalize_order(value): return value.strip().upper() """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", expected_definition_hash_changed=False, @@ -446,20 +516,26 @@ def normalize_order(value): PythonNodeIdentityChangeTestCase( description="decorator config changes update body and version identity", before_repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ def build_orders(ctx): return None """.strip() - + "\n", + + "\n", + ), }, after_repo_files={ - "python/tasks/orders.py": """ + **node_module_files( + "python/nodes/tasks/orders.py", + """ def build_orders(ctx): return None """.strip() - + "\n", + + "\n", + ), }, - entry_module_path="python/tasks/orders.py", + entry_module_path="python/nodes/tasks/orders.py", function_name="build_orders", node_type="asset", expected_definition_hash_changed=True, @@ -476,8 +552,8 @@ def test_given_python_node_source_change_when_building_identity_then_hashes_chan ) -> None: before_dir: Path = tmp_path / "before" after_dir: Path = tmp_path / "after" - before_dir.mkdir() - after_dir.mkdir() + before_dir.mkdir(parents=True) + after_dir.mkdir(parents=True) write_python_identity_repo(project_dir=before_dir, repo_files=test_case.before_repo_files) write_python_identity_repo(project_dir=after_dir, repo_files=test_case.after_repo_files) before_module: ModuleType = load_python_identity_module( diff --git a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_inventory.py b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_inventory.py index 920c0e8a9a..1c029a6892 100644 --- a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_inventory.py +++ b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_inventory.py @@ -94,7 +94,7 @@ def test_given_discovered_python_functions_when_building_graph_then_indexes_node loader_functions=( DiscoveredLoaderFunction( file_path=Path("/project/loaders/events.py"), - relative_path=Path("python/loaders/events.py"), + relative_path=Path("python/nodes/loaders/events.py"), name="load_events", function=load_events, depends_on=(prepare_orders,), @@ -103,7 +103,7 @@ def test_given_discovered_python_functions_when_building_graph_then_indexes_node asset_functions=( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="prepare_orders", function=prepare_orders, tags=test_case.expected_task_tags, @@ -114,7 +114,7 @@ def test_given_discovered_python_functions_when_building_graph_then_indexes_node ), DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="export_orders", function=export_orders, depends_on=(imported_prepare_orders,), @@ -126,7 +126,7 @@ def test_given_discovered_python_functions_when_building_graph_then_indexes_node ), DiscoveredAssetFunction( file_path=Path("/project/assets/notifications.py"), - relative_path=Path("python/assets/notifications.py"), + relative_path=Path("python/nodes/assets/notifications.py"), name="notify_orders", function=notify_orders, meta={"provider_usages": "user-owned"}, @@ -135,7 +135,7 @@ def test_given_discovered_python_functions_when_building_graph_then_indexes_node check_functions=( DiscoveredCheckFunction( file_path=Path("/project/checks/orders.py"), - relative_path=Path("python/checks/orders.py"), + relative_path=Path("python/nodes/checks/orders.py"), name="check_orders_export", function=check_orders_export, depends_on=(export_orders,), @@ -145,7 +145,7 @@ def test_given_discovered_python_functions_when_building_graph_then_indexes_node providers=( DiscoveredProvider( file_path=Path("/project/providers/slack.py"), - relative_path=Path("providers/slack.py"), + relative_path=Path("python/providers/slack.py"), name="slack_provider", provider_class=SlackProvider, settings=SlackProvider(), @@ -279,7 +279,7 @@ def test_given_fully_configured_python_nodes_when_building_then_identity_config_ loader_functions=( DiscoveredLoaderFunction( file_path=Path("/project/loaders/events.py"), - relative_path=Path("python/loaders/events.py"), + relative_path=Path("python/nodes/loaders/events.py"), name="load_events", function=load_events, destination="raw.events", @@ -292,7 +292,7 @@ def test_given_fully_configured_python_nodes_when_building_then_identity_config_ asset_functions=( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="prepare_orders", function=prepare_orders, tags=("orders",), @@ -303,7 +303,7 @@ def test_given_fully_configured_python_nodes_when_building_then_identity_config_ ), DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="export_orders", function=export_orders, tags=("orders",), @@ -317,7 +317,7 @@ def test_given_fully_configured_python_nodes_when_building_then_identity_config_ check_functions=( DiscoveredCheckFunction( file_path=Path("/project/checks/orders.py"), - relative_path=Path("python/checks/orders.py"), + relative_path=Path("python/nodes/checks/orders.py"), name="check_orders_export", function=check_orders_export, depends_on=(export_orders,), diff --git a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_run_selectors.py b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_run_selectors.py index f42a9bed93..43d13509f8 100644 --- a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_run_selectors.py +++ b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_run_selectors.py @@ -30,14 +30,14 @@ ), PythonSqlSelectorTestCase( description="selects expanded Python asset path for run", - select=("+path:python/assets",), + select=("+path:python/nodes/assets",), exclude=(), expected_sql_names=frozenset(), expected_python_node_names=frozenset({"prepare_orders", "export_orders"}), ), PythonSqlSelectorTestCase( description="selects a Python asset without its unselected Python dependency", - select=("path:python/assets",), + select=("path:python/nodes/assets",), exclude=(), expected_sql_names=frozenset(), expected_python_node_names=frozenset({"export_orders"}), diff --git a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_selectors.py b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_selectors.py index 1680c2d4b4..f267f826a8 100644 --- a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_selectors.py +++ b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_selectors.py @@ -66,7 +66,7 @@ ), PythonNodeSelectorTestCase( description="selects every Python node by the python root path", - select=("path:python",), + select=("path:python/nodes",), exclude=(), expected_names=frozenset( {"prepare_orders", "load_events", "export_orders", "check_orders_export"} @@ -74,37 +74,37 @@ ), PythonNodeSelectorTestCase( description="selects Python nodes by explicit tasks path", - select=("path:python/tasks",), + select=("path:python/nodes/tasks",), exclude=(), expected_names=frozenset({"prepare_orders"}), ), PythonNodeSelectorTestCase( description="selects Python nodes by explicit loaders path", - select=("path:python/loaders",), + select=("path:python/nodes/loaders",), exclude=(), expected_names=frozenset({"load_events"}), ), PythonNodeSelectorTestCase( description="selects Python nodes by explicit assets path", - select=("path:python/assets",), + select=("path:python/nodes/assets",), exclude=(), expected_names=frozenset({"export_orders"}), ), PythonNodeSelectorTestCase( description="selects Python nodes by explicit assets slash path", - select=("python/assets/",), + select=("python/nodes/assets/",), exclude=(), expected_names=frozenset({"export_orders"}), ), PythonNodeSelectorTestCase( description="selects Python nodes by leading slash assets path", - select=("/python/assets",), + select=("/python/nodes/assets",), exclude=(), expected_names=frozenset({"export_orders"}), ), PythonNodeSelectorTestCase( description="selects Python nodes by explicit checks path with upstream expansion", - select=("+path:python/checks",), + select=("+path:python/nodes/checks",), exclude=(), expected_names=frozenset({"prepare_orders", "export_orders", "check_orders_export"}), ), @@ -180,14 +180,14 @@ def test_given_python_node_selectors_when_resolving_then_returns_expected_names( select=("path:tasks",), exclude=(), expected_error_type=ValueError, - expected_error_fragment="use 'models/' or 'python/'", + expected_error_fragment="use 'sql/models/' or 'python/nodes/'", ), PythonNodeSelectorErrorTestCase( description="raises when explicit path selector matches no Python nodes", - select=("path:python/tasks/missing",), + select=("path:python/nodes/tasks/missing",), exclude=(), expected_error_type=ValueError, - expected_error_fragment="no Python nodes found under path 'python/tasks/missing'", + expected_error_fragment="no Python nodes found under path 'python/nodes/tasks/missing'", ), PythonNodeSelectorErrorTestCase( description="raises when SQL source selector is used for Python nodes", diff --git a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_unified_selectors.py b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_unified_selectors.py index f381604727..0bb75cbb51 100644 --- a/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_unified_selectors.py +++ b/tests/unit/src/sqlbuild/compiler/python_nodes/_helpers/test_unified_selectors.py @@ -70,35 +70,35 @@ ), PythonSqlSelectorTestCase( description="selects explicit models root path as SQL models", - select=("path:models",), + select=("path:sql/models",), exclude=(), expected_sql_names=frozenset({"orders"}), expected_python_node_names=frozenset(), ), PythonSqlSelectorTestCase( description="selects explicit Python task path", - select=("path:python/tasks",), + select=("path:python/nodes/tasks",), exclude=(), expected_sql_names=frozenset(), expected_python_node_names=frozenset({"prepare_orders"}), ), PythonSqlSelectorTestCase( description="selects expanded explicit Python asset path", - select=("+path:python/assets",), + select=("+path:python/nodes/assets",), exclude=(), expected_sql_names=frozenset(), expected_python_node_names=frozenset({"prepare_orders", "export_orders"}), ), PythonSqlSelectorTestCase( description="selects expanded explicit Python asset slash path", - select=("+python/assets/",), + select=("+python/nodes/assets/",), exclude=(), expected_sql_names=frozenset(), expected_python_node_names=frozenset({"prepare_orders", "export_orders"}), ), PythonSqlSelectorTestCase( description="selects expanded explicit Python asset leading slash path", - select=("+/python/assets",), + select=("+/python/nodes/assets",), exclude=(), expected_sql_names=frozenset(), expected_python_node_names=frozenset({"prepare_orders", "export_orders"}), diff --git a/tests/unit/src/sqlbuild/compiler/scopes/_test_helpers.py b/tests/unit/src/sqlbuild/compiler/scopes/_test_helpers.py index d58860beb8..fd099c5b9f 100644 --- a/tests/unit/src/sqlbuild/compiler/scopes/_test_helpers.py +++ b/tests/unit/src/sqlbuild/compiler/scopes/_test_helpers.py @@ -36,7 +36,7 @@ ) _FOLDERS: tuple[str, ...] = ("sales", "sale", "finance", "daily", "orders") -_ROOTS: tuple[str, ...] = ("models", "tests/unit", "functions/sql") +_ROOTS: tuple[str, ...] = ("sql/models", "tests/unit", "sql/functions/sql") _NAMES: tuple[str, ...] = ("status", "region", "tier", "limit", "currency", "channel") _NOISY_SPELLINGS: tuple[Callable[[random.Random, str], str], ...] = ( lambda _rng, path: path.replace("/", "\\"), @@ -146,7 +146,7 @@ def _targets(lookup: ScopeLookup) -> list[ResourceIdentity | str]: return [ *lookup.resources, *(resource.path for resource in lookup.index.resources), - "models/missing.sql", + "sql/models/missing.sql", "model:missing", ] diff --git a/tests/unit/src/sqlbuild/compiler/scopes/helpers.py b/tests/unit/src/sqlbuild/compiler/scopes/helpers.py index f7b3f5a890..b437aea855 100644 --- a/tests/unit/src/sqlbuild/compiler/scopes/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/scopes/helpers.py @@ -50,11 +50,11 @@ def unused_declaration_index(*, enforce_placement: bool) -> ScopeIndex: declarations=( DeclarationRecord( identity=declaration_identity, - path="constants/limit.sql", + path="sql/constants/limit.sql", line=1, column=1, scope=ScopeKind.GLOBAL, - ownership_root=OwnershipRoot("constants"), + ownership_root=OwnershipRoot("sql/constants"), ), ), completeness=ScopeCompleteness(runtime_usage=True, placement=False), @@ -72,7 +72,7 @@ def write_scope_cache_project( root, { "sqlbuild_project.toml": SCOPE_CACHE_PROJECT, - "models/orders.sql": SCOPE_CACHE_MODEL, + "sql/models/orders.sql": SCOPE_CACHE_MODEL, }, ) @@ -162,11 +162,11 @@ def declaration_record( return DeclarationRecord( DeclarationIdentity(kind, name, owner), - path or f"enums/{name}.sql", + path or f"sql/enums/{name}.sql", 1, 1, scope, - OwnershipRoot("models", resource_kind=ResourceKind.MODEL), + OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), owning_path=owner_path, ) @@ -176,17 +176,17 @@ def scope_index() -> ScopeIndex: model: ResourceIdentity = ResourceIdentity(kind=ResourceKind.MODEL, name="stg_orders") model_root: OwnershipRoot = OwnershipRoot( - path="models", + path="sql/models", kind=OwnershipRootKind.RESOURCE, resource_kind=ResourceKind.MODEL, ) enum: DeclarationRecord = DeclarationRecord( DeclarationIdentity(DeclarationKind.ENUM, "order_status"), - "enums/order_status.sql", + "sql/enums/order_status.sql", 2, 1, ScopeKind.GLOBAL, - OwnershipRoot("enums", OwnershipRootKind.GLOBAL), + OwnershipRoot("sql/enums", OwnershipRootKind.GLOBAL), enum=EnumMetadata( ( EnumMemberMetadata("OPEN"), @@ -197,25 +197,25 @@ def scope_index() -> ScopeIndex: ) constant: DeclarationRecord = DeclarationRecord( DeclarationIdentity(DeclarationKind.CONSTANT, "minimum_value"), - "models/staging/constants/limits.sql", + "sql/models/staging/constants/limits.sql", 8, 3, ScopeKind.INHERITED, - OwnershipRoot("models", resource_kind=ResourceKind.MODEL), - owning_path="models/staging", + OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), + owning_path="sql/models/staging", constant=ConstantMetadata("integer", render_as="value_list"), ) macro: DeclarationRecord = DeclarationRecord( DeclarationIdentity(DeclarationKind.MACRO, "normalize_status"), - "macros/python/normalize_status.py", + "sql/macros/python/normalize_status.py", 1, 1, ScopeKind.GLOBAL, - OwnershipRoot("macros", OwnershipRootKind.GLOBAL), + OwnershipRoot("sql/macros", OwnershipRootKind.GLOBAL), macro=MacroMetadata(("status",), (enum.identity,)), ) return ScopeIndex( - resources=(ResourceRecord(model, "models/staging/stg_orders.sql", model_root),), + resources=(ResourceRecord(model, "sql/models/staging/stg_orders.sql", model_root),), declarations=(macro, constant, enum), usages=(UsageRecord(model, constant.identity), UsageRecord(model, enum.identity)), completeness=ScopeCompleteness(runtime_usage=False), @@ -225,17 +225,17 @@ def scope_index() -> ScopeIndex: def report_scope_lookup(*, extra_globals: int = 0) -> ScopeLookup: """Return representative complete facts for scope report tests.""" - model_root: OwnershipRoot = OwnershipRoot("models", resource_kind=ResourceKind.MODEL) - global_root: OwnershipRoot = OwnershipRoot("constants", OwnershipRootKind.GLOBAL) + model_root: OwnershipRoot = OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL) + global_root: OwnershipRoot = OwnershipRoot("sql/constants", OwnershipRootKind.GLOBAL) orders: ResourceIdentity = ResourceIdentity(ResourceKind.MODEL, "orders") expected: ResourceIdentity = ResourceIdentity(ResourceKind.MODEL, "expected_orders") resources: tuple[ResourceRecord, ...] = ( - ResourceRecord(orders, "models/staging/orders.sql", model_root), - ResourceRecord(expected, "models/marts/expected_orders.sql", model_root), + ResourceRecord(orders, "sql/models/staging/orders.sql", model_root), + ResourceRecord(expected, "sql/models/marts/expected_orders.sql", model_root), ) global_constant: DeclarationRecord = DeclarationRecord( DeclarationIdentity(DeclarationKind.CONSTANT, "warehouse_password"), - "constants/warehouse_password.yml", + "sql/constants/warehouse_password.yml", 2, 3, ScopeKind.GLOBAL, @@ -244,12 +244,12 @@ def report_scope_lookup(*, extra_globals: int = 0) -> ScopeLookup: ) inherited: DeclarationRecord = DeclarationRecord( DeclarationIdentity(DeclarationKind.ENUM, "order_status"), - "models/staging/enums/order_status.sql", + "sql/models/staging/enums/order_status.sql", 1, 1, ScopeKind.INHERITED, model_root, - owning_path="models/staging", + owning_path="sql/models/staging", enum=EnumMetadata( tuple(EnumMemberMetadata(f"STATUS_{index:02d}") for index in range(25)), "VARCHAR", @@ -257,44 +257,44 @@ def report_scope_lookup(*, extra_globals: int = 0) -> ScopeLookup: ) sibling: DeclarationRecord = DeclarationRecord( DeclarationIdentity(DeclarationKind.ENUM, "mart_status"), - "models/marts/_enums/mart_status.sql", + "sql/models/marts/_enums/mart_status.sql", 1, 1, ScopeKind.LOCAL, model_root, - owning_path="models/marts", + owning_path="sql/models/marts", ) nearby_sibling: DeclarationRecord = DeclarationRecord( DeclarationIdentity(DeclarationKind.ENUM, "other_status"), - "models/other/_enums/other_status.sql", + "sql/models/other/_enums/other_status.sql", 1, 1, ScopeKind.LOCAL, model_root, - owning_path="models/other", + owning_path="sql/models/other", ) private: DeclarationRecord = DeclarationRecord( DeclarationIdentity(DeclarationKind.ENUM, "expected_status", expected), - "models/marts/expected_orders.sql", + "sql/models/marts/expected_orders.sql", 4, 2, ScopeKind.PRIVATE, model_root, - owning_path="models/marts", + owning_path="sql/models/marts", ) macro: DeclarationRecord = DeclarationRecord( DeclarationIdentity(DeclarationKind.MACRO, "normalize"), - "macros/python/normalize.py", + "sql/macros/python/normalize.py", 1, 1, ScopeKind.GLOBAL, - OwnershipRoot("macros", OwnershipRootKind.GLOBAL), + OwnershipRoot("sql/macros", OwnershipRootKind.GLOBAL), macro=MacroMetadata(("value",), (inherited.identity,), "secret-source-digest"), ) generated: tuple[DeclarationRecord, ...] = tuple( DeclarationRecord( DeclarationIdentity(DeclarationKind.CONSTANT, f"global_{index:05d}"), - f"constants/generated/{index:05d}.yml", + f"sql/constants/generated/{index:05d}.yml", 1, 1, ScopeKind.GLOBAL, @@ -308,8 +308,8 @@ def report_scope_lookup(*, extra_globals: int = 0) -> ScopeLookup: model_root, OwnershipRoot("tests/unit", resource_kind=ResourceKind.TEST), OwnershipRoot("tests/scenarios", resource_kind=ResourceKind.SCENARIO), - OwnershipRoot("functions/sql", resource_kind=ResourceKind.FUNCTION), - OwnershipRoot("sources", resource_kind=ResourceKind.SOURCE), + OwnershipRoot("sql/functions/sql", resource_kind=ResourceKind.FUNCTION), + OwnershipRoot("sql/sources", resource_kind=ResourceKind.SOURCE), ), resources=resources, declarations=( @@ -333,7 +333,7 @@ def report_scope_lookup(*, extra_globals: int = 0) -> ScopeLookup: return build_scope_lookup(index=index) -_RELOCATION_ROOT: OwnershipRoot = OwnershipRoot("models", resource_kind=ResourceKind.MODEL) +_RELOCATION_ROOT: OwnershipRoot = OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL) _CENTS_MACRO: DeclarationIdentity = DeclarationIdentity(DeclarationKind.MACRO, "to_cents") _ORDER_SHAPE: DeclarationIdentity = DeclarationIdentity(DeclarationKind.SCHEMA, "order_shape") @@ -355,21 +355,21 @@ def relocation_index(consumer_paths: tuple[str, ...]) -> ScopeIndex: declarations=( DeclarationRecord( identity=_ORDER_SHAPE, - path="models/staging/_sqlbuild/_schemas/order_shape.sql", + path="sql/models/staging/_sqlbuild/_schemas/order_shape.sql", line=1, column=1, scope=ScopeKind.LOCAL, ownership_root=_RELOCATION_ROOT, - owning_path="models/staging", + owning_path="sql/models/staging", ), DeclarationRecord( identity=_CENTS_MACRO, - path="models/staging/_sqlbuild/_macros/python/cents.py", + path="sql/models/staging/_sqlbuild/_macros/python/cents.py", line=1, column=1, scope=ScopeKind.LOCAL, ownership_root=_RELOCATION_ROOT, - owning_path="models/staging", + owning_path="sql/models/staging", ), ), usages=( diff --git a/tests/unit/src/sqlbuild/compiler/scopes/test_builder_and_visibility.py b/tests/unit/src/sqlbuild/compiler/scopes/test_builder_and_visibility.py index f5d207e61b..236f98398b 100644 --- a/tests/unit/src/sqlbuild/compiler/scopes/test_builder_and_visibility.py +++ b/tests/unit/src/sqlbuild/compiler/scopes/test_builder_and_visibility.py @@ -61,15 +61,15 @@ @pytest.mark.parametrize( "test_case", [ - ResourceExpectation("model", "model", "orders", "models/orders.sql", "models"), + ResourceExpectation("model", "model", "orders", "sql/models/orders.sql", "sql/models"), ResourceExpectation("test", "test", "orders_test", "tests/unit/orders.sql", "tests/unit"), ResourceExpectation( "scenario", "scenario", "checkout", "tests/scenarios/checkout.sql", "tests/scenarios" ), ResourceExpectation( - "function", "function", "tax", "functions/sql/tax.sql", "functions/sql" + "function", "function", "tax", "sql/functions/sql/tax.sql", "sql/functions/sql" ), - ResourceExpectation("source", "source", "raw_orders", "sources/raw.yml", "sources"), + ResourceExpectation("source", "source", "raw_orders", "sql/sources/raw.yml", "sql/sources"), ], ids=lambda case: case.description, ) @@ -77,10 +77,10 @@ def test_given_every_authored_resource_kind_when_building_then_uses_canonical_ro test_case: ResourceExpectation, ) -> None: test_path: Path = Path("tests/unit/orders.sql") - audit_path: Path = Path("audits/fresh.sql") + audit_path: Path = Path("sql/audits/fresh.sql") index: ScopeIndex = build_scope_index( discovered_inputs=discovered_inputs( - model_files=(discovered_model(name="orders", path="models/orders.sql"),), + model_files=(discovered_model(name="orders", path="sql/models/orders.sql"),), test_files=( DiscoveredSqlTestFile( test_path, @@ -101,8 +101,8 @@ def test_given_every_authored_resource_kind_when_building_then_uses_canonical_ro ), sql_hook_files=( DiscoveredSqlHookFile( - Path("hooks/sql/grant.sql"), - Path("hooks/sql/grant.sql"), + Path("sql/hooks/sql/grant.sql"), + Path("sql/hooks/sql/grant.sql"), "", {}, "SELECT 1", @@ -111,8 +111,8 @@ def test_given_every_authored_resource_kind_when_building_then_uses_canonical_ro ), sql_function_files=( DiscoveredSqlFunctionFile( - Path("functions/sql/tax.sql"), - Path("functions/sql/tax.sql"), + Path("sql/functions/sql/tax.sql"), + Path("sql/functions/sql/tax.sql"), "", {"name": "tax"}, "SELECT 1", @@ -128,8 +128,8 @@ def test_given_every_authored_resource_kind_when_building_then_uses_canonical_ro ), source_files=( DiscoveredSourceFile( - Path("sources/raw.yml"), - Path("sources/raw.yml"), + Path("sql/sources/raw.yml"), + Path("sql/sources/raw.yml"), "", (SourceEntry(name="raw_orders"),), ), @@ -170,37 +170,46 @@ def test_given_all_scope_tiers_when_resolving_then_classifies_without_shadow_res other: ResourceIdentity = ResourceIdentity(ResourceKind.MODEL, "other") resource: ResourceRecord = ResourceRecord( target, - "models/sales/daily/orders.sql", - OwnershipRoot("models", resource_kind=ResourceKind.MODEL), + "sql/models/sales/daily/orders.sql", + OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), ) declarations: tuple[DeclarationRecord, ...] = ( declaration_record(name="global", scope=ScopeKind.GLOBAL, owner_path=None), - declaration_record(name="root", scope=ScopeKind.INHERITED, owner_path="models"), - declaration_record(name="near", scope=ScopeKind.INHERITED, owner_path="models/sales"), + declaration_record(name="root", scope=ScopeKind.INHERITED, owner_path="sql/models"), + declaration_record(name="near", scope=ScopeKind.INHERITED, owner_path="sql/models/sales"), declaration_record( name="noncanonical", scope=ScopeKind.INHERITED, - owner_path=r"models\.\sales\daily\..", + owner_path=r"sql\models\.\sales\daily\..", ), - declaration_record(name="local", scope=ScopeKind.LOCAL, owner_path="models/sales/daily"), declaration_record( - name="_private", scope=ScopeKind.PRIVATE, owner_path="models/sales/daily", owner=target + name="local", scope=ScopeKind.LOCAL, owner_path="sql/models/sales/daily" ), - declaration_record(name="parent_local", scope=ScopeKind.LOCAL, owner_path="models/sales"), - declaration_record(name="sibling", scope=ScopeKind.INHERITED, owner_path="models/finance"), declaration_record( - name="descendant", scope=ScopeKind.INHERITED, owner_path="models/sales/daily/child" + name="_private", + scope=ScopeKind.PRIVATE, + owner_path="sql/models/sales/daily", + owner=target, + ), + declaration_record( + name="parent_local", scope=ScopeKind.LOCAL, owner_path="sql/models/sales" ), - declaration_record(name="prefix", scope=ScopeKind.INHERITED, owner_path="models/sale"), declaration_record( - name="_other", scope=ScopeKind.PRIVATE, owner_path="models/sales/daily", owner=other + name="sibling", scope=ScopeKind.INHERITED, owner_path="sql/models/finance" + ), + declaration_record( + name="descendant", scope=ScopeKind.INHERITED, owner_path="sql/models/sales/daily/child" + ), + declaration_record(name="prefix", scope=ScopeKind.INHERITED, owner_path="sql/models/sale"), + declaration_record( + name="_other", scope=ScopeKind.PRIVATE, owner_path="sql/models/sales/daily", owner=other ), ) resolution: VisibilityResolution = resolve_scope_visibility( lookup=build_scope_lookup( index=ScopeIndex(resources=(resource,), declarations=declarations) ), - target="models\\sales\\daily\\orders.sql", + target="sql\\models\\sales\\daily\\orders.sql", ) visible: dict[str, VisibilityReason] = { item.declaration.name: item.reason for item in resolution.visible @@ -246,22 +255,26 @@ def test_given_out_of_scope_declarations_when_resolving_then_returns_specific_re other: ResourceIdentity = ResourceIdentity(ResourceKind.MODEL, "other") resource: ResourceRecord = ResourceRecord( target, - "models/sales/daily/orders.sql", - OwnershipRoot("models", resource_kind=ResourceKind.MODEL), + "sql/models/sales/daily/orders.sql", + OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), ) declarations: tuple[DeclarationRecord, ...] = ( - declaration_record(name="parent_local", scope=ScopeKind.LOCAL, owner_path="models/sales"), - declaration_record(name="sibling", scope=ScopeKind.INHERITED, owner_path="models/finance"), + declaration_record( + name="parent_local", scope=ScopeKind.LOCAL, owner_path="sql/models/sales" + ), + declaration_record( + name="sibling", scope=ScopeKind.INHERITED, owner_path="sql/models/finance" + ), declaration_record( name="descendant", scope=ScopeKind.INHERITED, - owner_path="models/sales/daily/child", + owner_path="sql/models/sales/daily/child", ), - declaration_record(name="prefix", scope=ScopeKind.INHERITED, owner_path="models/sale"), + declaration_record(name="prefix", scope=ScopeKind.INHERITED, owner_path="sql/models/sale"), declaration_record( name="_other", scope=ScopeKind.PRIVATE, - owner_path="models/sales/daily", + owner_path="sql/models/sales/daily", owner=other, ), ) @@ -332,32 +345,32 @@ def test_given_public_duplicates_across_scopes_when_building_then_retains_all_an test_case: ExpectedBooleanCase, ) -> None: declaration: EnumDeclaration = EnumDeclaration( - "status", (EnumMember("OPEN", "OPEN"),), "VARCHAR", Path("enums/status.sql") + "status", (EnumMember("OPEN", "OPEN"),), "VARCHAR", Path("sql/enums/status.sql") ) files: tuple[DiscoveredEnumFile, ...] = ( DiscoveredEnumFile( - Path("enums/status.sql"), - Path("enums/status.sql"), + Path("sql/enums/status.sql"), + Path("sql/enums/status.sql"), "", (declaration,), ), DiscoveredEnumFile( - Path("models/enums/status.sql"), - Path("models/enums/status.sql"), + Path("sql/models/enums/status.sql"), + Path("sql/models/enums/status.sql"), "", (declaration,), ScopeKind.INHERITED, - Path("models"), - Path("models"), + Path("sql/models"), + Path("sql/models"), ), DiscoveredEnumFile( - Path("models/sales/_enums/status.sql"), - Path("models/sales/_enums/status.sql"), + Path("sql/models/sales/_enums/status.sql"), + Path("sql/models/sales/_enums/status.sql"), "", (declaration,), ScopeKind.LOCAL, - Path("models"), - Path("models/sales"), + Path("sql/models"), + Path("sql/models/sales"), ), ) index: ScopeIndex = build_scope_index(discovered_inputs=discovered_inputs(enum_files=files)) @@ -386,8 +399,8 @@ def test_given_duplicate_resource_identity_when_building_then_lookup_retains_eve index: ScopeIndex = build_scope_index( discovered_inputs=discovered_inputs( model_files=( - discovered_model(name="orders", path="models/a.sql"), - discovered_model(name="orders", path="models/b.sql"), + discovered_model(name="orders", path="sql/models/a.sql"), + discovered_model(name="orders", path="sql/models/b.sql"), ) ) ) @@ -410,35 +423,35 @@ def test_given_cross_kind_and_same_private_name_across_owners_when_building_then test_case: ExpectedBooleanCase, ) -> None: private: EnumDeclaration = EnumDeclaration( - "_status", (EnumMember("OPEN", "OPEN"),), "VARCHAR", Path("models/a.sql"), "a" + "_status", (EnumMember("OPEN", "OPEN"),), "VARCHAR", Path("sql/models/a.sql"), "a" ) enum_file: DiscoveredEnumFile = DiscoveredEnumFile( - Path("enums/status.sql"), - Path("enums/status.sql"), + Path("sql/enums/status.sql"), + Path("sql/enums/status.sql"), "", ( EnumDeclaration( - "status", (EnumMember("OPEN", "OPEN"),), "VARCHAR", Path("enums/status.sql") + "status", (EnumMember("OPEN", "OPEN"),), "VARCHAR", Path("sql/enums/status.sql") ), ), ) constant_file: DiscoveredConstantFile = DiscoveredConstantFile( - Path("constants/status.sql"), - Path("constants/status.sql"), + Path("sql/constants/status.sql"), + Path("sql/constants/status.sql"), "", ( ConstantDeclaration( "status", normalize_sql_value(raw_value=1, context="test"), - Path("constants/status.sql"), + Path("sql/constants/status.sql"), ), ), ) index: ScopeIndex = build_scope_index( discovered_inputs=discovered_inputs( model_files=( - discovered_model(name="a", path="models/a.sql", enums=(private,)), - discovered_model(name="b", path="models/b.sql", enums=(private,)), + discovered_model(name="a", path="sql/models/a.sql", enums=(private,)), + discovered_model(name="b", path="sql/models/b.sql", enums=(private,)), ), enum_files=(enum_file,), constant_files=(constant_file,), @@ -469,12 +482,12 @@ def test_given_reserved_private_name_when_building_then_emits_stable_name_diagno test_case: ExpectedBooleanCase, ) -> None: private: EnumDeclaration = EnumDeclaration( - "__status", (EnumMember("OPEN", "OPEN"),), "VARCHAR", Path("models/a.sql"), "a" + "__status", (EnumMember("OPEN", "OPEN"),), "VARCHAR", Path("sql/models/a.sql"), "a" ) index: ScopeIndex = build_scope_index( discovered_inputs=discovered_inputs( - model_files=(discovered_model(name="a", path="models/a.sql", enums=(private,)),) + model_files=(discovered_model(name="a", path="sql/models/a.sql", enums=(private,)),) ) ) @@ -494,7 +507,7 @@ def test_given_loaded_scoped_macro_when_building_then_metadata_is_safe_and_norma def normalize_status(value: object, fallback: str = "unknown") -> str: return str(value or fallback) - path: Path = Path("models/sales/macros/python/status.py") + path: Path = Path("sql/models/sales/macros/python/status.py") source = "def normalize_status(value, fallback='unknown'):\n return str(value or fallback)\n" index: ScopeIndex = build_scope_index( discovered_inputs=discovered_inputs( @@ -504,9 +517,9 @@ def normalize_status(value: object, fallback: str = "unknown") -> str: path, source, ScopeKind.INHERITED, - Path("models"), - Path("models/sales"), - Path("models/sales/macros"), + Path("sql/models"), + Path("sql/models/sales"), + Path("sql/models/sales/macros"), ), ) ), @@ -519,7 +532,7 @@ def normalize_status(value: object, fallback: str = "unknown") -> str: record: DeclarationRecord = index.declarations[0] assert (record.scope is ScopeKind.INHERITED) is test_case.expected_result - assert record.owning_path == "models/sales" + assert record.owning_path == "sql/models/sales" assert record.ownership_root.resource_kind is ResourceKind.MODEL assert record.macro is not None assert record.macro.parameters == ("value", "fallback") diff --git a/tests/unit/src/sqlbuild/compiler/scopes/test_lookup_and_metadata.py b/tests/unit/src/sqlbuild/compiler/scopes/test_lookup_and_metadata.py index af0ae86914..907ce27083 100644 --- a/tests/unit/src/sqlbuild/compiler/scopes/test_lookup_and_metadata.py +++ b/tests/unit/src/sqlbuild/compiler/scopes/test_lookup_and_metadata.py @@ -71,12 +71,12 @@ def test_given_unsorted_index_when_building_lookup_then_records_and_edges_are_ca "\U0001f600", ), expected_paths=( - "models/Zed.sql", - "models/\u00a0x.sql", - "models/cafe.sql", - "models/caf\u00e9.sql", - "models/e\u0301.sql", - "models/\U0001f600.sql", + "sql/models/Zed.sql", + "sql/models/\u00a0x.sql", + "sql/models/cafe.sql", + "sql/models/caf\u00e9.sql", + "sql/models/e\u0301.sql", + "sql/models/\U0001f600.sql", ), ), ], @@ -85,11 +85,11 @@ def test_given_unsorted_index_when_building_lookup_then_records_and_edges_are_ca def test_given_non_ascii_keys_when_building_lookup_then_mappings_follow_python_repr_order( test_case: UnicodeKeyOrderCase, ) -> None: - root: OwnershipRoot = OwnershipRoot("models", resource_kind=ResourceKind.MODEL) + root: OwnershipRoot = OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL) resources: tuple[ResourceRecord, ...] = tuple( ResourceRecord( identity=ResourceIdentity(kind=ResourceKind.MODEL, name=name), - path=f"models/{name}.sql", + path=f"sql/models/{name}.sql", ownership_root=root, ) for name in test_case.names @@ -172,7 +172,7 @@ def test_given_typed_constant_when_projecting_default_metadata_then_value_is_abs assert projection["schema_version"] == 3 assert constant["role"] == "constants" assert constant["visibility"] == "descendant_public" - assert constant["role_root"] == "models/staging/constants" + assert constant["role_root"] == "sql/models/staging/constants" assert constant["bucket_path"] is None assert constant["metadata"]["constant"] == { "logical_type": "integer", @@ -190,16 +190,16 @@ def test_given_typed_constant_when_projecting_default_metadata_then_value_is_abs ( DeclarationContainerProjectionCase( description="legacy declaration role has no navigation bucket", - path="models/orders/constants/policy.sql", - owning_path="models/orders", - expected_role_root="models/orders/constants", + path="sql/models/orders/constants/policy.sql", + owning_path="sql/models/orders", + expected_role_root="sql/models/orders/constants", expected_bucket_path=None, ), DeclarationContainerProjectionCase( description="grouped declaration role has no navigation bucket", - path="models/orders/_sqlbuild/constants/policy.sql", - owning_path="models/orders", - expected_role_root="models/orders/_sqlbuild/constants", + path="sql/models/orders/_sqlbuild/constants/policy.sql", + owning_path="sql/models/orders", + expected_role_root="sql/models/orders/_sqlbuild/constants", expected_bucket_path=None, ), ), @@ -214,7 +214,7 @@ def test_given_declaration_path_when_projecting_then_role_container_is_canonical line=1, column=1, scope=ScopeKind.INHERITED, - ownership_root=OwnershipRoot("models", resource_kind=ResourceKind.MODEL), + ownership_root=OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), owning_path=test_case.owning_path, ) diff --git a/tests/unit/src/sqlbuild/compiler/scopes/test_offline_cache.py b/tests/unit/src/sqlbuild/compiler/scopes/test_offline_cache.py index d6d6a523da..e64c7e5c71 100644 --- a/tests/unit/src/sqlbuild/compiler/scopes/test_offline_cache.py +++ b/tests/unit/src/sqlbuild/compiler/scopes/test_offline_cache.py @@ -86,10 +86,10 @@ def test_given_scoped_macro_test_when_loading_warm_cache_then_grant_provenance_i "sqlbuild_project.toml": ( 'name = "orders"\nadapter = "duckdb"\n[scopes]\nenforce_placement = false\n' ), - "models/orders/_sqlbuild/_macros/python/policy.py": ( + "sql/models/orders/_sqlbuild/_macros/python/policy.py": ( "def order_policy() -> str:\n return '2'\n" ), - "models/orders/summary.sql": ( + "sql/models/orders/summary.sql": ( 'MODEL (description "Order summary.");\nSELECT @py.order_policy() AS quantity' ), "tests/unit/macros/models/orders/test_order_policy__returns_quantity.sql": ( @@ -124,15 +124,15 @@ def test_given_macro_side_effect_when_loading_warm_cache_then_module_is_not_exec tmp_path, { "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": _MODEL, - "macros/python/side_effect.py": ( + "sql/models/orders.sql": _MODEL, + "sql/macros/python/side_effect.py": ( "from pathlib import Path\n" "Path(__file__).with_name('executed').write_text('yes')\n" "def identity(value):\n return str(value)\n" ), }, ) - marker: Path = tmp_path / "macros" / "python" / "executed" + marker: Path = tmp_path / "sql" / "macros" / "python" / "executed" load_or_build_scope_index(project_dir=tmp_path) marker.unlink() @@ -167,7 +167,7 @@ def test_given_no_cache_when_loading_twice_then_cache_is_bypassed( ( FingerprintMutationCase( "model content", - "models/orders.sql", + "sql/models/orders.sql", _MODEL, "MODEL(description 'Test model orders.');\nSELECT 2 AS id\n", True, @@ -268,10 +268,10 @@ def test_given_source_add_rename_and_delete_when_fingerprinting_then_paths_inval ) -> None: write_scope_cache_project(root=tmp_path, write_repo_files=write_repo_files) original: str | None = scope_index_fingerprint(project_dir=tmp_path) - added_path: Path = tmp_path / "models" / "added.sql" + added_path: Path = tmp_path / "sql" / "models" / "added.sql" added_path.write_text(_MODEL, encoding="utf-8") added: str | None = scope_index_fingerprint(project_dir=tmp_path) - renamed_path: Path = tmp_path / "models" / "renamed.sql" + renamed_path: Path = tmp_path / "sql" / "models" / "renamed.sql" added_path.rename(renamed_path) renamed: str | None = scope_index_fingerprint(project_dir=tmp_path) renamed_path.unlink() @@ -296,9 +296,9 @@ def test_given_authored_values_and_secrets_when_caching_then_payload_is_value_fr tmp_path, { "sqlbuild_project.toml": _PROJECT + f'\n[connection]\npassword = "{secret}"\n', - "models/orders.sql": _MODEL, - "constants/private.sql": f'CONSTANT (name token, value "{secret}");', - "enums/private.sql": f'ENUM (name status, members (SECRET "{secret}"));', + "sql/models/orders.sql": _MODEL, + "sql/constants/private.sql": f'CONSTANT (name token, value "{secret}");', + "sql/enums/private.sql": f'ENUM (name status, members (SECRET "{secret}"));', }, ) @@ -327,15 +327,15 @@ def test_given_target_aware_python_composition_when_switching_target_then_depend _PROJECT + '\ndefault_target = "dev"\n[targets.dev]\n[targets.prod]\n' ), "sqlbuild_local.toml": 'target = "dev"\n', - "models/orders.sql": "MODEL(description 'Test model orders.');\nSELECT @py.choose() AS value\n", - "macros/python/choose.py": ( - "from macros.python.dev import dev_macro\n" - "from macros.python.prod import prod_macro\n\n" + "sql/models/orders.sql": "MODEL(description 'Test model orders.');\nSELECT @py.choose() AS value\n", + "sql/macros/python/choose.py": ( + "from sql.macros.python.dev import dev_macro\n" + "from sql.macros.python.prod import prod_macro\n\n" "def choose(ctx):\n return dev_macro() " 'if ctx.target_name == "dev" else prod_macro()\n' ), - "macros/python/dev.py": 'def dev_macro():\n return "1"\n', - "macros/python/prod.py": 'def prod_macro():\n return "2"\n', + "sql/macros/python/dev.py": 'def dev_macro():\n return "1"\n', + "sql/macros/python/prod.py": 'def prod_macro():\n return "2"\n', }, ) @@ -365,10 +365,10 @@ def test_given_broken_declaration_category_when_loading_then_other_categories_re tmp_path, { "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": _MODEL, - "models/domain/enums/_enums/broken.sql": ("ENUM (name broken, members [BROKEN]);"), - "constants/limit.sql": "CONSTANT (name limit, value 1);", - "macros/python/identity.py": 'def identity():\n return "1"\n', + "sql/models/orders.sql": _MODEL, + "sql/models/domain/enums/_enums/broken.sql": ("ENUM (name broken, members [BROKEN]);"), + "sql/constants/limit.sql": "CONSTANT (name limit, value 1);", + "sql/macros/python/identity.py": 'def identity():\n return "1"\n', }, ) @@ -386,11 +386,11 @@ def test_given_broken_declaration_category_when_loading_then_other_categories_re TolerantMacroInventoryCase( description="syntax error retains valid composed macro and dependency", files={ - "macros/python/shared.py": "def shared():\n return 'shared'\n", - "macros/python/consumer.py": ( - "from macros.python.shared import shared\n\ndef consumer():\n return shared()\n" + "sql/macros/python/shared.py": "def shared():\n return 'shared'\n", + "sql/macros/python/consumer.py": ( + "from sql.macros.python.shared import shared\n\ndef consumer():\n return shared()\n" ), - "macros/python/broken.py": "def broken(:\n return 'broken'\n", + "sql/macros/python/broken.py": "def broken(:\n return 'broken'\n", }, expected_names=frozenset({"shared", "consumer"}), unexpected_names=frozenset({"broken"}), @@ -400,12 +400,14 @@ def test_given_broken_declaration_category_when_loading_then_other_categories_re TolerantMacroInventoryCase( description="scope-invalid macro import is omitted with diagnostic", files={ - "models/sales/_macros/python/shared.py": ("def shared():\n return 'shared'\n"), - "models/finance/macros/python/consumer.py": ( - "from models.sales._macros.python.shared import shared\n\n" + "sql/models/sales/_macros/python/shared.py": ( + "def shared():\n return 'shared'\n" + ), + "sql/models/finance/macros/python/consumer.py": ( + "from sql.models.sales._macros.python.shared import shared\n\n" "def consumer():\n return shared()\n" ), - "macros/python/broken.py": "def broken(:\n return 'broken'\n", + "sql/macros/python/broken.py": "def broken(:\n return 'broken'\n", }, expected_names=frozenset({"shared"}), unexpected_names=frozenset({"consumer", "broken"}), @@ -414,9 +416,9 @@ def test_given_broken_declaration_category_when_loading_then_other_categories_re TolerantMacroInventoryCase( description="name collision retains unrelated valid macro", files={ - "macros/python/valid.py": "def valid():\n return 'valid'\n", - "macros/python/first.py": "def duplicate():\n return 'first'\n", - "macros/python/second.py": "def duplicate():\n return 'second'\n", + "sql/macros/python/valid.py": "def valid():\n return 'valid'\n", + "sql/macros/python/first.py": "def duplicate():\n return 'first'\n", + "sql/macros/python/second.py": "def duplicate():\n return 'second'\n", }, expected_names=frozenset({"valid"}), unexpected_names=frozenset({"duplicate"}), @@ -425,12 +427,12 @@ def test_given_broken_declaration_category_when_loading_then_other_categories_re TolerantMacroInventoryCase( description="import cycle retains unrelated valid macro", files={ - "macros/python/valid.py": "def valid():\n return 'valid'\n", - "macros/python/first.py": ( - "from macros.python.second import second\n\ndef first():\n return second()\n" + "sql/macros/python/valid.py": "def valid():\n return 'valid'\n", + "sql/macros/python/first.py": ( + "from sql.macros.python.second import second\n\ndef first():\n return second()\n" ), - "macros/python/second.py": ( - "from macros.python.first import first\n\ndef second():\n return first()\n" + "sql/macros/python/second.py": ( + "from sql.macros.python.first import first\n\ndef second():\n return first()\n" ), }, expected_names=frozenset({"valid"}), @@ -440,13 +442,15 @@ def test_given_broken_declaration_category_when_loading_then_other_categories_re TolerantMacroInventoryCase( description="module path collision omits both ambiguous modules", files={ - "macros/python/valid.py": "def valid():\n return 'valid'\n", - "macros/python/a.b.py": "def dotted():\n return 'dotted'\n", - "macros/python/a/b.py": "def nested():\n return 'nested'\n", + "sql/macros/python/valid.py": "def valid():\n return 'valid'\n", + "sql/macros/python/a.b.py": "def dotted():\n return 'dotted'\n", + "sql/macros/python/a/b.py": "def nested():\n return 'nested'\n", }, expected_names=frozenset({"valid"}), unexpected_names=frozenset({"dotted", "nested"}), - expected_diagnostic_fragments=("Macro module path collision for 'macros.python.a.b'",), + expected_diagnostic_fragments=( + "Macro module path collision for 'sql.macros.python.a.b'", + ), ), ), ids=lambda case: case.description, @@ -460,7 +464,7 @@ def test_given_macro_fault_when_loading_offline_then_valid_macro_facts_are_retai tmp_path, { "sqlbuild_project.toml": _PROJECT, - "models/orders.sql": _MODEL, + "sql/models/orders.sql": _MODEL, **test_case.files, }, ) @@ -551,8 +555,8 @@ def test_given_placement_invalid_project_when_loading_then_complete_diagnostics_ tmp_path, { "sqlbuild_project.toml": _PROJECT, - "models/domain/constants/value.sql": "CONSTANT (name value, value 1);", - "models/domain/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/models/domain/constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/domain/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', }, ) @@ -579,8 +583,8 @@ def test_given_cached_placement_error_when_disabling_enforcement_then_cache_retu tmp_path, { "sqlbuild_project.toml": _PROJECT + "\n[scopes]\nenforce_placement = true\n", - "constants/value.sql": "CONSTANT (name value, value 1);", - "models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', + "sql/constants/value.sql": "CONSTANT (name value, value 1);", + "sql/models/orders.sql": 'MODEL (description "Test model orders.");\nSELECT @const("value") AS value', }, ) enforced: ScopeIndex = load_or_build_scope_index(project_dir=tmp_path) @@ -613,9 +617,9 @@ def test_given_one_broken_model_when_loading_then_valid_and_broken_paths_remain_ tmp_path, { "sqlbuild_project.toml": _PROJECT, - "models/valid.sql": _MODEL, - "models/broken.sql": "MODEL(\nSELECT 1", - "enums/status.sql": "ENUM status (OPEN = 'open');", + "sql/models/valid.sql": _MODEL, + "sql/models/broken.sql": "MODEL(\nSELECT 1", + "sql/enums/status.sql": "ENUM status (OPEN = 'open');", }, ) @@ -628,8 +632,8 @@ def test_given_one_broken_model_when_loading_then_valid_and_broken_paths_remain_ and not index.completeness.runtime_usage and paths >= { - (ResourceKind.MODEL, "models/valid.sql"), - (ResourceKind.MODEL, "models/broken.sql"), + (ResourceKind.MODEL, "sql/models/valid.sql"), + (ResourceKind.MODEL, "sql/models/broken.sql"), } and any(item.code is ScopeDiagnosticCode.RESOURCE_PARSE_ERROR for item in index.diagnostics) ) @@ -643,38 +647,38 @@ def test_given_one_broken_model_when_loading_then_valid_and_broken_paths_remain_ TolerantCategoryCase( description="SQL functions retain valid siblings", files={ - "functions/sql/valid.sql": "FUNCTION (description 'Test function valid.', returns INTEGER);\n1", - "functions/sql/broken.sql": "FUNCTION (\nSELECT 1", + "sql/functions/sql/valid.sql": "FUNCTION (description 'Test function valid.', returns INTEGER);\n1", + "sql/functions/sql/broken.sql": "FUNCTION (\nSELECT 1", }, expected_kind=ResourceKind.FUNCTION, - expected_paths=("functions/sql/broken.sql", "functions/sql/valid.sql"), + expected_paths=("sql/functions/sql/broken.sql", "sql/functions/sql/valid.sql"), ), TolerantCategoryCase( description="SQL hooks retain valid siblings", files={ - "hooks/sql/valid.sql": "HOOK (description 'Test hook valid.');\nSELECT 1", - "hooks/sql/broken.sql": "HOOK (\nSELECT 1", + "sql/hooks/sql/valid.sql": "HOOK (description 'Test hook valid.');\nSELECT 1", + "sql/hooks/sql/broken.sql": "HOOK (\nSELECT 1", }, expected_kind=DeclarationKind.SQL_HOOK, - expected_paths=("hooks/sql/valid.sql",), + expected_paths=("sql/hooks/sql/valid.sql",), ), TolerantCategoryCase( description="audits retain valid siblings", files={ - "audits/singular/valid.sql": "AUDIT ();\nSELECT 1", - "audits/singular/broken.sql": "AUDIT (\nSELECT 1", + "sql/audits/singular/valid.sql": "AUDIT ();\nSELECT 1", + "sql/audits/singular/broken.sql": "AUDIT (\nSELECT 1", }, expected_kind=DeclarationKind.SINGULAR_AUDIT, - expected_paths=("audits/singular/valid.sql",), + expected_paths=("sql/audits/singular/valid.sql",), ), TolerantCategoryCase( description="sources retain valid siblings", files={ - "sources/valid.yml": "sources:\n - name: raw_orders\n description: Test source raw_orders.\n table: orders\n", - "sources/broken.yml": "sources: [\n", + "sql/sources/valid.yml": "sources:\n - name: raw_orders\n description: Test source raw_orders.\n table: orders\n", + "sql/sources/broken.yml": "sources: [\n", }, expected_kind=ResourceKind.SOURCE, - expected_paths=("sources/broken.yml", "sources/valid.yml"), + expected_paths=("sql/sources/broken.yml", "sql/sources/valid.yml"), ), ), ids=lambda case: case.description, @@ -686,7 +690,7 @@ def test_given_broken_authored_file_when_loading_then_valid_category_siblings_ar ) -> None: write_repo_files( tmp_path, - {"sqlbuild_project.toml": _PROJECT, "models/orders.sql": _MODEL} | test_case.files, + {"sqlbuild_project.toml": _PROJECT, "sql/models/orders.sql": _MODEL} | test_case.files, ) index: ScopeIndex = load_or_build_scope_index(project_dir=tmp_path, no_cache=True) @@ -718,7 +722,7 @@ def test_given_partial_project_when_loading_then_incomplete_index_is_not_cached( tmp_path, { "sqlbuild_project.toml": _PROJECT, - "models/broken.sql": "MODEL (\nSELECT 1", + "sql/models/broken.sql": "MODEL (\nSELECT 1", }, ) diff --git a/tests/unit/src/sqlbuild/compiler/scopes/test_paths.py b/tests/unit/src/sqlbuild/compiler/scopes/test_paths.py index b51ef5ece4..5904fa9c00 100644 --- a/tests/unit/src/sqlbuild/compiler/scopes/test_paths.py +++ b/tests/unit/src/sqlbuild/compiler/scopes/test_paths.py @@ -13,18 +13,18 @@ [ PathNormalizationCase( description="posix_redundant_components", - path="models/./staging/orders/../stg_orders.sql", - expected_path="models/staging/stg_orders.sql", + path="sql/models/./staging/orders/../stg_orders.sql", + expected_path="sql/models/staging/stg_orders.sql", ), PathNormalizationCase( description="windows_separators", - path=r"models\staging\orders\stg_orders.sql", - expected_path="models/staging/orders/stg_orders.sql", + path=r"sql\models\staging\orders\stg_orders.sql", + expected_path="sql/models/staging/orders/stg_orders.sql", ), PathNormalizationCase( description="repeated_separators", - path="models//staging///stg_orders.sql", - expected_path="models/staging/stg_orders.sql", + path="sql/models//staging///stg_orders.sql", + expected_path="sql/models/staging/stg_orders.sql", ), ], ids=lambda case: case.description, @@ -40,7 +40,7 @@ def test_given_posix_or_windows_path_when_normalizing_then_returns_canonical_pos [ PathNormalizationCase("absolute", "/models/orders.sql", "project-relative"), PathNormalizationCase("windows_drive", "C:\\models\\orders.sql", "project-relative"), - PathNormalizationCase("escaping", "models/../../orders.sql", "escapes the project"), + PathNormalizationCase("escaping", "sql/models/../../../orders.sql", "escapes the project"), ], ids=lambda case: case.description, ) diff --git a/tests/unit/src/sqlbuild/compiler/scopes/test_placement.py b/tests/unit/src/sqlbuild/compiler/scopes/test_placement.py index 7460de6d22..c0d0181a0d 100644 --- a/tests/unit/src/sqlbuild/compiler/scopes/test_placement.py +++ b/tests/unit/src/sqlbuild/compiler/scopes/test_placement.py @@ -65,19 +65,19 @@ def test_given_test_usage_through_macro_when_validating_placement_then_test_path test_identity: ResourceIdentity = ResourceIdentity( ResourceKind.TEST, "order_policy__returns_quantity" ) - ownership_root: OwnershipRoot = OwnershipRoot("models", resource_kind=ResourceKind.MODEL) + ownership_root: OwnershipRoot = OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL) declaration: DeclarationRecord = DeclarationRecord( identity=macro_identity, - path="models/orders/_sqlbuild/_macros/python/policy.py", + path="sql/models/orders/_sqlbuild/_macros/python/policy.py", line=1, column=1, scope=ScopeKind.LOCAL, ownership_root=ownership_root, - owning_path="models/orders", + owning_path="sql/models/orders", ) index: ScopeIndex = ScopeIndex( resources=( - ResourceRecord(model_identity, "models/orders/orders.sql", ownership_root), + ResourceRecord(model_identity, "sql/models/orders/orders.sql", ownership_root), ResourceRecord( test_identity, "tests/unit/macros/models/orders/test_order_policy__returns_quantity.sql", @@ -153,8 +153,8 @@ def test_given_non_placement_error_when_placement_enforcement_disabled_then_vali "unused global is rejected", ScopeKind.GLOBAL, None, - "constants/limit.sql", - "constants", + "sql/constants/limit.sql", + "sql/constants", None, (), (ScopeDiagnosticCode.UNUSED_DECLARATION,), @@ -163,103 +163,103 @@ def test_given_non_placement_error_when_placement_enforcement_disabled_then_vali "global used by one owner is over broad", ScopeKind.GLOBAL, None, - "constants/limit.sql", - "constants", + "sql/constants/limit.sql", + "sql/constants", None, - ("models/domain/orders.sql",), + ("sql/models/domain/orders.sql",), (ScopeDiagnosticCode.OVER_BROAD_GLOBAL,), - expected_message_fragment="models/domain/_sqlbuild/_constants/", + expected_message_fragment="sql/models/domain/_sqlbuild/_constants/", ), PlacementValidationCase( "global across authored root children is accepted", ScopeKind.GLOBAL, None, - "constants/limit.sql", - "constants", + "sql/constants/limit.sql", + "sql/constants", None, - ("models/orders/orders.sql", "models/products/products.sql"), + ("sql/models/orders/orders.sql", "sql/models/products/products.sql"), (), ), PlacementValidationCase( "global used by authored root model recommends compatible legacy role", ScopeKind.GLOBAL, None, - "constants/limit.sql", - "constants", + "sql/constants/limit.sql", + "sql/constants", None, - ("models/orders.sql",), + ("sql/models/orders.sql",), (ScopeDiagnosticCode.OVER_BROAD_GLOBAL,), - expected_message_fragment="models/_constants/", + expected_message_fragment="sql/models/_constants/", ), PlacementValidationCase( "authored root inherited scope must be project global", ScopeKind.INHERITED, - "models", - "models/constants/limit.sql", - "models", + "sql/models", + "sql/models/constants/limit.sql", + "sql/models", ResourceKind.MODEL, - ("models/orders/orders.sql", "models/products/products.sql"), + ("sql/models/orders/orders.sql", "sql/models/products/products.sql"), (ScopeDiagnosticCode.REQUIRES_GLOBAL_PLACEMENT,), - expected_message_fragment="top-level constants/", + expected_message_fragment="top-level sql/constants/", ), PlacementValidationCase( "exact local is accepted", ScopeKind.LOCAL, - "models/domain", - "models/domain/_constants/limit.sql", - "models", + "sql/models/domain", + "sql/models/domain/_constants/limit.sql", + "sql/models", ResourceKind.MODEL, - ("models/domain/orders.sql",), + ("sql/models/domain/orders.sql",), (), ), PlacementValidationCase( "grouped exact local is accepted", ScopeKind.LOCAL, - "models/domain", - "models/domain/_sqlbuild/_constants/limit.sql", - "models", + "sql/models/domain", + "sql/models/domain/_sqlbuild/_constants/limit.sql", + "sql/models", ResourceKind.MODEL, - ("models/domain/orders.sql",), + ("sql/models/domain/orders.sql",), (), ), PlacementValidationCase( "local needed by descendant", ScopeKind.LOCAL, - "models/domain", - "models/domain/_constants/limit.sql", - "models", + "sql/models/domain", + "sql/models/domain/_constants/limit.sql", + "sql/models", ResourceKind.MODEL, - ("models/domain/child/orders.sql",), + ("sql/models/domain/child/orders.sql",), (ScopeDiagnosticCode.LOCAL_NEEDED_BY_DESCENDANT,), ), PlacementValidationCase( "inherited multi child lca is accepted", ScopeKind.INHERITED, - "models/domain", - "models/domain/constants/limit.sql", - "models", + "sql/models/domain", + "sql/models/domain/constants/limit.sql", + "sql/models", ResourceKind.MODEL, - ("models/domain/a/orders.sql", "models/domain/b/customers.sql"), + ("sql/models/domain/a/orders.sql", "sql/models/domain/b/customers.sql"), (), ), PlacementValidationCase( "grouped inherited multi child lca is accepted", ScopeKind.INHERITED, - "models/domain", - "models/domain/_sqlbuild/constants/limit.sql", - "models", + "sql/models/domain", + "sql/models/domain/_sqlbuild/constants/limit.sql", + "sql/models", ResourceKind.MODEL, - ("models/domain/a/orders.sql", "models/domain/b/customers.sql"), + ("sql/models/domain/a/orders.sql", "sql/models/domain/b/customers.sql"), (), ), PlacementValidationCase( "inherited at one consumer directory is over broad", ScopeKind.INHERITED, - "models/domain", - "models/domain/constants/limit.sql", - "models", + "sql/models/domain", + "sql/models/domain/constants/limit.sql", + "sql/models", ResourceKind.MODEL, - ("models/domain/orders.sql",), + ("sql/models/domain/orders.sql",), (ScopeDiagnosticCode.OVER_BROAD_INHERITED,), ), ), @@ -286,7 +286,7 @@ def test_given_complete_usage_when_validating_then_exact_placement_is_enforced( ResourceRecord( identity=ResourceIdentity(ResourceKind.MODEL, f"model_{index}"), path=path, - ownership_root=OwnershipRoot("models", resource_kind=ResourceKind.MODEL), + ownership_root=OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), ) for index, path in enumerate(test_case.consumer_paths) ) @@ -318,17 +318,27 @@ def test_given_complete_usage_when_validating_then_exact_placement_is_enforced( DeclarationChainPlacementCase( description="diamond chain shares an intermediate consumer", declarations=( - ("base", ScopeKind.LOCAL, "models/domain", "models/domain/_macros/python/base.py"), - ("left", ScopeKind.LOCAL, "models/domain", "models/domain/_macros/python/left.py"), + ( + "base", + ScopeKind.LOCAL, + "sql/models/domain", + "sql/models/domain/_macros/python/base.py", + ), + ( + "left", + ScopeKind.LOCAL, + "sql/models/domain", + "sql/models/domain/_macros/python/left.py", + ), ( "right", ScopeKind.LOCAL, - "models/domain", - "models/domain/_macros/python/right.py", + "sql/models/domain", + "sql/models/domain/_macros/python/right.py", ), ), declaration_usages=(("base", "left"), ("base", "right")), - model_consumers=(("models/domain/orders.sql", ("left", "right")),), + model_consumers=(("sql/models/domain/orders.sql", ("left", "right")),), expected_codes=(), ), DeclarationChainPlacementCase( @@ -337,13 +347,18 @@ def test_given_complete_usage_when_validating_then_exact_placement_is_enforced( ( "alpha", ScopeKind.LOCAL, - "models/domain", - "models/domain/_macros/python/alpha.py", + "sql/models/domain", + "sql/models/domain/_macros/python/alpha.py", + ), + ( + "beta", + ScopeKind.LOCAL, + "sql/models/domain", + "sql/models/domain/_macros/python/beta.py", ), - ("beta", ScopeKind.LOCAL, "models/domain", "models/domain/_macros/python/beta.py"), ), declaration_usages=(("alpha", "beta"), ("beta", "alpha")), - model_consumers=(("models/domain/orders.sql", ("beta",)),), + model_consumers=(("sql/models/domain/orders.sql", ("beta",)),), expected_codes=(), ), DeclarationChainPlacementCase( @@ -352,13 +367,18 @@ def test_given_complete_usage_when_validating_then_exact_placement_is_enforced( ( "base", ScopeKind.INHERITED, - "models/domain", - "models/domain/macros/python/base.py", + "sql/models/domain", + "sql/models/domain/macros/python/base.py", + ), + ( + "mid", + ScopeKind.LOCAL, + "sql/models/domain", + "sql/models/domain/_macros/python/mid.py", ), - ("mid", ScopeKind.LOCAL, "models/domain", "models/domain/_macros/python/mid.py"), ), declaration_usages=(("base", "mid"),), - model_consumers=(("models/domain/orders.sql", ("mid",)),), + model_consumers=(("sql/models/domain/orders.sql", ("mid",)),), expected_codes=(ScopeDiagnosticCode.OVER_BROAD_INHERITED,), ), DeclarationChainPlacementCase( @@ -367,19 +387,24 @@ def test_given_complete_usage_when_validating_then_exact_placement_is_enforced( ( "base_one", ScopeKind.LOCAL, - "models/domain", - "models/domain/_macros/python/base_one.py", + "sql/models/domain", + "sql/models/domain/_macros/python/base_one.py", ), ( "base_two", ScopeKind.LOCAL, - "models/domain", - "models/domain/_macros/python/base_two.py", + "sql/models/domain", + "sql/models/domain/_macros/python/base_two.py", + ), + ( + "mid", + ScopeKind.LOCAL, + "sql/models/domain", + "sql/models/domain/_macros/python/mid.py", ), - ("mid", ScopeKind.LOCAL, "models/domain", "models/domain/_macros/python/mid.py"), ), declaration_usages=(("base_one", "mid"), ("base_two", "mid")), - model_consumers=(("models/domain/orders.sql", ("mid",)),), + model_consumers=(("sql/models/domain/orders.sql", ("mid",)),), expected_codes=(), ), ), @@ -399,7 +424,7 @@ def test_given_declaration_consumption_chains_when_validating_then_anchors_resol line=1, column=1, scope=scope, - ownership_root=OwnershipRoot("models", resource_kind=ResourceKind.MODEL), + ownership_root=OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), owning_path=owning_path, ) for name, scope, owning_path, path in test_case.declarations @@ -414,7 +439,7 @@ def test_given_declaration_consumption_chains_when_validating_then_anchors_resol ResourceRecord( identity=model_identity, path=model_path, - ownership_root=OwnershipRoot("models", resource_kind=ResourceKind.MODEL), + ownership_root=OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), ) ) for declaration_name in declaration_names: @@ -455,12 +480,12 @@ def test_given_deep_diamond_ladder_when_validating_then_resolution_completes( declarations: tuple[DeclarationRecord, ...] = tuple( DeclarationRecord( identity=identity, - path=f"models/domain/_macros/{name}.py", + path=f"sql/models/domain/_macros/{name}.py", line=1, column=1, scope=ScopeKind.LOCAL, - ownership_root=OwnershipRoot("models", resource_kind=ResourceKind.MODEL), - owning_path="models/domain", + ownership_root=OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), + owning_path="sql/models/domain", ) for name, identity in identities.items() ) @@ -485,8 +510,8 @@ def test_given_deep_diamond_ladder_when_validating_then_resolution_completes( resources=( ResourceRecord( identity=model_identity, - path="models/domain/orders.sql", - ownership_root=OwnershipRoot("models", resource_kind=ResourceKind.MODEL), + path="sql/models/domain/orders.sql", + ownership_root=OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), ), ), declarations=declarations, @@ -505,9 +530,9 @@ def test_given_deep_diamond_ladder_when_validating_then_resolution_completes( PlacementValidationCase( "relationship", ScopeKind.LOCAL, - "models/domain", - "models/domain/_enums/state.sql", - "models", + "sql/models/domain", + "sql/models/domain/_enums/state.sql", + "sql/models", ResourceKind.MODEL, (), (), @@ -528,8 +553,8 @@ def test_given_relationship_and_cross_root_usages_when_validating_then_through_m 1, 1, ScopeKind.LOCAL, - OwnershipRoot("models", resource_kind=ResourceKind.MODEL), - owning_path="models/domain", + OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), + owning_path="sql/models/domain", ) resources: tuple[ResourceRecord, ...] = ( ResourceRecord( @@ -539,8 +564,8 @@ def test_given_relationship_and_cross_root_usages_when_validating_then_through_m ), ResourceRecord( model_identity, - "models/domain/orders.sql", - OwnershipRoot("models", resource_kind=ResourceKind.MODEL), + "sql/models/domain/orders.sql", + OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL), ), ) diff --git a/tests/unit/src/sqlbuild/compiler/scopes/test_relocation.py b/tests/unit/src/sqlbuild/compiler/scopes/test_relocation.py index cdbc2d4f3e..2faaa643d4 100644 --- a/tests/unit/src/sqlbuild/compiler/scopes/test_relocation.py +++ b/tests/unit/src/sqlbuild/compiler/scopes/test_relocation.py @@ -19,29 +19,29 @@ ( RelocationCase( description="sole consumer takes the schema and the macro it uses along", - consumer_paths=("models/staging/orders.sql",), - destination="models/marts/orders.sql", + consumer_paths=("sql/models/staging/orders.sql",), + destination="sql/models/marts/orders.sql", expected_paths=( - "models/marts/_sqlbuild/_schemas/order_shape.sql", - "models/marts/_sqlbuild/_macros/python/cents.py", + "sql/models/marts/_sqlbuild/_schemas/order_shape.sql", + "sql/models/marts/_sqlbuild/_macros/python/cents.py", ), ), RelocationCase( description="remaining consumers lift the schema while its macro stays beside it", - consumer_paths=("models/staging/orders.sql", "models/staging/refunds.sql"), - destination="models/staging/eu/orders.sql", - expected_paths=("models/staging/_sqlbuild/schemas/order_shape.sql",), + consumer_paths=("sql/models/staging/orders.sql", "sql/models/staging/refunds.sql"), + destination="sql/models/staging/eu/orders.sql", + expected_paths=("sql/models/staging/_sqlbuild/schemas/order_shape.sql",), ), RelocationCase( description="consumers spanning the models root use top-level roles", - consumer_paths=("models/staging/orders.sql", "models/staging/refunds.sql"), - destination="models/marts/orders.sql", - expected_paths=("schemas/order_shape.sql", "macros/python/cents.py"), + consumer_paths=("sql/models/staging/orders.sql", "sql/models/staging/refunds.sql"), + destination="sql/models/marts/orders.sql", + expected_paths=("sql/schemas/order_shape.sql", "sql/macros/python/cents.py"), ), RelocationCase( description="move within the owner changes nothing", - consumer_paths=("models/staging/orders.sql",), - destination="models/staging/orders_v2.sql", + consumer_paths=("sql/models/staging/orders.sql",), + destination="sql/models/staging/orders_v2.sql", expected_paths=(), ), ), diff --git a/tests/unit/src/sqlbuild/compiler/scopes/test_reports.py b/tests/unit/src/sqlbuild/compiler/scopes/test_reports.py index 8bad2dd96b..f609af449e 100644 --- a/tests/unit/src/sqlbuild/compiler/scopes/test_reports.py +++ b/tests/unit/src/sqlbuild/compiler/scopes/test_reports.py @@ -40,8 +40,8 @@ "test_case", ( ScopeReportTargetCase("qualified", "model:orders", "model:orders", ()), - ScopeReportTargetCase("exact_path", "models/staging/orders.sql", "model:orders", ()), - ScopeReportTargetCase("windows_path", r"models\staging\orders.sql", "model:orders", ()), + ScopeReportTargetCase("exact_path", "sql/models/staging/orders.sql", "model:orders", ()), + ScopeReportTargetCase("windows_path", r"sql\models\staging\orders.sql", "model:orders", ()), ScopeReportTargetCase( "bare", "orders", None, (ScopeDiagnosticCode.UNQUALIFIED_TARGET.value,) ), @@ -79,8 +79,8 @@ def test_given_resource_when_querying_then_sections_and_scope_chain_are_separate ] assert [item.identity for item in report.relationship_scope] == ["enum:mart_status"] assert [item.path for item in report.scope_chain] == [ - "models/staging", - "models", + "sql/models/staging", + "sql/models", "global", ] assert [item.identity for item in report.nearby_unavailable] == ["enum:other_status"] @@ -94,16 +94,16 @@ def test_given_prospective_paths_when_querying_then_visibility_is_pure_and_parti test_case: ExpectedBooleanCase, ) -> None: file_report: ScopeReport = query_scope_report( - lookup=report_scope_lookup(), at=r"models\staging\new.sql" + lookup=report_scope_lookup(), at=r"sql\models\staging\new.sql" ) directory_report: ScopeReport = query_scope_report( - lookup=report_scope_lookup(), at="models/staging", directory=True + lookup=report_scope_lookup(), at="sql/models/staging", directory=True ) invalid_report: ScopeReport = query_scope_report( lookup=report_scope_lookup(), at="../outside.sql" ) invalid_suffix: ScopeReport = query_scope_report( - lookup=report_scope_lookup(), at="models/staging/new.txt" + lookup=report_scope_lookup(), at="sql/models/staging/new.txt" ) assert "enum:order_status" in {item.identity for item in file_report.available} @@ -123,13 +123,13 @@ def test_given_empty_authored_root_when_querying_prospective_path_then_root_fact ) -> None: lookup: ScopeLookup = build_scope_lookup( index=ScopeIndex( - ownership_roots=(OwnershipRoot("models", resource_kind=ResourceKind.MODEL),) + ownership_roots=(OwnershipRoot("sql/models", resource_kind=ResourceKind.MODEL),) ) ) - report: ScopeReport = query_scope_report(lookup=lookup, at="models/new.sql") + report: ScopeReport = query_scope_report(lookup=lookup, at="sql/models/new.sql") - assert report.resource.path == "models/new.sql" + assert report.resource.path == "sql/models/new.sql" assert report.resource.prospective is test_case.expected_result assert report.diagnostics[-1].code is ScopeDiagnosticCode.INCOMPLETE_USAGE @@ -227,7 +227,7 @@ def test_given_folder_tree_when_browsing_and_listing_then_counts_are_exact( filters=ScopeReportFilters(page_size=10_001), ) - assert [item.path for item in root.folders] == ["global", "models"] + assert [item.path for item in root.folders] == ["global", "sql"] assert constants.folders[0].descendant_count == 10_000 assert listed.section.total == 10_000 assert len(listed.declarations) == 10_000 @@ -246,12 +246,12 @@ def test_given_target_when_browsing_and_listing_used_declarations_then_counts_ar lookup: ScopeLookup = report_scope_lookup() browse: ScopeBrowseResult = browse_scope_folders( lookup=lookup, - folder="models/marts", + folder="sql/models/marts", target="model:orders", ) listed: ScopeListResult = list_scope_declarations( lookup=lookup, - folder="models/marts", + folder="sql/models/marts", target="model:orders", filters=ScopeReportFilters(used_only=True), ) @@ -283,7 +283,7 @@ def test_given_declaration_when_explaining_then_metadata_is_typed_and_value_safe "render_as": None, "role": "constants", "visibility_label": "project", - "role_root": "constants", + "role_root": "sql/constants", "bucket_path": None, } assert test_case.expected_result @@ -318,7 +318,7 @@ def test_given_resource_move_when_previewing_then_deltas_and_grants_are_separate preview, diagnostics = preview_scope_move( lookup=report_scope_lookup(), resource="model:orders", - destination="models/marts/orders.sql", + destination="sql/models/marts/orders.sql", ) invalid, invalid_diagnostics = preview_scope_move( lookup=report_scope_lookup(), @@ -328,11 +328,11 @@ def test_given_resource_move_when_previewing_then_deltas_and_grants_are_separate occupied, occupied_diagnostics = preview_scope_move( lookup=report_scope_lookup(), resource="model:orders", - destination="models/marts/expected_orders.sql", + destination="sql/models/marts/expected_orders.sql", ) base_lookup: ScopeLookup = report_scope_lookup() source: ResourceRecord = base_lookup.index.resources[0] - duplicate_path: str = "models/marts/duplicate_orders.sql" + duplicate_path: str = "sql/models/marts/duplicate_orders.sql" duplicate_lookup: ScopeLookup = build_scope_lookup( index=replace( base_lookup.index, @@ -341,7 +341,7 @@ def test_given_resource_move_when_previewing_then_deltas_and_grants_are_separate ) duplicate, duplicate_diagnostics = preview_scope_move( lookup=duplicate_lookup, - resource="models/staging/orders.sql", + resource="sql/models/staging/orders.sql", destination=duplicate_path, ) diff --git a/tests/unit/src/sqlbuild/cost/test_snowflake_scale.py b/tests/unit/src/sqlbuild/cost/test_snowflake_scale.py index 04fadde417..19fb8be184 100644 --- a/tests/unit/src/sqlbuild/cost/test_snowflake_scale.py +++ b/tests/unit/src/sqlbuild/cost/test_snowflake_scale.py @@ -10,6 +10,7 @@ from typing import Any import pytest +from snowflake.connector.errors import ProgrammingError as SnowflakeProgrammingError from sqlbuild._native import ( CostCommandRequest, @@ -286,10 +287,23 @@ def test_given_a_history_read_timeout_when_collecting_then_only_retried_reads_ar ) +class _RefusingCursor: + """A role that may read neither the account nor its rate sheet: the list price is used.""" + + def execute(self, sql: str) -> None: + raise SnowflakeProgrammingError(msg=f"not authorized: {sql}", errno=2003) + + def close(self) -> None: + return None + + class _ClosingHistory(_FakeQueryHistory): def close(self) -> None: return None + def cursor(self) -> _RefusingCursor: + return _RefusingCursor() + class ProgrammingError(Exception): """Stands in for the Snowflake connector's error of the same name.""" diff --git a/tests/unit/src/sqlbuild/errors/setting_help/main/test_setting_help.py b/tests/unit/src/sqlbuild/errors/setting_help/main/test_setting_help.py index 1c26ec50b9..383f049c6f 100644 --- a/tests/unit/src/sqlbuild/errors/setting_help/main/test_setting_help.py +++ b/tests/unit/src/sqlbuild/errors/setting_help/main/test_setting_help.py @@ -63,10 +63,10 @@ "a snippet help shows every line to write", snippet_help( purpose="to describe it", - target="add this to seeds/lookups.yml", + target="add this to sql/seeds/lookups.yml", lines=("- name: product_types", " description: Product type catalogue"), ), - "to describe it, add this to seeds/lookups.yml:\n" + "to describe it, add this to sql/seeds/lookups.yml:\n" " - name: product_types\n" " description: Product type catalogue", ), diff --git a/tests/unit/src/sqlbuild/executor/build/_helpers/helpers.py b/tests/unit/src/sqlbuild/executor/build/_helpers/helpers.py index 2e2800504b..b4333160d1 100644 --- a/tests/unit/src/sqlbuild/executor/build/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/executor/build/_helpers/helpers.py @@ -74,7 +74,7 @@ def build_model_plan_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=materialization_type, action=action, reason=reason, @@ -98,7 +98,7 @@ def build_seed_plan_entry(*, name: str) -> SeedPlanEntry: destination=CompiledRelationLocation( database=None, schema="main", name=name, qualified_name=f"main.{name}" ), - file_path=Path(f"seeds/{name}.csv"), + file_path=Path(f"sql/seeds/{name}.csv"), columns=(), csv_settings=SeedCsvSettings(), ) @@ -142,8 +142,8 @@ def failing_source_node_test_loader(_ctx: object) -> list[dict[str, object]]: def build_discovered_source_loader(*, loader_name: str) -> DiscoveredLoaderFunction: return DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name=loader_name, function=source_node_test_loader, ) @@ -151,8 +151,8 @@ def build_discovered_source_loader(*, loader_name: str) -> DiscoveredLoaderFunct def build_failing_discovered_source_loader(*, loader_name: str) -> DiscoveredLoaderFunction: return DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name=loader_name, function=failing_source_node_test_loader, ) diff --git a/tests/unit/src/sqlbuild/executor/build/_helpers/test_scheduler.py b/tests/unit/src/sqlbuild/executor/build/_helpers/test_scheduler.py index 764ad8b30d..15a0cdd288 100644 --- a/tests/unit/src/sqlbuild/executor/build/_helpers/test_scheduler.py +++ b/tests/unit/src/sqlbuild/executor/build/_helpers/test_scheduler.py @@ -305,7 +305,7 @@ def maybe_skip(ctx: HookContext) -> object: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/maybe_skip.py"), + relative_path=Path("sql/hooks/python/maybe_skip.py"), name="maybe_skip", function=maybe_skip, ), diff --git a/tests/unit/src/sqlbuild/executor/clone/_helpers/fingerprinting/helpers.py b/tests/unit/src/sqlbuild/executor/clone/_helpers/fingerprinting/helpers.py index 118a40d383..433634e650 100644 --- a/tests/unit/src/sqlbuild/executor/clone/_helpers/fingerprinting/helpers.py +++ b/tests/unit/src/sqlbuild/executor/clone/_helpers/fingerprinting/helpers.py @@ -78,7 +78,7 @@ def build_model_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=materialization, action=PlanAction.CREATE_TABLE, reason=PlanReason.NO_CHANGE, @@ -94,7 +94,7 @@ def build_seed_entry(name: str, *, schema: str) -> SeedPlanEntry: key=CompiledObjectKey(resource_type=CompiledResourceType.SEED, name=name), name=name, destination=build_location(name=name, schema=schema), - file_path=Path(f"seeds/{name}.csv"), + file_path=Path(f"sql/seeds/{name}.csv"), columns=(), csv_settings=SeedCsvSettings(), ) diff --git a/tests/unit/src/sqlbuild/executor/clone/_helpers/helpers.py b/tests/unit/src/sqlbuild/executor/clone/_helpers/helpers.py index 5785b253de..f6937ae534 100644 --- a/tests/unit/src/sqlbuild/executor/clone/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/executor/clone/_helpers/helpers.py @@ -146,7 +146,7 @@ def build_clone_function_entry( return FunctionPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.UDF, name=name), name=name, - relative_path=Path("functions/sql") / f"{name}.sql", + relative_path=Path("sql/functions/sql") / f"{name}.sql", destination=destination, arguments=(), returns="INTEGER", @@ -183,7 +183,7 @@ def _build_retention_model(*, name: str, schema: str) -> CompiledModelView: key=key, deps=(), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), query_sql=f"SELECT 1 AS {name}_id", config=CompileModelConfig( time_travel_retention=ResolvedTimeTravelRetention( diff --git a/tests/unit/src/sqlbuild/executor/janitor/main/helpers.py b/tests/unit/src/sqlbuild/executor/janitor/main/helpers.py index a708950eac..3611546ba9 100644 --- a/tests/unit/src/sqlbuild/executor/janitor/main/helpers.py +++ b/tests/unit/src/sqlbuild/executor/janitor/main/helpers.py @@ -581,7 +581,7 @@ def build_project( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), deps=(), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), query_sql="select 1", config=CompileModelConfig(values={"migrate_from": migrate_from}), destination=CompiledRelationLocation( diff --git a/tests/unit/src/sqlbuild/executor/load/test_execute.py b/tests/unit/src/sqlbuild/executor/load/test_execute.py index 0048124707..79c5b624f5 100644 --- a/tests/unit/src/sqlbuild/executor/load/test_execute.py +++ b/tests/unit/src/sqlbuild/executor/load/test_execute.py @@ -91,8 +91,8 @@ def raw_orders_loader(ctx: LoaderContext) -> Iterator[dict[str, object]]: write_strategy=SourceWriteStrategy.TABLE, ), loader_function=DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name="raw_orders_loader", function=raw_orders_loader, ), @@ -154,8 +154,8 @@ def failing_loader(ctx: LoaderContext) -> Iterator[dict[str, object]]: write_strategy=SourceWriteStrategy.TABLE, ), loader_function=DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name="raw_orders_loader", function=failing_loader, ), @@ -228,8 +228,8 @@ def raw_orders_loader(ctx: LoaderContext) -> None: cursor_column="updated_at", ), loader_function=DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name=test_case.loader_name, function=raw_orders_loader, ), @@ -323,8 +323,8 @@ def raw_orders_loader( meta={"sqlbuild_loader_node": True}, ), loader_function=DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name=test_case.loader_name, function=raw_orders_loader, destination="staging_raw_orders", @@ -400,8 +400,8 @@ def raw_orders_loader(ctx: LoaderContext) -> None: meta={"sqlbuild_loader_node": True}, ), loader_function=DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name=test_case.loader_name, function=raw_orders_loader, destination="staging_raw_orders", @@ -468,8 +468,8 @@ def raw_orders_loader( meta={"sqlbuild_loader_node": True}, ), loader_function=DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name=test_case.loader_name, function=raw_orders_loader, destination="staging_raw_orders", @@ -532,8 +532,8 @@ def fetch_orders(ctx: LoaderContext) -> None: meta={"sqlbuild_loader_node": True}, ), loader_function=DiscoveredLoaderFunction( - file_path=Path("python/loaders/raw.py"), - relative_path=Path("python/loaders/raw.py"), + file_path=Path("python/nodes/loaders/raw.py"), + relative_path=Path("python/nodes/loaders/raw.py"), name=test_case.loader_name, function=fetch_orders, destination=test_case.loader_target, diff --git a/tests/unit/src/sqlbuild/executor/load/test_run.py b/tests/unit/src/sqlbuild/executor/load/test_run.py index c0af7947ca..43a99be365 100644 --- a/tests/unit/src/sqlbuild/executor/load/test_run.py +++ b/tests/unit/src/sqlbuild/executor/load/test_run.py @@ -67,8 +67,8 @@ def loader(_ctx: LoaderContext) -> None: sources=(SourceEntry(name="ordered", loader="ordered_loader"),), loader_functions=( DiscoveredLoaderFunction( - file_path=Path("python/loaders/ordered.py"), - relative_path=Path("python/loaders/ordered.py"), + file_path=Path("python/nodes/loaders/ordered.py"), + relative_path=Path("python/nodes/loaders/ordered.py"), name="ordered_loader", function=loader, ), @@ -161,27 +161,27 @@ def c_loader(_ctx: LoaderContext) -> None: ), loader_functions=( DiscoveredLoaderFunction( - file_path=Path("python/loaders/a.py"), - relative_path=Path("python/loaders/a.py"), + file_path=Path("python/nodes/loaders/a.py"), + relative_path=Path("python/nodes/loaders/a.py"), name="a_loader", function=a_loader, ), DiscoveredLoaderFunction( - file_path=Path("python/loaders/x.py"), - relative_path=Path("python/loaders/x.py"), + file_path=Path("python/nodes/loaders/x.py"), + relative_path=Path("python/nodes/loaders/x.py"), name="x_loader", function=x_loader, ), DiscoveredLoaderFunction( - file_path=Path("python/loaders/b.py"), - relative_path=Path("python/loaders/b.py"), + file_path=Path("python/nodes/loaders/b.py"), + relative_path=Path("python/nodes/loaders/b.py"), name="b_loader", function=b_loader, depends_on=(a_loader,), ), DiscoveredLoaderFunction( - file_path=Path("python/loaders/c.py"), - relative_path=Path("python/loaders/c.py"), + file_path=Path("python/nodes/loaders/c.py"), + relative_path=Path("python/nodes/loaders/c.py"), name="c_loader", function=c_loader, depends_on=(b_loader, x_loader), @@ -254,14 +254,14 @@ def second_loader(_ctx: LoaderContext) -> None: sources=sources, loader_functions=( DiscoveredLoaderFunction( - file_path=Path("python/loaders/first.py"), - relative_path=Path("python/loaders/first.py"), + file_path=Path("python/nodes/loaders/first.py"), + relative_path=Path("python/nodes/loaders/first.py"), name="first_loader", function=first_loader, ), DiscoveredLoaderFunction( - file_path=Path("python/loaders/second.py"), - relative_path=Path("python/loaders/second.py"), + file_path=Path("python/nodes/loaders/second.py"), + relative_path=Path("python/nodes/loaders/second.py"), name="second_loader", function=second_loader, ), diff --git a/tests/unit/src/sqlbuild/executor/pipeline/_helpers/helpers.py b/tests/unit/src/sqlbuild/executor/pipeline/_helpers/helpers.py index 322e2d4958..7eff39153f 100644 --- a/tests/unit/src/sqlbuild/executor/pipeline/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/executor/pipeline/_helpers/helpers.py @@ -287,7 +287,7 @@ def build_seed_plan_entry(*, name: str) -> SeedPlanEntry: name=name, qualified_name=name, ), - file_path=Path(f"seeds/{name}.csv"), + file_path=Path(f"sql/seeds/{name}.csv"), columns=(), csv_settings=DEFAULT_SEED_CSV_SETTINGS, ) @@ -400,7 +400,7 @@ def order_status_function_test_plan(*, body_sql: str, test_count: int) -> PlanOu FunctionPlanEntry( key=function_key, name="is_completed_order", - relative_path=Path("functions/sql/is_completed_order.sql"), + relative_path=Path("sql/functions/sql/is_completed_order.sql"), destination=destination, arguments=(FunctionArgument(name="order_status", type="VARCHAR"),), returns="BOOLEAN", @@ -435,7 +435,7 @@ def order_status_callee_test_plan(*, callee_body_sql: str, test_count: int) -> P FunctionPlanEntry( key=callee_key, name="status_matches", - relative_path=Path("functions/sql/status_matches.sql"), + relative_path=Path("sql/functions/sql/status_matches.sql"), destination=callee_destination, arguments=(FunctionArgument(name="order_status", type="VARCHAR"),), returns="BOOLEAN", diff --git a/tests/unit/src/sqlbuild/executor/pipeline/main/helpers.py b/tests/unit/src/sqlbuild/executor/pipeline/main/helpers.py index e0bf2cfe63..b7e95270ab 100644 --- a/tests/unit/src/sqlbuild/executor/pipeline/main/helpers.py +++ b/tests/unit/src/sqlbuild/executor/pipeline/main/helpers.py @@ -64,7 +64,7 @@ def build_schema_preflight_plan() -> PlanOutput: ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="orders"), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), materialization_type=MaterializationType.TABLE, action=PlanAction.CREATE_TABLE, reason=PlanReason.FIRST_RUN, @@ -79,7 +79,7 @@ def build_schema_preflight_plan() -> PlanOutput: key=CompiledObjectKey(resource_type=CompiledResourceType.SEED, name="statuses"), name="statuses", destination=_location(schema="dev", name="statuses"), - file_path=Path("seeds/statuses.csv"), + file_path=Path("sql/seeds/statuses.csv"), columns=(ColumnInfo(name="id", type="INTEGER"),), csv_settings=DEFAULT_SEED_CSV_SETTINGS, ), @@ -103,7 +103,7 @@ def build_schema_preflight_plan() -> PlanOutput: name="is_large_order", ), name="is_large_order", - relative_path=Path("functions/sql/is_large_order.sql"), + relative_path=Path("sql/functions/sql/is_large_order.sql"), destination=_location(schema="analytics", name="is_large_order"), arguments=(), returns="BOOLEAN", diff --git a/tests/unit/src/sqlbuild/executor/pipeline/main/test_schema_preflight.py b/tests/unit/src/sqlbuild/executor/pipeline/main/test_schema_preflight.py index 05e84836d5..d35d20d79c 100644 --- a/tests/unit/src/sqlbuild/executor/pipeline/main/test_schema_preflight.py +++ b/tests/unit/src/sqlbuild/executor/pipeline/main/test_schema_preflight.py @@ -121,7 +121,7 @@ def test_given_concurrent_microbatch_when_sizing_workers_then_retains_batch_conc entry: ModelPlanEntry = ModelPlanEntry( key=key, name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), materialization_type=MaterializationType.INCREMENTAL, action=PlanAction.INCREMENTAL_DELETE_INSERT, reason=PlanReason.NORMAL_INCREMENTAL, diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/helpers.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/helpers.py index d3b1f51b1b..28742402ef 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/helpers.py @@ -496,7 +496,7 @@ def build_ingress_task_asset_graph() -> PythonNodeGraph: ingress_task_function(), DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="publish_ingress_orders", function=publish_ingress_orders, depends_on=(prepare_ingress_orders,), @@ -509,7 +509,7 @@ def build_ingress_task_asset_graph() -> PythonNodeGraph: def ingress_task_function() -> DiscoveredAssetFunction: return DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="prepare_ingress_orders", function=prepare_ingress_orders, ) @@ -518,7 +518,7 @@ def ingress_task_function() -> DiscoveredAssetFunction: def ingress_loader_function() -> DiscoveredLoaderFunction: return DiscoveredLoaderFunction( file_path=Path("/project/loaders/orders.py"), - relative_path=Path("python/loaders/orders.py"), + relative_path=Path("python/nodes/loaders/orders.py"), name="load_ingress_orders", function=load_ingress_orders, depends_on=(prepare_ingress_orders,), @@ -568,14 +568,14 @@ def build_read_side_sql_task_asset_graph() -> PythonNodeGraph: asset_functions=( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="profile_stg_orders", function=profile_stg_orders, depends_on=(model("stg_orders"),), ), DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="export_stg_profile", function=export_stg_profile, depends_on=(profile_stg_orders,), @@ -617,7 +617,7 @@ def python_check_function_for_case(description: str) -> DiscoveredCheckFunction: }.get(description, passing_python_check) return DiscoveredCheckFunction( file_path=Path("/project/checks/orders.py"), - relative_path=Path("python/checks/orders.py"), + relative_path=Path("python/nodes/checks/orders.py"), name="check_upstream_task", function=function, depends_on=(check_upstream_task,), @@ -633,7 +633,7 @@ def build_python_check_graph(*, check_function: DiscoveredCheckFunction) -> Pyth asset_functions=( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="upstream_task", function=check_upstream_task, ), diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_discovered_items.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_discovered_items.py index 1239afd628..2d00506949 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_discovered_items.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_discovered_items.py @@ -60,7 +60,7 @@ def test_given_an_asset_node_when_running_it_then_discovered_items_supply_args_c ) -> None: node: DiscoveredAssetFunction = DiscoveredAssetFunction( file_path=Path("/project/python/plan/node.py"), - relative_path=Path("python/plan/node.py"), + relative_path=Path("python/nodes/plan/node.py"), name="step[b]", function=discovered_step, discovered=test_case.discovered, diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_execution.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_execution.py index ad3184719e..d2a7e40d84 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_execution.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_execution.py @@ -91,7 +91,7 @@ def test_given_successful_callable_when_result_persistence_fails_then_resource_o ) node: DiscoveredAssetFunction = DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="persist_orders", function=lambda: "ok", ) @@ -144,7 +144,7 @@ def test_given_successful_callable_when_owned_finalizer_fails_then_resource_only dispatcher.subscribe_lifecycle(subscriber=events.append, accepts_opaque=False) node: DiscoveredAssetFunction = DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="finalize_orders", function=lambda: "ok", ) @@ -197,13 +197,13 @@ def test_given_task_asset_chain_when_executing_python_nodes_then_records_results nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="fetch_orders", function=fetch_orders, ), DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="export_orders", function=export_orders, depends_on=(fetch_orders,), @@ -259,13 +259,13 @@ def test_given_provider_parameters_when_executing_python_nodes_then_providers_ar nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/provider.py"), - relative_path=Path("python/tasks/provider.py"), + relative_path=Path("python/nodes/tasks/provider.py"), name="provider_task", function=provider_task, ), DiscoveredAssetFunction( file_path=Path("/project/assets/provider.py"), - relative_path=Path("python/assets/provider.py"), + relative_path=Path("python/nodes/assets/provider.py"), name="provider_asset", function=provider_asset, ), @@ -317,13 +317,13 @@ def test_given_provider_container_when_executing_python_nodes_then_context_expos nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/provider.py"), - relative_path=Path("python/tasks/provider.py"), + relative_path=Path("python/nodes/tasks/provider.py"), name="context_provider_task", function=context_provider_task, ), DiscoveredAssetFunction( file_path=Path("/project/assets/provider.py"), - relative_path=Path("python/assets/provider.py"), + relative_path=Path("python/nodes/assets/provider.py"), name="context_provider_asset", function=context_provider_asset, ), @@ -377,13 +377,13 @@ def test_given_missing_provider_container_when_executing_python_nodes_then_failu nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/provider.py"), - relative_path=Path("python/tasks/provider.py"), + relative_path=Path("python/nodes/tasks/provider.py"), name="provider_task", function=provider_task, ), DiscoveredAssetFunction( file_path=Path("/project/assets/provider.py"), - relative_path=Path("python/assets/provider.py"), + relative_path=Path("python/nodes/assets/provider.py"), name="provider_asset", function=provider_asset, ), @@ -435,7 +435,7 @@ def test_given_missing_context_provider_when_executing_python_node_then_failure_ nodes=( DiscoveredAssetFunction( file_path=Path("/project/tasks/provider.py"), - relative_path=Path("python/tasks/provider.py"), + relative_path=Path("python/nodes/tasks/provider.py"), name="missing_context_provider_task", function=missing_context_provider_task, ), @@ -483,13 +483,13 @@ def test_given_ready_python_node_when_executing_then_uses_existing_run_state( run_state: PythonNodeRunState = PythonNodeRunState() task_node: DiscoveredAssetFunction = DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="fetch_orders", function=fetch_orders, ) asset_node: DiscoveredAssetFunction = DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="export_orders", function=export_orders, depends_on=(fetch_orders,), @@ -574,7 +574,7 @@ def test_given_cursor_overrides_when_executing_python_nodes_then_context_receive nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="cursor_window", function=cursor_window, ), @@ -626,13 +626,13 @@ def test_given_hard_skipped_upstream_when_executing_python_nodes_then_skips_down nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="skip_empty_orders", function=hard_skip_empty_orders, ), DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="export_after_skip", function=export_after_skip, depends_on=(hard_skip_empty_orders,), @@ -718,26 +718,26 @@ def test_given_mixed_python_skips_when_executing_nodes_then_fan_in_matches_mode( nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="skip_empty_orders", function=skip_function, ), DiscoveredAssetFunction( file_path=Path("/project/tasks/sibling.py"), - relative_path=Path("python/tasks/sibling.py"), + relative_path=Path("python/nodes/tasks/sibling.py"), name="successful_sibling", function=successful_sibling, ), DiscoveredAssetFunction( file_path=Path("/project/assets/intermediate.py"), - relative_path=Path("python/assets/intermediate.py"), + relative_path=Path("python/nodes/assets/intermediate.py"), name="export_after_skip", function=export_after_skip, depends_on=(skip_function,), ), DiscoveredAssetFunction( file_path=Path("/project/assets/final.py"), - relative_path=Path("python/assets/final.py"), + relative_path=Path("python/nodes/assets/final.py"), name="export_after_mixed_skip", function=export_after_mixed_skip, depends_on=(export_after_skip, successful_sibling), @@ -786,13 +786,13 @@ def test_given_failed_upstream_when_executing_python_nodes_then_blocks_downstrea nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="fail_orders", function=fail_orders, ), DiscoveredAssetFunction( file_path=Path("/project/assets/orders.py"), - relative_path=Path("python/assets/orders.py"), + relative_path=Path("python/nodes/assets/orders.py"), name="export_after_failure", function=export_after_failure, depends_on=(fail_orders,), @@ -848,7 +848,7 @@ def test_given_retry_policy_when_transient_failures_then_retries_and_succeeds( nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="flaky_task", function=flaky_task, retry=RetryPolicy( @@ -973,7 +973,7 @@ def test_given_retry_policy_when_attempts_exhausted_then_records_final_exception nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="flaky_task", function=flaky_task, retry=RetryPolicy( @@ -1032,7 +1032,7 @@ def test_given_retry_policy_when_exception_is_not_selected_then_does_not_retry( nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="flaky_task", function=flaky_task, retry=RetryPolicy(max_attempts=3, retry_on=TimeoutError, jitter=False), @@ -1086,7 +1086,7 @@ def test_given_retry_policy_when_backoff_exceeds_cap_then_sleep_is_capped( nodes: tuple[DiscoveredAssetFunction | DiscoveredAssetFunction, ...] = ( DiscoveredAssetFunction( file_path=Path("/project/tasks/orders.py"), - relative_path=Path("python/tasks/orders.py"), + relative_path=Path("python/nodes/tasks/orders.py"), name="flaky_task", function=flaky_task, retry=RetryPolicy( diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_fingerprinting.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_fingerprinting.py index d856b33a50..5a091d872e 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_fingerprinting.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_fingerprinting.py @@ -52,7 +52,7 @@ def test_given_python_identity_when_writing_fingerprint_then_uses_fingerprint_st identity=PythonNodeIdentity( node_type="asset", node_name="build_orders", - source_path="python/tasks/orders.py", + source_path="python/nodes/tasks/orders.py", source_hash="source-hash", definition_hash="definition-hash", version_hash="version-hash", diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_ingress_execution.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_ingress_execution.py index 30813069da..4f12d32d51 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_ingress_execution.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_ingress_execution.py @@ -227,7 +227,7 @@ def test_given_pre_recorded_hard_skip_when_scheduler_bypasses_downstream_then_on bypassed_node: DiscoveredPythonNode = DiscoveredPythonNode( kind=PythonNodeKind.ASSET, file_path=Path("/project/tasks/bypassed.py"), - relative_path=Path("python/tasks/bypassed.py"), + relative_path=Path("python/nodes/tasks/bypassed.py"), name="bypassed_task", function=scheduler_bypassed_task, ) diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/classes/helpers.py b/tests/unit/src/sqlbuild/executor/python_nodes/classes/helpers.py index a86656ae9d..109d5717be 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/classes/helpers.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/classes/helpers.py @@ -154,7 +154,7 @@ def item_graph( asset_functions=tuple( DiscoveredAssetFunction( file_path=Path("/project/python/plan.py"), - relative_path=Path("python/plan.py"), + relative_path=Path("python/nodes/plan.py"), name=name, function=run_item, depends_on=item_refs(parents), @@ -268,7 +268,7 @@ def writing_graph(steps: tuple[str, ...]) -> PythonNodeGraph: asset_functions=tuple( DiscoveredAssetFunction( file_path=Path("/project/python/plan.py"), - relative_path=Path("python/plan.py"), + relative_path=Path("python/nodes/plan.py"), name=step, function=write_step, discovered={ diff --git a/tests/unit/src/sqlbuild/executor/run/_helpers/helpers.py b/tests/unit/src/sqlbuild/executor/run/_helpers/helpers.py index 9bf270b38c..4f2b43724e 100644 --- a/tests/unit/src/sqlbuild/executor/run/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/executor/run/_helpers/helpers.py @@ -57,7 +57,7 @@ def build_result_model_plan_entry() -> ModelPlanEntry: name="orders", ), name="orders", - relative_path=Path("models/orders.sql"), + relative_path=Path("sql/models/orders.sql"), materialization_type=MaterializationType.TABLE, action=PlanAction.CREATE_TABLE, reason=PlanReason.FIRST_RUN, @@ -110,7 +110,7 @@ def build_snapshot_execution_plan_entry( name="customer_snapshot", ), name="customer_snapshot", - relative_path=Path("models/customer_snapshot.sql"), + relative_path=Path("sql/models/customer_snapshot.sql"), materialization_type=MaterializationType.SNAPSHOT, action=PlanAction.SNAPSHOT, reason=PlanReason.FIRST_RUN, @@ -346,7 +346,7 @@ def run_python_hook_with_relations( hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/lookups.py"), + relative_path=Path("sql/hooks/python/lookups.py"), name="refresh_lookup", function=function, reads=reads, diff --git a/tests/unit/src/sqlbuild/executor/run/_helpers/test_cursor_bounds.py b/tests/unit/src/sqlbuild/executor/run/_helpers/test_cursor_bounds.py index a597ba1243..46bfa0f61d 100644 --- a/tests/unit/src/sqlbuild/executor/run/_helpers/test_cursor_bounds.py +++ b/tests/unit/src/sqlbuild/executor/run/_helpers/test_cursor_bounds.py @@ -107,7 +107,7 @@ def test_given_typed_planner_cursor_input_when_building_runtime_spec_then_preser entry: ModelPlanEntry = ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name="events"), name="events", - relative_path=Path("models/events.sql"), + relative_path=Path("sql/models/events.sql"), materialization_type=MaterializationType.INCREMENTAL, action=PlanAction.INCREMENTAL_DELETE_INSERT, reason=PlanReason.NORMAL_INCREMENTAL, diff --git a/tests/unit/src/sqlbuild/executor/run/_helpers/test_hooks.py b/tests/unit/src/sqlbuild/executor/run/_helpers/test_hooks.py index ef1cf4065b..0ee02e2e1b 100644 --- a/tests/unit/src/sqlbuild/executor/run/_helpers/test_hooks.py +++ b/tests/unit/src/sqlbuild/executor/run/_helpers/test_hooks.py @@ -236,7 +236,7 @@ def notify(ctx: HookContext, message: str) -> None: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/notifications.py"), + relative_path=Path("sql/hooks/python/notifications.py"), name="notify", function=notify, ), @@ -311,7 +311,7 @@ def maybe_skip(ctx: HookContext) -> object: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/maybe_skip.py"), + relative_path=Path("sql/hooks/python/maybe_skip.py"), name="maybe_skip", function=maybe_skip, ), @@ -381,13 +381,13 @@ def should_not_run(ctx: HookContext) -> None: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/maybe_skip.py"), + relative_path=Path("sql/hooks/python/maybe_skip.py"), name="maybe_skip", function=maybe_skip, ), DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/should_not_run.py"), + relative_path=Path("sql/hooks/python/should_not_run.py"), name="should_not_run", function=should_not_run, ), @@ -447,7 +447,7 @@ def maybe_skip(ctx: HookContext) -> object: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/maybe_skip.py"), + relative_path=Path("sql/hooks/python/maybe_skip.py"), name="maybe_skip", function=maybe_skip, ), @@ -505,7 +505,7 @@ def invalid_return(ctx: HookContext) -> object: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/invalid_return.py"), + relative_path=Path("sql/hooks/python/invalid_return.py"), name="invalid_return", function=invalid_return, ), @@ -576,19 +576,19 @@ def uses_hook_context(hook_context: HookContext) -> object: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/aliases.py"), + relative_path=Path("sql/hooks/python/aliases.py"), name="uses_ctx", function=uses_ctx, ), DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/aliases.py"), + relative_path=Path("sql/hooks/python/aliases.py"), name="uses_context", function=uses_context, ), DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/aliases.py"), + relative_path=Path("sql/hooks/python/aliases.py"), name="uses_hook_context", function=uses_hook_context, ), @@ -638,7 +638,7 @@ def explode(ctx: HookContext) -> None: hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/explode.py"), + relative_path=Path("sql/hooks/python/explode.py"), name="explode", function=explode, ), diff --git a/tests/unit/src/sqlbuild/executor/run/_helpers/test_snapshot_adapter_boundary.py b/tests/unit/src/sqlbuild/executor/run/_helpers/test_snapshot_adapter_boundary.py index 306e9ae570..399ab58589 100644 --- a/tests/unit/src/sqlbuild/executor/run/_helpers/test_snapshot_adapter_boundary.py +++ b/tests/unit/src/sqlbuild/executor/run/_helpers/test_snapshot_adapter_boundary.py @@ -172,7 +172,7 @@ def test_given_existing_snapshot_target_when_executing_then_uses_adapter_rendere name="customer_snapshot", ), name="customer_snapshot", - relative_path=Path("models/customer_snapshot.sql"), + relative_path=Path("sql/models/customer_snapshot.sql"), materialization_type=MaterializationType.SNAPSHOT, action=PlanAction.SNAPSHOT, reason=PlanReason.NORMAL_INCREMENTAL, @@ -259,7 +259,7 @@ def test_given_existing_historical_timestamp_snapshot_when_executing_then_uses_a name="customer_snapshot", ), name="customer_snapshot", - relative_path=Path("models/customer_snapshot.sql"), + relative_path=Path("sql/models/customer_snapshot.sql"), materialization_type=MaterializationType.SNAPSHOT, action=PlanAction.SNAPSHOT, reason=PlanReason.NORMAL_INCREMENTAL, @@ -343,7 +343,7 @@ def test_given_existing_historical_timestamp_changes_snapshot_when_executing_the name="customer_snapshot", ), name="customer_snapshot", - relative_path=Path("models/customer_snapshot.sql"), + relative_path=Path("sql/models/customer_snapshot.sql"), materialization_type=MaterializationType.SNAPSHOT, action=PlanAction.SNAPSHOT, reason=PlanReason.NORMAL_INCREMENTAL, @@ -416,7 +416,7 @@ def test_given_new_historical_timestamp_changes_when_executing_then_uses_adapter name="customer_snapshot", ), name="customer_snapshot", - relative_path=Path("models/customer_snapshot.sql"), + relative_path=Path("sql/models/customer_snapshot.sql"), materialization_type=MaterializationType.SNAPSHOT, action=PlanAction.SNAPSHOT, reason=PlanReason.NORMAL_INCREMENTAL, diff --git a/tests/unit/src/sqlbuild/executor/run/_helpers/test_snapshot_lifecycle.py b/tests/unit/src/sqlbuild/executor/run/_helpers/test_snapshot_lifecycle.py index 9217840fbd..cd1d5088ff 100644 --- a/tests/unit/src/sqlbuild/executor/run/_helpers/test_snapshot_lifecycle.py +++ b/tests/unit/src/sqlbuild/executor/run/_helpers/test_snapshot_lifecycle.py @@ -68,7 +68,7 @@ hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/snapshot.py"), + relative_path=Path("sql/hooks/python/snapshot.py"), name="insert_hook_log", function=insert_snapshot_hook_log, ), @@ -189,7 +189,7 @@ def test_given_python_snapshot_hook_failure_when_executing_then_reports_hook_pha hook_functions=( DiscoveredHookFunction( file_path=Path(__file__), - relative_path=Path("hooks/python/snapshot.py"), + relative_path=Path("sql/hooks/python/snapshot.py"), name="fail_hook", function=fail_snapshot_hook, ), diff --git a/tests/unit/src/sqlbuild/executor/scenario/_helpers/helpers.py b/tests/unit/src/sqlbuild/executor/scenario/_helpers/helpers.py index 8dbd2bc5f1..5012885d1e 100644 --- a/tests/unit/src/sqlbuild/executor/scenario/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/executor/scenario/_helpers/helpers.py @@ -99,7 +99,7 @@ def build_snapshot_input_specs_test_plan( ), name="currency_codes", destination=_target("seed", "currency_codes"), - file_path=Path("seeds/currency_codes.csv"), + file_path=Path("sql/seeds/currency_codes.csv"), columns=(), csv_settings=DEFAULT_SEED_CSV_SETTINGS, ), @@ -111,7 +111,7 @@ def build_snapshot_input_specs_test_plan( name="daily_revenue", ), name="daily_revenue", - relative_path=Path("models/daily_revenue.sql"), + relative_path=Path("sql/models/daily_revenue.sql"), materialization_type=MaterializationType.TABLE, action=PlanAction.CREATE_TABLE, reason=PlanReason.FIRST_RUN, diff --git a/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_capture.py b/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_capture.py index ef2f111d58..e61b46c1e4 100644 --- a/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_capture.py +++ b/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_capture.py @@ -169,7 +169,7 @@ def test_given_multiple_capture_seeds_when_executing_then_operation_and_resource name="__sqb_51b385aebe20__seed__country_codes_regions", qualified_name="scenario_schema.__sqb_51b385aebe20__seed__country_codes_regions", ), - file_path=Path("seeds/regions.csv"), + file_path=Path("sql/seeds/regions.csv"), ) scenario_plan: ScenarioExecutionPlan = replace( SCENARIO_PLAN, diff --git a/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_snapshots.py b/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_snapshots.py index 175f1f0695..12aec45cc3 100644 --- a/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_snapshots.py +++ b/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_snapshots.py @@ -103,7 +103,7 @@ logical_name="currency_codes", source_target=SNAPSHOT_CAPTURE_PLAN.seed_entries[0].destination, file_path=Path("seeds/currency_codes.jsonl"), - capture_sql="seed_file:seeds/currency_codes.csv", + capture_sql="seed_file:sql/seeds/currency_codes.csv", ), ScenarioSnapshotCaptureRelationPlan( kind=ScenarioArtifactKind.SOURCE, @@ -269,7 +269,7 @@ def test_given_invalid_snapshot_jsonl_when_reading_then_raises_clear_error( tmp_path: Path, test_case: ScenarioSnapshotJsonlErrorTestCase, ) -> None: - file_path: Path = tmp_path / "sources" / "raw__orders.jsonl" + file_path: Path = tmp_path / "sql" / "sources" / "raw__orders.jsonl" file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(test_case.file_contents, encoding="utf-8") @@ -399,7 +399,7 @@ def test_given_snapshot_manifest_state_when_classifying_then_returns_expected_st kind=ScenarioArtifactKind.SEED, logical_name="currency_codes", file_path=Path("seeds/currency_codes.jsonl"), - capture_sql="seed_file:seeds/currency_codes.csv", + capture_sql="seed_file:sql/seeds/currency_codes.csv", ), ScenarioSnapshotInputSpec( kind=ScenarioArtifactKind.SOURCE, diff --git a/tests/unit/src/sqlbuild/executor/scenario/main/helpers.py b/tests/unit/src/sqlbuild/executor/scenario/main/helpers.py index 24332d22e7..0d14465816 100644 --- a/tests/unit/src/sqlbuild/executor/scenario/main/helpers.py +++ b/tests/unit/src/sqlbuild/executor/scenario/main/helpers.py @@ -322,7 +322,7 @@ def build_scenario_cleanup_test_plan( name="daily_revenue", ), name="daily_revenue", - relative_path=Path("models/daily_revenue.sql"), + relative_path=Path("sql/models/daily_revenue.sql"), materialization_type=model_materialization_type, action=PlanAction.CREATE_TABLE, reason=PlanReason.FIRST_RUN, @@ -357,7 +357,7 @@ def build_scenario_cleanup_test_plan_with_project_seed() -> ScenarioExecutionPla ), name="country_codes", destination=seed_target, - file_path=Path("seeds/country_codes.csv"), + file_path=Path("sql/seeds/country_codes.csv"), columns=(), csv_settings=DEFAULT_SEED_CSV_SETTINGS, ), @@ -425,7 +425,7 @@ def build_scenario_model_entry( return ModelPlanEntry( key=CompiledObjectKey(resource_type=CompiledResourceType.MODEL, name=name), name=name, - relative_path=Path(f"models/{name}.sql"), + relative_path=Path(f"sql/models/{name}.sql"), materialization_type=materialization_type, action=action, reason=PlanReason.FIRST_RUN, diff --git a/tests/unit/src/sqlbuild/integrations/dagster/helpers.py b/tests/unit/src/sqlbuild/integrations/dagster/helpers.py index c2ddd50488..913a677337 100644 --- a/tests/unit/src/sqlbuild/integrations/dagster/helpers.py +++ b/tests/unit/src/sqlbuild/integrations/dagster/helpers.py @@ -126,35 +126,35 @@ def build_dagster_test_dag() -> Mapping[str, Any]: "kind": "source", "name": "raw_orders", "asset_key": ["raw", "orders"], - "path": "sources/raw.yml", + "path": "sql/sources/raw.yml", }, { "id": "loader:shared_order_feed", "kind": "loader", "name": "shared_order_feed", "asset_key": ["shared_order_feed"], - "path": "python/loaders/orders.py", + "path": "python/nodes/loaders/orders.py", }, { "id": "loader:raw_orders_loader", "kind": "loader", "name": "raw_orders_loader", "asset_key": ["raw_orders_loader"], - "path": "python/loaders/orders.py", + "path": "python/nodes/loaders/orders.py", }, { "id": "seed:waffle_types", "kind": "seed", "name": "waffle_types", "asset_key": ["analytics", "waffle_types"], - "path": "seeds/waffle_types.csv", + "path": "sql/seeds/waffle_types.csv", }, { "id": "udf:normalize_email", "kind": "udf", "name": "normalize_email", "asset_key": ["analytics", "normalize_email"], - "path": "functions/normalize_email.sql", + "path": "sql/functions/normalize_email.sql", "language": "sql", }, { @@ -162,7 +162,7 @@ def build_dagster_test_dag() -> Mapping[str, Any]: "kind": "model", "name": "orders", "asset_key": ["analytics", "orders"], - "path": "models/orders.sql", + "path": "sql/models/orders.sql", "description": "Clean orders", "sql": 'MODEL (materialized table);\n\nSELECT * FROM __source("raw", "orders")', "tags": ["daily"], @@ -173,7 +173,7 @@ def build_dagster_test_dag() -> Mapping[str, Any]: "kind": "model", "name": "customers", "asset_key": ["analytics", "customers"], - "path": "models/customers.sql", + "path": "sql/models/customers.sql", "materialization_type": "view", }, ], @@ -189,7 +189,7 @@ def build_dagster_test_dag() -> Mapping[str, Any]: "kind": "audit", "name": "not_null", "checked_asset_ids": ["model:orders"], - "path": "audits/not_null.sql", + "path": "sql/audits/not_null.sql", "attached_column_name": "order_id", }, { @@ -197,7 +197,7 @@ def build_dagster_test_dag() -> Mapping[str, Any]: "kind": "audit", "name": "freshness", "checked_asset_ids": ["source:raw_orders"], - "path": "audits/freshness.sql", + "path": "sql/audits/freshness.sql", "attached_column_name": "loaded_at", }, { @@ -227,7 +227,7 @@ def build_python_augmented_dagster_test_dag() -> Mapping[str, Any]: "kind": "asset", "name": "prepare_orders", "asset_key": ["asset", "prepare_orders"], - "path": "python/assets/prepare_orders.py", + "path": "python/nodes/assets/prepare_orders.py", "tags": ["daily"], "group": "python", "meta": {"owner": "data"}, @@ -237,7 +237,7 @@ def build_python_augmented_dagster_test_dag() -> Mapping[str, Any]: "kind": "asset", "name": "orders_export", "asset_key": ["asset", "orders_export"], - "path": "python/assets/orders_export.py", + "path": "python/nodes/assets/orders_export.py", "tags": ["daily"], "group": "exports", "columns": [{"name": "order_id", "type": "integer"}], @@ -249,7 +249,7 @@ def build_python_augmented_dagster_test_dag() -> Mapping[str, Any]: "kind": "check", "name": "check_orders_export", "asset_key": ["check", "check_orders_export"], - "path": "python/checks/check_orders_export.py", + "path": "python/nodes/checks/check_orders_export.py", "tags": ["daily"], }, ] @@ -266,7 +266,7 @@ def build_python_augmented_dagster_test_dag() -> Mapping[str, Any]: "kind": "python_check", "name": "check_orders_export", "checked_asset_ids": ["asset:orders_export"], - "path": "python/checks/check_orders_export.py", + "path": "python/nodes/checks/check_orders_export.py", "severity": "error", "tags": ["daily"], }, @@ -550,7 +550,7 @@ def _selection_model_node(name: str) -> dict[str, Any]: "kind": "model", "name": name, "asset_key": ["analytics", name], - "path": f"models/{name}.sql", + "path": f"sql/models/{name}.sql", "materialization_type": "table", } diff --git a/tests/unit/src/sqlbuild/integrations/dagster/test_assets.py b/tests/unit/src/sqlbuild/integrations/dagster/test_assets.py index fcf4f2f94f..809ddb9562 100644 --- a/tests/unit/src/sqlbuild/integrations/dagster/test_assets.py +++ b/tests/unit/src/sqlbuild/integrations/dagster/test_assets.py @@ -54,30 +54,30 @@ "kind": "model", "name": "orders", "description": "Clean orders", - "path": "models/orders.sql", + "path": "sql/models/orders.sql", "sql": "SELECT 1", }, expected_description=("Clean orders\n\n**SQLBuild SQL:**\n```sql\nSELECT 1\n```"), ), DagsterDescriptionTestCase( description="non-SQL asset includes its source path", - node={"kind": "seed", "name": "waffles", "path": "seeds/waffles.csv"}, + node={"kind": "seed", "name": "waffles", "path": "sql/seeds/waffles.csv"}, expected_description=( - "SQLBuild seed `waffles`.\n\n**Source file:** `seeds/waffles.csv`" + "SQLBuild seed `waffles`.\n\n**Source file:** `sql/seeds/waffles.csv`" ), ), DagsterDescriptionTestCase( description="source path containing backticks remains one code span", - node={"kind": "seed", "name": "waffles", "path": "seeds/`waffles`.csv"}, + node={"kind": "seed", "name": "waffles", "path": "sql/seeds/`waffles`.csv"}, expected_description=( - "SQLBuild seed `waffles`.\n\n**Source file:** ``seeds/`waffles`.csv``" + "SQLBuild seed `waffles`.\n\n**Source file:** ``sql/seeds/`waffles`.csv``" ), ), DagsterDescriptionTestCase( description="source path whitespace is preserved", - node={"kind": "seed", "name": "waffles", "path": " seeds/waffles.csv "}, + node={"kind": "seed", "name": "waffles", "path": " sql/seeds/waffles.csv "}, expected_description=( - "SQLBuild seed `waffles`.\n\n**Source file:** ` seeds/waffles.csv `" + "SQLBuild seed `waffles`.\n\n**Source file:** ` sql/seeds/waffles.csv `" ), ), DagsterDescriptionTestCase( @@ -174,7 +174,7 @@ def is_asset_check(self, check: Mapping[str, Any]) -> bool: ), DagsterAssetSelectionTestCase( description="path selector", - select="path:models", + select="path:sql/models", exclude=None, expected_asset_keys=(("analytics", "customers"), ("analytics", "orders")), ), @@ -359,7 +359,7 @@ def assets_def() -> dg.MaterializeResult: "MODEL (materialized table);", ), expected_seed_description=( - "SQLBuild seed `waffle_types`.\n\n**Source file:** `seeds/waffle_types.csv`" + "SQLBuild seed `waffle_types`.\n\n**Source file:** `sql/seeds/waffle_types.csv`" ), ) ], diff --git a/tests/unit/src/sqlbuild/integrations/dbt/helpers.py b/tests/unit/src/sqlbuild/integrations/dbt/helpers.py index 24290f5e19..417d77d5f7 100644 --- a/tests/unit/src/sqlbuild/integrations/dbt/helpers.py +++ b/tests/unit/src/sqlbuild/integrations/dbt/helpers.py @@ -340,7 +340,9 @@ def build_compiled_project_with_model_specs( model_name: str sql: str for model_name, sql in sql_by_model_name.items(): - relative_path: Path = Path(path_by_model_name.get(model_name, f"models/{model_name}.sql")) + relative_path: Path = Path( + path_by_model_name.get(model_name, f"sql/models/{model_name}.sql") + ) model_file: DiscoveredSqlModelFile = DiscoveredSqlModelFile( file_path=Path("/repo") / relative_path, relative_path=relative_path, diff --git a/tests/unit/src/sqlbuild/integrations/dbt/test_plan_orchestration.py b/tests/unit/src/sqlbuild/integrations/dbt/test_plan_orchestration.py index 989a060164..6dec5a3b6d 100644 --- a/tests/unit/src/sqlbuild/integrations/dbt/test_plan_orchestration.py +++ b/tests/unit/src/sqlbuild/integrations/dbt/test_plan_orchestration.py @@ -78,10 +78,10 @@ "mart_orders": ("nightly",), } _SQLBUILD_PATHS: dict[str, str] = { - "stg_local": "models/staging/stg_local.sql", - "fact_orders": "models/marts/fact_orders.sql", - "mart_orders": "models/marts/mart_orders.sql", - "local_only": "models/local/local_only.sql", + "stg_local": "sql/models/staging/stg_local.sql", + "fact_orders": "sql/models/marts/fact_orders.sql", + "mart_orders": "sql/models/marts/mart_orders.sql", + "local_only": "sql/models/local/local_only.sql", } @@ -345,11 +345,11 @@ sqlbuild_model_sql_by_name=_SQLBUILD_SQL, sqlbuild_model_tags_by_name=_SQLBUILD_TAGS, sqlbuild_model_path_by_name=_SQLBUILD_PATHS, - select=("path:models/marts",), + select=("path:sql/models/marts",), exclude=(), full_dbt_ls_unique_ids=(), anchor_dbt_ls_unique_ids_by_term={}, - expected_dbt_ls_selects=(("path:models/marts",),), + expected_dbt_ls_selects=(("path:sql/models/marts",),), expected_sqlbuild_model_names=("fact_orders", "mart_orders"), expected_dbt_required_unique_ids=(), expected_dbt_required_selector_terms=(), @@ -359,8 +359,8 @@ ), expected_dbt_skipped=True, expected_sqlbuild_skipped=False, - dbt_command_args=("--select", "path:models/marts"), - expected_primary_dbt_command_argv=("dbt", "ls", "--select", "path:models/marts"), + dbt_command_args=("--select", "path:sql/models/marts"), + expected_primary_dbt_command_argv=("dbt", "ls", "--select", "path:sql/models/marts"), expected_path_translations=(), ), DbtPlanOrchestrationTestCase( @@ -370,11 +370,11 @@ sqlbuild_model_sql_by_name=_SQLBUILD_SQL, sqlbuild_model_tags_by_name=_SQLBUILD_TAGS, sqlbuild_model_path_by_name=_SQLBUILD_PATHS, - select=("path:models\\marts",), + select=("path:sql\\models\\marts",), exclude=(), full_dbt_ls_unique_ids=(), anchor_dbt_ls_unique_ids_by_term={}, - expected_dbt_ls_selects=(("path:models\\marts",),), + expected_dbt_ls_selects=(("path:sql\\models\\marts",),), expected_sqlbuild_model_names=("fact_orders", "mart_orders"), expected_dbt_required_unique_ids=(), expected_dbt_required_selector_terms=(), @@ -384,9 +384,9 @@ ), expected_dbt_skipped=True, expected_sqlbuild_skipped=False, - dbt_command_args=("--select", "path:models\\marts"), - expected_primary_dbt_command_argv=("dbt", "ls", "--select", "path:models\\marts"), - expected_path_translations=(("path:models\\marts", "path:models/marts"),), + dbt_command_args=("--select", "path:sql\\models\\marts"), + expected_primary_dbt_command_argv=("dbt", "ls", "--select", "path:sql\\models\\marts"), + expected_path_translations=(("path:sql\\models\\marts", "path:sql/models/marts"),), ), DbtPlanOrchestrationTestCase( description="does not run anchor ls for SQLBuild-owned path in mixed selectors", @@ -395,11 +395,11 @@ sqlbuild_model_sql_by_name=_SQLBUILD_SQL, sqlbuild_model_tags_by_name=_SQLBUILD_TAGS, sqlbuild_model_path_by_name=_SQLBUILD_PATHS, - select=("state:modified", "path:models/marts+"), + select=("state:modified", "path:sql/models/marts+"), exclude=(), full_dbt_ls_unique_ids=("model.analytics.int_orders",), anchor_dbt_ls_unique_ids_by_term={}, - expected_dbt_ls_selects=(("state:modified", "path:models/marts+"),), + expected_dbt_ls_selects=(("state:modified", "path:sql/models/marts+"),), expected_sqlbuild_model_names=("fact_orders", "mart_orders"), expected_dbt_required_unique_ids=(), expected_dbt_required_selector_terms=(), @@ -417,13 +417,13 @@ ), expected_dbt_skipped=False, expected_sqlbuild_skipped=False, - dbt_command_args=("--select", "state:modified", "path:models/marts+"), + dbt_command_args=("--select", "state:modified", "path:sql/models/marts+"), expected_primary_dbt_command_argv=( "dbt", "run", "--select", "state:modified", - "path:models/marts+", + "path:sql/models/marts+", ), expected_path_translations=(), ), diff --git a/tests/unit/src/sqlbuild/integrations/dbt/test_runner.py b/tests/unit/src/sqlbuild/integrations/dbt/test_runner.py index 041f4b0407..9cba1fc82f 100644 --- a/tests/unit/src/sqlbuild/integrations/dbt/test_runner.py +++ b/tests/unit/src/sqlbuild/integrations/dbt/test_runner.py @@ -216,7 +216,7 @@ def test_given_dbt_options_when_building_ls_argv_then_returns_expected_command( '{"unique_id":"model.analytics.orders","resource_type":"model",' '"package_name":"analytics","name":"orders",' '"fqn":["analytics","marts","orders"],' - '"original_file_path":"models/orders.sql"}\n' + '"original_file_path":"sql/models/orders.sql"}\n' "not json\n" '{"unique_id":"source.analytics.raw.orders","resource_type":"source"}\n' ), diff --git a/tests/unit/src/sqlbuild/integrations/dbt/test_selection.py b/tests/unit/src/sqlbuild/integrations/dbt/test_selection.py index 370ecb87c9..003db47b6b 100644 --- a/tests/unit/src/sqlbuild/integrations/dbt/test_selection.py +++ b/tests/unit/src/sqlbuild/integrations/dbt/test_selection.py @@ -59,10 +59,10 @@ } _SQLBUILD_PATHS: dict[str, str] = { - "stg_local": "models/staging/stg_local.sql", - "fact_orders": "models/marts/fact_orders.sql", - "mart_orders": "models/marts/mart_orders.sql", - "local_only": "models/local/local_only.sql", + "stg_local": "sql/models/staging/stg_local.sql", + "fact_orders": "sql/models/marts/fact_orders.sql", + "mart_orders": "sql/models/marts/mart_orders.sql", + "local_only": "sql/models/local/local_only.sql", } @@ -328,7 +328,7 @@ sqlbuild_model_sql_by_name=_SQLBUILD_SQL, sqlbuild_model_tags_by_name=_SQLBUILD_TAGS, sqlbuild_model_path_by_name=_SQLBUILD_PATHS, - select=("path:models/marts",), + select=("path:sql/models/marts",), exclude=(), dbt_anchor_unique_ids_by_term={}, expected_sqlbuild_model_names=("fact_orders", "mart_orders"), @@ -341,12 +341,12 @@ sqlbuild_model_sql_by_name=_SQLBUILD_SQL, sqlbuild_model_tags_by_name=_SQLBUILD_TAGS, sqlbuild_model_path_by_name=_SQLBUILD_PATHS, - select=("path:models\\marts",), + select=("path:sql\\models\\marts",), exclude=(), dbt_anchor_unique_ids_by_term={}, expected_sqlbuild_model_names=("fact_orders", "mart_orders"), expected_dbt_required_unique_ids=(), - expected_path_translations=(("path:models\\marts", "path:models/marts"),), + expected_path_translations=(("path:sql\\models\\marts", "path:sql/models/marts"),), ), DbtSelectionTestCase( description="selects SQLBuild explicit model path with upstream expansion", @@ -354,7 +354,7 @@ sqlbuild_model_sql_by_name=_SQLBUILD_SQL, sqlbuild_model_tags_by_name=_SQLBUILD_TAGS, sqlbuild_model_path_by_name=_SQLBUILD_PATHS, - select=("+path:models/marts",), + select=("+path:sql/models/marts",), exclude=(), dbt_anchor_unique_ids_by_term={}, expected_sqlbuild_model_names=("fact_orders", "mart_orders"), @@ -370,7 +370,7 @@ sqlbuild_model_sql_by_name=_SQLBUILD_SQL, sqlbuild_model_tags_by_name=_SQLBUILD_TAGS, sqlbuild_model_path_by_name=_SQLBUILD_PATHS, - select=("path:models/marts+",), + select=("path:sql/models/marts+",), exclude=(), dbt_anchor_unique_ids_by_term={}, expected_sqlbuild_model_names=("fact_orders", "mart_orders"), @@ -528,7 +528,7 @@ def test_given_dbt_interop_selectors_when_resolving_then_returns_expected_sqlbui ), sqlbuild_model_sql_by_name={"fact_orders": "select 1"}, sqlbuild_model_tags_by_name={}, - sqlbuild_model_path_by_name={"fact_orders": "models/marts/fact_orders.sql"}, + sqlbuild_model_path_by_name={"fact_orders": "sql/models/marts/fact_orders.sql"}, select=("stg_orders~fact_orders",), expected_error_fragment="endpoint 'stg_orders' is ambiguous across dbt models", ) diff --git a/tests/unit/src/sqlbuild/lint/_helpers/helpers.py b/tests/unit/src/sqlbuild/lint/_helpers/helpers.py index dfcb5f2de8..3ebedbdbf4 100644 --- a/tests/unit/src/sqlbuild/lint/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/lint/_helpers/helpers.py @@ -72,7 +72,7 @@ def write_orders_lint_project(*, project_dir: Path, model_bytes: bytes) -> Path: _ = (project_dir / "sqlbuild_project.toml").write_text( 'name = "orders"\nadapter = "duckdb"\n', encoding="utf-8" ) - model_path: Path = project_dir / "models" / "orders.sql" + model_path: Path = project_dir / "sql" / "models" / "orders.sql" model_path.parent.mkdir(parents=True) _ = model_path.write_bytes(model_bytes) test_path: Path = project_dir / "tests" / "test_orders.sql" @@ -90,14 +90,14 @@ def write_orders_lint_project(*, project_dir: Path, model_bytes: bytes) -> Path: def write_linked_orders_project(*, project_dir: Path) -> None: """Write models reached both directly and through file and directory links.""" - (project_dir / "models" / "orders").mkdir(parents=True) - (project_dir / "shared").mkdir() - (project_dir / "models" / "orders" / "orders.sql").write_text("SELECT 1 AS order_id\n") + (project_dir / "sql" / "models" / "orders").mkdir(parents=True) + (project_dir / "shared").mkdir(parents=True) + (project_dir / "sql" / "models" / "orders" / "orders.sql").write_text("SELECT 1 AS order_id\n") (project_dir / "shared" / "customers.sql").write_text("SELECT 1 AS customer_id\n") - (project_dir / "models" / "orders" / "customers_link.sql").symlink_to( + (project_dir / "sql" / "models" / "orders" / "customers_link.sql").symlink_to( project_dir / "shared" / "customers.sql" ) - (project_dir / "models" / "shared_link").symlink_to(project_dir / "shared") + (project_dir / "sql" / "models" / "shared_link").symlink_to(project_dir / "shared") def files_resolving_to(*, files: dict[Path, str], selected: frozenset[Path]) -> dict[Path, str]: diff --git a/tests/unit/src/sqlbuild/lint/_helpers/test_expansion.py b/tests/unit/src/sqlbuild/lint/_helpers/test_expansion.py index 927a91f511..c55889e30c 100644 --- a/tests/unit/src/sqlbuild/lint/_helpers/test_expansion.py +++ b/tests/unit/src/sqlbuild/lint/_helpers/test_expansion.py @@ -28,10 +28,10 @@ _NOT_NULL_AUDIT: str = "AUDIT ();\nSELECT 1 FROM @relation WHERE @column IS NULL\n" _BROKEN_MODEL: str = 'MODEL (description "Broken");\nSELECT @py.unknown()\n' _UNEXPANDABLE_FILES: dict[str, str] = { - "models/customers.sql": _CUSTOMERS_MODEL, - "models/orders.sql": _ORDERS_MODEL, - "models/aa_broken.sql": _BROKEN_MODEL, - "models/zz_broken.sql": _BROKEN_MODEL, + "sql/models/customers.sql": _CUSTOMERS_MODEL, + "sql/models/orders.sql": _ORDERS_MODEL, + "sql/models/aa_broken.sql": _BROKEN_MODEL, + "sql/models/zz_broken.sql": _BROKEN_MODEL, } @@ -41,10 +41,10 @@ BatchedPreparationTestCase( description="models, tests, and generic audits", files={ - "models/customers.sql": _CUSTOMERS_MODEL, - "models/orders.sql": _ORDERS_MODEL, + "sql/models/customers.sql": _CUSTOMERS_MODEL, + "sql/models/orders.sql": _ORDERS_MODEL, "tests/unit/test_orders.sql": _ORDERS_TEST, - "audits/generic/not_null.sql": _NOT_NULL_AUDIT, + "sql/audits/generic/not_null.sql": _NOT_NULL_AUDIT, }, expected_codes=("SQLCLEAN001",), ) @@ -69,7 +69,7 @@ def test_given_project_when_linting_then_bodies_of_every_kind_are_prepared_in_on [ UnexpandableFailureTestCase( description="first unexpandable file in path order is raised", - expected_error_file="models/aa_broken.sql", + expected_error_file="sql/models/aa_broken.sql", ) ], ids=lambda case: case.description, @@ -90,7 +90,7 @@ def test_given_unexpandable_files_when_linting_then_first_in_file_order_is_raise [ UnexpandableSkipTestCase( description="skipped unexpandable files are reported and the rest is linted", - expected_unexpandable=("models/aa_broken.sql", "models/zz_broken.sql"), + expected_unexpandable=("sql/models/aa_broken.sql", "sql/models/zz_broken.sql"), expected_codes=("SQLCLEAN001",), ) ], diff --git a/tests/unit/src/sqlbuild/lint/_helpers/test_header_wrapping.py b/tests/unit/src/sqlbuild/lint/_helpers/test_header_wrapping.py index 67505128c8..87d13b4048 100644 --- a/tests/unit/src/sqlbuild/lint/_helpers/test_header_wrapping.py +++ b/tests/unit/src/sqlbuild/lint/_helpers/test_header_wrapping.py @@ -50,10 +50,10 @@ def test_given_long_header_audits_when_formatting_then_lists_wrap_idempotently( config: LintConfig = LintConfig(line_width=test_case.line_width) formatted, faults = format_native_headers( - contents=test_case.header + _BODY, file_path=Path("models/orders.sql"), config=config + contents=test_case.header + _BODY, file_path=Path("sql/models/orders.sql"), config=config ) again, _ = format_native_headers( - contents=formatted, file_path=Path("models/orders.sql"), config=config + contents=formatted, file_path=Path("sql/models/orders.sql"), config=config ) assert faults == () diff --git a/tests/unit/src/sqlbuild/lint/_helpers/test_native.py b/tests/unit/src/sqlbuild/lint/_helpers/test_native.py index f3c067bb19..20dbf32563 100644 --- a/tests/unit/src/sqlbuild/lint/_helpers/test_native.py +++ b/tests/unit/src/sqlbuild/lint/_helpers/test_native.py @@ -24,7 +24,7 @@ LintRemediationTestCase, ) -FILE_PATH: Path = Path("models/example.sql") +FILE_PATH: Path = Path("sql/models/example.sql") DEFAULT_CONFIG: LintConfig = LintConfig() diff --git a/tests/unit/src/sqlbuild/lint/_helpers/test_project_files.py b/tests/unit/src/sqlbuild/lint/_helpers/test_project_files.py index ea414169a9..fe7e01964b 100644 --- a/tests/unit/src/sqlbuild/lint/_helpers/test_project_files.py +++ b/tests/unit/src/sqlbuild/lint/_helpers/test_project_files.py @@ -66,13 +66,13 @@ def test_given_discovered_project_when_collecting_files_then_returns_exact_autho [ SelectedProjectFilesTestCase( description="regular_file", - selected="models/orders/orders.sql", - expected_present=("models/orders/orders.sql",), + selected="sql/models/orders/orders.sql", + expected_present=("sql/models/orders/orders.sql",), ), SelectedProjectFilesTestCase( description="file_reached_through_links", selected="shared/customers.sql", - expected_present=("models/orders/customers_link.sql",), + expected_present=("sql/models/orders/customers_link.sql",), ), ], ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/lint/helpers.py b/tests/unit/src/sqlbuild/lint/helpers.py index 8b6c4b759d..3df72cdfb3 100644 --- a/tests/unit/src/sqlbuild/lint/helpers.py +++ b/tests/unit/src/sqlbuild/lint/helpers.py @@ -18,8 +18,8 @@ def write_fixture_format_project( """Write a contracted two-model project with one SQL fixture.""" (tmp_path / "sqlbuild_project.toml").write_text(project_toml, encoding="utf-8") - staging_model: Path = tmp_path / "models" / "stg_rows.sql" - staging_model.parent.mkdir() + staging_model: Path = tmp_path / "sql" / "models" / "stg_rows.sql" + staging_model.parent.mkdir(parents=True) staging_model.write_text( "MODEL (\n" ' description "Staged rows",\n' @@ -32,7 +32,7 @@ def write_fixture_format_project( "SELECT 1 AS id, TRUE AS flag\n", encoding="utf-8", ) - (tmp_path / "models" / "rows.sql").write_text( + (tmp_path / "sql" / "models" / "rows.sql").write_text( 'MODEL (description "Rows");\n\nSELECT id, flag FROM __ref("stg_rows")\n', encoding="utf-8", ) diff --git a/tests/unit/src/sqlbuild/lint/test_cli_format.py b/tests/unit/src/sqlbuild/lint/test_cli_format.py index e0146adeba..c5ef35c8ec 100644 --- a/tests/unit/src/sqlbuild/lint/test_cli_format.py +++ b/tests/unit/src/sqlbuild/lint/test_cli_format.py @@ -34,8 +34,8 @@ def test_given_unformatted_sql_when_formatting_then_mode_controls_writes( capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) original: str = 'MODEL (description "Orders");\nselect order_id,status from orders\n' model.write_text(original, encoding="utf-8") @@ -60,8 +60,8 @@ def test_given_legacy_lint_configuration_when_formatting_then_it_is_rejected( (tmp_path / "sqlbuild_project.toml").write_text( f'{PROJECT_TOML}\n[lint]\nselect = ["SQLCLEAN"]\n', encoding="utf-8" ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text('MODEL (description "Orders");\nSELECT 1 AS order_id\n', encoding="utf-8") exit_code: int = main(["--project-dir", str(tmp_path), "compile"]) @@ -81,8 +81,8 @@ def test_given_unselected_sql_rule_finding_when_formatting_then_rule_is_not_enfo capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\nSELECT order_id FROM orders LIMIT 1\n', encoding="utf-8", @@ -120,8 +120,8 @@ def test_given_redundant_typed_fixture_null_when_formatting_then_safe_fix_uses_c capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - staging_model: Path = tmp_path / "models" / "stg_orders.sql" - staging_model.parent.mkdir() + staging_model: Path = tmp_path / "sql" / "models" / "stg_orders.sql" + staging_model.parent.mkdir(parents=True) staging_model.write_text( "MODEL (\n" ' description "Staged orders",\n' @@ -134,7 +134,7 @@ def test_given_redundant_typed_fixture_null_when_formatting_then_safe_fix_uses_c "SELECT 1 AS order_id, CAST(NULL AS VARCHAR) AS status\n", encoding="utf-8", ) - (tmp_path / "models" / "orders.sql").write_text( + (tmp_path / "sql" / "models" / "orders.sql").write_text( 'MODEL (description "Orders");\n\nSELECT order_id, status FROM __ref("stg_orders")\n', encoding="utf-8", ) @@ -180,8 +180,8 @@ def test_given_all_null_empty_fixture_when_formatting_then_uses_empty_fixture_ma capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( "MODEL (\n" ' description "Orders",\n' @@ -231,8 +231,8 @@ def test_given_uncompilable_project_with_fixture_null_when_formatting_then_forma capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders");\n\nselect * from __ref("missing_orders")\n', encoding="utf-8", @@ -327,8 +327,8 @@ def test_given_middle_typed_null_when_formatting_then_star_safe_prefix_is_preser PROJECT_TOML + '\n[defaults]\ncontract = "enforced"\n', encoding="utf-8", ) - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) model.write_text( 'MODEL (description "Orders", columns (' "order_id (type INTEGER), status (type VARCHAR), amount (type DOUBLE)));\n" @@ -366,8 +366,8 @@ def test_given_empty_explicit_selector_when_formatting_then_no_files_are_modifie capsys: pytest.CaptureFixture[str], ) -> None: (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - model: Path = tmp_path / "models" / "orders.sql" - model.parent.mkdir() + model: Path = tmp_path / "sql" / "models" / "orders.sql" + model.parent.mkdir(parents=True) original: str = 'MODEL (description "Orders");\nselect 1 as order_id\n' model.write_text(original, encoding="utf-8") @@ -412,7 +412,7 @@ def test_given_macro_expanded_fixture_when_formatting_then_authored_source_is_no tmp_path=tmp_path, fixture_sql="@py.mock_rows()", ) - macro_file: Path = tmp_path / "macros" / "python" / "rows.py" + macro_file: Path = tmp_path / "sql" / "macros" / "python" / "rows.py" macro_file.parent.mkdir(parents=True) macro_file.write_text( "def mock_rows() -> str:\n" @@ -507,8 +507,8 @@ def test_given_test_path_selector_when_formatting_then_work_is_bounded_to_select PROJECT_TOML + '\n[defaults]\ncontract = "enforced"\n', encoding="utf-8", ) - model_dir: Path = tmp_path / "models" - model_dir.mkdir() + model_dir: Path = tmp_path / "sql" / "models" + model_dir.mkdir(parents=True) model_dir.joinpath("stg_orders.sql").write_text( 'MODEL (description "Test model stg_orders.", columns (order_id (type INTEGER), status (type VARCHAR)));\n' "SELECT 1 AS order_id, 'open' AS status\n", @@ -545,7 +545,7 @@ def test_given_test_path_selector_when_formatting_then_work_is_bounded_to_select encoding="utf-8", ) unselected_file: Path = tmp_path / "tests" / "unit" / "customers" / "test_other.sql" - unselected_file.parent.mkdir() + unselected_file.parent.mkdir(parents=True) unselected_file.write_text(fixture_sql, encoding="utf-8") _ = native_module.compile_stage_work_info(reset=True) diff --git a/tests/unit/src/sqlbuild/lint/test_expanded_lint.py b/tests/unit/src/sqlbuild/lint/test_expanded_lint.py index 8f798ab4a9..e13c743c37 100644 --- a/tests/unit/src/sqlbuild/lint/test_expanded_lint.py +++ b/tests/unit/src/sqlbuild/lint/test_expanded_lint.py @@ -61,12 +61,12 @@ def test_given_lint_context_when_building_then_project_is_discovered_once( description="lint expansion uses configured adapter array rendering", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "constants/countries.sql": ( + "sql/constants/countries.sql": ( 'CONSTANT (name countries, value ["GB", "FR"], render_as array);\n' ), - "models/demo.sql": f'{HEADER}SELECT @const("countries") AS countries\n', + "sql/models/demo.sql": f'{HEADER}SELECT @const("countries") AS countries\n', }, - model_path="models/demo.sql", + model_path="sql/models/demo.sql", authored_sql='SELECT @const("countries") AS countries', expected_sql="SELECT ['GB', 'FR'] AS countries", ), @@ -74,10 +74,10 @@ def test_given_lint_context_when_building_then_project_is_discovered_once( description="lint expansion uses inherited declaration visibility", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "models/domain/constants/value.sql": "CONSTANT (name value, value 9);\n", - "models/domain/child/demo.sql": f'{HEADER}SELECT @const("value") AS value\n', + "sql/models/domain/constants/value.sql": "CONSTANT (name value, value 9);\n", + "sql/models/domain/child/demo.sql": f'{HEADER}SELECT @const("value") AS value\n', }, - model_path="models/domain/child/demo.sql", + model_path="sql/models/domain/child/demo.sql", authored_sql='SELECT @const("value") AS value', expected_sql="SELECT 9 AS value", ), @@ -85,8 +85,8 @@ def test_given_lint_context_when_building_then_project_is_discovered_once( description="lint expansion uses expected model declaration grants", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "models/domain/_constants/value.sql": "CONSTANT (name value, value 12);\n", - "models/domain/orders.sql": f"{HEADER}SELECT 1 AS value\n", + "sql/models/domain/_constants/value.sql": "CONSTANT (name value, value 12);\n", + "sql/models/domain/orders.sql": f"{HEADER}SELECT 1 AS value\n", "tests/unit/other/orders_test.sql": ( "TEST ();\nWITH __expected__orders AS " '(SELECT @const("value") AS value) SELECT 1\n' @@ -125,8 +125,8 @@ def test_given_typed_constant_when_building_lint_context_then_uses_adapter_rende description="diagnostic inside macro output is attributed to the call site", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "macros/python/m.py": BAD_CONDITION_MACRO, - "models/demo.sql": f"{HEADER}SELECT value FROM t WHERE @py.bad_condition()\n", + "sql/macros/python/m.py": BAD_CONDITION_MACRO, + "sql/models/demo.sql": f"{HEADER}SELECT value FROM t WHERE @py.bad_condition()\n", }, expected_positions=((5, 27),), expected_message_fragments=("in SQL generated by @py.bad_condition()",), @@ -138,7 +138,7 @@ def test_given_typed_constant_when_building_lint_context_then_uses_adapter_rende description="diagnostic in authored SQL keeps its exact position", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "models/demo.sql": f"{HEADER}SELECT value FROM t WHERE value = NULL\n", + "sql/models/demo.sql": f"{HEADER}SELECT value FROM t WHERE value = NULL\n", }, expected_positions=((5, 33),), expected_message_fragments=(), @@ -150,7 +150,7 @@ def test_given_typed_constant_when_building_lint_context_then_uses_adapter_rende description="unbound audit parameter is linted without a parse failure", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "audits/generic/expr.sql": ( + "sql/audits/generic/expr.sql": ( 'AUDIT ();\n\nSELECT *\nFROM __ref("@model")\nWHERE NOT (@expression)\n' ), }, @@ -161,7 +161,7 @@ def test_given_typed_constant_when_building_lint_context_then_uses_adapter_rende description="model-local declarations expand in their owning model", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "models/demo.sql": ( + "sql/models/demo.sql": ( 'MODEL (\n description "ok",\n' " enums (_status [A]),\n" " constants (_limit 1)\n);\n" @@ -219,7 +219,9 @@ def test_given_generic_audit_arguments_when_linting_then_template_is_analyzed( tmp_path: Path, ) -> None: _ = (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - audit: Path = tmp_path / "audits" / "generic" / "measurement" / "accepted_values_where.sql" + audit: Path = ( + tmp_path / "sql" / "audits" / "generic" / "measurement" / "accepted_values_where.sql" + ) audit.parent.mkdir(parents=True) _ = audit.write_text( "AUDIT (evaluation measurement, value measured_value);\n\n" @@ -252,7 +254,7 @@ def test_given_generic_audit_argument_when_mapping_then_generated_region_is_not_ tmp_path: Path, ) -> None: _ = (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - audit: Path = tmp_path / "audits" / "generic" / "expression.sql" + audit: Path = tmp_path / "sql" / "audits" / "generic" / "expression.sql" audit.parent.mkdir(parents=True) contents: str = "AUDIT ();\nSELECT 1 FROM @relation\n" _ = audit.write_text(contents, encoding="utf-8") @@ -283,7 +285,7 @@ def test_given_unknown_macro_call_in_generic_audit_when_linting_then_it_fails_cl tmp_path: Path, ) -> None: _ = (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - audit: Path = tmp_path / "audits" / "generic" / "unknown_macro.sql" + audit: Path = tmp_path / "sql" / "audits" / "generic" / "unknown_macro.sql" audit.parent.mkdir(parents=True) _ = audit.write_text("AUDIT ();\nSELECT @py.unknown()\n", encoding="utf-8") @@ -307,11 +309,11 @@ def test_given_reserved_parent_directories_when_linting_model_then_classificatio test_case: LintBehaviorTestCase, tmp_path: Path, ) -> None: - project_dir: Path = tmp_path / "audits" / "generic" / "hooks" / "project" + project_dir: Path = tmp_path / "sql" / "audits" / "generic" / "sql" / "hooks" / "project" project_dir.mkdir(parents=True) _ = (project_dir / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - model: Path = project_dir / "models" / "demo.sql" - model.parent.mkdir() + model: Path = project_dir / "sql" / "models" / "demo.sql" + model.parent.mkdir(parents=True) _ = model.write_text(f"{HEADER}SELECT @@CTX:run_id AS value\n", encoding="utf-8") with pytest.raises(ProjectCompileError) as error: @@ -325,14 +327,14 @@ def test_given_reserved_parent_directories_when_linting_model_then_classificatio [ LintCompileFailureTestCase( description="missing project config fails instead of linting a fiction", - project_files={"models/demo.sql": f"{HEADER}SELECT 1 AS x FROM t\n"}, + project_files={"sql/models/demo.sql": f"{HEADER}SELECT 1 AS x FROM t\n"}, expected_message_fragment="must compile first", ), LintCompileFailureTestCase( description="missing env variable in SQL fails with the variable named", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "models/demo.sql": f"{HEADER}SELECT 1 AS x FROM @@ENV:SQLBUILD_ABSENT_VAR\n", + "sql/models/demo.sql": f"{HEADER}SELECT 1 AS x FROM @@ENV:SQLBUILD_ABSENT_VAR\n", }, expected_message_fragment="SQLBUILD_ABSENT_VAR", ), @@ -340,9 +342,9 @@ def test_given_reserved_parent_directories_when_linting_model_then_classificatio description="unsupported project module imports fail before lint expansion", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "macros/python/orders.py": "import macros.python.shared\n", - "macros/python/shared.py": "def shared_macro() -> str:\n return 'order_id'\n", - "models/demo.sql": f"{HEADER}SELECT 1 AS x\n", + "sql/macros/python/orders.py": "import sql.macros.python.shared\n", + "sql/macros/python/shared.py": "def shared_macro() -> str:\n return 'order_id'\n", + "sql/models/demo.sql": f"{HEADER}SELECT 1 AS x\n", }, expected_message_fragment="module imports are not supported", ), @@ -350,8 +352,8 @@ def test_given_reserved_parent_directories_when_linting_model_then_classificatio description="inaccessible declaration fails lint with compile visibility diagnostic", project_files={ "sqlbuild_project.toml": PROJECT_TOML, - "models/one/_constants/value.sql": "CONSTANT (name value, value 1);\n", - "models/two/demo.sql": f'{HEADER}SELECT @const("value") AS value\n', + "sql/models/one/_constants/value.sql": "CONSTANT (name value, value 1);\n", + "sql/models/two/demo.sql": f'{HEADER}SELECT @const("value") AS value\n', }, expected_message_fragment="known but inaccessible", ), diff --git a/tests/unit/src/sqlbuild/lint/test_run_lint.py b/tests/unit/src/sqlbuild/lint/test_run_lint.py index c19fcc0cd1..63c4d800dc 100644 --- a/tests/unit/src/sqlbuild/lint/test_run_lint.py +++ b/tests/unit/src/sqlbuild/lint/test_run_lint.py @@ -48,23 +48,23 @@ [ LintProjectTestCase( description="model without description faults", - files={"models/no_description.sql": NO_DESCRIPTION_MODEL}, + files={"sql/models/no_description.sql": NO_DESCRIPTION_MODEL}, expected_fault_codes=(("no_description.sql", "description-present"),), ), LintProjectTestCase( description="clean project reports no violations", - files={"models/fine.sql": CLEAN_MODEL}, + files={"sql/models/fine.sql": CLEAN_MODEL}, expected_fault_codes=(), ), LintProjectTestCase( description="schema declarations are discovered for linting", - files={"schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));\n"}, + files={"sql/schemas/order.sql": "SCHEMA (name order, columns (id (type INTEGER)));\n"}, expected_fault_codes=(), ), LintProjectTestCase( description="scoped declaration file preserves every header", files={ - "models/_enums/status.sql": ( + "sql/models/_enums/status.sql": ( 'ENUM (name "status", members [OPEN, CLOSED]);\n' 'ENUM (name "tier", members [ONE, TWO]);\n' ) @@ -101,17 +101,17 @@ def test_given_synthetic_project_when_linting_then_results_match_expected( FormatProjectTestCase( description="leading comment is relocated into the description", files={ - "models/commented.sql": ( + "sql/models/commented.sql": ( "-- A comment.\nMODEL (\n materialized table\n);\nSELECT 1 AS x FROM t\n" ) }, - expected_written_fragments={"models/commented.sql": 'description "A comment.",'}, + expected_written_fragments={"sql/models/commented.sql": 'description "A comment.",'}, expected_fault_codes=(), expected_formatted_count=1, ), FormatProjectTestCase( description="missing description is a fault and the file is still formatted", - files={"models/no_description.sql": NO_DESCRIPTION_MODEL}, + files={"sql/models/no_description.sql": NO_DESCRIPTION_MODEL}, expected_written_fragments={}, expected_fault_codes=("description-present",), expected_formatted_count=1, @@ -119,13 +119,13 @@ def test_given_synthetic_project_when_linting_then_results_match_expected( FormatProjectTestCase( description="SQLBuild reference calls survive canonical formatting", files={ - "models/reference.sql": ( + "sql/models/reference.sql": ( 'MODEL (description "Reference formatting.");\n' 'select order_id from __ref("orders")\n' ) }, expected_written_fragments={ - "models/reference.sql": 'FROM __ref("orders")', + "sql/models/reference.sql": 'FROM __ref("orders")', }, expected_fault_codes=(), expected_formatted_count=1, @@ -133,13 +133,13 @@ def test_given_synthetic_project_when_linting_then_results_match_expected( FormatProjectTestCase( description="measurement audit queries format as separate bodies", files={ - "audits/generic/measurement.sql": ( + "sql/audits/generic/measurement.sql": ( "AUDIT (evaluation measurement, value measured_value);\n" "MEASURE (SELECT COUNT(*) AS measured_value FROM @relation);\n" "EVIDENCE (SELECT * FROM @relation WHERE @condition);\n" ) }, - expected_written_fragments={"audits/generic/measurement.sql": "MEASURE (SELECT"}, + expected_written_fragments={"sql/audits/generic/measurement.sql": "MEASURE (SELECT"}, expected_fault_codes=(), expected_formatted_count=1, ), @@ -178,8 +178,8 @@ def test_given_synthetic_project_when_formatting_then_results_match_expected( description="path default describes only the models under its path", project_toml=PROJECT_TOML + '\n[path_defaults.marts]\ndescription = "Mart model"\n', files={ - "models/marts/orders.sql": "MODEL ();\nSELECT 1 AS x\n", - "models/staging/stg_orders.sql": "MODEL ();\nSELECT 1 AS x\n", + "sql/models/marts/orders.sql": "MODEL ();\nSELECT 1 AS x\n", + "sql/models/staging/stg_orders.sql": "MODEL ();\nSELECT 1 AS x\n", }, expected_description_faults=(("stg_orders.sql", "description-present"),), ), @@ -187,10 +187,10 @@ def test_given_synthetic_project_when_formatting_then_results_match_expected( description="description resolution never imports project Python", project_toml=PROJECT_TOML + '\n[path_defaults.marts]\ndescription = "Mart model"\n', files={ - "providers/orders_api.py": 'raise RuntimeError("project Python was imported")\n', - "python/tasks/refresh.py": 'raise RuntimeError("project Python was imported")\n', - "models/marts/orders.sql": "MODEL ();\nSELECT 1 AS x\n", - "models/staging/stg_orders.sql": "MODEL ();\nSELECT 1 AS x\n", + "python/providers/orders_api.py": 'raise RuntimeError("project Python was imported")\n', + "python/nodes/tasks/refresh.py": 'raise RuntimeError("project Python was imported")\n', + "sql/models/marts/orders.sql": "MODEL ();\nSELECT 1 AS x\n", + "sql/models/staging/stg_orders.sql": "MODEL ();\nSELECT 1 AS x\n", }, expected_description_faults=(("stg_orders.sql", "description-present"),), ), @@ -198,13 +198,13 @@ def test_given_synthetic_project_when_formatting_then_results_match_expected( description="model schema description satisfies the header only when present", project_toml=PROJECT_TOML, files={ - "schemas/orders.sql": ( + "sql/schemas/orders.sql": ( 'SCHEMA (name order_shape, description "One row per order", ' "columns (id (type INTEGER)));\n" "SCHEMA (name bare_shape, columns (id (type INTEGER)));\n" ), - "models/orders.sql": "MODEL (model_schema order_shape);\nSELECT 1 AS id\n", - "models/returns.sql": "MODEL (model_schema bare_shape);\nSELECT 1 AS id\n", + "sql/models/orders.sql": "MODEL (model_schema order_shape);\nSELECT 1 AS id\n", + "sql/models/returns.sql": "MODEL (model_schema bare_shape);\nSELECT 1 AS id\n", }, expected_description_faults=(("returns.sql", "description-present"),), ), @@ -252,7 +252,7 @@ def test_given_inherited_descriptions_when_formatting_then_faults_match_compile_ def test_given_authored_newline_style_when_formatting_then_style_is_preserved( test_case: FormatNewlineTestCase, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: - target: Path = tmp_path / "models" / "crlf.sql" + target: Path = tmp_path / "sql" / "models" / "crlf.sql" _ = target.parent.mkdir(parents=True) target.write_bytes(test_case.contents) _ = (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") @@ -277,7 +277,7 @@ def test_given_non_ascii_sql_when_native_linting_then_span_maps_to_authored_colu ) -> None: _ = test_case _ = (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - target: Path = tmp_path / "models" / "unicode.sql" + target: Path = tmp_path / "sql" / "models" / "unicode.sql" _ = target.parent.mkdir(parents=True) _ = target.write_text( "MODEL (description \"ok\");\nSELECT 'é' AS label FROM items WHERE value = NULL\n", @@ -307,8 +307,8 @@ def test_given_comment_free_body_when_formatting_twice_then_output_is_canonical_ ) -> None: _ = test_case _ = (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - target: Path = tmp_path / "models" / "messy.sql" - target.parent.mkdir() + target: Path = tmp_path / "sql" / "models" / "messy.sql" + target.parent.mkdir(parents=True) _ = target.write_text( 'MODEL (description "ok");\nselect a,b from items where a=1\n', encoding="utf-8", @@ -340,8 +340,8 @@ def test_given_commented_body_when_formatting_then_comment_is_preserved_in_canon _ = test_case _ = (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") contents: str = 'MODEL (description "ok");\nSELECT a, /* preserve exactly */ b FROM items\n' - target: Path = tmp_path / "models" / "commented_body.sql" - target.parent.mkdir() + target: Path = tmp_path / "sql" / "models" / "commented_body.sql" + target.parent.mkdir(parents=True) _ = target.write_text(contents, encoding="utf-8") report: dict[str, object] = format_project_json(project_dir=tmp_path, capsys=capsys) @@ -429,8 +429,8 @@ def test_given_inline_directive_when_linting_then_it_is_a_fault_printing_the_exc tmp_path: Path, ) -> None: _ = (tmp_path / "sqlbuild_project.toml").write_text(PROJECT_TOML, encoding="utf-8") - target: Path = tmp_path / "models" / "sample.sql" - target.parent.mkdir() + target: Path = tmp_path / "sql" / "models" / "sample.sql" + target.parent.mkdir(parents=True) _ = target.write_text( 'MODEL (description "ok");\n' "-- sqb: ignore SQLCLEAN004 because this fixture intentionally samples one row\n" @@ -451,7 +451,7 @@ def test_given_inline_directive_when_linting_then_it_is_a_fault_printing_the_exc assert ( "[[rules.rule_exceptions]]\n" ' rule = "SQLCLEAN004"\n' - ' path = "models/sample.sql"\n' + ' path = "sql/models/sample.sql"\n' ' reason = "this fixture intentionally samples one row"' ) in remediation @@ -470,7 +470,7 @@ def test_given_header_fault_directive_when_rejecting_then_mandatory_fault_remain test_case: LintBehaviorTestCase, tmp_path: Path, ) -> None: - target: Path = tmp_path / "models" / "missing_description.sql" + target: Path = tmp_path / "sql" / "models" / "missing_description.sql" contents: str = ( "-- sqb: ignore description-present because this must not bypass compiler policy\n" "MODEL (materialized table);\n" diff --git a/tests/unit/src/sqlbuild/provider/_helpers/test_injection.py b/tests/unit/src/sqlbuild/provider/_helpers/test_injection.py index 0ba9419ac2..1e582867e2 100644 --- a/tests/unit/src/sqlbuild/provider/_helpers/test_injection.py +++ b/tests/unit/src/sqlbuild/provider/_helpers/test_injection.py @@ -189,8 +189,8 @@ def test_given_provider_name_conflicts_with_context_parameter_when_calling_then_ expected_error_fragment=( "Provider parameter 'marker_provider' is annotated with MarkerProvider imported as " "'alias_marker', but provider 'marker_provider' was discovered as " - "providers.marker.MarkerProvider. Import project providers using the project-root " - "providers package path" + "python.providers.marker.MarkerProvider. Import project providers using the project path " + "of the providers package" ), ) ], @@ -200,7 +200,7 @@ def test_given_provider_class_imported_through_alias_when_calling_then_guides_us test_case: ProviderInjectionErrorTestCase, tmp_path: Path, ) -> None: - provider_file: Path = tmp_path / "providers" / "marker.py" + provider_file: Path = tmp_path / "python" / "providers" / "marker.py" provider_file.parent.mkdir(parents=True) provider_file.write_text( "from sqlbuild.providers import Provider\n\nclass MarkerProvider(Provider):\n '''Test provider MarkerProvider.'''\n pass\n", @@ -210,7 +210,7 @@ def test_given_provider_class_imported_through_alias_when_calling_then_guides_us sys.path.insert(0, str(tmp_path)) try: canonical_module: ModuleType = load_module( - module_name="providers.marker", + module_name="python.providers.marker", file_path=provider_file, ) alias_module: ModuleType = load_module( @@ -237,5 +237,5 @@ def marker_consumer(marker_provider: object) -> None: ) finally: sys.path = old_path - sys.modules.pop("providers.marker", None) + sys.modules.pop("python.providers.marker", None) sys.modules.pop("alias_marker", None) diff --git a/tests/unit/src/sqlbuild/python_nodes/helpers.py b/tests/unit/src/sqlbuild/python_nodes/helpers.py new file mode 100644 index 0000000000..9608907017 --- /dev/null +++ b/tests/unit/src/sqlbuild/python_nodes/helpers.py @@ -0,0 +1,150 @@ +"""Write inline Python node modules under the file names their declarations require.""" + +from __future__ import annotations + +import ast +import re +from pathlib import PurePosixPath + +_NODE_DECORATORS: frozenset[str] = frozenset({"loader", "asset", "check", "factory"}) +_KIND_FILES: dict[str, str] = {"loader": "loader.py", "asset": "asset.py"} +_FACTORY_FILES: dict[str, str] = { + "loader": "loaders.py", + "asset": "assets.py", + "check": "checks.py", +} +_CHECKS_FILE: str = "checks.py" +_MIXED_FACTORY_FILE: str = "factory.py" +_UNSEEN_FACTORY_FILE: str = "assets.py" +_INIT_FILE: str = "__init__.py" +_ROOT_PARENTS: re.Pattern[str] = re.compile( + r"(Path\(__file__\)(?:\.resolve\(\))?\.parents\[)(\d+)(\])" +) +_MIN_ROOT_PARENTS: int = 2 + + +def node_module_files(module_path: str, source: str) -> dict[str, str]: + """The project files for the module `source` written at `module_path`. + + A module declaring nodes becomes a package at `module_path` without its suffix: one unit + folder per loader, asset or factory, named for the declaration and holding the kind-named + file, `checks.py` with the module's checks, and an `__init__.py` re-exporting every node so + imports of the original module keep working. A module without nodes is written unchanged. + Each file gets its own copy of module-level state, so state nodes share must live in a helper + module they import. + """ + + tree: ast.Module = ast.parse(source) + nodes: list[tuple[ast.FunctionDef | ast.AsyncFunctionDef, str]] = [ + (item, kind) + for item in tree.body + if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) + and (kind := _declared_kind(item)) is not None + ] + if not nodes: + return {module_path: source} + if any(isinstance(item, ast.ImportFrom) and item.level for item in ast.walk(tree)): + raise ValueError(f"{module_path} declares nodes with relative imports") + lines: list[str] = source.split("\n") + names: frozenset[str] = frozenset(item.name for item, _ in nodes) + others: list[ast.stmt] = [item for item in tree.body if _declared_kind(item) is None] + package: PurePosixPath = PurePosixPath(module_path).with_suffix("") + placed: dict[str, str] = {item.name: _piece_path(package, item, kind) for item, kind in nodes} + preamble: str = "\n".join(_segment(lines, item) for item in others).strip("\n") + pieces: dict[str, list[ast.FunctionDef | ast.AsyncFunctionDef]] = {} + for item, _ in nodes: + pieces.setdefault(placed[item.name], []).append(item) + files: dict[str, str] = { + piece: _piece_source( + preamble=preamble, + imports=_sibling_imports(piece=piece, members=members, names=names, placed=placed), + body="\n\n\n".join(_segment(lines, member) for member in members), + depth=len(PurePosixPath(piece).parts) - 1, + ) + for piece, members in pieces.items() + } + files[str(package / _INIT_FILE)] = "".join( + f"from .{_relative_module(placed[item.name], package)} import {item.name}\n" + for item, _ in nodes + ) + return files + + +def _relative_module(path: str, package: PurePosixPath) -> str: + return ".".join(PurePosixPath(path).relative_to(package).with_suffix("").parts) + + +def _declared_kind(item: ast.AST) -> str | None: + if not isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): + return None + for decorator in item.decorator_list: + target: ast.expr = decorator.func if isinstance(decorator, ast.Call) else decorator + name: str | None = ( + target.id if isinstance(target, ast.Name) else getattr(target, "attr", None) + ) + if name in _NODE_DECORATORS: + return name + return None + + +def _piece_path( + package: PurePosixPath, item: ast.FunctionDef | ast.AsyncFunctionDef, kind: str +) -> str: + if kind == "check": + return str(package / _CHECKS_FILE) + if kind != "factory": + return str(package / item.name / _KIND_FILES[kind]) + inner: set[str] = { + found + for child in ast.walk(item) + if child is not item and (found := _declared_kind(child)) is not None and found != "factory" + } + file_name: str = ( + _UNSEEN_FACTORY_FILE + if not inner + else _FACTORY_FILES[next(iter(inner))] + if len(inner) == 1 + else _MIXED_FACTORY_FILE + ) + return str(package / item.name / file_name) + + +def _sibling_imports( + *, + piece: str, + members: list[ast.FunctionDef | ast.AsyncFunctionDef], + names: frozenset[str], + placed: dict[str, str], +) -> str: + used: set[str] = { + child.id for member in members for child in ast.walk(member) if isinstance(child, ast.Name) + } + return "".join( + f"from {PurePosixPath(placed[name]).with_suffix('').as_posix().replace('/', '.')} " + f"import {name}\n" + for name in sorted(used & names) + if placed[name] != piece + ) + + +def _piece_source(*, preamble: str, imports: str, body: str, depth: int) -> str: + head: str = "\n".join(part for part in (preamble, imports.rstrip("\n")) if part) + text: str = (f"{head}\n\n\n" if head else "") + body + "\n" + return _ROOT_PARENTS.sub( + lambda match: ( + match.group(1) + + (str(depth) if int(match.group(2)) >= _MIN_ROOT_PARENTS else match.group(2)) + + match.group(3) + ), + text, + ) + + +def _segment(lines: list[str], item: ast.stmt) -> str: + start: int = item.lineno + if ( + isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) + and item.decorator_list + ): + start = min(decorator.lineno for decorator in item.decorator_list) + return "\n".join(lines[start - 1 : item.end_lineno]) diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/helpers.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/helpers.py index 7e27738425..6afd3e8850 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/helpers.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/helpers.py @@ -52,7 +52,7 @@ def project_with_scope(*, index: ScopeIndex) -> CompiledProjectView: project: CompiledProjectView = build_project( name="orders", - relative_path="models/orders.sql", + relative_path="sql/models/orders.sql", sql="SELECT 1 AS id", config_values={}, ) @@ -182,7 +182,7 @@ def write_rule( f' code="{code}",', ' slug="test-rule",', ' message="test rule fault",', - ' remediation="Fix this model at its models// path.",', + ' remediation="Fix this model at its sql/models// path.",', f" enabled_by_default={enabled_by_default},", ")", subject_signature, @@ -229,7 +229,7 @@ def custom_rule_inputs( (tmp_path / "rules" / "input.json").write_text("{}", encoding="utf-8") project: CompiledProjectView = build_project( name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=_MODEL_SQL, config_values={}, ) @@ -266,13 +266,13 @@ def two_model_project( orders: CompiledProjectView = build_project( name="orders", - relative_path="models/orders.sql", + relative_path="sql/models/orders.sql", sql="SELECT 1 AS order_id", config_values={}, ) customers: CompiledProjectView = build_project( name="customers", - relative_path="models/customers.sql", + relative_path="sql/models/customers.sql", sql=customers_sql, config_values=customers_config, ) @@ -308,7 +308,7 @@ def evaluate_contract_rule( ) project: CompiledProjectView = build_project( name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="WITH orders AS (SELECT id FROM source_orders) SELECT id FROM orders", config_values=config_values, ) diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_catalogue.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_catalogue.py index 084e9ade6f..83e29dff2c 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_catalogue.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_catalogue.py @@ -265,7 +265,7 @@ def test_given_minimum_test_rule_when_rendering_guidance_then_all_surfaces_have_ test_case: PolicyGuidanceTestCase, ) -> None: override: ThresholdOverride = ThresholdOverride( - paths=("models/mart/**",), + paths=("sql/models/mart/**",), thresholds={"min_tests_per_model": 2}, reason="marts require two focused tests", ) @@ -282,7 +282,7 @@ def test_given_minimum_test_rule_when_rendering_guidance_then_all_surfaces_have_ result: RulesResult = evaluate( project=build_project( name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="SELECT id + 1 AS id FROM orders", config_values={"materialized": "table"}, ), diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_config.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_config.py index e5ff522e95..ba5e2c3807 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_config.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_config.py @@ -21,11 +21,11 @@ ) _EXCEPTION_ENTRY: str = ( - '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\npath = "models/orders.sql"\n' + '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\npath = "sql/models/orders.sql"\n' 'reason = "A reviewed sample"\n' ) _IGNORE_ENTRY: str = ( - '[[rules.rule_ignores]]\nrules = ["SQLCLEAN"]\npaths = ["models/examples/**"]\n' + '[[rules.rule_ignores]]\nrules = ["SQLCLEAN"]\npaths = ["sql/models/examples/**"]\n' 'reason = "Examples keep minimal SQL"\n' ) @@ -75,7 +75,7 @@ ), RulesConfigErrorTestCase( description="reasonless ignore", - source=('[[rules.rule_ignores]]\nrules = ["SQBRMODEL"]\npaths = ["models/**"]\n'), + source=('[[rules.rule_ignores]]\nrules = ["SQBRMODEL"]\npaths = ["sql/models/**"]\n'), expected_error_pattern="rules.rule_ignores.reason", ), RulesConfigErrorTestCase( @@ -104,7 +104,7 @@ RulesConfigErrorTestCase( description="reasonless threshold override", source=( - '[[rules.threshold_overrides]]\npaths = ["models/mart/**"]\n' + '[[rules.threshold_overrides]]\npaths = ["sql/models/mart/**"]\n' "thresholds = { min_tests_per_model = 2 }\n" ), expected_error_pattern="rules.threshold_overrides.reason", @@ -112,7 +112,7 @@ RulesConfigErrorTestCase( description="unknown scoped threshold", source=( - '[[rules.threshold_overrides]]\npaths = ["models/mart/**"]\n' + '[[rules.threshold_overrides]]\npaths = ["sql/models/mart/**"]\n' 'reason = "marts need stronger coverage"\n' "thresholds = { max_models = 2 }\n" ), @@ -121,7 +121,7 @@ RulesConfigErrorTestCase( description="project-wide threshold used as path override", source=( - '[[rules.threshold_overrides]]\npaths = ["models/mart/**"]\n' + '[[rules.threshold_overrides]]\npaths = ["sql/models/mart/**"]\n' 'reason = "custom rule evidence is project-wide"\n' "thresholds = { min_custom_rule_test_cases = 2 }\n" ), @@ -130,7 +130,7 @@ RulesConfigErrorTestCase( description="invalid threshold override glob", source=( - '[[rules.threshold_overrides]]\npaths = ["models/["]\n' + '[[rules.threshold_overrides]]\npaths = ["sql/models/["]\n' 'reason = "invalid migration pattern"\n' "thresholds = { min_tests_per_model = 2 }\n" ), @@ -168,7 +168,7 @@ RulesConfigErrorTestCase( description="relation for a Rule that reports no relation", source=( - '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\npath = "models/orders.sql"\n' + '[[rules.rule_exceptions]]\nrule = "SQLCLEAN004"\npath = "sql/models/orders.sql"\n' 'relation = "customers"\nreason = "A reviewed sample"\n' ), expected_error_pattern="sets relation, but only SQLCLEAN038 report a joined relation", @@ -176,7 +176,7 @@ RulesConfigErrorTestCase( description="cte without relation", source=( - '[[rules.rule_exceptions]]\nrule = "SQLCLEAN038"\npath = "models/orders.sql"\n' + '[[rules.rule_exceptions]]\nrule = "SQLCLEAN038"\npath = "sql/models/orders.sql"\n' 'cte = "checks"\nreason = "Deliberate"\n' ), expected_error_pattern="sets cte without relation", @@ -206,7 +206,7 @@ description="allowed qualifier paths that are not a list", source=( "[rules.rule_options.SQBRPROJECT107]\n" - 'allowed_qualifiers = [{ paths = "models/sales/*", reason = "Exports." }]\n' + 'allowed_qualifiers = [{ paths = "sql/models/sales/*", reason = "Exports." }]\n' ), expected_error_pattern="allowed_qualifiers entries must be", ), @@ -222,7 +222,7 @@ description="allowed paths entry with an empty reason", source=( "[rules.rule_options.SQBRPROJECT107]\n" - 'allowed_qualifiers = [{ paths = ["models/sales/*"], reason = " " }]\n' + 'allowed_qualifiers = [{ paths = ["sql/models/sales/*"], reason = " " }]\n' ), expected_error_pattern=r"allowed_qualifiers entries need a non-empty reason$", ), @@ -246,10 +246,10 @@ description="allowed path listed twice in one entry", source=( "[rules.rule_options.SQBRPROJECT107]\n" - 'allowed_qualifiers = [{ paths = ["models/sales/*", "models/sales/*"], ' + 'allowed_qualifiers = [{ paths = ["sql/models/sales/*", "sql/models/sales/*"], ' 'reason = "Exports." }]\n' ), - expected_error_pattern=r"allowed_qualifiers entry lists path models/sales/\* twice", + expected_error_pattern=r"allowed_qualifiers entry lists path sql/models/sales/\* twice", ), RulesConfigErrorTestCase( description="duplicate allowed qualifier glob", @@ -323,7 +323,7 @@ def test_given_removed_allow_exceptions_when_loading_then_raises_error_explainin RelationExceptionConfigTestCase( description="relation-level exception narrowed to a CTE", source=( - '[[rules.rule_exceptions]]\nrule = "SQLCLEAN038"\npath = "models/orders.sql"\n' + '[[rules.rule_exceptions]]\nrule = "SQLCLEAN038"\npath = "sql/models/orders.sql"\n' 'relation = "order_policy"\ncte = "order_checks"\n' 'reason = "Every order is checked against every policy"\n' ), diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_custom_rule_reads.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_custom_rule_reads.py index a79e4f3baf..262bec51a0 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_custom_rule_reads.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_custom_rule_reads.py @@ -191,7 +191,7 @@ def test_given_private_view_access_when_evaluating_repeatedly_then_rule_is_never ), body=_FLAG_ORDERS.format(condition="'orders' in _owners(ctx)").strip(), expected_rerun_hits=0, - expected_finding_paths=("models/orders.sql",), + expected_finding_paths=("sql/models/orders.sql",), ), ), ids=lambda case: case.description, @@ -243,7 +243,7 @@ def test_given_untracked_rule_reading_hidden_file_when_file_changes_then_rule_re condition="'orders' in ctx.project.tree.read_text('config/owners.yaml')" ).strip(), expected_rerun_hits=1, - expected_finding_paths=("models/orders.sql",), + expected_finding_paths=("sql/models/orders.sql",), ), ), ids=lambda case: case.description, @@ -264,7 +264,7 @@ def test_given_file_edited_while_rules_run_when_rerunning_then_new_contents_are_ customers_sql=_CUSTOMERS_SQL, customers_config={} ) site: Path = tmp_path.parent / f"{tmp_path.name}-site" - site.mkdir() + site.mkdir(parents=True) _ = (site / "sitecustomize.py").write_text(_STALE_OBSERVATION_SITECUSTOMIZE, encoding="utf-8") monkeypatch.setenv("PYTHONPATH", os.pathsep.join((str(site), os.environ.get("PYTHONPATH", "")))) during_edit: CustomRulesOutcome = evaluate_cached_custom_rules( diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_custom_rules.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_custom_rules.py index a32df2bf26..1950277b04 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_custom_rules.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_custom_rules.py @@ -293,7 +293,7 @@ def test_given_project_wide_rule_when_reading_project_context_then_cache_is_allo rule_exceptions=( RuleExemption( rule="XSQBRT101", - path="models/mart/commerce__mart__orders.sql", + path="sql/models/mart/commerce__mart__orders.sql", reason="Tracked custom-rule migration", ), ), @@ -306,7 +306,7 @@ def test_given_project_wide_rule_when_reading_project_context_then_cache_is_allo rule_ignores=( RuleIgnore( rules=("XSQBRT",), - paths=("models/mart/**",), + paths=("sql/models/mart/**",), reason="Tracked custom-rule migration", ), ), @@ -326,7 +326,7 @@ def test_given_common_suppression_when_custom_rule_faults_then_native_policy_sup project: CompiledProjectView config: RulesConfig project, config = custom_rule_inputs(tmp_path=tmp_path, test_case=custom_rule_case) - relative_path: str = "models/mart/commerce__mart__orders.sql" + relative_path: str = "sql/models/mart/commerce__mart__orders.sql" target: Path = tmp_path / relative_path target.parent.mkdir(parents=True) target.write_text("WITH final AS (SELECT 1 AS id) SELECT id FROM final\n", encoding="utf-8") diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_incremental_native_rules.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_incremental_native_rules.py index 991de44938..a36c12c932 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_incremental_native_rules.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_incremental_native_rules.py @@ -16,25 +16,25 @@ _ORDERS: IncrementalModelSpec = IncrementalModelSpec( name="commerce__mart__orders", - relative_path="models/commerce/mart/commerce__mart__orders.sql", + relative_path="sql/models/commerce/mart/commerce__mart__orders.sql", sql="WITH orders AS (SELECT * FROM source_orders) SELECT order_id FROM orders WHERE amount > 7", config_values={"materialized": "table"}, ) _CUSTOMERS: IncrementalModelSpec = IncrementalModelSpec( name="commerce__mart__customers", - relative_path="models/commerce/mart/commerce__mart__customers.sql", + relative_path="sql/models/commerce/mart/commerce__mart__customers.sql", sql="SELECT customer_id FROM warehouse.raw.customers", ) _PRODUCTS: IncrementalModelSpec = IncrementalModelSpec( name="commerce__stg__products", - relative_path="models/commerce/staging/commerce__stg__products.sql", + relative_path="sql/models/commerce/staging/commerce__stg__products.sql", sql="SELECT * FROM warehouse.raw.products", ) _EDITED_ORDERS: IncrementalModelSpec = replace(_ORDERS, sql=_ORDERS.sql.replace("> 7", "> 9")) _RENAMED_PRODUCTS: IncrementalModelSpec = replace( _PRODUCTS, name="commerce__stg__catalog_products", - relative_path="models/commerce/staging/commerce__stg__catalog_products.sql", + relative_path="sql/models/commerce/staging/commerce__stg__catalog_products.sql", ) EDIT_SEQUENCE: tuple[IncrementalRulesStep, ...] = ( @@ -102,12 +102,12 @@ def test_given_edit_sequence_when_evaluating_incrementally_then_each_result_equa tmp_path: Path, test_case: IncrementalRulesModeTestCase ) -> None: cached_dir: Path = tmp_path / "cached" - cached_dir.mkdir() + cached_dir.mkdir(parents=True) observed: set[str] = set() for index, step in enumerate(EDIT_SEQUENCE): full_dir: Path = tmp_path / f"full_{index}" - full_dir.mkdir() + full_dir.mkdir(parents=True) incremental: RulesResult = evaluate_incremental_step( step=step, project_dir=cached_dir, diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_native_facts.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_native_facts.py index 87df1531a2..b44d09f21e 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_native_facts.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_native_facts.py @@ -43,7 +43,7 @@ def test_given_compiled_sql_facts_when_evaluating_native_then_exact_safe_rows_ar ) -> None: project: CompiledProjectView = build_project( name="orders", - relative_path="models/orders.sql", + relative_path="sql/models/orders.sql", sql="SELECT 1", config_values={}, ) diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_typed_constants.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_typed_constants.py index 28a64c9b6b..d2d3b0e759 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_typed_constants.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/engine/test_typed_constants.py @@ -31,7 +31,7 @@ def test_given_typed_constant_when_building_native_row_then_value_and_type_are_p declaration: ConstantDeclaration = ConstantDeclaration( name="rules", value=normalize_sql_value(raw_value=test_case.raw_value, context="constant 'rules'"), - relative_path=Path("constants/rules.sql"), + relative_path=Path("sql/constants/rules.sql"), ) _, _, members, value, value_type, render_as = declaration_rows( diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/host/helpers.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/host/helpers.py index c6bf7c5a0d..1badae1b29 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/host/helpers.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/host/helpers.py @@ -96,7 +96,7 @@ def orders_project(*, model_count: int, edits: dict[str, str] | None = None) -> } sql_by_name.update(edits or {}) projects: list[CompiledProjectView] = [ - build_project(name=name, relative_path=f"models/{name}.sql", sql=sql, config_values={}) + build_project(name=name, relative_path=f"sql/models/{name}.sql", sql=sql, config_values={}) for name, sql in sql_by_name.items() ] return project_with( diff --git a/tests/unit/src/sqlbuild/rule_engine/_helpers/run/test_native_rows.py b/tests/unit/src/sqlbuild/rule_engine/_helpers/run/test_native_rows.py index fb97c862b8..f1c144c669 100644 --- a/tests/unit/src/sqlbuild/rule_engine/_helpers/run/test_native_rows.py +++ b/tests/unit/src/sqlbuild/rule_engine/_helpers/run/test_native_rows.py @@ -35,7 +35,7 @@ def test_given_config_value_the_encoder_rejects_when_building_natively_then_rule ) -> None: project: CompiledProjectView = build_project( name="orders", - relative_path="models/orders.sql", + relative_path="sql/models/orders.sql", sql="SELECT 1", config_values={"priority": test_case.rejected_value}, ) diff --git a/tests/unit/src/sqlbuild/rule_engine/classes/audit_facts/helpers.py b/tests/unit/src/sqlbuild/rule_engine/classes/audit_facts/helpers.py index ffa490ec3f..b52715000e 100644 --- a/tests/unit/src/sqlbuild/rule_engine/classes/audit_facts/helpers.py +++ b/tests/unit/src/sqlbuild/rule_engine/classes/audit_facts/helpers.py @@ -11,7 +11,7 @@ def build_audit(*, name: str, attached_target_name: str | None) -> CompiledAuditView: - relative_path: Path = Path(f"audits/{name}.sql") + relative_path: Path = Path(f"sql/audits/{name}.sql") audit_file: DiscoveredAuditFile = DiscoveredAuditFile( file_path=relative_path, relative_path=relative_path, diff --git a/tests/unit/src/sqlbuild/rule_engine/classes/audit_facts/test_audit_facts.py b/tests/unit/src/sqlbuild/rule_engine/classes/audit_facts/test_audit_facts.py index 633f04db9d..cc6cdc7d99 100644 --- a/tests/unit/src/sqlbuild/rule_engine/classes/audit_facts/test_audit_facts.py +++ b/tests/unit/src/sqlbuild/rule_engine/classes/audit_facts/test_audit_facts.py @@ -46,7 +46,7 @@ def test_given_attached_and_project_audits_when_querying_model_then_returns_only project: CompiledProjectView = project_with( project=build_project( name="orders", - relative_path="models/orders.sql", + relative_path="sql/models/orders.sql", sql="SELECT 1 AS order_id", config_values={}, ), @@ -56,7 +56,7 @@ def test_given_attached_and_project_audits_when_querying_model_then_returns_only facts: AuditFacts = AuditFacts(project=project) attached_audits: tuple[CompiledAuditView, ...] = facts.for_model( - Model(name="orders", path=Path("models/orders.sql"), materialization="view") + Model(name="orders", path=Path("sql/models/orders.sql"), materialization="view") ) assert tuple(audit.name for audit in attached_audits) == test_case.expected_attached_names assert tuple(audit.name for audit in facts.all()) == test_case.expected_all_names diff --git a/tests/unit/src/sqlbuild/rule_engine/classes/model_test_facts/test_model_test_facts.py b/tests/unit/src/sqlbuild/rule_engine/classes/model_test_facts/test_model_test_facts.py index ade7e7839a..efa14a2e33 100644 --- a/tests/unit/src/sqlbuild/rule_engine/classes/model_test_facts/test_model_test_facts.py +++ b/tests/unit/src/sqlbuild/rule_engine/classes/model_test_facts/test_model_test_facts.py @@ -53,7 +53,7 @@ def test_given_model_and_non_model_tests_when_querying_model_then_returns_each_m project: CompiledProjectView = project_with( project=build_project( name=test_case.model_name, - relative_path="models/orders.sql", + relative_path="sql/models/orders.sql", sql="SELECT 1 AS order_id", config_values={}, ), @@ -63,7 +63,7 @@ def test_given_model_and_non_model_tests_when_querying_model_then_returns_each_m facts: ModelTestFacts = ModelTestFacts(project=project) matching_tests: tuple[CompiledSqlTest, ...] = facts.for_model( - Model(name=test_case.model_name, path=Path("models/orders.sql"), materialization="view") + Model(name=test_case.model_name, path=Path("sql/models/orders.sql"), materialization="view") ) assert tuple(test.name for test in matching_tests) == test_case.expected_matching_names assert tuple(test.name for test in facts.all()) == test_case.expected_all_names diff --git a/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/helpers.py b/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/helpers.py index 10ab2663ff..5aa896f4d3 100644 --- a/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/helpers.py +++ b/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/helpers.py @@ -13,18 +13,20 @@ def linked_project_tree(tmp_path: Path) -> ProjectTree: root: Path = tmp_path / "orders" outside: Path = tmp_path / "outside" - (root / "models").mkdir(parents=True) + (root / "sql" / "models").mkdir(parents=True) (root / "rules" / "inputs").mkdir(parents=True) - outside.mkdir() - (root / "models" / "orders.sql").write_text(ORDERS_SQL, encoding="utf-8") - (root / "models" / "notes.txt").write_text("notes\n", encoding="utf-8") + outside.mkdir(parents=True) + (root / "sql" / "models" / "orders.sql").write_text(ORDERS_SQL, encoding="utf-8") + (root / "sql" / "models" / "notes.txt").write_text("notes\n", encoding="utf-8") (root / "rules" / "inputs" / "limits.yaml").write_text(LIMITS_YAML, encoding="utf-8") (outside / "customers.sql").write_text("SELECT 1 AS customer_id\n", encoding="utf-8") - (root / "models" / "orders_alias.sql").symlink_to(root / "models" / "orders.sql") - (root / "models" / "customers.sql").symlink_to(outside / "customers.sql") - (root / "linked_models").symlink_to(root / "models", target_is_directory=True) + (root / "sql" / "models" / "orders_alias.sql").symlink_to( + root / "sql" / "models" / "orders.sql" + ) + (root / "sql" / "models" / "customers.sql").symlink_to(outside / "customers.sql") + (root / "linked_models").symlink_to(root / "sql" / "models", target_is_directory=True) (root / "outside_models").symlink_to(outside, target_is_directory=True) project: CompiledProjectView = build_project( - name="orders", relative_path="models/orders.sql", sql=ORDERS_SQL, config_values={} + name="orders", relative_path="sql/models/orders.sql", sql=ORDERS_SQL, config_values={} ) return ProjectTree(project_dir=root, project=project) diff --git a/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/test_queries.py b/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/test_queries.py index d841596fc6..db2ca269db 100644 --- a/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/test_queries.py +++ b/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/test_queries.py @@ -16,10 +16,12 @@ @pytest.mark.parametrize( "test_case", ( - TreeQueryTestCase("project root", "", ("models", "rules")), - TreeQueryTestCase("current directory", ".", ("models", "rules")), + TreeQueryTestCase("project root", "", ("rules", "sql")), + TreeQueryTestCase("current directory", ".", ("rules", "sql")), TreeQueryTestCase( - "folder with trailing slash", "models/", ("models/notes.txt", "models/orders.sql") + "folder with trailing slash", + "sql/models/", + ("sql/models/notes.txt", "sql/models/orders.sql"), ), TreeQueryTestCase("nested folder", "./rules//inputs", ("rules/inputs/limits.yaml",)), TreeQueryTestCase("missing folder", "missing", ()), @@ -43,12 +45,13 @@ def test_given_directory_when_listing_children_then_returns_direct_entries( "everything", "", ( - "models", - "models/notes.txt", - "models/orders.sql", "rules", "rules/inputs", "rules/inputs/limits.yaml", + "sql", + "sql/models", + "sql/models/notes.txt", + "sql/models/orders.sql", ), ), TreeQueryTestCase("folder", "rules/", ("rules/inputs", "rules/inputs/limits.yaml")), @@ -69,9 +72,9 @@ def test_given_directory_when_listing_descendants_then_returns_entries_below_it( @pytest.mark.parametrize( "test_case", ( - TreeQueryTestCase("star crosses folders", "*.sql", ("models/orders.sql",)), + TreeQueryTestCase("star crosses folders", "*.sql", ("sql/models/orders.sql",)), TreeQueryTestCase("single character", "rule?", ("rules",)), - TreeQueryTestCase("negated set", "[!m]*s", ("rules", "rules/inputs")), + TreeQueryTestCase("negated set", "[!s]*s", ("rules", "rules/inputs")), TreeQueryTestCase("no match", "*.py", ()), ), ids=lambda case: case.description, @@ -89,8 +92,12 @@ def test_given_pattern_when_globbing_then_returns_fnmatch_matches( @pytest.mark.parametrize( "test_case", ( - RelativePartsTestCase("relative path", "models/orders.sql", "", ("models", "orders.sql")), - RelativePartsTestCase("beneath a folder", "models/orders.sql", "models/", ("orders.sql",)), + RelativePartsTestCase( + "relative path", "sql/models/orders.sql", "", ("sql", "models", "orders.sql") + ), + RelativePartsTestCase( + "beneath a folder", "sql/models/orders.sql", "sql/models/", ("orders.sql",) + ), ), ids=lambda case: case.description, ) @@ -111,10 +118,10 @@ def test_given_path_when_reading_relative_parts_then_returns_project_relative_pa "through a linked folder", "orders/linked_models/orders.sql", "", - ("models", "orders.sql"), + ("sql", "models", "orders.sql"), ), RelativePartsTestCase( - "beneath a folder", "orders/models/orders.sql", "models", ("orders.sql",) + "beneath a folder", "orders/sql/models/orders.sql", "sql/models", ("orders.sql",) ), ), ids=lambda case: case.description, @@ -134,7 +141,9 @@ def test_given_absolute_path_inside_project_when_reading_relative_parts_then_str @pytest.mark.parametrize( "test_case", ( - RelativePartsTestCase("not beneath", "models/orders.sql", "rules", None, "is not beneath"), + RelativePartsTestCase( + "not beneath", "sql/models/orders.sql", "rules", None, "is not beneath" + ), RelativePartsTestCase("absolute outside", "/", "", None, "escapes the project"), ), ids=lambda case: case.description, diff --git a/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/test_read_text.py b/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/test_read_text.py index df5918535e..9afd4661a3 100644 --- a/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/test_read_text.py +++ b/tests/unit/src/sqlbuild/rule_engine/classes/project_tree/test_read_text.py @@ -17,10 +17,10 @@ @pytest.mark.parametrize( "test_case", ( - ReadTextTestCase("regular file", "models/orders.sql", expected_text=ORDERS_SQL), + ReadTextTestCase("regular file", "sql/models/orders.sql", expected_text=ORDERS_SQL), ReadTextTestCase("nested file", "rules/inputs/limits.yaml", expected_text=LIMITS_YAML), - ReadTextTestCase("dot prefix", "./models/orders.sql", expected_text=ORDERS_SQL), - ReadTextTestCase("symlinked file", "models/orders_alias.sql", expected_text=ORDERS_SQL), + ReadTextTestCase("dot prefix", "./sql/models/orders.sql", expected_text=ORDERS_SQL), + ReadTextTestCase("symlinked file", "sql/models/orders_alias.sql", expected_text=ORDERS_SQL), ReadTextTestCase("symlinked folder", "linked_models/orders.sql", expected_text=ORDERS_SQL), ), ids=lambda case: case.description, @@ -39,15 +39,19 @@ def test_given_readable_project_file_when_reading_text_twice_then_returns_its_co @pytest.mark.parametrize( "test_case", ( - ReadTextTestCase("missing file", "models/missing.sql", expected_error="does not exist"), + ReadTextTestCase("missing file", "sql/models/missing.sql", expected_error="does not exist"), ReadTextTestCase("directory", "models", expected_error="does not exist"), ReadTextTestCase("project root", "", expected_error="does not exist"), - ReadTextTestCase("beneath a file", "models/orders.sql/x.sql", expected_error="not exist"), + ReadTextTestCase( + "beneath a file", "sql/models/orders.sql/x.sql", expected_error="not exist" + ), ReadTextTestCase( "folder linked outside", "outside_models/customers.sql", expected_error="not exist" ), - ReadTextTestCase("file linked outside", "models/customers.sql", expected_error="not exist"), - ReadTextTestCase("untracked suffix", "models/notes.txt", expected_error="tracked file"), + ReadTextTestCase( + "file linked outside", "sql/models/customers.sql", expected_error="not exist" + ), + ReadTextTestCase("untracked suffix", "sql/models/notes.txt", expected_error="tracked file"), ReadTextTestCase("parent escape", "../outside/customers.sql", expected_error="escapes"), ), ids=lambda case: case.description, @@ -56,7 +60,7 @@ def test_given_unreadable_project_path_when_reading_text_then_raises_usage_error tmp_path: Path, test_case: ReadTextTestCase ) -> None: tree: ProjectTree = linked_project_tree(tmp_path) - _ = tree.read_text("models/orders.sql") + _ = tree.read_text("sql/models/orders.sql") with pytest.raises(RuleUsageError, match=test_case.expected_error): _ = tree.read_text(test_case.path) diff --git a/tests/unit/src/sqlbuild/rule_engine/main/evaluate/helpers.py b/tests/unit/src/sqlbuild/rule_engine/main/evaluate/helpers.py index b2ae63b01c..3d200730f5 100644 --- a/tests/unit/src/sqlbuild/rule_engine/main/evaluate/helpers.py +++ b/tests/unit/src/sqlbuild/rule_engine/main/evaluate/helpers.py @@ -22,7 +22,7 @@ name="status", members=(EnumMember(name="ACTIVE", value="active"),), scalar_type="VARCHAR", - relative_path=Path("enums/status.sql"), + relative_path=Path("sql/enums/status.sql"), model_name=None, ) diff --git a/tests/unit/src/sqlbuild/rule_engine/main/evaluate/test_cache_and_suppressions.py b/tests/unit/src/sqlbuild/rule_engine/main/evaluate/test_cache_and_suppressions.py index 0142313abe..c8c750d965 100644 --- a/tests/unit/src/sqlbuild/rule_engine/main/evaluate/test_cache_and_suppressions.py +++ b/tests/unit/src/sqlbuild/rule_engine/main/evaluate/test_cache_and_suppressions.py @@ -37,7 +37,7 @@ def test_given_unchanged_builtin_inputs_when_evaluating_twice_then_second_run_hi ) -> None: project: CompiledProjectView = build_project( name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="SELECT * FROM orders", config_values={}, ) @@ -72,7 +72,7 @@ def test_given_authored_sql_changes_when_compiled_sql_is_same_then_cache_is_inva compiled_sql: str = "WITH final AS (SELECT 1 AS id) SELECT id FROM final WHERE id > 7" project: CompiledProjectView = build_project( name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=compiled_sql, config_values={}, ) @@ -109,7 +109,7 @@ def test_given_exact_exception_when_fault_exists_then_suppresses_fault( tmp_path: Path, test_case: PolicyBehaviorTestCase, ) -> None: - relative_path = "models/mart/commerce__mart__orders.sql" + relative_path = "sql/models/mart/commerce__mart__orders.sql" target: Path = tmp_path / relative_path target.parent.mkdir(parents=True) target.write_text("SELECT * FROM orders\n", encoding="utf-8") @@ -149,7 +149,7 @@ def test_given_stale_exact_exception_when_evaluating_then_raises_error( tmp_path: Path, test_case: PolicyBehaviorTestCase, ) -> None: - relative_path = "models/mart/commerce__mart__orders.sql" + relative_path = "sql/models/mart/commerce__mart__orders.sql" target: Path = tmp_path / relative_path target.parent.mkdir(parents=True) target.write_text("WITH final AS (SELECT 1 AS id) SELECT id FROM final\n", encoding="utf-8") @@ -184,7 +184,7 @@ def test_given_scoped_ignore_when_fault_exists_then_suppresses_fault( tmp_path: Path, test_case: PolicyBehaviorTestCase, ) -> None: - relative_path = "models/legacy/commerce__mart__orders.sql" + relative_path = "sql/models/legacy/commerce__mart__orders.sql" project: CompiledProjectView = build_project( name="commerce__mart__orders", relative_path=relative_path, @@ -196,7 +196,7 @@ def test_given_scoped_ignore_when_fault_exists_then_suppresses_fault( rule_ignores=( RuleIgnore( rules=("SQBRCONTRACT",), - paths=("models/legacy/**",), + paths=("sql/models/legacy/**",), reason="Legacy migration boundary", ), ), diff --git a/tests/unit/src/sqlbuild/rule_engine/main/evaluate/test_evaluate.py b/tests/unit/src/sqlbuild/rule_engine/main/evaluate/test_evaluate.py index eae4595e5b..bb0faa26d2 100644 --- a/tests/unit/src/sqlbuild/rule_engine/main/evaluate/test_evaluate.py +++ b/tests/unit/src/sqlbuild/rule_engine/main/evaluate/test_evaluate.py @@ -19,7 +19,7 @@ PolicyEvaluationTestCase( description="empty selection disables policy", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="SELECT * FROM raw.orders", config_values={}, select=(), @@ -28,7 +28,7 @@ PolicyEvaluationTestCase( description="contract rule faults missing enforced contract", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="WITH orders AS (SELECT id FROM source_orders) SELECT id FROM orders", config_values={"materialized": "table"}, select=("SQBRCONTRACT101",), @@ -37,7 +37,7 @@ PolicyEvaluationTestCase( description="direct enum member comparison passes", model_name="commerce__int_clean__orders", - relative_path="models/intermediate/commerce__int_clean__orders.sql", + relative_path="sql/models/intermediate/commerce__int_clean__orders.sql", sql=( 'WITH upstream AS (SELECT * FROM __ref("commerce__stg__orders")), ' "filtered AS (SELECT status FROM upstream WHERE upstream.status = 'active') " @@ -57,7 +57,7 @@ PolicyEvaluationTestCase( description="modified controlled enum column faults", model_name="commerce__int_clean__orders", - relative_path="models/intermediate/commerce__int_clean__orders.sql", + relative_path="sql/models/intermediate/commerce__int_clean__orders.sql", sql=( 'WITH upstream AS (SELECT * FROM __ref("commerce__stg__orders")), ' "filtered AS (SELECT status FROM upstream " @@ -78,7 +78,7 @@ PolicyEvaluationTestCase( description="uppercased controlled enum column faults", model_name="commerce__int_clean__orders", - relative_path="models/intermediate/commerce__int_clean__orders.sql", + relative_path="sql/models/intermediate/commerce__int_clean__orders.sql", sql=( 'SELECT status FROM __ref("commerce__stg__orders") AS upstream ' "WHERE UPPER(upstream.status) = 'active'" @@ -96,7 +96,7 @@ PolicyEvaluationTestCase( description="cast controlled enum column faults", model_name="commerce__int_clean__orders", - relative_path="models/intermediate/commerce__int_clean__orders.sql", + relative_path="sql/models/intermediate/commerce__int_clean__orders.sql", sql=( 'SELECT status FROM __ref("commerce__stg__orders") AS upstream ' "WHERE CAST(upstream.status AS VARCHAR) = 'active'" @@ -114,7 +114,7 @@ PolicyEvaluationTestCase( description="direct source enum column modifier passes", model_name="commerce__stg__orders__vendor", - relative_path="models/staging/commerce__stg__orders__vendor.sql", + relative_path="sql/models/staging/commerce__stg__orders__vendor.sql", sql=( 'WITH raw_orders AS (SELECT * FROM __source("vendor_orders")), ' "filtered AS (SELECT status FROM raw_orders " @@ -135,7 +135,7 @@ PolicyEvaluationTestCase( description="transitive source enum column modifier faults", model_name="commerce__stg__orders__vendor", - relative_path="models/staging/commerce__stg__orders__vendor.sql", + relative_path="sql/models/staging/commerce__stg__orders__vendor.sql", sql=( 'WITH raw_orders AS (SELECT * FROM __source("vendor_orders")), ' "renamed AS (SELECT status FROM raw_orders), " @@ -158,7 +158,7 @@ PolicyEvaluationTestCase( description="modified enum member faults for direct source comparison", model_name="commerce__stg__orders__vendor", - relative_path="models/staging/commerce__stg__orders__vendor.sql", + relative_path="sql/models/staging/commerce__stg__orders__vendor.sql", sql=( 'WITH raw_orders AS (SELECT * FROM __source("vendor_orders")), ' "filtered AS (SELECT status FROM raw_orders " @@ -179,7 +179,7 @@ PolicyEvaluationTestCase( description="bare string faults for direct source comparison", model_name="commerce__stg__orders__vendor", - relative_path="models/staging/commerce__stg__orders__vendor.sql", + relative_path="sql/models/staging/commerce__stg__orders__vendor.sql", sql=( 'WITH raw_orders AS (SELECT * FROM __source("vendor_orders")), ' "filtered AS (SELECT status FROM raw_orders " @@ -194,7 +194,7 @@ PolicyEvaluationTestCase( description="numeric decision faults", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="WITH filtered AS (SELECT id FROM items WHERE item_count > 7) SELECT id FROM filtered", config_values={"materialized": "table", "contract": "enforced"}, select=("SQBRDECLARATION102",), @@ -203,7 +203,7 @@ PolicyEvaluationTestCase( description="numeric between bounds fault", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="SELECT id FROM items WHERE item_count BETWEEN 30 AND 61", config_values={"materialized": "table", "contract": "enforced"}, select=("SQBRDECLARATION102",), @@ -212,7 +212,7 @@ PolicyEvaluationTestCase( description="numeric value list faults", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="SELECT id FROM items WHERE item_count IN (30, 31, 45)", config_values={"materialized": "table", "contract": "enforced"}, select=("SQBRDECLARATION102",), @@ -221,7 +221,7 @@ PolicyEvaluationTestCase( description="canonical numeric decision passes", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="WITH filtered AS (SELECT id FROM items WHERE item_count > 0) SELECT id FROM filtered", config_values={"materialized": "table", "contract": "enforced"}, select=("SQBRDECLARATION102",), @@ -230,7 +230,7 @@ PolicyEvaluationTestCase( description="numeric decision in projected case faults", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( "SELECT CASE WHEN item_count > 7 THEN 'large' ELSE 'small' END AS batch_size " "FROM items" @@ -242,7 +242,7 @@ PolicyEvaluationTestCase( description="enum decision in projected case faults", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( "SELECT CASE WHEN status = 'active' THEN 1 ELSE 0 END AS is_win " 'FROM __ref("commerce__stg__orders")' @@ -256,7 +256,7 @@ PolicyEvaluationTestCase( description="constant-backed numeric decision in projected case passes", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( "SELECT CASE WHEN item_count > 7 THEN 'large' ELSE 'small' END AS batch_size " "FROM items" @@ -272,7 +272,7 @@ PolicyEvaluationTestCase( description="cast precision does not authorize expanded constant value", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( "SELECT CAST(CASE WHEN item_count > 38 THEN 1 ELSE 0 END " "AS NUMBER(38, 0)) AS batch_size FROM items" @@ -288,7 +288,7 @@ PolicyEvaluationTestCase( description="authored numeric decision still faults when it matches cast precision", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( "SELECT CAST(CASE WHEN item_count > 38 THEN 1 ELSE 0 END " "AS NUMBER(38, 0)) AS batch_size FROM items" @@ -300,7 +300,7 @@ PolicyEvaluationTestCase( description="constant-backed numeric decision ignores digits in identifiers and strings", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( "SELECT CASE WHEN item_count > 7 THEN 'tier 7' ELSE 'small' END AS batch_size_7 " "FROM items" @@ -316,7 +316,7 @@ PolicyEvaluationTestCase( description="query-only numeric decision with model alias faults", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( "SELECT CASE WHEN item_count > 7 THEN 'large' ELSE 'small' END AS model FROM items;" ), @@ -327,7 +327,7 @@ PolicyEvaluationTestCase( description="negative one and one numeric decisions pass", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=("SELECT id FROM items WHERE previous_rank = -1 OR current_rank = 1"), config_values={"materialized": "table", "contract": "enforced"}, select=("SQBRDECLARATION102",), @@ -336,7 +336,7 @@ PolicyEvaluationTestCase( description="projected boolean comparison outside case passes", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql="SELECT item_count > 7 AS is_large_batch FROM items", config_values={"materialized": "table", "contract": "enforced"}, select=("SQBRDECLARATION102",), @@ -345,7 +345,7 @@ PolicyEvaluationTestCase( description="comparison-valued case result is not a decision site", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( "SELECT CASE WHEN enabled THEN item_count > 7 ELSE FALSE END AS is_large FROM items" ), @@ -356,7 +356,7 @@ PolicyEvaluationTestCase( description="view marker mismatch faults", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql="WITH orders AS (SELECT id FROM source_orders) SELECT id FROM orders", config_values={"materialized": "table", "contract": "enforced"}, select=("SQBRMODEL103",), @@ -365,7 +365,7 @@ PolicyEvaluationTestCase( description="retired source token faults", model_name="sales__stg__orders__legacy_partner", - relative_path="models/staging/sales__stg__orders__legacy_partner.sql", + relative_path="sql/models/staging/sales__stg__orders__legacy_partner.sql", sql="WITH orders AS (SELECT id FROM source_orders) SELECT id FROM orders", config_values={"materialized": "table", "contract": "enforced"}, select=("SQBRPROJECT103",), @@ -377,7 +377,7 @@ PolicyEvaluationTestCase( description="function and seed references are not source tokens", model_name="sales__stg__orders__partner", - relative_path="models/staging/sales__stg__orders__partner.sql", + relative_path="sql/models/staging/sales__stg__orders__partner.sql", sql="WITH orders AS (SELECT id FROM source_orders) SELECT id FROM orders", config_values={"materialized": "table", "contract": "enforced"}, select=("SQBRPROJECT103",), @@ -392,7 +392,7 @@ PolicyEvaluationTestCase( description="lone star exemption passes", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql="WITH orders AS (SELECT id FROM source_orders) SELECT * FROM orders", config_values={"materialized": "view", "contract": "enforced"}, select=("SQBRMODEL102",), @@ -400,7 +400,7 @@ rules_config=RulesConfig( select_star_allow=( SelectStarAllow( - paths=("models/mart/*.sql",), + paths=("sql/models/mart/*.sql",), reason="Intentional passthrough view", ), ) @@ -409,7 +409,7 @@ PolicyEvaluationTestCase( description="lone star over dynamic pivot passes", model_name="commerce__mart__order_totals", - relative_path="models/mart/commerce__mart__order_totals.sql", + relative_path="sql/models/mart/commerce__mart__order_totals.sql", sql=( "SELECT * FROM source_orders " "PIVOT(SUM(amount) FOR category IN (ANY ORDER BY category))" @@ -421,7 +421,7 @@ PolicyEvaluationTestCase( description="lone star over static pivot faults", model_name="commerce__mart__order_totals", - relative_path="models/mart/commerce__mart__order_totals.sql", + relative_path="sql/models/mart/commerce__mart__order_totals.sql", sql=( "SELECT * FROM source_orders " "PIVOT(SUM(amount) FOR category IN ('standard', 'priority'))" @@ -433,7 +433,7 @@ PolicyEvaluationTestCase( description="mixed star over dynamic pivot faults", model_name="commerce__mart__order_totals", - relative_path="models/mart/commerce__mart__order_totals.sql", + relative_path="sql/models/mart/commerce__mart__order_totals.sql", sql=( "SELECT *, 1 AS marker FROM source_orders " "PIVOT(SUM(amount) FOR category IN (ANY ORDER BY category))" @@ -445,7 +445,7 @@ PolicyEvaluationTestCase( description="lone star over joined dynamic pivot faults", model_name="commerce__mart__order_totals", - relative_path="models/mart/commerce__mart__order_totals.sql", + relative_path="sql/models/mart/commerce__mart__order_totals.sql", sql=( "SELECT * FROM source_orders " "PIVOT(SUM(amount) FOR category IN (ANY ORDER BY category)) totals " @@ -458,7 +458,7 @@ PolicyEvaluationTestCase( description="valid dependency import passes", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")), ' "final AS (SELECT id FROM orders) SELECT id FROM final" @@ -471,7 +471,7 @@ PolicyEvaluationTestCase( description="subject folder after intermediate refinement passes", model_name="commerce__int_clean__orders", - relative_path="models/commerce/intermediate/clean/payments/commerce__int_clean__orders.sql", + relative_path="sql/models/commerce/intermediate/clean/payments/commerce__int_clean__orders.sql", sql="SELECT 1 AS order_id", config_values={"materialized": "table"}, select=("SQBRPROJECT102",), @@ -480,7 +480,7 @@ PolicyEvaluationTestCase( description="subject folder before complete intermediate refinement passes", model_name="commerce__int_clean__orders", - relative_path="models/commerce/payments/intermediate/clean/commerce__int_clean__orders.sql", + relative_path="sql/models/commerce/payments/intermediate/clean/commerce__int_clean__orders.sql", sql="SELECT 1 AS order_id", config_values={"materialized": "table"}, select=("SQBRPROJECT102",), @@ -489,7 +489,7 @@ PolicyEvaluationTestCase( description="commented and quoted dependency text is ignored", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")), ' "final AS (SELECT id, '__ref(\"ignored_string\")' AS note FROM orders " @@ -505,7 +505,7 @@ PolicyEvaluationTestCase( description="transformed dependency import faults", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( 'WITH orders AS (SELECT p.id FROM __ref("commerce__stg__orders") p ' "JOIN lookup l ON p.id = l.id), final AS (SELECT id FROM orders) " @@ -519,7 +519,7 @@ PolicyEvaluationTestCase( description="duplicate dependency import faults", model_name="commerce__mart__orders", - relative_path="models/mart/commerce__mart__orders.sql", + relative_path="sql/models/mart/commerce__mart__orders.sql", sql=( 'WITH orders_a AS (SELECT * FROM __ref("commerce__stg__orders")), ' 'orders_b AS (SELECT * FROM __ref("commerce__stg__orders")), ' @@ -533,7 +533,7 @@ PolicyEvaluationTestCase( description="passthrough skips minimum checks", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")) SELECT * FROM orders' ), @@ -545,7 +545,7 @@ PolicyEvaluationTestCase( description="plain column passthrough shares import and exemption classification", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")) ' "SELECT id, price AS current_price FROM orders" @@ -558,7 +558,7 @@ PolicyEvaluationTestCase( description="join import is neither star-exempt nor passthrough", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders") p ' "JOIN lookup l ON p.id = l.id) SELECT id FROM orders" @@ -571,7 +571,7 @@ PolicyEvaluationTestCase( description="aggregate projection is not passthrough", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")) ' "SELECT COUNT(id) AS price_count FROM orders" @@ -584,7 +584,7 @@ PolicyEvaluationTestCase( description="case projection is not passthrough", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")) ' "SELECT CASE WHEN price > 0 THEN id ELSE NULL END AS id FROM orders" @@ -597,7 +597,7 @@ PolicyEvaluationTestCase( description="extra logical cte is not passthrough", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")), ' "renamed AS (SELECT id FROM orders) SELECT id FROM renamed" @@ -610,7 +610,7 @@ PolicyEvaluationTestCase( description="extra dependency is not passthrough", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")), ' 'inventory AS (SELECT * FROM __ref("commerce__stg__inventory")) ' @@ -627,7 +627,7 @@ PolicyEvaluationTestCase( description="derived expression is not passthrough", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")) ' "SELECT price * 100 AS price_cents FROM orders" @@ -640,7 +640,7 @@ PolicyEvaluationTestCase( description="nontrivial filter is not passthrough", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")) ' "SELECT id FROM orders WHERE price > 0" @@ -653,7 +653,7 @@ PolicyEvaluationTestCase( description="unrelated terminal source is not passthrough", model_name="commerce__mart_v__orders", - relative_path="models/mart/commerce__mart_v__orders.sql", + relative_path="sql/models/mart/commerce__mart_v__orders.sql", sql=( 'WITH orders AS (SELECT * FROM __ref("commerce__stg__orders")) ' "SELECT id FROM unrelated" @@ -692,7 +692,7 @@ def test_given_selected_rules_when_evaluating_then_reports_expected_faults( PolicyEvaluationTestCase( description="architecture-named subject folder before intermediate refinement", model_name="commerce__int_clean__orders", - relative_path="models/commerce/intermediate/mart/clean/commerce__int_clean__orders.sql", + relative_path="sql/models/commerce/intermediate/mart/clean/commerce__int_clean__orders.sql", sql="SELECT 1 AS order_id", config_values={"materialized": "table"}, select=("SQBRPROJECT102",), @@ -723,7 +723,7 @@ def test_given_subject_before_layer_when_evaluating_then_reports_canonical_path( '"intermediate/clean" contiguous' ) assert finding.remediation == ( - 'Move the model to "models/commerce/intermediate/clean/mart/' + 'Move the model to "sql/models/commerce/intermediate/clean/mart/' 'commerce__int_clean__orders.sql"; preserve subject folders outside ' '"intermediate/clean". Use rules.layout with SQBRPROJECT201-204 to enforce ' "domain and subdomain ordering." diff --git a/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule/helpers.py b/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule/helpers.py index f2999fc798..1a08948a17 100644 --- a/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule/helpers.py +++ b/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule/helpers.py @@ -15,7 +15,9 @@ code="XSQBRD001", slug="required-domain", message="model belongs to the wrong domain", - remediation="Move this model beneath models// and rename its domain prefix.", + remediation=( + "Move this model beneath sql/models// and rename its domain prefix." + ), options=(REQUIRED_DOMAIN,), ) def required_domain(*, model: Model, ctx: RuleContext) -> list[Finding]: diff --git a/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule/test_evaluate_rule.py b/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule/test_evaluate_rule.py index fe27c524b7..46947754d7 100644 --- a/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule/test_evaluate_rule.py +++ b/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule/test_evaluate_rule.py @@ -43,12 +43,12 @@ "WITH final AS (SELECT 1 AS id)\n" "SELECT id FROM final\n" ), - path="models/mart/commerce__mart__orders.sql", + path="sql/models/mart/commerce__mart__orders.sql", config={"required_domain": "support"}, expected_finding_count=1, ), expected_code="XSQBRD001", - expected_path="models/mart/commerce__mart__orders.sql", + expected_path="sql/models/mart/commerce__mart__orders.sql", ) ], ids=lambda case: case.description, @@ -75,7 +75,7 @@ def test_given_rule_case_when_evaluating_then_runs_real_pipeline( "WITH final AS (SELECT 1 AS id)\n" "SELECT id FROM final\n" ), - path="models/mart/commerce__mart__orders.sql", + path="sql/models/mart/commerce__mart__orders.sql", config={"required_domain": "support"}, expected_finding_count=1, ), @@ -136,7 +136,7 @@ def test_given_same_custom_rule_when_using_public_and_native_paths_then_faults_h rule_case=RuleCase( description="first evaluation reports nothing", source="MODEL (description 'Test model.', materialized table);\n\nSELECT 1 AS id\n", - path="models/mart/commerce__mart__orders.sql", + path="sql/models/mart/commerce__mart__orders.sql", expected_finding_count=0, ), expected_error_pattern=( @@ -180,10 +180,10 @@ def test_given_declared_status_column_when_rule_reads_enum_types_then_sees_decla f" columns (\n status (type {test_case.status_type}),\n ),\n);\n\n" "SELECT 'open' AS status\n" ), - path="models/orders.sql", + path="sql/models/orders.sql", files=( RuleFile( - path="models/_enums/order_status.sql", + path="sql/models/_enums/order_status.sql", source='ENUM (name order_status, members (OPEN "open", CLOSED "closed"));\n', ), ), diff --git a/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule_project/test_project_rules_directory.py b/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule_project/test_project_rules_directory.py index 55de77eaee..2e717db0d7 100644 --- a/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule_project/test_project_rules_directory.py +++ b/tests/unit/src/sqlbuild/rule_engine/main/evaluate_rule_project/test_project_rules_directory.py @@ -53,7 +53,7 @@ def test_given_project_rule_when_evaluating_then_uses_its_own_rules_directory( test_case=RuleCase( description=test_case.description, source='MODEL (description "Orders");\nSELECT 1 AS order_id\n', - path="models/orders.sql", + path="sql/models/orders.sql", files=tuple( RuleFile(path=path, source=source) for path, source in test_case.case_files ), diff --git a/tests/unit/src/sqlbuild/rule_engine/main/render_result/test_render_result.py b/tests/unit/src/sqlbuild/rule_engine/main/render_result/test_render_result.py index c526a87aa8..cd61a812ce 100644 --- a/tests/unit/src/sqlbuild/rule_engine/main/render_result/test_render_result.py +++ b/tests/unit/src/sqlbuild/rule_engine/main/render_result/test_render_result.py @@ -22,7 +22,7 @@ findings=( Finding( code="SQBRCONTRACT101", - path=Path("models/mart/commerce__mart__orders.sql"), + path=Path("sql/models/mart/commerce__mart__orders.sql"), line=3, column=7, message="model SQL must keep transformation logic in top-level CTEs", diff --git a/tests/unit/src/sqlbuild/rule_engine/main/run_rules/test_run_rules.py b/tests/unit/src/sqlbuild/rule_engine/main/run_rules/test_run_rules.py index 12b78fb7ac..f843fb4fe2 100644 --- a/tests/unit/src/sqlbuild/rule_engine/main/run_rules/test_run_rules.py +++ b/tests/unit/src/sqlbuild/rule_engine/main/run_rules/test_run_rules.py @@ -56,8 +56,8 @@ def test_given_sql_analysis_state_when_running_rules_then_type_proof_rules_follo + test_case.settings_toml, encoding="utf-8", ) - models: Path = tmp_path / "models" - models.mkdir() + models: Path = tmp_path / "sql" / "models" + models.mkdir(parents=True) (models / "orders.sql").write_text( "MODEL (description 'Test model orders.',\n" " contract enforced,\n" diff --git a/tests/unit/src/sqlbuild/rule_engine/main/skills/test_skills.py b/tests/unit/src/sqlbuild/rule_engine/main/skills/test_skills.py index bdccd3cc09..55af3d8986 100644 --- a/tests/unit/src/sqlbuild/rule_engine/main/skills/test_skills.py +++ b/tests/unit/src/sqlbuild/rule_engine/main/skills/test_skills.py @@ -171,7 +171,7 @@ def test_given_exact_exception_when_installing_then_selected_guidance_is_retaine rule_exceptions=( RuleExemption( rule="SQBRMODEL101", - path="models/mart/commerce__mart__orders.sql", + path="sql/models/mart/commerce__mart__orders.sql", reason="Migration is tracked", ), ), diff --git a/tests/unit/src/sqlbuild/runtime/event_exporting/classes/helpers.py b/tests/unit/src/sqlbuild/runtime/event_exporting/classes/helpers.py index b62bc6c831..78f6db4d55 100644 --- a/tests/unit/src/sqlbuild/runtime/event_exporting/classes/helpers.py +++ b/tests/unit/src/sqlbuild/runtime/event_exporting/classes/helpers.py @@ -47,8 +47,8 @@ def blocking_exporter(*, event: LifecycleEvent, blocking_provider: BlockingProvi def blocking_discovery() -> tuple[ tuple[DiscoveredProvider, ...], tuple[DiscoveredEventExporter, ...] ]: - provider_path: Path = Path("providers/blocking.py") - exporter_path: Path = Path("sinks/blocking.py") + provider_path: Path = Path("python/providers/blocking.py") + exporter_path: Path = Path("python/event_sinks/blocking.py") provider: DiscoveredProvider = DiscoveredProvider( file_path=provider_path, relative_path=provider_path, diff --git a/tests/unit/src/sqlbuild/runtime/event_exporting/classes/test_command_scope.py b/tests/unit/src/sqlbuild/runtime/event_exporting/classes/test_command_scope.py index fb66a4c64c..c9a3ac2612 100644 --- a/tests/unit/src/sqlbuild/runtime/event_exporting/classes/test_command_scope.py +++ b/tests/unit/src/sqlbuild/runtime/event_exporting/classes/test_command_scope.py @@ -16,8 +16,8 @@ EventExporterDispatcher, EventExportSummary, ) +from sqlbuild.event_sinks import CommandOutputRecord, CommandOutputStream from sqlbuild.providers import Provider -from sqlbuild.sinks import CommandOutputRecord, CommandOutputStream from tests.unit.src.sqlbuild.runtime.event_exporting.classes._test_types import ( EventExporterTeardownTestCase, SharedSinkProviderTestCase, @@ -98,8 +98,8 @@ def publish_output(*, record: CommandOutputRecord, destination: Destination) -> del record provider_ids.append(id(destination)) - provider_path: Path = tmp_path / "providers/destination.py" - sink_path: Path = tmp_path / "sinks/destination.py" + provider_path: Path = tmp_path / "python/providers/destination.py" + sink_path: Path = tmp_path / "python/event_sinks/destination.py" usage: DiscoveredProviderUsage = DiscoveredProviderUsage( provider_name="destination", parameter_name="destination", @@ -108,21 +108,21 @@ def publish_output(*, record: CommandOutputRecord, destination: Destination) -> ) provider: DiscoveredProvider = DiscoveredProvider( file_path=provider_path, - relative_path=Path("providers/destination.py"), + relative_path=Path("python/providers/destination.py"), name="destination", provider_class=Destination, settings=Destination(), ) lifecycle_sink: DiscoveredEventExporter = DiscoveredEventExporter( file_path=sink_path, - relative_path=Path("sinks/destination.py"), + relative_path=Path("python/event_sinks/destination.py"), name="publish_lifecycle", function=publish_lifecycle, provider_usages=(usage,), ) output_sink: DiscoveredCommandOutputSink = DiscoveredCommandOutputSink( file_path=sink_path, - relative_path=Path("sinks/destination.py"), + relative_path=Path("python/event_sinks/destination.py"), name="publish_output", function=publish_output, streams=frozenset(CommandOutputStream), diff --git a/tests/unit/src/sqlbuild/runtime/event_exporting/classes/test_dispatcher.py b/tests/unit/src/sqlbuild/runtime/event_exporting/classes/test_dispatcher.py index f3d6c4c8f2..8215f6af48 100644 --- a/tests/unit/src/sqlbuild/runtime/event_exporting/classes/test_dispatcher.py +++ b/tests/unit/src/sqlbuild/runtime/event_exporting/classes/test_dispatcher.py @@ -19,13 +19,13 @@ EventExportSeverity, EventExportSummary, ) +from sqlbuild.event_sinks import CommandOutputRecord, CommandOutputStream from sqlbuild.observability import LifecycleEvent from sqlbuild.runtime.event_exporting.exceptions import EventExporterInputError from sqlbuild.runtime.event_exporting.main._invoke_lifecycle_event_sink import ( invoke_lifecycle_event_sink, ) from sqlbuild.runtime.output_capture.models import BoundCommandOutputSink -from sqlbuild.sinks import CommandOutputRecord, CommandOutputStream from tests.unit.src.sqlbuild.runtime.event_exporting.classes._test_types import ( EventExporterDispatcherTestCase, HealthIntervalTestCase, @@ -143,7 +143,6 @@ def test_given_idle_dispatcher_when_waiting_then_it_does_not_poll_and_still_deli ) -> None: delivered: list[threading.Event] = [threading.Event(), threading.Event()] published: list[int] = [] - caller_thread: int = threading.get_ident() waits: list[tuple[int, float | None]] = [] condition_wait: Callable[[threading.Condition, float | None], bool] = threading.Condition.wait @@ -158,17 +157,23 @@ def publish(*, event: LifecycleEvent) -> None: delivered[len(published)].set() published.append(1) + existing_threads: set[int | None] = {thread.ident for thread in threading.enumerate()} dispatcher: EventExporterDispatcher = EventExporterDispatcher( exporters=(BoundEventExporter("publish", publish, {}),), ) dispatcher.enqueue(lifecycle_event()) assert delivered[0].wait(timeout=2.0) time.sleep(0.05) + # Threads left by earlier tests wait too, so count only the threads this dispatcher started. + dispatcher_threads: set[int | None] = { + thread.ident for thread in threading.enumerate() + } - existing_threads + assert dispatcher_threads waits.clear() time.sleep(test_case.idle_seconds) - # Other threads of a busy process wait too; only waits shorter than the idle safety timeout poll. + # Only waits shorter than the idle safety timeout poll. idle_waits: int = sum( - thread != caller_thread and timeout is not None and timeout < test_case.polling_seconds + thread in dispatcher_threads and timeout is not None and timeout < test_case.polling_seconds for thread, timeout in waits ) started: float = time.monotonic() diff --git a/tests/unit/src/sqlbuild/runtime/event_exporting/helpers.py b/tests/unit/src/sqlbuild/runtime/event_exporting/helpers.py index 6faca8e083..1f17358b64 100644 --- a/tests/unit/src/sqlbuild/runtime/event_exporting/helpers.py +++ b/tests/unit/src/sqlbuild/runtime/event_exporting/helpers.py @@ -6,6 +6,7 @@ "invocation_started", "invocation_completed", "invocation_failed", + "invocation_phase", "run_started", "run_completed", "run_failed", diff --git a/tests/unit/src/sqlbuild/runtime/event_exporting/test_sinks.py b/tests/unit/src/sqlbuild/runtime/event_exporting/test_sinks.py index 9153782600..5cba470696 100644 --- a/tests/unit/src/sqlbuild/runtime/event_exporting/test_sinks.py +++ b/tests/unit/src/sqlbuild/runtime/event_exporting/test_sinks.py @@ -6,17 +6,17 @@ import pytest from sqlbuild._native import EventExportSeverity -from sqlbuild.runtime.event_exporting.exceptions import EventExporterInputError -from sqlbuild.sinks import ( - CommandOutputSinkDefinition, +from sqlbuild.event_sinks import ( + CommandOutputEventSinkDefinition, CommandOutputStream, LifecycleEventKind, LifecycleEventSinkDefinition, - command_output_sink, - get_command_output_sink_definition, + command_output_event_sink, + get_command_output_event_sink_definition, get_lifecycle_event_sink_definition, lifecycle_event_sink, ) +from sqlbuild.runtime.event_exporting.exceptions import EventExporterInputError from tests.unit.src.sqlbuild.runtime.event_exporting._test_types import SinkApiTestCase @@ -119,11 +119,11 @@ def publish(event: object) -> None: def test_given_command_output_decorator_when_reading_then_streams_are_typed( test_case: SinkApiTestCase, ) -> None: - @command_output_sink(name="stdout_only", streams={"stdout"}) + @command_output_event_sink(name="stdout_only", streams={"stdout"}) def publish(record: object) -> None: del record - definition: CommandOutputSinkDefinition | None = get_command_output_sink_definition( + definition: CommandOutputEventSinkDefinition | None = get_command_output_event_sink_definition( cast(Callable[..., object], publish) ) @@ -146,7 +146,7 @@ def publish(event: object) -> None: del event assert test_case.expected_name is None - assert get_command_output_sink_definition(cast(Callable[..., object], publish)) is None + assert get_command_output_event_sink_definition(cast(Callable[..., object], publish)) is None @pytest.mark.parametrize( @@ -160,7 +160,7 @@ def test_given_invalid_sink_name_when_decorating_then_rejects_declaration( assert test_case.expected_name is not None with pytest.raises(EventExporterInputError, match=test_case.expected_name): - @command_output_sink(name="Bad-Name") + @command_output_event_sink(name="Bad-Name") def publish(record: object) -> None: del record @@ -176,7 +176,7 @@ def test_given_invalid_command_output_stream_when_decorating_then_rejects_declar assert test_case.expected_name is not None with pytest.raises(EventExporterInputError, match=test_case.expected_name): - @command_output_sink(streams={"diagnostic"}) + @command_output_event_sink(streams={"diagnostic"}) def publish(record: object) -> None: del record diff --git a/tests/unit/src/sqlbuild/runtime/output_capture/main/helpers.py b/tests/unit/src/sqlbuild/runtime/output_capture/main/helpers.py index 1745e7fa78..e6315a6287 100644 --- a/tests/unit/src/sqlbuild/runtime/output_capture/main/helpers.py +++ b/tests/unit/src/sqlbuild/runtime/output_capture/main/helpers.py @@ -1,6 +1,6 @@ from datetime import UTC, datetime -from sqlbuild.sinks import CommandOutputRecord, CommandOutputStream +from sqlbuild.event_sinks import CommandOutputRecord, CommandOutputStream def command_output_record() -> CommandOutputRecord: diff --git a/tests/unit/src/sqlbuild/runtime/output_capture/main/test_command_output_json.py b/tests/unit/src/sqlbuild/runtime/output_capture/main/test_command_output_json.py index 63a5dc0733..3487f4c2ec 100644 --- a/tests/unit/src/sqlbuild/runtime/output_capture/main/test_command_output_json.py +++ b/tests/unit/src/sqlbuild/runtime/output_capture/main/test_command_output_json.py @@ -4,7 +4,7 @@ import pytest -from sqlbuild.sinks import ( +from sqlbuild.event_sinks import ( CommandOutputRecord, CommandOutputValidationError, command_output_from_json, diff --git a/tests/unit/src/sqlbuild/runtime/output_capture/main/test_command_output_record.py b/tests/unit/src/sqlbuild/runtime/output_capture/main/test_command_output_record.py index d6efef2257..eebf8f55e3 100644 --- a/tests/unit/src/sqlbuild/runtime/output_capture/main/test_command_output_record.py +++ b/tests/unit/src/sqlbuild/runtime/output_capture/main/test_command_output_record.py @@ -4,7 +4,7 @@ import pytest -from sqlbuild.sinks import CommandOutputRecord, CommandOutputValidationError +from sqlbuild.event_sinks import CommandOutputRecord, CommandOutputValidationError from tests.unit.src.sqlbuild.runtime.output_capture.main._test_types import ( InvalidReplacementRecordTestCase, ReplacementRecordTestCase, diff --git a/ui/e2e/budgets.spec.ts b/ui/e2e/budgets.spec.ts index 20647f7d48..ba7fc15b76 100644 --- a/ui/e2e/budgets.spec.ts +++ b/ui/e2e/budgets.spec.ts @@ -389,15 +389,17 @@ const BUDGETS: Record = { // 40 rows' label and wrap classes, the rest the tab switch. Measured layouts 3, styles 12–17. '10K open the folder view': { layouts: 5, styles: 24, mutations: 456, nodes: 7300, drawn: 44, reads: 1 }, // Expand all swaps the window's rows for the expanded tree's (316 row insertions and removals) and - // rewrites their cells' classes. Measured layouts 1, styles 11–16. - '10K expand all': { layouts: 3, styles: 23, mutations: 577, nodes: 5700, drawn: 28, reads: 0 }, + // rewrites their cells' classes. Measured layouts 1, styles 11–16, mutations 590 since the selection + // bar became one row and the tree's window one row taller. + '10K expand all': { layouts: 3, styles: 23, mutations: 592, nodes: 5700, drawn: 28, reads: 0 }, // Opening one folder inserts its 20 subfolder rows and rewrites the window's cell classes (440). // Measured layouts 1–2, styles 9–15. '10K open one folder': { layouts: 5, styles: 23, mutations: 469, nodes: 7500, drawn: 48, reads: 0 }, // 20 wheel steps of 400 px over the expanded tree: like the Checks list, each step swaps rows in and out // of the window (2,142) and rewrites the recycled cells' classes (6,579), one layout per step. - // Measured layouts 20, styles 45–53, mutations 8,800. - '10K opened tree scroll': { layouts: 22, styles: 63, mutations: 8802, nodes: 5700, drawn: 28, reads: 0 }, + // Measured layouts 20, styles 45–53, mutations 9,000 (8,800 before the selection bar became one row + // and the window one row taller). + '10K opened tree scroll': { layouts: 22, styles: 63, mutations: 9002, nodes: 5700, drawn: 28, reads: 0 }, // Reads the Overview, its timeline and the cost summary once each, and draws the attention card's 9 // items and the timeline. Measured layouts 3–4, styles 22–31, mutations 140–141. '10K back to the Overview': { layouts: 7, styles: 42, mutations: 143, nodes: 4600, drawn: 12, reads: 3 }, diff --git a/ui/e2e/compact.spec.ts b/ui/e2e/compact.spec.ts index 7c7071504b..39aed75150 100644 --- a/ui/e2e/compact.spec.ts +++ b/ui/e2e/compact.spec.ts @@ -1,10 +1,11 @@ import { expect, test } from '@playwright/test'; import { zoomTo } from './zoom'; -// Zoomed out, cards take their compact form: a one-line pill, a ring in the colour of the card's state -// holding its kind's icon, then the part of its name that tells it apart from its siblings. The name -// never wraps, shows at 12 px or more on screen, shrinks to fit before it is cut, and is cut at its -// start, keeping the end that tells it apart. Cards are drawn in full down to 0.82. +// Zoomed out, cards are drawn in stages: in full down to 0.8; then node cards show their name alone, +// enlarged to about 10 px on screen, while other cards show their pill; then every card is a one-line +// pill, a dot in the colour of the card's state and the part of its name that tells it apart from its +// siblings; then the dot alone. A name never wraps, shrinks to fit before it is cut, and is cut at its +// end, except a discovered step's, which first drops the prefix it shares with its siblings. // With SHOTS set, each graph is also photographed at each zoom: SHOTS=/some/dir npx playwright test e2e/compact.spec.ts const shots = process.env.SHOTS; @@ -19,6 +20,7 @@ const GRAPHS: { name: string; path: string; click?: string }[] = [ /** Each compact pill wholly in view that breaks a rule, as problems. */ function pillProblems(): string[] { + const stage = document.querySelector('.graph-canvas')!.dataset.stage; const problems: string[] = []; const flow = document.querySelector('.svelte-flow')!.getBoundingClientRect(); const zoom = Number(/scale\(([\d.]+)\)/.exec(document.querySelector('.svelte-flow__viewport')!.style.transform)?.[1] ?? 1); @@ -45,39 +47,61 @@ function pillProblems(): string[] { return tone; } const visible: string[] = []; + const inView = (box: DOMRect) => box.left >= flow.left && box.right <= flow.right && box.top >= flow.top && box.bottom <= flow.bottom; + /** Whether `text` is `whole` or `whole` cut as the stages cut it: its end, or a shared prefix and then the rest's end. */ + const cutRight = (text: string, whole: string) => { + if (text === whole) return true; + const kept = text.replace(/…$/, ''); + const joint = (at: number) => at > 0 && /[_.[/:-]/.test(whole[at - 1]); + if (!text.startsWith('…') && !text.endsWith('…')) { + // A shared prefix cut short, then the rest that tells it apart whole: `hier…supplier`. + const [head, rest] = text.split('…'); + return whole.startsWith(head) && whole.endsWith(rest) && joint(whole.length - rest.length); + } + if (!text.startsWith('…')) return whole.startsWith(kept); + const rest = kept.slice(1); + return joint(whole.indexOf(rest)); + }; + const oneLine = (el: HTMLElement, px: number) => getComputedStyle(el).whiteSpace === 'nowrap' && el.getClientRects().length === 1 && el.getBoundingClientRect().height <= px * 1.8; for (const node of document.querySelectorAll('.svelte-flow__node')) { const card = node.firstElementChild as HTMLElement; const pill = card?.querySelector(':scope > .cface .pill'); - if (!pill) continue; + // A name-only card: its own frame, its name alone at about 10 px on screen, on one line, fitted. + const nameOnly = node.classList.contains('svelte-flow__node-asset') ? card?.querySelector(':scope > .head .name') : null; + if (nameOnly && (!pill || !pill.getClientRects().length)) { + if (!inView(card.getBoundingClientRect()) || stage !== 'name') continue; + const text = nameOnly.textContent ?? ''; + const px = parseFloat(getComputedStyle(nameOnly).fontSize) * zoom; + visible.push(`${node.parentElement?.dataset.id ?? ''} / ${text}`); + if (px < 9.5) problems.push(`${nameOnly.title}: its name shows at ${px.toFixed(2)} px`); + if (!oneLine(nameOnly, px)) problems.push(`${nameOnly.title}: its name wraps`); + if (nameOnly.scrollWidth > nameOnly.clientWidth + 0.5) problems.push(`${nameOnly.title}: "${text}" overflows its card`); + if (!cutRight(text, nameOnly.dataset.label ?? '')) problems.push(`${nameOnly.title}: shows "${text}", not its name cut at the end`); + continue; + } + if (!pill || !pill.getClientRects().length) continue; const box = pill.getBoundingClientRect(); - if (box.left < flow.left || box.right > flow.right || box.top < flow.top || box.bottom > flow.bottom) continue; + if (!inView(box)) continue; const full = pill.title; - const name = [...pill.querySelectorAll('.nm')].find((n) => getComputedStyle(n).display !== 'none'); - if (!name) { - problems.push(`${full}: no name shown`); + const dot = pill.querySelector('.dot')!; + const want = expected(card); + if (want && getComputedStyle(dot).backgroundColor !== want) problems.push(`${full}: its dot is ${getComputedStyle(dot).backgroundColor}, its state ${want}`); + const name = pill.querySelector('.nm')!; + if (stage === 'dot') { + if (getComputedStyle(name).display !== 'none') problems.push(`${full}: a dot shows its name`); + visible.push(`dot ${visible.length}`); continue; } - // Down to 0.5 what each shows tells siblings apart; further out, about four characters can't, so their tails must. - visible.push(`${pill.dataset.parent ?? ''} / ${zoom >= 0.49 ? (name.textContent ?? '') : (name.dataset.tail ?? '')}`); - const px = parseFloat(getComputedStyle(name).fontSize) * zoom; - if (px < 11.95) problems.push(`${full}: its name shows at ${px.toFixed(2)} px`); - if (Math.abs(box.height - 30) > 1) problems.push(`${full}: its pill is ${box.height.toFixed(1)} px tall`); - // One line: never wrapped, one line box. - if (getComputedStyle(name).whiteSpace !== 'nowrap' || name.getClientRects().length !== 1 || name.getBoundingClientRect().height > px * 1.6) problems.push(`${full}: its name wraps`); - // It fits; cut only once it can shrink no further, and then in its middle, keeping both ends. const text = name.textContent ?? ''; const tail = name.dataset.tail ?? ''; - const [head, end = ''] = text.split('…'); + visible.push(`${pill.dataset.parent ?? ''} / ${text}`); + const px = parseFloat(getComputedStyle(name).fontSize) * zoom; + if (px < 9) problems.push(`${full}: its name shows at ${px.toFixed(2)} px`); + if (!oneLine(name, px)) problems.push(`${full}: its name wraps`); if (name.scrollWidth > name.clientWidth + 0.5) problems.push(`${full}: "${text}" overflows its pill`); - if (text.includes('…') && px > 12.05) problems.push(`${full}: cut at ${px.toFixed(2)} px, before shrinking to 12`); - if (!full.endsWith(tail) || !tail.startsWith(head) || !tail.endsWith(end)) problems.push(`${full}: shows "${text}", not its tail "${tail}" cut in the middle`); - const ring = pill.querySelector('.ring')!; - const want = expected(card); - if (want && getComputedStyle(ring).borderTopColor !== want) problems.push(`${full}: its ring is ${getComputedStyle(ring).borderTopColor}, its state ${want}`); + if (!full.endsWith(tail) || !cutRight(text, tail)) problems.push(`${full}: shows "${text}", not its tail "${tail}" cut at the end`); } probe.remove(); - const repeated = visible.filter((t, i) => visible.indexOf(t) !== i); - if (repeated.length) problems.push(`names shown more than once among siblings: ${[...new Set(repeated)].join(', ')}`); if (!visible.length) problems.push('no compact card in view'); return problems; } @@ -85,7 +109,7 @@ function pillProblems(): string[] { test.use({ viewport: { width: 1600, height: 900 } }); for (const { name, path, click } of GRAPHS) { - test(`${name}: zoomed out, each card is a one-line pill with its state's ring`, async ({ page }) => { + test(`${name}: zoomed out, cards show their name alone, then a one-line pill with its state's dot, then the dot`, async ({ page }) => { test.setTimeout(90_000); await page.goto(path); await page.locator('.graph-canvas:not(.unfitted) .svelte-flow__node').first().waitFor({ timeout: 20_000 }); @@ -93,55 +117,38 @@ for (const { name, path, click } of GRAPHS) { await page.waitForTimeout(800); const canvas = page.locator('.graph-canvas').first(); - // Just above the compact zoom, cards are still drawn in full. - await zoomTo(page, 0.85); + // Just above the name-only stage, cards are still drawn in full. + await zoomTo(page, 0.82); await expect(canvas).not.toHaveClass(/\bcompact\b/); if (shots) await page.screenshot({ path: `${shots}/compact-${name}-z085-full.png` }); - for (const zoom of [0.7, 0.5, 0.4]) { + for (const [zoom, stage] of [[0.7, 'name'], [0.45, 'name'], [0.35, 'pill'], [0.32, 'pill'], [0.25, 'dot']] as const) { await zoomTo(page, zoom); - await expect(canvas).toHaveClass(/\bcompact\b/); + await expect(canvas).toHaveAttribute('data-stage', stage); if (shots) await page.screenshot({ path: `${shots}/compact-${name}-z0${Math.round(zoom * 100)}.png` }); expect(await page.evaluate(pillProblems), `${name} at ${zoom}`).toEqual([]); } }); } -test('a job pill’s play triangle sits in the middle of its ring', async ({ page }) => { - await page.goto('/jobs/warehouse_nightly?mock'); - await page.locator('.graph-canvas:not(.unfitted) .svelte-flow__node').first().waitFor({ timeout: 20_000 }); - await page.waitForTimeout(800); - for (const zoom of [0.7, 0.5]) { - await zoomTo(page, zoom); - const offsets = await page.evaluate(() => - [...document.querySelectorAll('.pill[data-kind="job"] .ring')].map((ring) => { - // The triangle's corners: two on its left edge, one at its right tip; its centroid a third of the way across. - const path = ring.querySelector('svg path')!; - const b = path.getBBox(); - const m = path.getScreenCTM()!; - const centroid = new DOMPoint(b.x + b.width / 3, b.y + b.height / 2).matrixTransform(m); - const r = ring.getBoundingClientRect(); - return { dx: centroid.x - (r.left + r.width / 2), dy: centroid.y - (r.top + r.height / 2), size: r.width }; - }) - ); - expect(offsets.length, 'job pills in view').toBeGreaterThan(0); - for (const o of offsets) { - expect(Math.abs(o.dx), `horizontally, in a ${o.size.toFixed(1)} px ring at ${zoom}`).toBeLessThanOrEqual(0.5); - expect(Math.abs(o.dy), `vertically, at ${zoom}`).toBeLessThanOrEqual(0.5); - } - } -}); - test('a selected pill stands out from the rest', async ({ page }) => { await page.goto('/lineage?mock'); await page.locator('.graph-canvas:not(.unfitted) .svelte-flow__node').first().waitFor({ timeout: 20_000 }); await page.waitForTimeout(800); - await zoomTo(page, 0.5); + await zoomTo(page, 0.34); const pills = page.locator('.cface .pill'); + // Two pills wholly in view of the graph, so neither sits under the sidebar. + const [one, two] = await pills.evaluateAll((all) => { + const flow = document.querySelector('.graph-canvas')!.getBoundingClientRect(); + return all.flatMap((p, i) => { + const b = p.getBoundingClientRect(); + return b.left >= flow.left && b.right <= flow.right && b.top >= flow.top && b.bottom <= flow.bottom ? [i] : []; + }); + }); const looks = (i: number) => pills.nth(i).evaluate((p) => ({ border: getComputedStyle(p).borderTopColor, ring: getComputedStyle(p).boxShadow, fill: getComputedStyle(p).backgroundColor })); - const before = await looks(1); - await pills.nth(1).click(); - const [selected, other] = [await looks(1), await looks(2)]; + const before = await looks(one); + await pills.nth(one).click(); + const [selected, other] = [await looks(one), await looks(two)]; const primary = await page.evaluate(() => { const i = document.body.appendChild(document.createElement('i')); i.style.color = getComputedStyle(document.documentElement).getPropertyValue('--primary'); const c = getComputedStyle(i).color; i.remove(); return c; }); expect(selected.border).toBe(primary); expect(selected.ring).not.toBe('none'); diff --git a/ui/e2e/concurrency.spec.ts b/ui/e2e/concurrency.spec.ts index c99948b9f4..688796ce8d 100644 --- a/ui/e2e/concurrency.spec.ts +++ b/ui/e2e/concurrency.spec.ts @@ -1,41 +1,51 @@ import { expect, test, type Page } from '@playwright/test'; import { FakeControl } from './support/fake-control'; -// The Concurrency panel on job and group pages: plain facts about what runs alongside what. With +// The Concurrency panel on job and group pages: key-value facts about what runs alongside what. With // SHOTS set, each page is photographed: SHOTS=/some/dir npx playwright test e2e/concurrency.spec.ts const shots = process.env.SHOTS; test.use({ viewport: { width: 1600, height: 1000 } }); -/** The panel's lines, as text, once the page has loaded; a group page opens its details first. */ +/** The panel's rows as "Label: value", and each pool as its own line, once the page has loaded; a group page opens its details first. */ async function panel(page: Page, job: string, group = false): Promise { await page.goto(`/jobs/${job}?mock`); if (group) await page.getByRole('button', { name: 'Toggle details' }).click({ timeout: 20_000 }); - const lines = page.locator('ul.concurrency > li'); - await expect(lines.first()).toBeVisible({ timeout: 20_000 }); - await lines.last().scrollIntoViewIfNeeded(); + const keys = page.locator('.concurrency dt'); + await expect(keys.first()).toBeVisible({ timeout: 20_000 }); + await keys.last().scrollIntoViewIfNeeded(); if (shots) await page.screenshot({ path: `${shots}/concurrency-panel-${job}.png` }); // Each fact, without the runs holding a pool now, which change as the mock's runs do. - return (await lines.allInnerTexts()).map((t) => t.replace(/\s+/g, ' ').replace(/ Running now: .*$/, '').trim()); + const clean = (t: string) => t.replace(/\s+/g, ' ').replace(/ Running now: .*$/, '').trim(); + const labels = await keys.allInnerTexts(); + const values = await page.locator('.concurrency dd').evaluateAll((all) => + all.map((dd) => { + const pools = [...dd.querySelectorAll('ul.pools > li')].map((li) => (li as HTMLElement).innerText); + return pools.length ? pools : [(dd as HTMLElement).innerText]; + }) + ); + return labels.flatMap((label, i) => (values[i].length > 1 || label.trim() === 'Pools' && values[i][0] !== 'None' ? values[i].map(clean) : [`${label.trim()}: ${clean(values[i][0])}`])); } test('a job states its run concurrency limit, overlap, and its pool', async ({ page }) => { const lines = await panel(page, 'core_build'); expect(lines).toEqual([ - "Inside a run: at most 8 of this job's nodes at once", - 'Never alongside runs writing the same tables (automatic)', - 'If triggered while running: is skipped', + 'Nodes at once: 8', + 'Shared tables: Exclusive · automatic', + 'When already running: Skip', 'warehouse_heavy: takes 1 of 1 (capped on this server; the project allows 3), shared with reporting_exports, close_of_business' ]); - await expect(page.getByRole('link', { name: 'How concurrency works' })).toHaveAttribute('href', 'https://sqlbuild.com/docs/concepts/concurrency/'); - await expect(page.locator('ul.concurrency a', { hasText: 'reporting_exports' })).toHaveAttribute('href', /\/jobs\/reporting_exports/); + await expect(page.getByRole('button', { name: 'How concurrency works' })).toBeVisible(); + await expect(page.locator('.insp-sec', { hasText: 'Concurrency' }).getByRole('link', { name: 'Docs' })).toHaveAttribute('href', 'https://sqlbuild.com/docs/concepts/concurrency/'); + await expect(page.getByRole('button', { name: 'About Nodes at once' })).toBeVisible(); + await expect(page.locator('ul.pools a', { hasText: 'reporting_exports' })).toHaveAttribute('href', /\/jobs\/reporting_exports/); }); test('a job without its own setting states the limit its runs get, without naming where it is set', async ({ page }) => { for (const [job, line] of [ - ['marts_only', "Inside a run: at most 6 of this job's nodes at once"], - ['activity_microbatch', "Inside a run: at most 2 of this job's nodes at once"], - ['revenue_refresh', "Inside a run: at most 4 of this job's nodes at once"], - ['load_sources', "Inside a run: at most 4 of this job's nodes at once"] + ['marts_only', 'Nodes at once: 6'], + ['activity_microbatch', 'Nodes at once: 2'], + ['revenue_refresh', 'Nodes at once: 4'], + ['load_sources', 'Nodes at once: 4'] ] as const) { expect((await panel(page, job))[0], job).toBe(line); } @@ -43,7 +53,7 @@ test('a job without its own setting states the limit its runs get, without namin test('a job in two pools lists each, and a job that waits says so', async ({ page }) => { const lines = await panel(page, 'reporting_exports'); - expect(lines).toContain('If triggered while running: waits'); + expect(lines).toContain('When already running: Queue'); expect(lines).toContain('supplier_api: takes 1 of 2, shared with load_sources'); expect(lines.filter((l) => l.includes(': takes '))).toHaveLength(2); }); @@ -51,13 +61,13 @@ test('a job in two pools lists each, and a job that waits says so', async ({ pag test('a group capped below what it asks takes the whole pool, shown as a warning', async ({ page }) => { const lines = await panel(page, 'close_of_business', true); expect(lines).toContain('Takes the whole warehouse_heavy pool on this server (capped at 1; the project asks for 3), shared with core_build, reporting_exports'); - await expect(page.locator('ul.concurrency li.pool.clamped')).toHaveCount(1); + await expect(page.locator('ul.pools li.pool.clamped')).toHaveCount(1); }); test('a group in no pool says so', async ({ page }) => { const lines = await panel(page, 'nightly_all', true); - expect(lines).toContain('Pools: none'); - expect(lines[0]).toBe('Members without their own limit: at most 4 nodes at once'); + expect(lines).toContain('Pools: None'); + expect(lines[0]).toBe('Nodes at once: 4'); }); test("the location shows the server's pool-cap warning", async ({ page }) => { @@ -81,13 +91,13 @@ test("a published job's limit comes through the server's job read as a plain lim }); await server.install(page); for (const [job, line, group] of [ - ['orders_job', "Inside a run: at most 2 of this job's nodes at once", false], - ['refunds_job', "Inside a run: at most 16 of this job's nodes at once", false], - ['nightly', 'Members without their own limit: at most 16 nodes at once', true] + ['orders_job', '2', false], + ['refunds_job', '16', false], + ['nightly', '16', true] ] as const) { await page.goto(`/jobs/${job}`); if (group) await page.getByRole('button', { name: 'Toggle details' }).click({ timeout: 20_000 }); - const first = page.locator('ul.concurrency > li').first(); - await expect(first, job).toHaveText(line, { timeout: 20_000 }); + await expect(page.locator('.concurrency dt').first(), job).toHaveText('Nodes at once', { timeout: 20_000 }); + await expect(page.locator('.concurrency dd').first(), job).toHaveText(line); } }); diff --git a/ui/e2e/cost-perf.spec.ts b/ui/e2e/cost-perf.spec.ts new file mode 100644 index 0000000000..1e25eef1d9 --- /dev/null +++ b/ui/e2e/cost-perf.spec.ts @@ -0,0 +1,84 @@ +import { expect, test, type Page } from '@playwright/test'; +import { interactionCost, median, type InteractionCost } from './support/main-thread'; + +// The Cost page on a large project (`?mock&costs`: 2,281 models, 30 jobs): opening a row and moving +// to another level each run at most a frame (16 ms) of the page's own script, and draw their result +// within 50 ms of the input. Each is judged on the median of five, so a one-off stall of a shared +// machine doesn't fail it; the timings are printed either way. + +test.use({ viewport: { width: 1600, height: 1000 } }); +test.describe.configure({ mode: 'serial' }); + +/** The page's own script for one interaction, at most: one frame. */ +const SCRIPT_MS = 16; +/** From the input to the frame that draws its result, at most, with style, layout and paint. */ +const TO_FRAME_MS = 50; +const TIMES = 5; + +async function open(page: Page, path: string) { + await page.goto(path); + await page.locator('tr.expandable').first().waitFor({ timeout: 20_000 }); + await page.waitForTimeout(800); +} + +/** The cost of each of `TIMES` runs of `act`, after `before` puts the page back, judged on their medians. */ +async function judge(page: Page, name: string, before: () => Promise, act: () => Promise) { + const runs: InteractionCost[] = []; + for (let i = 0; i < TIMES; i++) { + await before(); + await page.waitForTimeout(300); + runs.push(await interactionCost(page, act)); + } + const list = (pick: (r: InteractionCost) => number) => runs.map((r) => pick(r).toFixed(1)).join(', '); + console.info(`Cost, ${name}: script ${list((r) => r.script)} ms; input to frame ${list((r) => r.toFrame)} ms`); + expect.soft(median(runs.map((r) => r.script)), `ms of the page's script when ${name}`).toBeLessThan(SCRIPT_MS); + expect.soft(median(runs.map((r) => r.toFrame)), `ms from the input to the frame when ${name}`).toBeLessThan(TO_FRAME_MS); +} + +test('opening a row of the Cost tree stays within a frame of script', async ({ page }) => { + test.setTimeout(120_000); + await open(page, '/cost?mock&costs&still'); + const row = page.locator('tr.expandable').nth(1); + // With the mouse, anywhere on the row, and with Enter; each run opens the row closed before. + await judge( + page, + 'opening a job with a click', + () => row.hover({ position: { x: 600, y: 10 } }), + async () => { + await page.mouse.down(); + await page.mouse.up(); + } + ); + await judge( + page, + 'opening a job with Enter', + () => row.focus(), + () => page.keyboard.press('Enter') + ); +}); + +test('moving to another level of the Cost tree stays within a frame of script', async ({ page }) => { + test.setTimeout(120_000); + await open(page, '/cost?mock&costs&still'); + const crumbs = page.getByRole('navigation', { name: 'Breadcrumb' }); + const jobName = page.locator('tr.expandable .row-name').first(); + await judge( + page, + 'drilling into a job', + async () => { + if ((await crumbs.getByRole('link').count()) > 0) await crumbs.getByRole('link', { name: 'All' }).click(); + await jobName.waitFor(); + await jobName.hover(); + }, + () => jobName.click() + ); + await judge( + page, + 'going back up to every job', + async () => { + if ((await crumbs.getByRole('link').count()) === 0) await page.locator('tr.expandable .row-name').first().click(); + await crumbs.getByRole('link', { name: 'All' }).hover(); + }, + () => crumbs.getByRole('link', { name: 'All' }).click() + ); +}); diff --git a/ui/e2e/cost.spec.ts b/ui/e2e/cost.spec.ts new file mode 100644 index 0000000000..94d8242af3 --- /dev/null +++ b/ui/e2e/cost.spec.ts @@ -0,0 +1,99 @@ +import { expect, test, type Page } from '@playwright/test'; + +// The Cost page: under Operate for a location whose adapter reports cost; the selection (in the URL) +// decides what it shows. Rows open in place, names drill in by narrowing the selection, breadcrumbs +// and Back go up again, a model opens in a drawer, and a refused selection shows nothing. + +test.use({ viewport: { width: 1600, height: 1000 } }); + +const crumbs = (page: Page) => page.getByRole('navigation', { name: 'Breadcrumb' }); +const rows = (page: Page) => page.locator('.drill tbody tr[data-kind]'); +/** + * A drill's URL is first a shallow entry (pushState), then made a real one by the selection's + * replacing navigation. Back before that lands is overwritten by it, so wait for the real entry. + */ +const settled = (page: Page) => page.waitForFunction(() => !history.state?.['sveltekit:pageurl']); + +async function open(page: Page, path: string) { + await page.goto(path); + await rows(page).first().waitFor({ timeout: 20_000 }); +} + +test('Cost is under Operate for a Snowflake location only', async ({ page }) => { + await page.goto('/?mock'); + const sidebar = page.locator('nav').first(); + await expect(sidebar.getByRole('link', { name: 'Cost' })).toBeVisible({ timeout: 20_000 }); + await page.getByRole('button', { name: 'Switch location' }).click(); + await page.getByRole('menuitemradio', { name: /waffle-shop-dev/ }).click(); + await expect(page.getByRole('button', { name: 'Switch location' })).toContainText('waffle-shop-dev'); + await expect(sidebar.getByRole('link', { name: 'Cost' })).toHaveCount(0); +}); + +test('a job’s name drills in by selecting it, and the breadcrumb and Back go up again', async ({ page }) => { + await open(page, '/cost?mock&costs'); + const job = rows(page).first(); + const name = (await job.locator('.row-name').innerText()).trim(); + await job.locator('.row-name').click(); + await expect(page).toHaveURL(new RegExp(`select=job%3A${name}`)); + await expect(crumbs(page)).toContainText(name); + await expect(page.locator('.selection-bar')).toContainText(`job:${name}`); + await expect(rows(page).first()).toHaveAttribute('data-kind', 'folder'); + // A folder narrows the selection to the job's models in it. + await rows(page).first().locator('.row-name').click(); + await expect(page).toHaveURL(/path%3Asql%2Fmodels%2F/); + await settled(page); + await page.goBack(); + await expect(crumbs(page).getByRole('link')).toHaveCount(1); + await crumbs(page).getByRole('link', { name: 'All' }).click(); + await expect(crumbs(page).getByRole('link')).toHaveCount(0); + await expect(page.locator('.selection-bar')).not.toContainText('job:'); +}); + +test('a click anywhere on a row, or Enter, opens it in place; Expand and Collapse all', async ({ page }) => { + await open(page, '/cost?mock&costs'); + const first = rows(page).nth(1); + await expect(first).toHaveAttribute('aria-expanded', 'false'); + await first.click({ position: { x: 700, y: 10 } }); + await expect(first).toHaveAttribute('aria-expanded', 'true'); + await expect(page.locator('.drill tbody tr[data-kind="folder"]').first()).toBeVisible(); + await first.press('Enter'); + await expect(first).toHaveAttribute('aria-expanded', 'false'); + await page.getByRole('button', { name: 'Expand all' }).click(); + await expect(page.locator('.drill tbody tr[aria-expanded="true"]').first()).toBeVisible(); + await page.getByRole('button', { name: 'Collapse all' }).click(); + await expect(page.locator('.drill tbody tr[aria-expanded="true"]')).toHaveCount(0); + // Rows that open read as one target: the pointer anywhere on them. + expect(await first.evaluate((tr) => getComputedStyle(tr).cursor)).toBe('pointer'); +}); + +test('a model opens in the drawer with the jobs that spent its cost, and Escape closes it', async ({ page }) => { + await open(page, '/cost?mock&costs&select=job:ml_features_daily&flat=1'); + const model = page.locator('.drill tbody tr[data-kind="model"]').first(); + const name = (await model.locator('.row-name').innerText()).trim(); + await model.locator('.row-name').click(); + const drawer = page.getByRole('complementary', { name }); + await expect(drawer).toBeVisible(); + await expect(drawer.getByText('ml_features_daily')).toBeVisible(); + await expect(drawer.locator('table').last().locator('tbody tr').first()).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(drawer).toHaveCount(0); +}); + +test('Add puts a row into the selection, and a refused selection shows nothing', async ({ page }) => { + await open(page, '/cost?mock&costs'); + const job = rows(page).nth(2); + const name = (await job.locator('.row-name').innerText()).trim(); + await job.hover(); + await job.getByRole('button', { name: `Add ${name} to the selection` }).click(); + await expect(page).toHaveURL(new RegExp(`select=job%3A${name}`)); + await page.goto('/cost?mock&costs&select=no_such_model'); + await expect(page.locator('.drill')).toContainText('No nodes selected.', { timeout: 20_000 }); + await expect(rows(page)).toHaveCount(0); + await expect(page.locator('.sb-msg.err')).toBeVisible(); +}); + +test('the small mock shows its runs’ cost in dollars at the project’s price', async ({ page }) => { + await open(page, '/cost?mock'); + await expect(page.locator('.strip')).toContainText('$3.00 per credit'); + await expect(rows(page).first().locator('td').nth(1)).toContainText('$'); +}); diff --git a/ui/e2e/discovered-job.spec.ts b/ui/e2e/discovered-job.spec.ts new file mode 100644 index 0000000000..147e7e2493 --- /dev/null +++ b/ui/e2e/discovered-job.spec.ts @@ -0,0 +1,41 @@ +import { expect, test } from '@playwright/test'; + +// A job whose nodes come from a discovered set: the graph frames the set's steps under a header that +// collapses it, cards read by step, and the side panel shows the set, or a step's item and the set. +for (const width of [2000, 1280]) { + test(`at ${width} px a discovered set is framed, named by its steps, and nothing overflows`, async ({ page }) => { + await page.setViewportSize({ width, height: 1000 }); + await page.goto('/jobs/forecast_v2_eu_job?mock'); + const header = page.getByRole('button', { name: 'Collapse discovered set forecast_eu_plan' }); + await expect(header).toBeVisible({ timeout: 20_000 }); + await expect(header).toContainText('discovered set · 36 steps'); + await expect(page.locator('.svelte-flow__node[data-id="asset:forecast_eu[gbm_chain_d1]"]')).toContainText('gbm_chain_d1'); + const panel = page.locator('.insp-sec', { hasText: 'Discovered set' }).first(); + await expect(panel).toContainText('forecast_eu_plan'); + await expect(panel).toContainText('Steps'); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(overflow).toBeLessThanOrEqual(0); + }); +} + +test('the set header collapses the set to one node and opens it again', async ({ page }) => { + await page.goto('/jobs/forecast_v2_eu_job?mock'); + const collapse = page.getByRole('button', { name: 'Collapse discovered set forecast_eu_plan' }); + await collapse.click({ timeout: 20_000 }); + const expand = page.getByRole('button', { name: 'Expand discovered set forecast_eu_plan' }); + await expect(expand).toHaveAttribute('aria-expanded', 'false'); + await expect(page.locator('.svelte-flow__node[data-id="asset:forecast_eu[gbm_chain_d1]"]')).toHaveCount(0); + await expand.focus(); + await page.keyboard.press('Enter'); + await expect(page.getByRole('button', { name: 'Collapse discovered set forecast_eu_plan' })).toHaveAttribute('aria-expanded', 'true'); +}); + +test('a selected step shows its item and its set, and the failed set its error', async ({ page }) => { + await page.goto('/jobs/forecast_v2_us_job?mock'); + await page.locator('.svelte-flow__node[data-id="asset:forecast_us[gbm_chain_d1]"]').click({ timeout: 20_000 }); + const rail = page.locator('.rail'); + await expect(rail.getByText('Item', { exact: true })).toBeVisible(); + await expect(rail).toContainText('depth'); + await expect(rail).toContainText('Fetch failed'); + await expect(rail).toContainText('503 Service Unavailable'); +}); diff --git a/ui/e2e/ignored-audits.spec.ts b/ui/e2e/ignored-audits.spec.ts index ed35b31407..14a9a6d2ae 100644 --- a/ui/e2e/ignored-audits.spec.ts +++ b/ui/e2e/ignored-audits.spec.ts @@ -53,7 +53,7 @@ test('a job that ignores audit failures says so in its settings', async ({ page await page.goto('/jobs/core_build?mock'); await expect(page.getByTestId('job-ignores-audit-failures')).toHaveText("Audit failures don't stop runs", { timeout: 20_000 }); await page.goto('/jobs/marts_only?mock'); - await expect(page.locator('ul.concurrency')).toBeVisible({ timeout: 20_000 }); + await expect(page.locator('.concurrency')).toBeVisible({ timeout: 20_000 }); await expect(page.getByTestId('job-ignores-audit-failures')).toHaveCount(0); }); diff --git a/ui/e2e/insecure-context.spec.ts b/ui/e2e/insecure-context.spec.ts index 168f813f48..0baa3b1b6a 100644 --- a/ui/e2e/insecure-context.spec.ts +++ b/ui/e2e/insecure-context.spec.ts @@ -55,3 +55,20 @@ test('a one-time secret that cannot be copied is selected, with a hint to copy i await expect(issued.getByRole('alert')).toContainText('copy it with Ctrl+C'); expect(await page.evaluate(() => String(getSelection()))).toBe(await issued.locator('code').innerText()); }); + +test('a key shown in a modal dialog copies without navigator.clipboard, and Copy reads again after a moment', async ({ page }) => { + await page.goto('/admin/people?mock&tab=service-accounts&open=ci-runner'); + const panel = page.getByTestId('service-account-panel'); + await panel.getByTestId('rotate-key').click({ timeout: 20_000 }); + const dialog = page.getByTestId('rotate-dialog'); + await dialog.getByRole('button', { name: 'Rotate key' }).click(); + const reveal = dialog.getByTestId('key-reveal'); + const key = (await reveal.locator('code').innerText()).trim(); + await reveal.getByRole('button', { name: 'Copy' }).click(); + await expect.poll(() => page.evaluate(() => (window as unknown as { copied: string[] }).copied)).toEqual([key]); + await expect(reveal.getByRole('button', { name: 'Copied' })).toBeVisible(); + await expect(reveal.getByRole('button', { name: 'Copy' })).toBeVisible({ timeout: 5_000 }); + await reveal.getByRole('button', { name: 'Copy' }).click(); + await expect.poll(() => page.evaluate(() => (window as unknown as { copied: string[] }).copied)).toEqual([key, key]); + await expect(reveal.getByRole('alert')).toHaveCount(0); +}); diff --git a/ui/e2e/jobs-list.spec.ts b/ui/e2e/jobs-list.spec.ts new file mode 100644 index 0000000000..a95ed4b85b --- /dev/null +++ b/ui/e2e/jobs-list.spec.ts @@ -0,0 +1,26 @@ +import { expect, test } from '@playwright/test'; + +// The Jobs list: every row is one height, with name and description on two lines, and cells holding +// several items keep them on one line with a "+N" badge, at wide and narrow widths alike. +for (const width of [2000, 1280]) { + test(`at ${width} px every job row has one height and nothing overflows sideways`, async ({ page }) => { + await page.setViewportSize({ width, height: 900 }); + await page.goto('/jobs?mock'); + const rows = page.locator('table tbody tr'); + await expect(rows.first()).toBeVisible({ timeout: 20_000 }); + const heights = await rows.evaluateAll((all) => all.map((r) => Math.round(r.getBoundingClientRect().height))); + expect(new Set(heights).size, `row heights ${heights.join(', ')}`).toBe(1); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(overflow).toBeLessThanOrEqual(0); + }); +} + +test('a cell with more selectors than fit shows +N, and its popup lists them all', async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 900 }); + await page.goto('/jobs?mock'); + const badge = page.getByRole('button', { name: /^All \d+ selectors$/ }).first(); + await expect(badge).toBeVisible({ timeout: 20_000 }); + const total = Number((await badge.getAttribute('aria-label'))?.match(/\d+/)?.[0]); + await badge.click(); + await expect(page.locator('.fit-pop .fit-pop-item')).toHaveCount(total); +}); diff --git a/ui/e2e/layout.spec.ts b/ui/e2e/layout.spec.ts index ba703cb828..f846ebcd55 100644 --- a/ui/e2e/layout.spec.ts +++ b/ui/e2e/layout.spec.ts @@ -18,6 +18,7 @@ const PAGES = [ '/changes', '/checks', '/connections', + '/cost', '/jobs', '/lineage', '/locations', diff --git a/ui/e2e/overview-cost-activity.spec.ts b/ui/e2e/overview-cost-activity.spec.ts new file mode 100644 index 0000000000..a3a21e344f --- /dev/null +++ b/ui/e2e/overview-cost-activity.spec.ts @@ -0,0 +1,43 @@ +import { expect, test } from '@playwright/test'; + +// The Overview's top row has a 7-day cost card, linking to the Cost page, for a location whose adapter reports cost, and its +// Activity lists the jobs active in the window first, folding the idle ones. +test.use({ viewport: { width: 1600, height: 1000 } }); + +test('a Snowflake location shows Cost · 7 days in the top row, linking to the Cost page', async ({ page }) => { + await page.goto('/?mock'); + const card = page.getByTestId('cost-card'); + await expect(card).toContainText('Cost · 7 days', { timeout: 20_000 }); + await card.getByRole('link', { name: 'By job and folder' }).click(); + await expect(page).toHaveURL(/\/cost(\?|$)/); + await expect(page.getByRole('navigation', { name: 'Breadcrumb' })).toBeVisible({ timeout: 20_000 }); +}); + +test('a location whose adapter reports no cost has no cost card', async ({ page }) => { + await page.goto('/?mock'); + await expect(page.getByTestId('cost-card')).toBeVisible({ timeout: 20_000 }); + await page.getByRole('button', { name: 'Switch location' }).click(); + await page.getByRole('menuitemradio', { name: /waffle-shop-dev/ }).click(); + await expect(page.getByRole('button', { name: 'Switch location' })).toContainText('waffle-shop-dev'); + await expect(page.locator('.metric').first()).toBeVisible({ timeout: 20_000 }); + await expect(page.getByTestId('cost-card')).toHaveCount(0); +}); + +test('Activity folds idle jobs, opens them in place, and a search finds them folded or not', async ({ page }) => { + await page.goto('/?mock'); + const activity = page.locator('.surface-panel', { has: page.getByRole('heading', { name: 'Activity' }) }); + const fold = activity.getByRole('button', { name: /^\d+ idle jobs?$/ }); + await expect(fold).toBeVisible({ timeout: 20_000 }); + const idle = Number((await fold.innerText()).match(/\d+/)?.[0]); + const rows = activity.locator('.tl-body .row:not(.fold)'); + const folded = await rows.count(); + await fold.click(); + await expect(fold).toHaveAttribute('aria-expanded', 'true'); + await expect(rows).toHaveCount(folded + idle); + await fold.click(); + await expect(rows).toHaveCount(folded); + // A search lists every match, idle or not, without the fold. + const name = (await activity.locator('.tl-body .row:not(.fold) .job-name').first().innerText()).trim(); + await activity.getByPlaceholder('Search jobs').fill(name); + await expect(activity.getByRole('button', { name: /idle job/ })).toHaveCount(0); +}); diff --git a/ui/e2e/selection.spec.ts b/ui/e2e/selection.spec.ts index 870eb5d916..c94465582c 100644 --- a/ui/e2e/selection.spec.ts +++ b/ui/e2e/selection.spec.ts @@ -43,7 +43,7 @@ test('a selection is typed, picked, widened, copied, narrowed and built', async const count = page.locator('.sb-count'); await expect(count).toHaveText(/^\d+ nodes?$/); - await expect(page.locator('.sb-msg')).toContainText('Reads as: nodes tagged finance and everything upstream of them'); + await expect(page.locator('.sb-msg')).toHaveCount(0); await expect.poll(() => new URL(page.url()).searchParams.get('select')).toBe('+tag:finance'); await page.getByRole('button', { name: /Copy as/ }).click(); @@ -55,7 +55,6 @@ test('a selection is typed, picked, widened, copied, narrowed and built', async await field(page, 'Except').pressSequentially('tag:revenue'); await page.keyboard.press('Enter'); await expect(chips(page, 1)).toHaveText([/tag:revenue/]); - await expect(page.locator('.sb-msg')).toContainText('minus nodes tagged revenue'); await expect(count).toHaveText(/^\d+ nodes?$/); await expect.poll(() => new URL(page.url()).searchParams.get('exclude')).toBe('tag:revenue'); await page.getByRole('button', { name: /Copy as/ }).click(); diff --git a/ui/e2e/support/main-thread.ts b/ui/e2e/support/main-thread.ts new file mode 100644 index 0000000000..dd22bf068b --- /dev/null +++ b/ui/e2e/support/main-thread.ts @@ -0,0 +1,70 @@ +import type { Page } from '@playwright/test'; + +// How much main-thread work an interaction costs, from a Chrome trace: the page's own script time +// (JavaScript from the input on, without the style and layout it forces), and the time from the +// input to the end of the frame that draws its result. Data that arrives later isn't counted. + +type TraceEvent = { name: string; ph: string; ts: number; dur?: number; pid: number; tid: number; args?: { name?: string; data?: { type?: string } } }; + +export type InteractionCost = { + /** Ms of JavaScript the page ran for the input, forced style and layout left out. */ + script: number; + /** Ms from the input to the end of the frame that draws the update. */ + toFrame: number; +}; + +/** Events in which the page's JavaScript runs. */ +const SCRIPT = new Set(['FunctionCall', 'EventDispatch', 'TimerFire', 'FireAnimationFrame', 'RunMicrotasks', 'EvaluateScript', 'v8.callFunction']); +/** Browser work that script can force while it runs. */ +const FORCED = new Set(['UpdateLayoutTree', 'Layout', 'RecalcStyle']); +/** The input events an interaction dispatches. */ +const INPUTS = new Set(['mousedown', 'mouseup', 'click', 'keydown', 'keyup', 'keypress']); +/** Events that end a frame. */ +const FRAME = new Set(['Paint']); + +const end = (e: TraceEvent) => e.ts + (e.dur ?? 0); +/** Total length of `events` with overlaps counted once. */ +function covered(events: TraceEvent[]): number { + let total = 0; + let until = -Infinity; + for (const e of [...events].sort((a, b) => a.ts - b.ts)) { + const from = Math.max(e.ts, until); + if (end(e) > from) total += end(e) - from; + until = Math.max(until, end(e)); + } + return total; +} + +/** The cost of `act`, counting what the main thread does from its first input for `window` ms. */ +export async function interactionCost(page: Page, act: () => Promise, window = 50): Promise { + const cdp = await page.context().newCDPSession(page); + const events: TraceEvent[] = []; + cdp.on('Tracing.dataCollected', ({ value }) => events.push(...(value as TraceEvent[]))); + const done = new Promise((resolve) => cdp.once('Tracing.tracingComplete', () => resolve())); + await cdp.send('Tracing.start', { categories: 'devtools.timeline,disabled-by-default-devtools.timeline', transferMode: 'ReportEvents' }); + await act(); + await page.waitForTimeout(window + 250); + await cdp.send('Tracing.end'); + await done; + await cdp.detach(); + const main = new Set(events.filter((e) => e.name === 'thread_name' && e.args?.name === 'CrRendererMain').map((e) => `${e.pid}:${e.tid}`)); + const on = events.filter((e) => e.ph === 'X' && main.has(`${e.pid}:${e.tid}`)); + const input = on.filter((e) => e.name === 'EventDispatch' && ['mousedown', 'keydown', 'click'].includes(e.args?.data?.type ?? '')).sort((a, b) => a.ts - b.ts)[0]; + if (!input) return { script: 0, toFrame: 0 }; + const within = on.filter((e) => e.ts >= input.ts && e.ts < input.ts + window * 1000); + const scripts = within.filter((e) => SCRIPT.has(e.name)); + const forced = within.filter((e) => FORCED.has(e.name) && scripts.some((s) => e.ts >= s.ts && end(e) <= end(s))); + // The input's own handlers (the click or key that updates the page, usually the longest), then the + // first frame drawn after them. + const handled = within + .filter((e) => e.name === 'EventDispatch' && INPUTS.has(e.args?.data?.type ?? '')) + .reduce((longest, e) => ((e.dur ?? 0) > (longest.dur ?? 0) ? e : longest), input); + const frame = on.filter((e) => FRAME.has(e.name) && e.ts >= end(handled)).sort((a, b) => a.ts - b.ts)[0]; + return { + script: (covered(scripts) - covered(forced)) / 1000, + toFrame: ((frame ? end(frame) : end(handled)) - input.ts) / 1000 + }; +} + +/** The middle of `values`. */ +export const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; diff --git a/ui/src/lib/api/client.ts b/ui/src/lib/api/client.ts index 3c9baf2f17..13820ef6c6 100644 --- a/ui/src/lib/api/client.ts +++ b/ui/src/lib/api/client.ts @@ -1,4 +1,5 @@ import type { + DiscoveredSet, AdhocRunCheck, PlanResult, PlanPage, @@ -39,6 +40,9 @@ import type { IgnoredAuditFailure, RunCostRow, CostSummary, + CostSelection, + CostSelectionQuery, + CostSeriesGroup, AutomaticWithdrawal, ConditionShape, NodeBuildCost, @@ -87,6 +91,8 @@ export interface ApiClient extends PlatformApi { * through the shared catalog store (`$lib/state/catalog.svelte`), which reads it once per snapshot. */ listCatalogNodes(scope: Scope): Promise; + /** The current snapshot's discovered sets and the nodes their items became; none before a publication. */ + readDiscovered(scope: Scope): Promise; /** Every node's build state at the current status version, for applying `node_status` changes to a listing. */ listNodeStates(scope: Scope): Promise; /** `listing` and `checks` are current `listCatalogNodes` and `listChecks` results the caller already holds, so they aren't read again. */ @@ -127,6 +133,10 @@ export interface ApiClient extends PlatformApi { listRunCost(scope: Scope, runId: string): Promise; /** Estimated query cost of the runs that started in the last `days` days, by job, warehouse size and node. */ getCostSummary(scope: Scope, days: number): Promise; + /** A selection's estimated query cost over the last `query.days` whole UTC days, job by node. */ + readCostSelection(scope: Scope, query: CostSelectionQuery): Promise; + /** Daily credits of up to 200 groups of a selection, in the groups' order. */ + readCostSeries(scope: Scope, query: CostSelectionQuery, groups: CostSeriesGroup[]): Promise; /** One node's estimated query cost per build over the last `days` days, newest first. */ listNodeCosts(scope: Scope, nodeKey: string, days: number): Promise; /** One statement's SQL, fetched when its row is expanded. `view.sql` */ diff --git a/ui/src/lib/api/http-client.test.ts b/ui/src/lib/api/http-client.test.ts index b3125878d1..78d7040645 100644 --- a/ui/src/lib/api/http-client.test.ts +++ b/ui/src/lib/api/http-client.test.ts @@ -773,6 +773,34 @@ describe('republish', () => { }); }); +describe('readDiscovered', () => { + it('reads the current snapshot\'s sets with each item\'s node, and none before a publication', async () => { + const bodies: unknown[] = [ + { + snapshot_id: 's-1', + generation: 3, + published_at: '2026-11-23T10:00:00Z', + sets: [{ name: 'forecast_plan', status: 'ok', items: 1, digest: 'd-1', tags: { release: '0.58.0' }, assets: ['forecast'], nodes: [{ key: 'asset:forecast[train]', asset: 'forecast', step: 'train', args: { region: 'eu' } }] }] + }, + null + ]; + const calls: Request[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (request: Request) => { + calls.push(request); + return Response.json(bodies[calls.length - 1]); + }) + ); + const client = createHttpClient({ baseUrl: 'http://ui.test', onUnauthorized: () => {} }); + expect(await client.readDiscovered(ORDERS)).toEqual([ + { name: 'forecast_plan', status: 'ok', items: 1, fetchedAt: null, lastGoodAt: null, digest: 'd-1', error: null, checkEverySeconds: null, tags: { release: '0.58.0' }, assets: ['forecast'], nodes: [{ key: 'asset:forecast[train]', asset: 'forecast', step: 'train', args: { region: 'eu' } }] } + ]); + expect(new URL(calls[0].url).pathname).toBe('/api/control/locations/0191f0aa-orders/targets/development/discovered'); + expect(await client.readDiscovered(ORDERS)).toEqual([]); + }); +}); + describe('requestWarehouseSync', () => { function server(status: number) { const calls: Request[] = []; diff --git a/ui/src/lib/api/http-client.ts b/ui/src/lib/api/http-client.ts index 1f1ec68b7e..ad40fd68c0 100644 --- a/ui/src/lib/api/http-client.ts +++ b/ui/src/lib/api/http-client.ts @@ -21,11 +21,12 @@ import { jobDetailOf, runWindowOf, toJob, toTick, toTrigger, toTriggerStateEvent import { timelineOf } from './http-timeline'; import { RUN_WINDOW, groupRunNodes, parseRunCursor, planResultOf, queueEntriesOf, toAdhocCheck, runDetailOf, runRowPageOver, runsMatching, runTabCountsOf, toRunNode, toRuns, toRunEvent, toRunOutput, toRunStatements, toIgnoredAuditFailures, toRunCostRows, toCostSummary, toNodeBuildCosts } from './http-runs'; import { toSelectionEvaluation, toSelectionVocabulary } from './http-selection'; +import { costSeriesGroups, toCostSelection } from './http-cost'; import type { ChangeSubscription, ChangedChannel, ChangedSignal, ConnectionState } from './signals'; -import type { AuthMode, Bootstrap, BuiltInRole, Capability, Location, NavCounts, PlatformEvent, RepublishResult, Scope, Snapshot, WarehouseSync } from './types'; +import type { AuthMode, Bootstrap, BuiltInRole, Capability, DiscoveredSet, Location, NavCounts, PlatformEvent, RepublishResult, Scope, Snapshot, WarehouseSync } from './types'; import type { Account, AuditEntry, AuditQuery, ConnectionTest, IssuedToken, KeyRotation, LocationDetail, NewPasswordAccount, NewServiceAccount, ServiceAccount, ServerSettings, WarehouseConnection, LocationSummary, PlatformEventQuery, PlatformEventRecord, PlatformHealth, MaintenanceHistory, ProviderConnection, RoleAssignment, RoleAssignmentRequest, RoleDefinition, RoleDetail } from './types/platform'; import type { Acknowledgement, CatalogNode, CatalogNodeDetail, Check, CheckDetail, CheckEvidence, CheckSql, NodeStates, NodeStatusDelta, Overview, SnapshotChange, ColumnLineage, AttentionAcknowledgement, ConditionShape, AutomaticWithdrawal } from './types/build'; -import type { NodeOutputIndex, NodeOutputPage, NodeOutputSearch, RunNode, RunOutputFollow, AdhocRunCheck, AdhocRunRequest, BulkRunResult, SelectionEvaluation, SelectionRequest, SelectionVocabulary, PlanDiff, PlanPage, PlanPageSection, PlanResult, QueueEntry, Timeline, Job, JobDetail, JobLaunchOptions, RerunMode, SnapshotNode, Run, RunDetail, RunListQuery, RunRowPage, RunRowQuery, RunTabCounts, Trigger, TriggerDetail, TriggerState, RunEventPage, RunNodeError, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostSummary, NodeBuildCost, StatementSql } from './types/operate'; +import type { NodeOutputIndex, NodeOutputPage, NodeOutputSearch, RunNode, RunOutputFollow, AdhocRunCheck, AdhocRunRequest, BulkRunResult, SelectionEvaluation, SelectionRequest, SelectionVocabulary, PlanDiff, PlanPage, PlanPageSection, PlanResult, QueueEntry, Timeline, Job, JobDetail, JobLaunchOptions, RerunMode, SnapshotNode, Run, RunDetail, RunListQuery, RunRowPage, RunRowQuery, RunTabCounts, Trigger, TriggerDetail, TriggerState, RunEventPage, RunNodeError, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostSummary, CostSelection, CostSelectionQuery, CostSeriesGroup, NodeBuildCost, StatementSql } from './types/operate'; import { newRequestId } from '$lib/browser/request-id'; type Wire = components['schemas']; @@ -49,6 +50,8 @@ const SUPPORTED: ReadonlySet = new Set([ 'listRunIgnoredAudits', 'listRunCost', 'getCostSummary', + 'readCostSelection', + 'readCostSeries', 'listNodeCosts', 'getStatementSql', 'listRunOutput', @@ -457,6 +460,22 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, if (!data) throw new ApiError(errorText(error, response), response.status); return toCostSummary(data); }, + async readCostSelection(scope: Scope, query: CostSelectionQuery): Promise { + const { locationId, target } = parseLocationKey(scope.locationId); + const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/cost/selection', { params: { path: { location_id: locationId, target }, query } }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return toCostSelection(data); + }, + async readCostSeries(scope: Scope, query: CostSelectionQuery, groups: CostSeriesGroup[]): Promise { + const { locationId, target } = parseLocationKey(scope.locationId); + const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/cost/series', { + params: { path: { location_id: locationId, target }, query: { ...query, groups: costSeriesGroups(groups) } } + }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return data.series; + }, async listNodeCosts(scope: Scope, nodeKey: string, days: number): Promise { const { locationId, target } = parseLocationKey(scope.locationId); const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/nodes/{node_key}/cost', { @@ -761,6 +780,27 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, if (!response.ok) throw new ApiError(errorText(error, response), response.status); }, /** Asks the location to publish again, then long-polls until it has or the request expires. */ + async readDiscovered(scope: Scope): Promise { + const { locationId, target } = parseLocationKey(scope.locationId); + const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/discovered', { + params: { path: { location_id: locationId, target } } + }); + if (response.status === 401) onUnauthorized(); + if (error) throw new ApiError(errorText(error, response), response.status); + return (data?.sets ?? []).map((s) => ({ + name: s.name, + status: s.status, + items: s.items, + fetchedAt: s.fetched_at ?? null, + lastGoodAt: s.last_good_at ?? null, + digest: s.digest ?? null, + error: s.error ?? null, + checkEverySeconds: s.check_every_seconds ?? null, + tags: s.tags, + assets: s.assets, + nodes: s.nodes.map((n) => ({ key: n.key, asset: n.asset, step: n.step, args: n.args })) + })); + }, async republish(scope: Scope): Promise { const { locationId, target } = parseLocationKey(scope.locationId); const path = { location_id: locationId, target }; diff --git a/ui/src/lib/api/http-cost.ts b/ui/src/lib/api/http-cost.ts new file mode 100644 index 0000000000..a05f63decf --- /dev/null +++ b/ui/src/lib/api/http-cost.ts @@ -0,0 +1,48 @@ +// Server cost reads of a selection, in the UI's shapes. + +import type { components } from '$control/schema.d.ts'; +import { toSelectionProblem } from './http-selection'; +import { priceSource } from './http-runs'; +import type { CostSelection, CostSeriesGroup } from './types/operate'; + +type Wire = components['schemas']; + +export function toCostSelection(wire: Wire['CostSelectionRecord']): CostSelection { + const series = (list: Wire['CostSeriesRecord'][]) => list.map((s) => ({ key: s.key ?? null, credits: s.credits })); + return { + snapshotId: wire.snapshot_id ?? null, + since: wire.since, + days: wire.days, + dates: wire.dates, + error: toSelectionProblem(wire.error), + price: wire.price ? { usdPerCredit: wire.price.usd_per_credit, source: priceSource(wire.price.source, true) ?? 'config' } : null, + credits: wire.credits, + previousCredits: wire.previous_credits, + usd: wire.usd ?? null, + previousUsd: wire.previous_usd ?? null, + runs: wire.runs, + incompleteRuns: wire.incomplete_runs, + queries: wire.queries, + seconds: wire.seconds, + bytesScanned: wire.bytes_scanned, + facts: wire.facts.map((f) => ({ + job: f.job ?? null, + nodeKey: f.node_key, + folder: f.folder, + credits: f.credits, + previousCredits: f.previous_credits, + usd: f.usd ?? null, + previousUsd: f.previous_usd ?? null, + seconds: f.seconds, + runs: f.runs, + queries: f.queries, + bytesScanned: f.bytes_scanned + })), + jobDaily: series(wire.job_daily), + folderDaily: series(wire.folder_daily) + }; +} + +/** Groups as the series read takes them, in its JSON. */ +export const costSeriesGroups = (groups: CostSeriesGroup[]) => + JSON.stringify(groups.map((g) => ({ job: g.job ?? null, manual: g.manual ?? false, folder: g.folder ?? null, node_key: g.nodeKey ?? null }))); diff --git a/ui/src/lib/api/http-overview.test.ts b/ui/src/lib/api/http-overview.test.ts index 46a62cb3e8..4ef0b9094f 100644 --- a/ui/src/lib/api/http-overview.test.ts +++ b/ui/src/lib/api/http-overview.test.ts @@ -103,7 +103,6 @@ describe('overview from live reads', () => { }); it('leaves parts without a server read empty instead of zero', () => { - expect(overview.metrics.cost).toBeNull(); const unknown = overviewOf({ runs: [], checks: [], nodes: [{ ...node('model:a', 'table', 'models/a.sql'), stale: null }], changes: [], events: [], triggers: [], acknowledgements: new Map(), conditions: { snoozeSeconds: 86_400, acknowledgements: [] }, scopeKey: 'loc-1:dev', now }); expect(unknown.groups).toBeNull(); }); diff --git a/ui/src/lib/api/http-overview.ts b/ui/src/lib/api/http-overview.ts index aaf6a2179a..fa243cfefa 100644 --- a/ui/src/lib/api/http-overview.ts +++ b/ui/src/lib/api/http-overview.ts @@ -115,8 +115,7 @@ export function overviewOf({ runs, checks, nodes, changes, events, triggers, ack active: recent.filter((r) => ACTIVE_STATUSES.has(r.status)).length }, checks: checkCountsOf(checks), - stale: { nodes: staleNodes, changed: changed.length, behind: behind.length, sources: null }, - cost: null + stale: { nodes: staleNodes, changed: changed.length, behind: behind.length, sources: null } }, attention: withConditions(attention, conditions.acknowledgements, now), attentionSnoozeSeconds: conditions.snoozeSeconds, diff --git a/ui/src/lib/api/http-runs.ts b/ui/src/lib/api/http-runs.ts index f49a9fa00a..3f3ffe7ffb 100644 --- a/ui/src/lib/api/http-runs.ts +++ b/ui/src/lib/api/http-runs.ts @@ -1,7 +1,7 @@ import type { components } from '$control/schema.d.ts'; import { isActiveRun, isUnfinishedNode, UNFINISHED_NODE_STATUSES } from '$lib/status'; import type { Capability, Principal } from './types'; -import type { AdhocRunCheck, LaunchVerb, NodeCounts, NodeKind, PlanChanged, PlanDocument, PlanPage, PlanPageSection, PlanResult, PlanWarning, QueueEntry, QueueWait, Run, RunDetail, RunListQuery, RunNode, RunNodeStatus, RunRow, RunRowPage, RunRowQuery, RunTabCounts, RunEvent, RunEventCheck, RunEventLevel, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostGroup, CostSummary, NodeBuildCost } from './types/operate'; +import type { AdhocRunCheck, LaunchVerb, NodeCounts, NodeKind, PlanChanged, PlanDocument, PlanPage, PlanPageSection, PlanResult, PlanWarning, QueueEntry, QueueWait, Run, RunDetail, RunListQuery, RunNode, RunNodeStatus, RunRow, RunRowPage, RunRowQuery, RunTabCounts, RunEvent, RunEventCheck, RunEventLevel, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostGroup, CostSummary, PriceSource, NodeBuildCost } from './types/operate'; import { RECALL_EVENT_TYPES, SCHEDULER_FACTS } from './types/operate'; type Wire = components['schemas']; @@ -468,7 +468,8 @@ export function toRunEvent(wire: Wire['RunEventRecord'], runId: string): RunEven statementId: wire.statement_id ?? null, attempt: null, message, - check: type === 'audit_completed' ? checkOf(wire) : null + check: type === 'audit_completed' ? checkOf(wire) : null, + phase: wire.phase ? { phase: wire.phase, durationMs: wire.duration_ms ?? null, count: wire.phase_count ?? null, name: wire.phase_name ?? null, detail: wire.phase_detail ?? null } : null }; } @@ -563,6 +564,14 @@ export function toRunOutput(wire: Wire['RunOutput']): RunOutputLine[] { const COST_STATUSES: RunCostRow['status'][] = ['complete', 'partial', 'pending', 'collection_failed', 'unavailable']; +const PRICE_SOURCES: readonly PriceSource[] = ['config', 'rate_sheet', 'list_price', 'mixed']; + +/** A price's source; dollars recorded before sources were came from the project's price. */ +export const priceSource = (source: string | null | undefined, priced: boolean): PriceSource | null => { + const known = PRICE_SOURCES.find((s) => s === source); + return known ?? (priced ? 'config' : null); +}; + const costStatus = (status: string): RunCostRow['status'] => COST_STATUSES.find((s) => s === status) ?? 'unavailable'; const toCostGroup = (g: Wire['CostGroup']): CostGroup => ({ key: g.key ?? null, credits: g.credits, usd: g.usd ?? null, seconds: g.seconds, runs: g.runs }); @@ -572,6 +581,7 @@ export function toCostSummary(wire: Wire['CostSummaryRecord']): CostSummary { since: wire.since, credits: wire.credits, usd: wire.usd ?? null, + priceSource: priceSource(wire.usd_per_credit_source, wire.usd != null), runs: wire.runs, incompleteRuns: wire.incomplete_runs, byJob: wire.by_job.map(toCostGroup), @@ -588,6 +598,7 @@ export function toNodeBuildCosts(wire: Wire['NodeCostRecord'][]): NodeBuildCost[ status: costStatus(c.status), credits: c.credits, usd: c.usd ?? null, + priceSource: priceSource(c.usd_per_credit_source, c.usd != null), seconds: c.seconds, queryCount: c.query_count })); @@ -608,6 +619,7 @@ export function toRunCostRows(wire: Wire['WarehouseResourceCostRecord'][]): RunC bytesScanned: r.bytes_scanned, credits: Number(r.estimated_credits), usd: r.estimated_usd == null ? null : Number(r.estimated_usd), + priceSource: priceSource(r.usd_per_credit_source, r.estimated_usd != null), status: costStatus(r.status), statementsExpected: r.statements_expected, statementsObserved: r.statements_observed diff --git a/ui/src/lib/api/http-selection.ts b/ui/src/lib/api/http-selection.ts index 2b630ea296..848b33bed3 100644 --- a/ui/src/lib/api/http-selection.ts +++ b/ui/src/lib/api/http-selection.ts @@ -1,28 +1,34 @@ // Server selection evaluations and selector vocabularies, in the UI's shapes. import type { components } from '$control/schema.d.ts'; -import type { SelectionEvaluation, SelectionVocabulary, VocabularyEntry } from './types/operate'; +import type { SelectionEvaluation, SelectionProblem, SelectionVocabulary, VocabularyEntry } from './types/operate'; type Wire = components['schemas']; export function toSelectionEvaluation(wire: Wire['SelectionEvaluation']): SelectionEvaluation { - const problem = wire.error ?? null; return { snapshotId: wire.snapshot_id ?? null, count: wire.count, keys: wire.keys, nextOffset: wire.next_offset ?? null, - error: problem && { - code: problem.code ?? null, - message: problem.message, - help: problem.help ?? null, - location: problem.location ?? null, - suggestions: problem.suggestions, - refused: problem.refused ? toRefusal(problem.refused) : null - } + error: toSelectionProblem(wire.error) }; } +/** Why the server refuses a selection, in the UI's shape; null when it doesn't. */ +export function toSelectionProblem(problem: Wire['SelectionProblem'] | null | undefined): SelectionProblem | null { + return problem + ? { + code: problem.code ?? null, + message: problem.message, + help: problem.help ?? null, + location: problem.location ?? null, + suggestions: problem.suggestions, + refused: problem.refused ? toRefusal(problem.refused) : null + } + : null; +} + /** The server's refused part in the UI's shape: its index as `part`, and a bare name or glob as type `null`. */ function toRefusal(refused: Wire['SelectionRefusal']): NonNullable['refused'] { const bare = refused.type === 'name' || refused.type === 'glob'; diff --git a/ui/src/lib/api/index.ts b/ui/src/lib/api/index.ts index c435e8b1d5..238222961a 100644 --- a/ui/src/lib/api/index.ts +++ b/ui/src/lib/api/index.ts @@ -2,6 +2,7 @@ import type { ApiClient } from "./client"; import { createHttpClient } from "./http-client"; import { MockApiClient, type MockOptions } from "./mock/mock-client"; import { largeProject } from "./mock/large-project"; +import { costProject } from "./mock/cost-project"; import { hugeProject } from "./mock/huge-project"; import { awkward } from "./mock/awkward"; import { missingSecrets } from "./mock/missing-secrets"; @@ -92,11 +93,13 @@ export function createClient( }); // `?summary`: the large project with a plan shaped like a large real one's summary (CHI-1563). const summary = search.has("summary"); + // `?costs`: the Cost page's reads and selections answered by a large Snowflake project (cost-project.ts). + const costed = search.has("costs") ? costProject(mock) : mock; const sized = search.has("huge") - ? hugeProject(mock) + ? hugeProject(costed) : search.has("large") || summary - ? largeProject(mock, { summary }) - : mock; + ? largeProject(costed, { summary }) + : costed; const secrets = search.has("secrets") ? missingSecrets(sized, { sink: search.get("secrets") === "sink" }) : sized; diff --git a/ui/src/lib/api/mock/build-fixtures.ts b/ui/src/lib/api/mock/build-fixtures.ts index 7a918cacab..e3ee730092 100644 --- a/ui/src/lib/api/mock/build-fixtures.ts +++ b/ui/src/lib/api/mock/build-fixtures.ts @@ -57,7 +57,7 @@ export const NODE_SPECS: Record = { stg_inventory: { materialization: 'view', description: 'Stock counts from the warehouse system.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null']), c('on_hand', 'bigint', 'Units on hand', ['not_null'])] }, stg_products: { materialization: 'view', description: 'Products from the catalogue.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null', 'unique'])] }, dim_products: { materialization: 'table', description: 'One row per product.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null', 'unique']), c('category', 'varchar', 'Category', ['not_null'])] }, - fct_stock_levels: { materialization: 'incremental', description: 'Stock level of each product, by hour.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null']), c('on_hand', 'bigint', 'Units on hand')] }, + fct_stock_levels: { materialization: 'incremental · delete_insert', description: 'Stock level of each product, by hour.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null']), c('on_hand', 'bigint', 'Units on hand')] }, agg_stock_by_day: { materialization: 'table', description: 'Stock by day.', schema: 'ANALYTICS', columns: [c('day', 'date', 'Day', ['not_null'])] }, rpt_low_stock: { materialization: 'table', description: 'Products below their reorder point.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null'])] }, stg_shipping: { materialization: 'view', description: 'Shipments from the carrier feed.', schema: 'ANALYTICS', columns: [c('shipment_id', 'bigint', 'Shipment', ['not_null', 'unique'])] }, diff --git a/ui/src/lib/api/mock/build.ts b/ui/src/lib/api/mock/build.ts index 5ef5584c3a..e2ee71c759 100644 --- a/ui/src/lib/api/mock/build.ts +++ b/ui/src/lib/api/mock/build.ts @@ -280,7 +280,6 @@ export class MockBuild { attention.push({ kind: 'calendar_low', triggerId: t.id, triggerName: t.name, detail: t.warning! }); } - const cost = this.#hasCost(scope) ? recent.reduce((s, r) => s + (r.cost?.value ?? 0), 0) : null; const latest = runs.find((r) => r.endedAt); return this.#ctx.reply({ metrics: { @@ -298,9 +297,7 @@ export class MockBuild { active: recent.filter((r) => ['queued', 'launched', 'running', 'unresponsive'].includes(r.status)).length }, checks: countChecks(checks), - stale: { nodes: new Set([...changed, ...behind]).size, changed: changed.length, behind: behind.length, sources: staleSources.length }, - // The mock holds one day of costed runs; the server's baseline is the rolling average of the same window. - cost: cost === null ? null : { last24h: round(cost), baseline: round(cost * 0.78), baselineDays: 7, unit: 'credits' } + stale: { nodes: new Set([...changed, ...behind]).size, changed: changed.length, behind: behind.length, sources: staleSources.length } }, attention: withConditions(attention, this.#ctx.operate.conditionAcknowledgements(), now), attentionSnoozeSeconds: 86_400, diff --git a/ui/src/lib/api/mock/cost-project.ts b/ui/src/lib/api/mock/cost-project.ts new file mode 100644 index 0000000000..92945f2dbc --- /dev/null +++ b/ui/src/lib/api/mock/cost-project.ts @@ -0,0 +1,446 @@ +// A Snowflake project the size of a real one for the Cost page, turned on with `?mock&costs`: 2,281 +// models in nested folders, 30 jobs and builds by hand, over 60 days. Deterministic, so screenshots +// compare; the timeline follows the clock. Its selections resolve over its own models, and each job's +// cost is split over the models it builds by weight. Pure apart from wrapping the client it is given. + +import type { ApiClient } from '../client'; +import type { CostFact, CostSelection, CostSelectionQuery, CostSeriesGroup, NodeBuildCost, RunStatus, Scope, SelectionEvaluation, SelectionProblem, SelectionVocabulary, VocabularyEntry } from '../types'; +import { costPeriod, inCostGroup } from './cost-rows'; + +/** A folder as `path:` selects it: models under `sql/models/`, Python nodes under their own root. */ +const pathOf = (folder: string) => (folder.startsWith('python/') ? folder : `sql/models/${folder}`); + +/** Leaf folders, their model count and model name prefix: 2,281 models. */ +const FOLDERS: [string, number, string][] = [ + ['staging/orders', 90, 'stg'], + ['staging/customers', 80, 'stg'], + ['staging/payments', 70, 'stg'], + ['staging/events', 110, 'stg'], + ['staging/inventory', 70, 'stg'], + ['staging/partners/web', 60, 'stg'], + ['staging/partners/feeds', 50, 'stg'], + ['staging/support', 40, 'stg'], + ['staging/products', 70, 'stg'], + ['intermediate/orders', 90, 'int'], + ['intermediate/customers', 70, 'int'], + ['intermediate/inventory', 60, 'int'], + ['intermediate/sessions/web', 70, 'int'], + ['intermediate/sessions/app', 50, 'int'], + ['intermediate/pricing', 80, 'int'], + ['marts/core', 120, 'fct'], + ['marts/finance', 60, 'fct'], + ['marts/marketing', 80, 'dim'], + ['marts/product', 70, 'fct'], + ['marts/support', 50, 'dim'], + ['finance/ledger', 60, 'fin'], + ['finance/revenue', 60, 'fin'], + ['finance/fx', 40, 'fin'], + ['marketing/attribution', 80, 'mkt'], + ['marketing/campaigns', 60, 'mkt'], + ['marketing/audiences', 50, 'mkt'], + ['product/experiments', 70, 'prd'], + ['product/metrics', 100, 'prd'], + ['ml/features', 45, 'ml'], + ['ml/training', 25, 'ml'], + ['ml/scoring', 25, 'ml'], + ['reporting/daily', 80, 'rpt'], + ['reporting/exports', 60, 'rpt'], + ['snapshots', 56, 'snap'], + ['python/nodes/loaders', 18, 'py'], + ['python/nodes/checks', 12, 'py'] +]; +const ENTITIES = ['orders', 'order_lines', 'customers', 'sessions', 'events', 'payments', 'refunds', 'invoices', 'products', 'inventory', 'shipments', 'returns', 'campaigns', 'clicks', 'impressions', 'subscriptions', 'accounts', 'users', 'devices', 'pageviews', 'carts', 'promotions', 'suppliers', 'stores', 'warehouses', 'forecasts', 'features', 'experiments', 'ledger', 'fx_rates', 'tickets', 'reviews']; +const SUFFIXES = ['', '_daily', '_hourly', '_enriched', '_latest', '_history', '_by_region', '_by_channel', '_scd', '_rollup', '_v2', '_agg', '_dedup', '_flat', '_wide', '_weekly']; + +/** The job key runs started by hand or from the CLI are kept under here; they have no job. */ +const MANUAL = ''; + +/** Job, runs a day (fractions run every few days), credits a run, warehouse size, folders it builds. */ +const JOBS: [string, number, number, string, string[]][] = [ + ['nightly_full_refresh', 1, 96, 'Large', ['staging', 'intermediate', 'marts', 'finance', 'marketing', 'product', 'reporting']], + ['events_hourly', 24, 2.4, 'Medium', ['staging/events', 'intermediate/sessions']], + ['sessions_hourly', 24, 1.6, 'Medium', ['intermediate/sessions', 'marts/product']], + ['orders_15min', 96, 0.11, 'X-Small', ['staging/orders']], + ['finance_close', 1, 18.5, 'Medium', ['finance']], + ['ml_features_daily', 1, 24, 'Large', ['ml/features', 'ml/scoring']], + ['ml_training_weekly', 1 / 7, 140, 'Large', ['ml/training']], + ['marketing_attribution', 2, 6.2, 'Medium', ['marketing/attribution', 'marts/marketing']], + ['product_metrics', 4, 2.1, 'Small', ['product/metrics']], + ['reporting_refresh', 6, 0.9, 'Small', ['reporting/daily']], + ['snapshots_daily', 1, 4.4, 'Small', ['snapshots']], + ['inventory_hourly', 24, 0.32, 'X-Small', ['staging/inventory', 'intermediate/inventory']], + ['payments_hourly', 24, 0.28, 'X-Small', ['staging/payments', 'finance/ledger']], + ['customers_daily', 1, 3.6, 'Small', ['marts/core', 'intermediate/customers']], + ['campaigns_daily', 1, 2.9, 'Small', ['marketing/campaigns', 'marketing/audiences']], + ['exports_daily', 1, 1.4, 'X-Small', ['reporting/exports']], + ['fx_rates_hourly', 24, 0.04, 'X-Small', ['finance/fx']], + ['partner_loaders', 12, 0.12, 'X-Small', ['python/nodes/loaders', 'staging/partners/feeds']], + ['shipments_4h', 6, 0.7, 'Small', ['staging/orders', 'intermediate/orders']], + ['returns_daily', 1, 1.1, 'X-Small', ['intermediate/orders', 'marts/core']], + ['experiments_daily', 1, 3.3, 'Small', ['product/experiments']], + ['subscriptions_daily', 1, 2.2, 'Small', ['marts/finance', 'finance/revenue']], + ['devices_daily', 1, 0.8, 'X-Small', ['staging/events']], + ['tickets_hourly', 24, 0.05, 'X-Small', ['staging/support', 'marts/support']], + ['reviews_daily', 1, 0.4, 'X-Small', ['staging/products']], + ['ledger_backfill', 1 / 10, 58, 'Large', ['finance/ledger']], + ['marts_weekly_rebuild', 1 / 7, 72, 'Large', ['marts', 'intermediate']], + ['forecasts_daily', 1, 7.5, 'Medium', ['ml/scoring', 'finance/revenue']], + ['suppliers_weekly', 1 / 7, 3.1, 'Small', ['staging/partners']], + ['data_quality', 4, 0.6, 'Small', ['python/nodes/checks', 'marts/core']] +]; +/** What runs started by hand or from the CLI built. */ +const MANUAL_FOLDERS = ['marts/core', 'intermediate/pricing']; +/** Credits an hour by size, for warehouse time. */ +const RATE: Record = { 'X-Small': 1, Small: 2, Medium: 4, Large: 8 }; + + +function prng(seed: number) { + return () => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +type Model = { key: string; folder: string; weight: number; queries: number; bytes: number; rising: boolean }; +type Run = { id: string; job: string | null; at: number; status: RunStatus; credits: number; seconds: number }; +type Job = { key: string; size: string; models: Model[]; weight: number }; + +let world: { models: Model[]; jobs: Map; runs: Run[]; hour: number } | null = null; + +const under = (folder: string, prefixes: string[]) => prefixes.some((p) => folder === p || folder.startsWith(`${p}/`)); + +function build(now: number) { + const hour = Math.floor(now / 3_600_000); + if (world?.hour === hour) return world; + const rand = prng(1650); + const models: Model[] = []; + const used = new Set(); + for (const [folder, count, prefix] of FOLDERS) { + for (let i = 0; i < count; i++) { + let key = ''; + for (let n = 0; !key || used.has(key); n++) key = `${prefix}_${ENTITIES[Math.floor(rand() * ENTITIES.length)]}${SUFFIXES[Math.floor(rand() * SUFFIXES.length)]}${n > 2 ? `_${n}` : ''}`; + used.add(key); + // A few models take most of a job's time. + const weight = rand() ** 10 * 600 + rand(); + models.push({ key, folder, weight, queries: 1 + Math.floor(rand() * 4), bytes: weight * 2e9 * (0.5 + rand()), rising: rand() < 0.04 }); + } + } + const jobs = new Map(); + const addJob = (key: string, size: string, folders: string[]) => { + const mine = models.filter((m) => under(m.folder, folders)); + jobs.set(key, { key, size, models: mine, weight: mine.reduce((t, m) => t + m.weight, 0) }); + }; + for (const [job, , , size, folders] of JOBS) addJob(job, size, folders); + addJob(MANUAL, 'Medium', MANUAL_FOLDERS); + + const runs: Run[] = []; + const start = (hour - 60 * 24) * 3_600_000; + const id = (at: number, salt: number) => ((Math.floor(at / 1000) * salt) >>> 0).toString(16).padStart(8, '0'); + for (const [job, perDay, credits, size] of JOBS) { + const every = 86_400_000 / perDay; + for (let at = start + rand() * every; at < now; at += every) { + const noisy = credits * (0.7 + rand() * 0.6) * (rand() < 0.01 ? 5 + rand() * 4 : 1) * (at > now - 9 * 86_400_000 && job === 'events_hourly' ? 1.45 : 1); + const roll = rand(); + const status: RunStatus = now - at < every && now - at < 1_200_000 ? 'running' : roll < 0.03 ? 'failed' : roll < 0.06 ? 'partial' : 'success'; + const spent = status === 'failed' ? noisy * 0.3 : noisy; + runs.push({ id: id(at, 2654435761), job, at, status, credits: spent, seconds: (spent / RATE[size]) * 3600 }); + } + } + // Runs started by hand or from the CLI: a few big backfills. + for (let i = 0; i < 40; i++) { + const at = start + rand() * (now - start - 3_600_000); + const spent = rand() < 0.2 ? 30 + rand() * 60 : 0.5 + rand() * 6; + runs.push({ id: id(at, 2246822519), job: null, at, status: 'success', credits: spent, seconds: (spent / 4) * 3600 }); + } + world = { models, jobs, runs: runs.sort((a, b) => b.at - a.at), hour }; + return world; +} + + +type Meta = { key: string; folder: string; path: string; tags: string[]; layer: number; entity: string }; + +const ENTITY = /(order_lines|orders|customers|sessions|events|payments|refunds|invoices|products|inventory|shipments|returns|campaigns|clicks|impressions|subscriptions|accounts|users|devices|pageviews|carts|promotions|suppliers|stores|warehouses|forecasts|features|experiments|ledger|fx_rates|tickets|reviews)/; +const LAYER: Record = { staging: 0, python: 0, intermediate: 1, snapshots: 3 }; + + +function tagsOf(key: string, folder: string): string[] { + const tags: string[] = []; + if (folder.startsWith('finance') || folder === 'marts/finance' || /ledger|invoices|payments|refunds/.test(key)) tags.push('finance'); + if (/customers|users|accounts|devices/.test(key)) tags.push('pii'); + if (key.includes('_hourly')) tags.push('hourly'); + if (folder.startsWith('ml')) tags.push('ml'); + if (folder.startsWith('reporting') || folder.startsWith('marts')) tags.push('reporting'); + return tags; +} + +let held: { at: number; metas: Meta[]; byKey: Map; jobs: Map } | null = null; +function catalog() { + const hour = Math.floor(Date.now() / 3_600_000); + if (held?.at === hour) return held; + const metas = build(Date.now()).models.map((m) => ({ key: m.key, folder: m.folder, path: pathOf(m.folder), tags: tagsOf(m.key, m.folder), layer: LAYER[m.folder.split('/')[0]] ?? 2, entity: ENTITY.exec(m.key)?.[1] ?? '' })); + held = { at: hour, metas, byKey: new Map(metas.map((m) => [m.key, m])), jobs: new Map([...build(Date.now()).jobs.values()].map((j) => [j.key, j.models.map((m) => m.key)])) }; + return held; +} + +const glob = (pattern: string) => new RegExp(`^${pattern.replace(/[.^$()|\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')}$`); + +/** Mock lineage: a model's upstream is the earlier layers' models of the same entity; downstream the later ones. */ +function expand(keys: Set, up: boolean, down: boolean): Set { + if (!up && !down) return keys; + const { metas, byKey } = catalog(); + const out = new Set(keys); + for (const k of keys) { + const m = byKey.get(k); + if (!m?.entity) continue; + for (const o of metas) if (o.entity === m.entity && ((up && o.layer < m.layer) || (down && o.layer > m.layer))) out.add(o.key); + } + return out; +} + +function matchPart(raw: string): Set | null { + const { metas, byKey, jobs } = catalog(); + const up = raw.startsWith('+'); + const down = raw.length > 1 && raw.endsWith('+'); + const core = raw.replace(/^\+/, '').replace(/\+$/, ''); + const colon = core.indexOf(':'); + const type = colon > 0 ? core.slice(0, colon) : null; + const value = colon > 0 ? core.slice(colon + 1) : core; + let hits: Set; + if (type === 'job') hits = new Set(jobs.get(value) ?? []); + else if (type === 'path' || (type === null && value.includes('/'))) { + const p = value.replace(/\/$/, ''); + hits = new Set(metas.filter((m) => m.path === p || m.path.startsWith(`${p}/`)).map((m) => m.key)); + } else if (type === 'tag') hits = new Set(metas.filter((m) => m.tags.some((t) => glob(value).test(t))).map((m) => m.key)); + else if (type === 'kind') hits = value === 'model' || value === 'table' ? new Set(metas.map((m) => m.key)) : new Set(); + else if (type === null) hits = /[*?]/.test(value) ? new Set(metas.filter((m) => glob(value).test(m.key)).map((m) => m.key)) : byKey.has(value) ? new Set([value]) : new Set(); + else return null; + if (!hits.size) return null; + return expand(hits, up, down); +} + +function suggest(raw: string): string[] { + const { metas, jobs } = catalog(); + const core = raw.replace(/^\+/, '').replace(/\+$/, ''); + const colon = core.indexOf(':'); + const type = colon > 0 ? core.slice(0, colon) : null; + const value = (colon > 0 ? core.slice(colon + 1) : core).toLowerCase(); + const pool = type === 'job' ? [...jobs.keys()].filter((j) => j !== MANUAL) : type === 'tag' ? [...new Set(metas.flatMap((m) => m.tags))] : type === null ? metas.map((m) => m.key) : []; + const close = pool.filter((v) => v.toLowerCase().startsWith(value.slice(0, 3))).slice(0, 1); + return close.map((v) => raw.replace(core, `${type ? `${type}:` : ''}${v}`)); +} + +/** The models a selection selects, as `model:` keys, or why `sqb` would refuse it. */ +function evaluateCostSelection(select: string, exclude: string): SelectionEvaluation { + const resolve = (field: 'select' | 'exclude', text: string): Set | SelectionProblem => { + const chosen = new Set(); + for (const match of text.matchAll(/\S+/g)) { + const token = match[0]; + let hits = null as Set | null; + for (const [index, part] of token.split(',').entries()) { + const found = matchPart(part); + if (!found) { + const bare = part.replace(/^\+/, '').replace(/\+$/, ''); + const colon = bare.indexOf(':'); + const refused = { part: index, type: colon > 0 ? bare.slice(0, colon) : null, value: colon > 0 ? bare.slice(colon + 1) : bare }; + const suggestions = suggest(part).map((s) => token.replace(part, s)); + return { code: 'S007', message: `unknown selector name '${part}'`, help: null, location: { field, token, start: match.index!, end: match.index! + token.length }, suggestions, refused }; + } + const prev: Set | null = hits; + hits = prev ? new Set([...prev].filter((k) => found.has(k))) : found; + } + for (const k of hits ?? []) chosen.add(k); + } + return chosen; + }; + const reply = (keys: string[], error: SelectionProblem | null): SelectionEvaluation => ({ snapshotId: 'mock-snapshot', count: keys.length, keys, nextOffset: null, error }); + const selected = select.trim() ? resolve('select', select) : new Set(catalog().metas.map((m) => m.key)); + if (!(selected instanceof Set)) return reply([], selected); + const excluded = exclude.trim() ? resolve('exclude', exclude) : new Set(); + if (!(excluded instanceof Set)) return reply([], excluded); + const keys = [...selected].filter((k) => !excluded.has(k)).sort(); + if (!keys.length) return reply([], { code: null, message: 'the selectors match no nodes in the current publication', help: null, location: null, suggestions: [], refused: null }); + return reply(keys.map((k) => `model:${k}`), null); +} + +/** Tags, folders and jobs of the Cost mock, for the selection field's suggestions. */ +function costVocabulary(): SelectionVocabulary { + const { metas, jobs } = catalog(); + const counted = (values: string[]): VocabularyEntry[] => { + const counts = new Map(); + for (const v of values) counts.set(v, (counts.get(v) ?? 0) + 1); + return [...counts].sort(([a], [b]) => a.localeCompare(b)).map(([value, count]) => ({ value, count })); + }; + const folders = (path: string) => path.split('/').map((_, i, parts) => parts.slice(0, i + 1).join('/')); + return { + snapshotId: 'mock-snapshot', + tags: counted(metas.flatMap((m) => m.tags)), + paths: counted(metas.flatMap((m) => folders(m.path))), + jobs: [...jobs].filter(([j]) => j !== MANUAL).map(([value, keys]) => ({ value, count: keys.length })).sort((a, b) => a.value.localeCompare(b.value)), + sources: [], + seeds: [], + kinds: [{ value: 'model', count: metas.length }] + }; +} + + +/** Each job's share of a model's cost: the model's weight among the job's models. */ +function shares(): Map { + const out = new Map(); + for (const job of build(Date.now()).jobs.values()) out.set(job.key, job.models.map((model) => ({ model, share: model.weight / job.weight }))); + return out; +} + +const DAY = 86_400_000; +/** The project's `usd_per_credit`. */ +const PRICE = 3; + +/** The last reads, by query and hour, so batches of series don't build them again. */ +const reads = new Map; jobTotal: Map }>(); + +function cached(query: CostSelectionQuery) { + const key = `${Math.floor(Date.now() / 3_600_000)}\u0000${query.days}\u0000${query.select}\u0000${query.exclude}`; + let hit = reads.get(key); + if (!hit) { + const read = costSelection(query); + const byJob = new Map(); + const jobTotal = new Map(); + for (const f of read.facts) { + (byJob.get(f.job) ?? byJob.set(f.job, []).get(f.job)!).push(f); + jobTotal.set(f.job, (jobTotal.get(f.job) ?? 0) + f.credits); + } + if (reads.size > 20) reads.clear(); + reads.set(key, (hit = { read, byJob, jobTotal })); + } + return hit; +} + +function costSelection(query: CostSelectionQuery): CostSelection { + const now = Date.now(); + const period = costPeriod(query.days, now); + const evaluated = query.select.trim() || query.exclude.trim() ? evaluateCostSelection(query.select, query.exclude) : null; + const chosen = evaluated && new Set(evaluated.keys); + const { runs } = build(now); + const byJob = new Map(); + for (const r of runs) { + if (r.at < period.previous) continue; + const key = r.job ?? MANUAL; + const j = byJob.get(key) ?? byJob.set(key, { credits: 0, previous: 0, seconds: 0, runs: 0, daily: Array(query.days).fill(0), pending: 0 }).get(key)!; + const day = period.day(r.at); + if (day === null) j.previous += r.credits; + else { + j.credits += r.credits; + j.seconds += r.seconds; + j.runs += 1; + j.daily[day] += r.credits; + if (r.status === 'running' || r.status === 'partial') j.pending += 1; + } + } + const facts: CostFact[] = []; + const folderDaily = new Map(); + const jobDaily = new Map(); + let runCount = 0; + let incomplete = 0; + for (const [job, parts] of shares()) { + const j = byJob.get(job); + if (!j) continue; + let any = false; + for (const { model, share } of parts) { + const key = `model:${model.key}`; + if (chosen && !chosen.has(key)) continue; + any = true; + const credits = j.credits * share; + facts.push({ job: job || null, nodeKey: key, folder: model.folder, credits, previousCredits: j.previous * share * (model.rising ? 0.45 : 1), usd: credits * PRICE, previousUsd: j.previous * share * (model.rising ? 0.45 : 1) * PRICE, seconds: j.seconds * share, runs: j.runs, queries: model.queries * j.runs, bytesScanned: Math.round(model.bytes * j.runs) }); + const top = model.folder.split('/')[0]; + const f = folderDaily.get(top) ?? folderDaily.set(top, Array(query.days).fill(0)).get(top)!; + const d = jobDaily.get(job || null) ?? jobDaily.set(job || null, Array(query.days).fill(0)).get(job || null)!; + j.daily.forEach((v, i) => { + f[i] += v * share; + d[i] += v * share; + }); + } + if (any) { + runCount += j.runs; + incomplete += j.pending; + } + } + facts.sort((a, b) => b.credits - a.credits); + const sum = (pick: (f: CostFact) => number) => facts.reduce((t, f) => t + pick(f), 0); + const error: SelectionProblem | null = evaluated?.error ?? null; + return { + snapshotId: 'mock-snapshot', + since: new Date(period.first).toISOString(), + days: query.days, + dates: period.dates, + error, + price: error || !facts.length ? null : { usdPerCredit: PRICE, source: 'config' }, + credits: error ? 0 : sum((f) => f.credits), + previousCredits: error ? 0 : sum((f) => f.previousCredits), + usd: error ? null : sum((f) => f.credits) * PRICE, + previousUsd: error ? null : sum((f) => f.previousCredits) * PRICE, + runs: error ? 0 : runCount, + incompleteRuns: error ? 0 : incomplete, + queries: error ? 0 : sum((f) => f.queries), + seconds: error ? 0 : sum((f) => f.seconds), + bytesScanned: error ? 0 : sum((f) => f.bytesScanned), + facts: error ? [] : facts, + jobDaily: error ? [] : [...jobDaily].map(([key, credits]) => ({ key, credits })), + folderDaily: error ? [] : [...folderDaily].map(([key, credits]) => ({ key, credits })) + }; +} + +function costSeries(query: CostSelectionQuery, groups: CostSeriesGroup[]): number[][] { + const { read, byJob, jobTotal } = cached(query); + const daily = new Map(read.jobDaily.map((s) => [s.key, s.credits])); + return groups.map((g) => { + const out = Array(query.days).fill(0); + const facts = g.manual ? (byJob.get(null) ?? []) : g.job !== undefined ? (byJob.get(g.job) ?? []) : read.facts; + for (const f of facts) { + if (!inCostGroup(g, f)) continue; + const total = jobTotal.get(f.job) || 1; + (daily.get(f.job) ?? []).forEach((v, i) => (out[i] += (v * f.credits) / total)); + } + return out; + }); +} + +/** A model's cost in each of its jobs' builds over the period, newest first. */ +function nodeCosts(nodeKey: string, days: number): NodeBuildCost[] { + const now = Date.now(); + const name = nodeKey.slice(nodeKey.indexOf(':') + 1); + const since = now - days * DAY; + const mine = new Map(); + for (const [job, parts] of shares()) for (const p of parts) if (p.model.key === name) mine.set(job, p.share); + return build(now) + .runs.filter((r) => r.at >= since && mine.has(r.job ?? MANUAL)) + .map((r) => { + const share = mine.get(r.job ?? MANUAL)!; + return { buildRunId: `build-${r.id}`, runId: r.job ? r.id : null, startedAt: new Date(r.at).toISOString(), status: r.status === 'running' ? 'pending' : 'complete', credits: r.credits * share, usd: r.credits * share * PRICE, priceSource: 'config', seconds: r.seconds * share, queryCount: 2 }; + }); +} + +/** The client with the Cost page's reads, and the selections they take, answered by the large cost project. */ +export function costProject(client: ApiClient): ApiClient { + // Answered after a delay, worked out then, as a server would: not in the task that asked. + const reply = (make: () => T) => new Promise((resolve) => setTimeout(() => resolve(make()), 60)); + return new Proxy(client, { + get(target, prop, receiver) { + if (prop === 'readCostSelection') return (_scope: Scope, query: CostSelectionQuery) => reply(() => cached(query).read); + if (prop === 'readCostSeries') return (_scope: Scope, query: CostSelectionQuery, groups: CostSeriesGroup[]) => reply(() => costSeries(query, groups)); + if (prop === 'listNodeCosts') return (_scope: Scope, nodeKey: string, days: number) => reply(() => nodeCosts(nodeKey, days)); + if (prop === 'evaluateSelection') + return (_scope: Scope, request: { select: string; exclude: string; offset?: number; limit?: number }) => { + return reply(() => { + const all = evaluateCostSelection(request.select, request.exclude); + const offset = request.offset ?? 0; + const limit = request.limit ?? 1000; + return { ...all, keys: all.keys.slice(offset, offset + limit), nextOffset: offset + limit < all.keys.length ? offset + limit : null }; + }); + }; + if (prop === 'selectionVocabulary') return () => reply(() => costVocabulary()); + const value = Reflect.get(target, prop, receiver); + return typeof value === 'function' ? value.bind(target) : value; + } + }); +} diff --git a/ui/src/lib/api/mock/cost-rows.test.ts b/ui/src/lib/api/mock/cost-rows.test.ts new file mode 100644 index 0000000000..610a7501c6 --- /dev/null +++ b/ui/src/lib/api/mock/cost-rows.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; +import { costFolder, costSelectionOf, costSeriesOf, type CostRowIn } from './cost-rows'; + +const DAY = 86_400_000; +const now = Date.parse('2026-11-23T12:00:00Z'); +const row = (runId: string, job: string | null, nodeKey: string, daysAgo: number, credits: number, usd: number | null = credits * 3): CostRowIn => ({ + runId, + job, + nodeKey, + folder: costFolder(`sql/models/${nodeKey === 'orders' ? 'staging/' : ''}${nodeKey}.sql`), + startedAt: now - daysAgo * DAY, + pending: false, + credits, + usd, + seconds: 60, + queries: 2, + bytes: 10 +}); + +describe('the mock’s cost of a selection', () => { + it('splits job by node over whole days ending today, with the period before', () => { + const read = costSelectionOf([row('a', 'daily', 'orders', 0, 0.1), row('a', 'daily', 'customers', 0, 0.05), row('b', null, 'orders', 1, 0.04), row('c', 'daily', 'orders', 9, 0.2)], 7, now); + expect(read.dates).toHaveLength(7); + expect(read.dates.at(-1)).toBe('2026-11-23'); + expect(read.facts.map((f) => [f.job, f.nodeKey, f.folder, f.credits, f.previousCredits])).toEqual([ + ['daily', 'orders', 'staging', 0.1, 0.2], + ['daily', 'customers', '', 0.05, 0], + [null, 'orders', 'staging', 0.04, 0] + ]); + expect([read.runs, read.price?.source, read.price?.usdPerCredit]).toEqual([2, 'config', 3]); + expect(read.jobDaily.find((s) => s.key === null)?.credits[5]).toBe(0.04); + }); + + it('has no price once any row has none', () => { + expect(costSelectionOf([row('a', 'daily', 'orders', 0, 0.1, null)], 7, now).price).toBeNull(); + }); + + it('gives each group its credits per day', () => { + const rows = [row('a', 'daily', 'orders', 0, 0.1), row('b', null, 'orders', 0, 0.04)]; + expect(costSeriesOf(rows, 7, now, [{ job: 'daily' }, { manual: true }, { folder: 'staging' }]).map((s) => s[6])).toEqual([0.1, 0.04, 0.14]); + }); +}); diff --git a/ui/src/lib/api/mock/cost-rows.ts b/ui/src/lib/api/mock/cost-rows.ts new file mode 100644 index 0000000000..fd86e70762 --- /dev/null +++ b/ui/src/lib/api/mock/cost-rows.ts @@ -0,0 +1,109 @@ +// A selection's cost read from cost rows, as the server sums them: whole UTC days ending today, the +// period before, job by node, and daily series by job, top-level folder or any group. Pure. + +import type { CostFact, CostSelection, CostSeriesGroup, SelectionProblem } from '../types'; + +/** One selected node's cost in one build. */ +export type CostRowIn = { runId: string; job: string | null; nodeKey: string; folder: string; startedAt: number; pending: boolean; credits: number; usd: number | null; seconds: number; queries: number; bytes: number }; + +const DAY = 86_400_000; + +/** The period's first day (ms), its dates, and the day index of a time (null before it). */ +export function costPeriod(days: number, now: number) { + const first = Math.floor(now / DAY) * DAY - (days - 1) * DAY; + const dates = Array.from({ length: days }, (_, i) => new Date(first + i * DAY).toISOString().slice(0, 10)); + const day = (at: number) => (at < first ? null : Math.min(days - 1, Math.floor((at - first) / DAY))); + return { first, previous: first - days * DAY, dates, day }; +} + +/** A node's folder from its published path: without `sql/models/` (or `models/`), other roots as published. */ +export function costFolder(path: string | undefined): string { + if (!path) return 'other'; + const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''; + return dir.replace(/^(sql\/)?models(\/|$)/, ''); +} + +const addUsd = (a: number | null, b: number | null) => (a === null || b === null ? null : a + b); + +export function costSelectionOf(rows: CostRowIn[], days: number, now: number, error: SelectionProblem | null = null): CostSelection { + const period = costPeriod(days, now); + const facts = new Map }>(); + const jobDaily = new Map(); + const folderDaily = new Map(); + const runs = new Set(); + const pending = new Set(); + let usd: number | null = 0; + let previousUsd: number | null = 0; + for (const r of rows) { + if (r.startedAt < period.previous) continue; + const id = `${r.job ?? ''}\u0000${r.nodeKey}`; + let f = facts.get(id); + if (!f) facts.set(id, (f = { job: r.job, nodeKey: r.nodeKey, folder: r.folder, credits: 0, previousCredits: 0, usd: 0, previousUsd: 0, seconds: 0, runs: 0, queries: 0, bytesScanned: 0, runSet: new Set() })); + const day = period.day(r.startedAt); + if (day === null) { + f.previousCredits += r.credits; + f.previousUsd = addUsd(f.previousUsd, r.usd); + previousUsd = addUsd(previousUsd, r.usd); + continue; + } + f.credits += r.credits; + f.usd = addUsd(f.usd, r.usd); + f.seconds += r.seconds; + f.runSet.add(r.runId); + f.queries += r.queries; + f.bytesScanned += r.bytes; + usd = addUsd(usd, r.usd); + runs.add(r.runId); + if (r.pending) pending.add(r.runId); + const job = jobDaily.get(r.job) ?? jobDaily.set(r.job, Array(days).fill(0)).get(r.job)!; + job[day] += r.credits; + const top = r.folder.split('/')[0]; + const folder = folderDaily.get(top) ?? folderDaily.set(top, Array(days).fill(0)).get(top)!; + folder[day] += r.credits; + } + const list: CostFact[] = [...facts.values()].map(({ runSet, ...f }) => ({ ...f, runs: runSet.size })).sort((a, b) => b.credits - a.credits); + const sum = (pick: (f: CostFact) => number) => list.reduce((t, f) => t + pick(f), 0); + const credits = sum((f) => f.credits); + const priced = runs.size ? usd : null; + return { + snapshotId: 'mock-snapshot', + since: new Date(period.first).toISOString(), + days, + dates: period.dates, + error, + price: priced !== null && credits > 0 ? { usdPerCredit: priced / credits, source: 'config' } : null, + credits, + previousCredits: sum((f) => f.previousCredits), + usd: priced, + previousUsd, + runs: runs.size, + incompleteRuns: pending.size, + queries: sum((f) => f.queries), + seconds: sum((f) => f.seconds), + bytesScanned: sum((f) => f.bytesScanned), + facts: error ? [] : list, + jobDaily: [...jobDaily].map(([key, credits]) => ({ key, credits })), + folderDaily: [...folderDaily].map(([key, credits]) => ({ key, credits })) + }; +} + +/** Whether a row is in a group: every field the group gives matches. */ +export function inCostGroup(g: CostSeriesGroup, r: { job: string | null; folder: string; nodeKey: string }): boolean { + const job = g.manual ? r.job === null : g.job === undefined || r.job === g.job; + const folder = !g.folder || r.folder === g.folder || r.folder.startsWith(`${g.folder}/`); + return job && folder && (g.nodeKey === undefined || r.nodeKey === g.nodeKey); +} + +/** Each group's credits per day of the period. */ +export function costSeriesOf(rows: CostRowIn[], days: number, now: number, groups: CostSeriesGroup[]): number[][] { + const period = costPeriod(days, now); + const out = groups.map(() => Array(days).fill(0)); + for (const r of rows) { + const day = period.day(r.startedAt); + if (day === null) continue; + groups.forEach((g, i) => { + if (inCostGroup(g, r)) out[i][day] += r.credits; + }); + } + return out; +} diff --git a/ui/src/lib/api/mock/discovered.ts b/ui/src/lib/api/mock/discovered.ts new file mode 100644 index 0000000000..527a44b894 --- /dev/null +++ b/ui/src/lib/api/mock/discovered.ts @@ -0,0 +1,112 @@ +// Two discovered sets, each feeding a `for_each` asset whose +// items become one node per step, as `asset:[]`. +// One set is fresh; the other's newest fetch failed, so its nodes keep the last good items. Pure. + +import type { SnapshotNode } from '../types'; +import type { DiscoveredSet } from '../types/build'; + +const MIN = 60_000; +const HOUR = 60 * MIN; + +type Step = [step: string, upstream: string[], args?: Record]; + +/** The EU forecast plan: 36 steps, as a model release lists them. */ +const EU: Step[] = [ + ['id_mappings', []], + ['seasonal_data', ['id_mappings']], + ['regional_seasonal_data', ['id_mappings']], + ['regional_scores', ['regional_seasonal_data']], + ['regional_inputs', ['regional_scores', 'seasonal_data']], + ['cleaned_sales', ['id_mappings']], + ['hierarchy_data', ['id_mappings']], + ['hierarchy_category', ['hierarchy_data']], + ['hierarchy_supplier', ['hierarchy_data']], + ['hierarchy_product', ['hierarchy_category', 'hierarchy_supplier']], + ['popularity_scores', ['seasonal_data', 'cleaned_sales']], + ['gbm_inputs', ['regional_inputs', 'popularity_scores']], + ['gbm_chain_d1', ['gbm_inputs'], { depth: '1' }], + ['gbm_chain_d3', ['gbm_inputs'], { depth: '3' }], + ['gbm_gru', ['gbm_chain_d1', 'gbm_chain_d3']], + ['itemgraph', ['hierarchy_product', 'regional_inputs']], + ['itemloop', ['itemgraph']], + ['itemcluster', ['itemgraph', 'popularity_scores']], + ['transformer_inputs', ['regional_inputs', 'hierarchy_product']], + ['transformer_predictions', ['transformer_inputs']], + ['topk_predict_base', ['gbm_gru', 'itemloop'], { k: '5' }], + ['itemrnnboost', ['itemcluster', 'cleaned_sales']], + ['itemcorr', ['itemloop', 'itemcluster']], + ['model_meta_features', ['gbm_gru', 'itemrnnboost', 'itemcorr', 'transformer_predictions']], + ['topk_predictions', ['topk_predict_base', 'model_meta_features'], { k: '5' }], + ['blender_inputs', ['model_meta_features']], + ['blender_training', ['blender_inputs', 'topk_predictions'], { gpu: 'true' }], + ['blender_predictions', ['blender_training']], + ['store_calibration', ['blender_predictions']], + ['channel_blend', ['store_calibration']], + ['confidence_bands', ['store_calibration']], + ['forecast_export', ['channel_blend', 'confidence_bands']], + ['forecast_qa', ['forecast_export']], + ['feature_importance', ['blender_training']], + ['drift_report', ['model_meta_features']], + ['forecast_publish', ['forecast_qa']] +]; + +/** The US plan: a few steps, whose newest fetch failed. */ +const US: Step[] = [ + ['id_mappings', []], + ['seasonal_data', ['id_mappings']], + ['gbm_chain_d1', ['seasonal_data'], { depth: '1' }], + ['itemloop', ['seasonal_data']], + ['blender_training', ['gbm_chain_d1', 'itemloop'], { gpu: 'true' }], + ['forecast_publish', ['blender_training']] +]; + +type Plan = { set: string; asset: string; job: string; region: string; steps: Step[] }; + +export const DISCOVERED_PLANS: Plan[] = [ + { set: 'forecast_eu_plan', asset: 'forecast_eu', job: 'forecast_v2_eu_job', region: 'EU', steps: EU }, + { set: 'forecast_us_plan', asset: 'forecast_us', job: 'forecast_v2_us_job', region: 'US', steps: US } +]; + +const stepKey = (asset: string, step: string) => `asset:${asset}[${step}]`; +const pathOf = (asset: string) => `src/forecast_pipelines/definitions/models/regions/${asset.split('_')[1]}/discovered_model_steps.py`; + +/** Every step node, in the snapshot's shape. */ +export const DISCOVERED_NODES: SnapshotNode[] = DISCOVERED_PLANS.flatMap((p) => { + const group = `forecast_${p.region.toLowerCase()}`; + return p.steps.map(([step, upstream]): SnapshotNode => ({ key: stepKey(p.asset, step), kind: 'asset', group, tags: ['forecast', group, 'discovered'], path: pathOf(p.asset), cursor: null, upstream: upstream.map((u) => stepKey(p.asset, u)) })); +}); + +/** The sets as `readDiscovered` would report them, with the nodes each item became. */ +export function discoveredSets(now: number): DiscoveredSet[] { + const at = (ms: number) => new Date(now - ms).toISOString(); + const [eu, us] = DISCOVERED_PLANS; + const nodes = (p: Plan) => p.steps.map(([step, , args]) => ({ key: stepKey(p.asset, step), asset: p.asset, step, args: { step, region: p.region, ...args } })); + return [ + { + name: eu.set, + status: 'ok', + items: eu.steps.length, + fetchedAt: at(2 * HOUR + 14 * MIN), + lastGoodAt: at(2 * HOUR + 14 * MIN), + digest: 'sha256:3be1c0a94f27d8e6b1a05c3f9e72d4a816c0b59e2f37a1d8c4e6b09f5a2d7c13', + error: null, + checkEverySeconds: 900, + tags: { release: 'f59ed676a9f8c41b2e07d3a5c96b8e14f2a7d0c3', plan_digest: '3be1c0a94f27', max_parallel: '4', region: 'EU' }, + assets: [eu.asset], + nodes: nodes(eu) + }, + { + name: us.set, + status: 'failed', + items: us.steps.length, + fetchedAt: at(11 * MIN), + lastGoodAt: at(2 * 24 * HOUR + 3 * HOUR), + digest: 'sha256:9d41e7b2c0a85f3e6d17b94c2a0e58f1d3b6c79a4e2f08d5b1c7a93e6f40d82b', + error: 'GET https://releases.example.com/us/latest/plan.json: 503 Service Unavailable', + checkEverySeconds: 900, + tags: { release: '7c2e19b04d6a3f85e1b97c0d2a4f6e38b5c1d907', plan_digest: '9d41e7b2c0a8', max_parallel: '2', region: 'US' }, + assets: [us.asset], + nodes: nodes(us) + } + ]; +} diff --git a/ui/src/lib/api/mock/mock-client.ts b/ui/src/lib/api/mock/mock-client.ts index c3d279dbdd..1952b42ecd 100644 --- a/ui/src/lib/api/mock/mock-client.ts +++ b/ui/src/lib/api/mock/mock-client.ts @@ -21,6 +21,7 @@ import type { BuiltInRole, Capability, CurrentUser, + DiscoveredSet, Job, JobDetail, JobLaunchOptions, @@ -43,6 +44,9 @@ import type { IgnoredAuditFailure, CostSummary, NodeBuildCost, + CostSelection, + CostSelectionQuery, + CostSeriesGroup, NodeState, NodeStates, RepublishResult, Scope, @@ -60,6 +64,7 @@ import { MockOperate } from './operate-store'; import type { PlatformApi } from '../platform-client'; import { MockPlatformApi } from './platform'; import { MockBuild } from './build'; +import { discoveredSets } from './discovered'; export type MockOptions = { role?: BuiltInRole; @@ -192,6 +197,10 @@ export class MockApiClient implements ApiClient { this.#location(args[0]); return this.#build.overview(args[0]); } + readDiscovered(_scope: Scope): Promise { + return this.#reply(discoveredSets(this.#createdAt)); + } + listCatalogNodes(...args: Parameters) { this.#location(args[0]); return this.#build.listCatalogNodes(...args); @@ -298,6 +307,16 @@ export class MockApiClient implements ApiClient { return this.#operate.getCostSummary(scope, days); } + async readCostSelection(scope: Scope, query: CostSelectionQuery): Promise { + this.#location(scope); + return this.#operate.readCostSelection(scope, query); + } + + async readCostSeries(scope: Scope, query: CostSelectionQuery, groups: CostSeriesGroup[]): Promise { + this.#location(scope); + return this.#operate.readCostSeries(scope, query, groups); + } + async listNodeCosts(scope: Scope, nodeKey: string, days: number): Promise { this.#location(scope); return this.#operate.listNodeCosts(scope, nodeKey, days); diff --git a/ui/src/lib/api/mock/operate-graph-selection.test.ts b/ui/src/lib/api/mock/operate-graph-selection.test.ts index 44607fcb82..c41a74c09f 100644 --- a/ui/src/lib/api/mock/operate-graph-selection.test.ts +++ b/ui/src/lib/api/mock/operate-graph-selection.test.ts @@ -22,8 +22,9 @@ describe('mock selection evaluation', () => { }); it('counts models of every materialization as one kind', () => { + // 4 plus 42 discovered steps (discovered.ts). expect(mockVocabulary().kinds).toEqual([ - { value: 'asset', count: 4 }, + { value: 'asset', count: 46 }, { value: 'loader', count: 2 }, { value: 'model', count: 31 }, { value: 'seed', count: 1 }, diff --git a/ui/src/lib/api/mock/operate-graph.ts b/ui/src/lib/api/mock/operate-graph.ts index 71fdf13522..3c82163a70 100644 --- a/ui/src/lib/api/mock/operate-graph.ts +++ b/ui/src/lib/api/mock/operate-graph.ts @@ -2,6 +2,7 @@ // resolves selectors against the real snapshot; this stands in for it. import type { NodeKind, SnapshotNode } from '../types'; +import { DISCOVERED_NODES } from './discovered'; import type { SelectionProblem, SelectionVocabulary, VocabularyEntry } from '../types/operate'; function node( @@ -72,7 +73,9 @@ export const SNAPSHOT_NODES: SnapshotNode[] = [ // A Python task that fails with a pandas KeyError traceback after printing a few thousand lines. node('score_customers_v2', 'asset', 'ml', ['dim_customers'], { path: 'models/ml/score_customers_v2.py' }), // A notebook runner that prints about 2 million lines (CHI-1597). - node('notebook_runner', 'asset', 'ml', ['fact_orders'], { path: 'models/ml/notebook_runner.py' }) + node('notebook_runner', 'asset', 'ml', ['fact_orders'], { path: 'models/ml/notebook_runner.py' }), + // Discovered steps of two forecast plans (discovered.ts). + ...DISCOVERED_NODES ]; const BY_KEY = new Map(SNAPSHOT_NODES.map((n) => [n.key, n])); @@ -197,7 +200,7 @@ function matchPart(part: string): Set | null { const jobKeys = type === 'job' ? new Set(jobNodesOf(value)) : null; const base = SNAPSHOT_NODES.filter((n) => jobKeys ? jobKeys.has(n.key) : - type === 'tag' ? n.tags.includes(value) : type === 'kind' ? selectorKind(n) === value : type === 'path' ? folderOf(n) === value || folderOf(n).startsWith(`${value}/`) : n.key === value + type === 'tag' ? n.tags.includes(value) : type === 'kind' ? selectorKind(n) === value : type === 'path' ? folderOf(n) === value.replace(/^sql\//, '') || folderOf(n).startsWith(`${value.replace(/^sql\//, '')}/`) : n.key === value ); if (!base.length) return null; const out = new Set(base.map((n) => n.key)); diff --git a/ui/src/lib/api/mock/operate-store.ts b/ui/src/lib/api/mock/operate-store.ts index 523217be45..483fbe7e34 100644 --- a/ui/src/lib/api/mock/operate-store.ts +++ b/ui/src/lib/api/mock/operate-store.ts @@ -52,6 +52,10 @@ import type { RunCostRow, CostSummary, NodeBuildCost, + CostSelection, + CostSelectionQuery, + CostSeriesGroup, + SelectionProblem, RunTabCounts, Scope, SnapshotNode, @@ -91,6 +95,7 @@ import { type TriggerDef } from './operate'; import { SCHEDULER } from './principals'; +import { costFolder, costPeriod, costSelectionOf, costSeriesOf, type CostRowIn } from './cost-rows'; import { ancestors, evaluateMockSelection, isWritable, mockVocabulary, resolveSelection, SNAPSHOT_NODES, snapshotNode, sortTopologically, edgesWithin, writeSetOf } from './operate-graph'; import { commandOf, @@ -416,6 +421,7 @@ export class MockOperate { since: new Date(since).toISOString(), credits: total.credits, usd: total.runs.size ? total.usd : null, + priceSource: total.runs.size && total.usd !== null ? 'config' : null, runs: total.runs.size, incompleteRuns, byJob: ranked(byJob), @@ -424,6 +430,37 @@ export class MockOperate { }); } + /** The cost rows of the selected nodes over twice `days`, for the cost reads of a selection. */ + #selectionRows(scope: Scope, query: CostSelectionQuery): { rows: CostRowIn[]; error: SelectionProblem | null } { + const now = Date.now(); + const { previous } = costPeriod(query.days, now); + const evaluated = query.select.trim() || query.exclude.trim() ? evaluateMockSelection(query.select, query.exclude) : null; + if (evaluated?.error) return { rows: [], error: evaluated.error }; + const chosen = evaluated && new Set(evaluated.keys); + const rows: CostRowIn[] = []; + for (const rec of this.#records) { + const at = rec.run.startedAt ? Date.parse(rec.run.startedAt) : NaN; + if (!(at >= previous)) continue; + const costs = this.#costRows(scope, rec, now); + const pending = costs.some((r) => r.resourceType === '_total' && (r.status === 'pending' || r.status === 'partial')); + for (const r of costs) { + if (r.resourceType === '_total' || !r.nodeKey || (chosen && !chosen.has(r.nodeKey))) continue; + rows.push({ runId: r.buildRunId, job: rec.run.jobKey, nodeKey: r.nodeKey, folder: costFolder(snapshotNode(r.nodeKey)?.path), startedAt: at, pending, credits: r.credits, usd: r.usd, seconds: r.seconds, queries: r.queryCount, bytes: r.bytesScanned }); + } + } + return { rows, error: null }; + } + + readCostSelection(scope: Scope, query: CostSelectionQuery): Promise { + const { rows, error } = this.#selectionRows(scope, query); + return this.#ctx.reply(costSelectionOf(rows, query.days, Date.now(), error)); + } + + readCostSeries(scope: Scope, query: CostSelectionQuery, groups: CostSeriesGroup[]): Promise { + if (groups.length > 200) throw new ApiError('at most 200 groups per request', 400); + return this.#ctx.reply(costSeriesOf(this.#selectionRows(scope, query).rows, query.days, Date.now(), groups)); + } + /** One node's cost in each build of the window, newest first. */ listNodeCosts(scope: Scope, nodeKey: string, days: number): Promise { const now = Date.now(); @@ -442,6 +479,7 @@ export class MockOperate { status: run.status, credits: mine.reduce((t, r) => t + r.credits, 0), usd: mine.some((r) => r.usd === null) ? null : mine.reduce((t, r) => t + (r.usd ?? 0), 0), + priceSource: mine.some((r) => r.usd === null) ? null : 'config', seconds: mine.reduce((t, r) => t + r.seconds, 0), queryCount: mine.reduce((t, r) => t + r.queryCount, 0) }); @@ -474,6 +512,7 @@ export class MockOperate { bytesScanned: queryCount * 52_428_800, credits, usd: priced ? credits * 3 : null, + priceSource: priced ? 'config' : null, status, statementsExpected: statements.length, statementsObserved: status === 'pending' ? 0 : statements.length diff --git a/ui/src/lib/api/mock/operate.ts b/ui/src/lib/api/mock/operate.ts index ed62a0bc04..a35f52f0e2 100644 --- a/ui/src/lib/api/mock/operate.ts +++ b/ui/src/lib/api/mock/operate.ts @@ -23,6 +23,7 @@ import type { TriggerStateEvent } from '../types'; import { CI_ACCOUNT, DEMO_USER, OPS_USER, SCHEDULER, SENSOR_DAEMON } from './principals'; +import { DISCOVERED_PLANS } from './discovered'; import { BIG_GROUP, bigGroupFile, bigGroupSelect, bigGroupShape } from './big-group'; import { resolveSelection, setJobResolver, writeSetOf } from './operate-graph'; import type { RunEnd, RunRecord, RunScript } from './run-detail'; @@ -400,6 +401,30 @@ JOB_DEFS.push( } ); +// A job per discovered forecast plan, selecting its steps (discovered.ts). +JOB_DEFS.push( + ...DISCOVERED_PLANS.map( + (p): JobDef => ({ + key: p.job, + kind: 'job', + description: `Demand forecast v2 for ${p.region}, one node per step of the release plan`, + select: `tag:forecast_${p.region.toLowerCase()}`, + exclude: [], + members: [], + overlap: 'skip', + onFailure: null, + pools: {}, + priority: 0, + sourceFile: `src/forecast_pipelines/definitions/models/regions/${p.region.toLowerCase()}/jobs.py`, + settings: {}, + targets: null, + owner: 'forecasting', + criticalNodes: [], + declaration: decl(`src/forecast_pipelines/definitions/models/regions/${p.region.toLowerCase()}/jobs.py`, 12, `${p.job} = job("${p.job}", select="tag:forecast_${p.region.toLowerCase()}")`) + }) + ) +); + /** Waits a group declares instead of those its members' lineage gives: the big group's whole upstreams. */ export const DECLARED_WAITS: Record> = { [BIG_GROUP]: BIG.waits }; diff --git a/ui/src/lib/api/mock/platform.ts b/ui/src/lib/api/mock/platform.ts index 309f5d169c..c9caa7b496 100644 --- a/ui/src/lib/api/mock/platform.ts +++ b/ui/src/lib/api/mock/platform.ts @@ -770,21 +770,33 @@ export class MockPlatformApi implements PlatformApi { async listWarehouseConnections(): Promise { const synced = new Date(Date.now() - 4 * 60_000).toISOString(); + // The 14 tables a location mirrors; Marketing's statistics read times out and its last check failed. + const tableNames = ['audit_results', 'catalog', 'column_migrations', 'consumption', 'fingerprints', 'freshness', 'janitor_events', 'microbatches', 'migrations', 'node_results', 'observations', 'old_name_views', 'resource_costs', 'statistics']; + const failedAt = new Date(Date.now() - 2 * 60_000).toISOString(); + const lastGood = new Date(Date.now() - 3 * 3_600_000).toISOString(); const connections = this.#ctx.locations.flatMap((l) => this.#warehouse({ locationId: l.id }) .filter((c) => c.purpose === 'target') - .map((c) => ({ - id: l.id, - location: l.name, - target: c.target, - // Shows the page as it will look once locations publish their settings and the sync schedule. - details: mockConnectionDetails(c), - stateLocation: { database: typeof c.values.database === 'string' ? c.values.database : null, schema: 'sqlbuild' }, - lastTest: this.#connectionTests.get(`${l.id}/${c.name}`) ?? c.lastTest, - nextSyncAt: new Date(Date.now() + 26 * 60_000).toISOString(), - halted: false, - tables: ['audit_results', 'catalog', 'fingerprints', 'statistics'].map((table, i) => ({ table, at: synced, recordsSent: 12 * (i + 1), elapsedMs: 180 + 40 * i, failure: null, error: null, waiting: false, lastSyncedAt: synced, mirroredTotal: 4_800 * (i + 1) })) - })) + .map((c) => { + const broken = l.id === LOCATION_MARKETING; + const failedTest: ConnectionTest = { outcome: 'failed', at: failedAt, durationMs: 30_000, trigger: 'manual', by: null, message: 'Connection to db.example.com:5432 timed out after 30 s' }; + return { + id: l.id, + location: l.name, + target: c.target, + // Shows the page as it will look once locations publish their settings and the sync schedule. + details: mockConnectionDetails(c), + stateLocation: { database: typeof c.values.database === 'string' ? c.values.database : null, schema: 'sqlbuild' }, + lastTest: this.#connectionTests.get(`${l.id}/${c.name}`) ?? (broken ? failedTest : c.lastTest), + nextSyncAt: new Date(Date.now() + 26 * 60_000).toISOString(), + halted: false, + tables: tableNames.map((table, i) => + broken && table === 'statistics' + ? { table, at: failedAt, recordsSent: 0, elapsedMs: 30_000, failure: 'Failed while reading the warehouse: no reply within 30 s, on a page of 100 relations', error: 'canceling statement due to statement timeout', waiting: false, lastSyncedAt: lastGood, mirroredTotal: 21_400 } + : { table, at: synced, recordsSent: 12 * ((i % 5) + 1), elapsedMs: 180 + 40 * (i % 6), failure: null, error: null, waiting: false, lastSyncedAt: synced, mirroredTotal: 1_200 * ((i * 7) % 13 + 1) } + ) + }; + }) ); return this.#ctx.reply(structuredClone(connections)); } diff --git a/ui/src/lib/api/mock/run-detail.ts b/ui/src/lib/api/mock/run-detail.ts index 5b84c35dae..80fdc96715 100644 --- a/ui/src/lib/api/mock/run-detail.ts +++ b/ui/src/lib/api/mock/run-detail.ts @@ -343,6 +343,7 @@ export function statusReason(status: RunStatus, nodes: RunNode[]): string | null const LEVEL: Record = { node_log: 'info', invocation_started: 'info', + invocation_phase: 'info', invocation_completed: 'info', invocation_failed: 'error', resource_attempt_started: 'debug', diff --git a/ui/src/lib/api/types/build.ts b/ui/src/lib/api/types/build.ts index 13362de09d..7911b66f13 100644 --- a/ui/src/lib/api/types/build.ts +++ b/ui/src/lib/api/types/build.ts @@ -81,6 +81,27 @@ export type CatalogNode = { checks: CheckCounts | null; }; +// ---- discovered sets ---- + +/** One discovered set of the current snapshot, as `readDiscovered` reads it back, with the nodes its items became. */ +export type DiscoveredSet = { + name: string; + status: 'ok' | 'failed' | 'never'; + items: number; + fetchedAt: Iso | null; + lastGoodAt: Iso | null; + digest: string | null; + /** Why the newest fetch failed, secrets masked. */ + error: string | null; + checkEverySeconds: number | null; + /** The tags of the result the set serves, such as `release` and `plan_digest`. */ + tags: Record; + /** The `for_each` assets reading the set. */ + assets: string[]; + /** Each item's node, with the item's arguments. */ + nodes: { key: string; asset: string; step: string; args: Record }[]; +}; + // ---- node states ---- /** A node's build state, the part of a catalog node that changes between publications. */ @@ -416,8 +437,6 @@ export type OverviewMetrics = { checks: CheckCounts; /** Distinct stale nodes, and how many are changed or behind (a node can be both); null when the server reports no project-wide build state, and `sources` null when source freshness is not checked. */ stale: { nodes: number; changed: number; behind: number; sources: number | null } | null; - /** Null when the adapter has no cost data. */ - cost: { last24h: number; baseline: number; baselineDays: number; unit: CostUnit } | null; }; /** Build status per group: current, stale (changed or behind) and failed. */ diff --git a/ui/src/lib/api/types/operate.ts b/ui/src/lib/api/types/operate.ts index 98f240d01f..5ae81298fc 100644 --- a/ui/src/lib/api/types/operate.ts +++ b/ui/src/lib/api/types/operate.ts @@ -253,6 +253,8 @@ export const RECALL_EVENT_TYPES = [ // A Python node's `ctx.log` line: few, deliberate, kept as events. 'node_log', 'invocation_started', + // A finished step of the worker's command: discovered, compiled, matched, connected, inspected, planned, or a saved discovered set. + 'invocation_phase', 'invocation_completed', 'invocation_failed', 'resource_attempt_started', @@ -298,6 +300,17 @@ export type RunEvent = { message: string; /** For `audit_completed`: which check ran, how it came out and how many rows it found. */ check?: RunEventCheck | null; + /** For `invocation_phase`: which step finished, how long it took, what it counted, what it is about and its sub-steps. */ + phase?: RunEventPhase | null; +}; + +/** One finished step of a worker's command before its nodes run. */ +export type RunEventPhase = { + phase: string; + durationMs: number | null; + count: number | null; + name: string | null; + detail: string | null; }; /** A check's result in a run: its name as declared, its outcome, the rows it found, and its identity for its evidence. */ @@ -343,21 +356,24 @@ export type RunCostRow = { seconds: number; bytesScanned: number; credits: number; - /** Null without a configured credit price; the UI never guesses one. */ + /** Null without a price per credit; the UI never guesses one. */ usd: number | null; + /** Where `usd`'s price per credit came from (`PriceSource`); null without one. */ + priceSource: PriceSource | null; status: Exclude; statementsExpected: number; statementsObserved: number; }; -export type RunCostResource = { nodeKey: string; credits: number; usd: number | null; seconds: number; queryCount: number; bytesScanned: number; warehouses: string[] }; -export type RunCostWarehouse = { name: string; size: string; credits: number; usd: number | null; seconds: number; queryCount: number }; +export type RunCostResource = { nodeKey: string; credits: number; usd: number | null; priceSource: PriceSource | null; seconds: number; queryCount: number; bytesScanned: number; warehouses: string[] }; +export type RunCostWarehouse = { name: string; size: string; credits: number; usd: number | null; priceSource: PriceSource | null; seconds: number; queryCount: number }; /** A run's estimated query cost, with its resources and warehouses most expensive first. */ export type RunCostBreakdown = { status: RunCostStatus; credits: number; usd: number | null; + priceSource: PriceSource | null; seconds: number; queryCount: number; statementsExpected: number; @@ -373,8 +389,9 @@ export type CostGroup = { key: string | null; credits: number; usd: number | nul export type CostSummary = { since: string; credits: number; - /** Null when any run in the window had no configured credit price. */ + /** Null when any run in the window had no price per credit. */ usd: number | null; + priceSource: PriceSource | null; runs: number; /** Runs whose cost is still pending or partial, which a later build re-reads. */ incompleteRuns: number; @@ -384,6 +401,67 @@ export type CostSummary = { byNode: CostGroup[]; }; +/** + * Where a price per credit came from: the project's `[cost] usd_per_credit`, the account's rate + * sheet, the list price for its region (an estimate), or several of the first two. + */ +export type PriceSource = 'config' | 'rate_sheet' | 'list_price' | 'mixed'; + +/** The price a cost read's dollars use, and where it came from. */ +export type CostPrice = { usdPerCredit: number; source: PriceSource }; + +/** One job's estimated query cost on one node over a period, and in the period before it. */ +export type CostFact = { + /** Null for builds no server run started (by hand or from the command line). */ + job: string | null; + nodeKey: string; + /** The node's folder: without `sql/models/` for SQL models (empty at its top), other roots as published, `other` when unknown. */ + folder: string; + credits: number; + previousCredits: number; + usd: number | null; + previousUsd: number | null; + seconds: number; + runs: number; + queries: number; + bytesScanned: number; +}; + +/** Credits per day of a cost read's period, for one job or top-level folder (`key`). */ +export type CostSeries = { key: string | null; credits: number[] }; + +/** A selection's estimated query cost over a period of whole UTC days, job by node, with daily series. */ +export type CostSelection = { + snapshotId: string | null; + since: string; + days: number; + /** The period's days, `YYYY-MM-DD`, oldest first; every series follows them. */ + dates: string[]; + /** Why `sqb` refuses the selection; facts and series are then empty. */ + error: SelectionProblem | null; + /** Null unless every observation had a configured credit price. */ + price: CostPrice | null; + credits: number; + previousCredits: number; + usd: number | null; + previousUsd: number | null; + runs: number; + incompleteRuns: number; + queries: number; + seconds: number; + bytesScanned: number; + /** Most expensive first. */ + facts: CostFact[]; + jobDaily: CostSeries[]; + folderDaily: CostSeries[]; +}; + +/** A cost read's period and selection, as `sqb build --select … --exclude …` takes it. */ +export type CostSelectionQuery = { days: number; select: string; exclude: string }; + +/** One group of a batch of daily cost series: selected nodes matching every field given. */ +export type CostSeriesGroup = { job?: string; manual?: boolean; folder?: string; nodeKey?: string }; + /** One node's estimated query cost in one build, across every warehouse it used. */ export type NodeBuildCost = { buildRunId: string; @@ -394,6 +472,7 @@ export type NodeBuildCost = { status: Exclude; credits: number; usd: number | null; + priceSource: PriceSource | null; seconds: number; queryCount: number; }; diff --git a/ui/src/lib/browser/clipboard.ts b/ui/src/lib/browser/clipboard.ts index 69caebfad7..099b988d5d 100644 --- a/ui/src/lib/browser/clipboard.ts +++ b/ui/src/lib/browser/clipboard.ts @@ -1,8 +1,12 @@ // Copies text. `navigator.clipboard` exists only in secure contexts (HTTPS or localhost), and the UI is also // served over plain HTTP behind a proxy, so without it the text is copied from a hidden textarea. -/** Copies `text`; whether it was copied. Call it from a click, which the fallback needs. */ -export async function copyText(text: string): Promise { +/** + * Copies `text`; whether it was copied. Call it from a click, which the fallback needs, and pass the + * clicked element: the fallback's textarea goes next to it, so it can be selected inside a modal + * dialog, which makes everything outside it inert. + */ +export async function copyText(text: string, near?: Element | null): Promise { if (navigator.clipboard?.writeText) { try { await navigator.clipboard.writeText(text); @@ -19,10 +23,13 @@ export async function copyText(text: string): Promise { const focused = document.activeElement as HTMLElement | null; const selection = document.getSelection(); const ranges = selection ? Array.from({ length: selection.rangeCount }, (_, i) => selection.getRangeAt(i)) : []; - document.body.append(area); + (near?.parentElement ?? document.body).append(area); + area.focus({ preventScroll: true }); area.select(); try { - return document.execCommand('copy'); + // An inert textarea can't take the selection, and `execCommand` may still report success. + const selected = document.activeElement === area && area.selectionEnd - area.selectionStart === text.length; + return selected && document.execCommand('copy'); } catch { return false; } finally { diff --git a/ui/src/lib/browser/copy-state.svelte.ts b/ui/src/lib/browser/copy-state.svelte.ts new file mode 100644 index 0000000000..aa81fcebd4 --- /dev/null +++ b/ui/src/lib/browser/copy-state.svelte.ts @@ -0,0 +1,30 @@ +import { copyText } from './clipboard'; + +/** How long a copy button says "Copied" before it reads "Copy" again. */ +export const COPIED_MS = 2000; + +/** + * A copy button's state: `copied` for a moment after each copy that worked, `failed` after one that + * didn't. Each press copies again. + */ +export function createCopyState() { + let copied = $state(false); + let failed = $state(false); + let timer: ReturnType | undefined; + return { + get copied() { + return copied; + }, + get failed() { + return failed; + }, + /** Copy `text` from a click on `near`; whether it was copied. */ + async copy(text: string, near?: Element | null): Promise { + clearTimeout(timer); + copied = await copyText(text, near); + failed = !copied; + if (copied) timer = setTimeout(() => (copied = false), COPIED_MS); + return copied; + } + }; +} diff --git a/ui/src/lib/build-area/labels.ts b/ui/src/lib/build-area/labels.ts index 0bf90108bf..f9e9dafba6 100644 --- a/ui/src/lib/build-area/labels.ts +++ b/ui/src/lib/build-area/labels.ts @@ -5,6 +5,8 @@ import Download from '@lucide/svelte/icons/download'; import Eye from '@lucide/svelte/icons/eye'; import GitMerge from '@lucide/svelte/icons/git-merge'; import Layers from '@lucide/svelte/icons/layers'; +import ChartGantt from '@lucide/svelte/icons/chart-gantt'; +import Repeat from '@lucide/svelte/icons/repeat'; import Package from '@lucide/svelte/icons/package'; import SquareFunction from '@lucide/svelte/icons/square-function'; import TableProperties from '@lucide/svelte/icons/table-properties'; @@ -96,8 +98,8 @@ export const nodeIcon: Record = { table: Table2, incremental: Layers, merge: GitMerge, - delete_insert: Layers, - microbatch: Layers, + delete_insert: Repeat, + microbatch: ChartGantt, asset: Package, udf: SquareFunction, table_fn: TableProperties diff --git a/ui/src/lib/components/app-sidebar.svelte b/ui/src/lib/components/app-sidebar.svelte index 6f4718cc45..ee483a46d7 100644 --- a/ui/src/lib/components/app-sidebar.svelte +++ b/ui/src/lib/components/app-sidebar.svelte @@ -10,7 +10,7 @@ import { signOutFor } from '$lib/platform/sign-out'; import ScopeSwitcher from './shell/scope-switcher.svelte'; - const visibleGroups = $derived(visibleNav(app.client, app.capabilities)); + const visibleGroups = $derived(visibleNav(app.client, app.capabilities, app.location?.target.adapter)); const signOut = $derived(signOutFor(app.bootstrap)); const badgeTone: Record = { diff --git a/ui/src/lib/components/build-area/folder-tree.svelte b/ui/src/lib/components/build-area/folder-tree.svelte index c8383f829f..72d2854038 100644 --- a/ui/src/lib/components/build-area/folder-tree.svelte +++ b/ui/src/lib/components/build-area/folder-tree.svelte @@ -111,8 +111,8 @@ {#snippet row(r)} {#if r.kind === 'folder'} {@const f = r.folder} - - labelClick(e, r)} data-testid="folder-label"> + labelClick(e, r)}> +
{#if r.expandable} @@ -183,7 +183,8 @@ :global(.folders) td { height: 36px; padding-block: 0 !important; } :global(.folders .sort) { color: inherit; font-size: 12px; font-weight: 500; } :global(.folders .sort:hover) { color: var(--foreground); } - .label.toggles { cursor: pointer; } + /* A folder that opens: its name underlines on the row's hover (the shared `expandable` rules do the rest). */ + tr:global(.expandable):hover .label a { text-decoration: underline; } .inner { display: flex; min-width: 0; align-items: center; gap: 6px; } .inner a { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .label a:hover, .leaf a:hover { color: var(--primary); text-decoration: underline; } diff --git a/ui/src/lib/components/code/sql-viewer.svelte b/ui/src/lib/components/code/sql-viewer.svelte index c223a4a162..778b8f0929 100644 --- a/ui/src/lib/components/code/sql-viewer.svelte +++ b/ui/src/lib/components/code/sql-viewer.svelte @@ -1,5 +1,5 @@ diff --git a/ui/src/lib/components/copy-button.svelte b/ui/src/lib/components/copy-button.svelte index 1db7d1c84e..91581752d0 100644 --- a/ui/src/lib/components/copy-button.svelte +++ b/ui/src/lib/components/copy-button.svelte @@ -1,5 +1,5 @@ diff --git a/ui/src/lib/components/graph/compact-face.svelte b/ui/src/lib/components/graph/compact-face.svelte index 77ec59971f..3701949994 100644 --- a/ui/src/lib/components/graph/compact-face.svelte +++ b/ui/src/lib/components/graph/compact-face.svelte @@ -1,46 +1,31 @@ @@ -54,18 +39,21 @@ align-items: center; pointer-events: none; } - /* Shown by the canvas once the view settles below the compact zoom; the card's own frame and lines - give way to the pill. */ - :global(.graph-canvas.compact) .cface { + /* Shown by the canvas once the view settles below the full cards' zoom; the card's own frame and + lines give way to the pill. Node cards show their name alone first, so not at that stage. */ + :global(.graph-canvas.compact:not([data-stage='name'])) .cface, + :global(.graph-canvas[data-stage='name'] .svelte-flow__node:not(.svelte-flow__node-asset)) .cface { display: flex; } - :global(.graph-canvas.compact .svelte-flow__node > :has(> .cface)) { + :global(.graph-canvas.compact:not([data-stage='name']) .svelte-flow__node > :has(> .cface)), + :global(.graph-canvas[data-stage='name'] .svelte-flow__node:not(.svelte-flow__node-asset) > :has(> .cface)) { border-color: transparent; background: transparent; box-shadow: none; overflow: visible; } - :global(.graph-canvas.compact .svelte-flow__node > :has(> .cface) > :not(.cface)) { + :global(.graph-canvas.compact:not([data-stage='name']) .svelte-flow__node > :has(> .cface) > :not(.cface)), + :global(.graph-canvas[data-stage='name'] .svelte-flow__node:not(.svelte-flow__node-asset) > :has(> .cface) > :not(.cface)) { visibility: hidden; } .pill { @@ -73,10 +61,10 @@ display: flex; box-sizing: border-box; width: 100%; - height: calc(30px * var(--u)); + height: min(calc(26px * var(--u)), 100%); align-items: center; - gap: calc(8px * var(--u)); - padding: 0 calc(14px * var(--u)) 0 calc(4px * var(--u)); + gap: calc(6px * var(--u)); + padding: 0 calc(8px * var(--u)) 0 calc(6px * var(--u)); border: calc(1px * var(--u)) solid color-mix(in srgb, var(--foreground) 11%, transparent); border-radius: 999px; background: var(--card); @@ -93,28 +81,15 @@ background: color-mix(in srgb, var(--primary) 16%, var(--card)); box-shadow: 0 0 0 calc(3px * var(--u)) color-mix(in srgb, var(--primary) 40%, transparent); } - .ring { - display: grid; - box-sizing: border-box; - width: calc(20px * var(--u)); - height: calc(20px * var(--u)); + /* The card's state. */ + .dot { + width: calc(10px * var(--u)); + height: calc(10px * var(--u)); flex: none; - place-items: center; - border: calc(2px * var(--u)) solid var(--tone); border-radius: 50%; - color: color-mix(in srgb, var(--foreground) 78%, transparent); - } - .ring :global(svg) { - width: var(--icon); - height: var(--icon); - } - /* A play triangle's weight sits a twelfth of its box left of the box's centre: moved right by that, - it looks centred in the ring. */ - .ring.play :global(svg) { - transform: translateX(calc(var(--icon) / 12)); + background: var(--tone); } .nm { - display: none; min-width: 0; overflow: hidden; color: var(--foreground); @@ -123,10 +98,18 @@ line-height: 1.2; white-space: nowrap; } - :global(.graph-canvas[data-compact='1']) .nm[data-level='1'], - :global(.graph-canvas[data-compact='2']) .nm[data-level='2'], - :global(.graph-canvas[data-compact='3']) .nm[data-level='3'] { - display: block; + /* Zoomed out furthest, the dot alone. */ + :global(.graph-canvas[data-stage='dot']) .pill { + width: max-content; + margin: 0 auto; + padding: calc(5px * var(--u)); + } + :global(.graph-canvas[data-stage='dot']) .dot { + width: calc(14px * var(--u)); + height: calc(14px * var(--u)); + } + :global(.graph-canvas[data-stage='dot']) .nm { + display: none; } /* On the pill's top right, outside the name's room. */ .cbadge { diff --git a/ui/src/lib/components/graph/compact-tails.test.ts b/ui/src/lib/components/graph/compact-tails.test.ts index 7e0957292b..d6fb02fac8 100644 --- a/ui/src/lib/components/graph/compact-tails.test.ts +++ b/ui/src/lib/components/graph/compact-tails.test.ts @@ -78,20 +78,15 @@ describe('a pill name too long to fit', () => { ]); }); - it('loses its middle, keeping both ends, so siblings still read differently', () => { + it('loses its end, keeping its start, never its middle', () => { const tails = compactTails(names); const shown = names.map((n) => pillText(tails.get(n)!, 12, 100, measure)); - // Thirteen characters fit: four from the start, an ellipsis, eight from the end. - expect(shown[0]).toBe('orde…e__alpha'); - expect(shown[7]).toBe('regi…_country'); + // Thirteen characters fit: twelve from the start and an ellipsis. + expect(shown[0]).toBe('order_type__…'); + expect(shown[7]).toBe('region_usabi…'); expect(shown[3]).toBe('delta'); - for (const [i, s] of shown.entries()) { - const [head, end = ''] = s.split('…'); - expect(tails.get(names[i])!.startsWith(head) && tails.get(names[i])!.endsWith(end)).toBe(true); - } - // Names that differ only at their start keep it. - expect(['stg_customers_daily', 'dim_customers_daily'].map((n) => pillText(n, 12, 80, measure))).toEqual(['stg…s_daily', 'dim…s_daily']); - expect(new Set(shown).size).toBe(names.length); + for (const [i, s] of shown.entries()) expect(tails.get(names[i])!.startsWith(s.replace(/…$/, ''))).toBe(true); for (const s of shown) expect(measure(s, 12)).toBeLessThanOrEqual(100); }); + }); diff --git a/ui/src/lib/components/graph/compact-tails.ts b/ui/src/lib/components/graph/compact-tails.ts index e85d2c1898..9e908ad6f1 100644 --- a/ui/src/lib/components/graph/compact-tails.ts +++ b/ui/src/lib/components/graph/compact-tails.ts @@ -2,6 +2,8 @@ // sibling card (in the same box, or loose on the graph) ends with, so `orders__stg__events` reads // `events` unless a sibling shares that ending. Pure. +import { sharedLeads } from '$lib/lineage/discovered-labels'; + /** The title a card shows: its label, else its name, its job's key or its folder. */ export function compactTitleOf(data: Record | undefined): string | null { const title = data?.label ?? data?.name ?? data?.jobKey ?? data?.group; @@ -44,7 +46,17 @@ export function siblingTails(cards: { id: string; parent: string; title: string return byId; } +/** Each card's pill name's shared lead among its siblings' pill names (`sharedLeads`), by card id. */ +export function siblingLeads(cards: { id: string; parent: string }[], tails: Map): Map { + const byId = new Map(); + for (const siblings of Map.groupBy(cards, (c) => c.parent).values()) { + const leads = sharedLeads(siblings.map((c) => tails.get(c.id) ?? '')); + for (const c of siblings) byId.set(c.id, leads.get(tails.get(c.id) ?? '') ?? 0); + } + return byId; +} + /** The context key a graph canvas gives its cards their pill names under. */ export const COMPACT_TAILS = Symbol('compact-tails'); /** A card's pill name and its parent box, by card id; undefined outside a graph canvas. */ -export type CompactTails = { tail: (id: string) => string | undefined; parent: (id: string) => string | undefined }; +export type CompactTails = { tail: (id: string) => string | undefined; parent: (id: string) => string | undefined; lead: (id: string) => number; zoom: () => number }; diff --git a/ui/src/lib/components/graph/compact-title.ts b/ui/src/lib/components/graph/compact-title.ts index 70b5642fc1..e880941090 100644 --- a/ui/src/lib/components/graph/compact-title.ts +++ b/ui/src/lib/components/graph/compact-title.ts @@ -1,79 +1,144 @@ -// Text measured to fit a card: the status line's parts, and a zoomed-out pill's name. A pill's name is -// sized on screen, as large as fits between `PILL.minFont` and `PILL.maxFont`; a name too long even -// then loses its middle, keeping its start and, more of, its end: siblings differ at either end -// (`stg_orders`, `dim_orders`; `region_check`, `region_country`). Worked out once per compact level, -// never per zoom step. +// Text measured to fit a card: the status line's parts, a name-only card's name and a zoomed-out +// pill's name. A name too long loses its end, keeping its start, except a discovered step's, which +// first drops the prefix it shares with its siblings. Widths are measured once per font, size and +// text (sizes come in half or quarter px steps), so zooming a large graph doesn't measure every card +// again. They aren't scaled from one size: the browser rounds each glyph's advance at small sizes. -import { CARD_WIDTH } from '$lib/lineage/fit'; +import { CARD_WIDTH, LABEL_MIN_ZOOM, NAME_MAX_PX, NAME_SCREEN_PX, PILL_ZOOM } from '$lib/lineage/fit'; /** The width of `text` at `font` px (and `weight`), in px. */ export type Measure = (text: string, font: number, weight?: number) => number; -/** A zoomed-out pill's parts, in px on screen. */ -export const PILL = { height: 30, ring: 20, padLeft: 5, gap: 8, padRight: 14, border: 1, minFont: 12, maxFont: 14, weight: 500 } as const; +/** A pill's parts on screen: a status dot, padding, and the name's size range. */ +export const PILL = { dot: 10, padLeft: 6, gap: 6, padRight: 8, border: 1, minFont: 10, maxFont: 12.5, weight: 500 } as const; -/** Room for a pill's name on screen at `zoom`: the card's width less the pill's ring and padding. */ +/** Room for a pill's name on screen at `zoom`: the card's full width less the dot and padding, which shrink with the card below `LABEL_MIN_ZOOM`. */ export function pillRoom(zoom: number): number { - return CARD_WIDTH * zoom - 2 * PILL.border - PILL.padLeft - PILL.ring - PILL.gap - PILL.padRight; + const parts = 2 * PILL.border + PILL.padLeft + PILL.dot + PILL.gap + PILL.padRight; + return CARD_WIDTH * zoom - parts * Math.min(1, zoom / LABEL_MIN_ZOOM); } /** The largest size, in quarter px from `PILL.maxFont` down to `PILL.minFont`, at which `text` fits `room`. */ export function pillFont(text: string, room: number, measure: Measure): number { - const { minFont, maxFont, weight } = PILL; - const widest = measure(text, maxFont, weight); - if (widest <= room) return maxFont; - // Width grows with the size, so start near where it fits and step down to be sure. - let font = Math.max(minFont, Math.min(maxFont, Math.floor(((maxFont * room) / widest) * 4) / 4)); - while (font > minFont && measure(text, font, weight) > room) font -= 0.25; + let font: number = PILL.maxFont; + while (font > PILL.minFont && measure(text, font, PILL.weight) > room) font -= 0.25; return font; } -/** `text` without its middle: `kept` characters, a third from its start and the rest from its end. */ -function middleCut(text: string, kept: number): string { - const head = Math.floor(kept / 3); - return `${text.slice(0, head)}…${kept - head ? text.slice(-(kept - head)) : ''}`; +/** + * `text` as it fits `room` at `font`: whole; else, with a shared `lead` (a discovered step's), + * cut inside the lead so the distinct rest stays whole, then the rest's end; else its end cut, + * keeping its start. + */ +export function pillText(text: string, font: number, room: number, measure: Measure, lead = 0, weight: number = PILL.weight): string { + const fits = (t: string) => measure(t, font, weight) <= room; + if (fits(text)) return text; + const endCut = (t: string, before = '') => { + let [lo, hi] = [0, t.length - 1]; + while (lo < hi) { + const mid = Math.ceil((lo + hi) / 2); + if (fits(`${before}${t.slice(0, mid)}…`)) lo = mid; + else hi = mid - 1; + } + return `${before}${t.slice(0, lo)}…`; + }; + if (lead > 0) { + // A discovered key's closing bracket goes with its prefix: `forecast_eu[gbm_gru]` reads `…gbm_gru`. + const rest = text.slice(lead).replace(/\]$/, ''); + for (let k = lead - 1; k >= 0; k--) if (fits(`${text.slice(0, k)}…${rest}`)) return `${text.slice(0, k)}…${rest}`; + return endCut(rest, '…'); + } + return endCut(text); +} + +/** A pill name's fit at the pill stage's lowest zoom, where the card is narrowest. */ +export function pillFit(text: string, lead: number, measure: Measure): { px: number; text: string } { + const room = pillRoom(PILL_ZOOM); + const px = pillFont(text, room, measure); + return { px, text: pillText(text, px, room, measure, lead) }; +} + +/** A name-only card's name size in canvas px at `zoom`, rounded up to half a px so a fit at it holds on screen. */ +export function nameOnlyPx(zoom: number): number { + return Math.ceil(Math.min(NAME_MAX_PX, Math.max(12.5, NAME_SCREEN_PX / zoom)) * 2) / 2; } -/** `text` at `font` as it fits `room`: whole, or with its middle cut to the most characters that fit. */ -export function pillText(text: string, font: number, room: number, measure: Measure): string { - if (measure(text, font, PILL.weight) <= room) return text; - let [lo, hi] = [0, text.length - 1]; - while (lo < hi) { - const mid = Math.ceil((lo + hi) / 2); - if (measure(middleCut(text, mid), font, PILL.weight) <= room) lo = mid; - else hi = mid - 1; +/** A name-only card's icon size in canvas px at `zoom`. */ +export const nameOnlyIcon = (zoom: number) => 14 * Math.min(1 / zoom, 1.8); + +const nameOnlyFits = new Map(); +const KEPT_FITS = 20_000; +/** A name-only card's name as it fits the card at `zoom`, worked out once per name, size and lead. */ +export function nameOnlyText(label: string, zoom: number, lead: number, measure: Measure): string { + const px = nameOnlyPx(zoom); + const key = `${px}\u0000${lead}\u0000${label}`; + let text = nameOnlyFits.get(key); + if (text === undefined) { + const room = CARD_WIDTH - 2 - 20 - 8 - nameOnlyIcon(zoom); + text = pillText(label, px, room, measure, lead, 600); + if (nameOnlyFits.size > KEPT_FITS) nameOnlyFits.clear(); + if (measured(measure)) nameOnlyFits.set(key, text); } - return middleCut(text, lo); + return text; } let context: CanvasRenderingContext2D | null | undefined; const loading = new Set(); -/** A measurer in `family` (or the family `family()` names when it is measured), estimating generously until the font has loaded. */ +/** Fonts known to have loaded, so they aren't checked again. */ +const loaded = new Set(); +/** Text widths by font (weight, size and family), then text; a font's are dropped past `KEPT_WIDTHS`, as times in status lines keep changing. */ +const widths = new Map>(); +const KEPT_WIDTHS = 20_000; +/** Measurers that measured real widths, as opposed to estimating while their font loads. */ +const real = new WeakSet(); +const measured = (measure: Measure) => real.has(measure); + +/** A measurer in the family `family()` names, estimating generously until the font has loaded. */ function measureIn(family: () => string, fallback: number): Measure { - return (text, font, weight = 600) => { - const spec = `${weight} ${font}px ${family()}`; + const measure: Measure = (text, font, weight = 600) => { + const name = family(); if (context === undefined) context = typeof document === 'undefined' ? null : document.createElement('canvas').getContext('2d'); if (!context) return text.length * font * fallback; - if (!document.fonts?.check(spec)) { + const face = `${weight} ${font}px ${name}`; + if (!loaded.has(face) && !document.fonts?.check(face)) { // Ask for the font, so it loads (and the text is fitted again) even before it first shows. - const face = `${weight} 16px ${family()}`; if (!loading.has(face)) { loading.add(face); void document.fonts?.load(face).catch(() => {}); } + real.delete(measure); return text.length * font * fallback; } - context.font = spec; - return context.measureText(text).width; + loaded.add(face); + real.add(measure); + let known = widths.get(face); + if (!known || known.size > KEPT_WIDTHS) widths.set(face, (known = new Map())); + let width = known.get(text); + if (width === undefined) { + context.font = face; + width = context.measureText(text).width; + known.set(text, width); + } + return width; }; + return measure; } -/** The cards' own font, Inter, as the status line measures it. */ -export const measureText: Measure = measureIn(() => '"Inter Variable", sans-serif', 0.64); +/** The family the page sets CSS variable `name` to, read once: it doesn't change while the page runs. */ +function pageFamily(name: string, fallback: string): () => string { + let family: string | undefined; + return () => { + if (family !== undefined) return family; + if (typeof document === 'undefined') return fallback; + const set = getComputedStyle(document.documentElement).getPropertyValue(name).trim(); + if (set) family = set; + return set || fallback; + }; +} +/** The cards' font, as the page sets `--font-mono` (IBM Plex Mono). */ +const cardFamily = pageFamily('--font-mono', 'monospace'); +/** The cards' name and status line font, as the status line measures it. */ +export const measureText: Measure = measureIn(cardFamily, 0.62); /** The pills' name font: whatever the page sets `--font-node-compact` to. */ -function compactFamily(): string { - if (typeof document === 'undefined') return 'sans-serif'; - return getComputedStyle(document.documentElement).getPropertyValue('--font-node-compact').trim() || 'sans-serif'; -} -export const measureCompact: Measure = measureIn(compactFamily, 0.66); +export const measureCompact: Measure = measureIn(pageFamily('--font-node-compact', 'sans-serif'), 0.66); diff --git a/ui/src/lib/components/graph/graph-canvas.svelte b/ui/src/lib/components/graph/graph-canvas.svelte index f03a07ad59..9b1dfbfde8 100644 --- a/ui/src/lib/components/graph/graph-canvas.svelte +++ b/ui/src/lib/components/graph/graph-canvas.svelte @@ -2,14 +2,14 @@ import '@xyflow/svelte/dist/style.css'; import { Controls, SvelteFlow, ViewportPortal, type Edge, type Node, type Viewport } from '@xyflow/svelte'; import { setContext, untrack } from 'svelte'; - import { COMPACT_TAILS, compactTitleOf, siblingTails, type CompactTails } from './compact-tails'; + import { COMPACT_TAILS, compactTitleOf, siblingLeads, siblingTails, type CompactTails } from './compact-tails'; import { unzoom } from '$lib/lineage/hit-area'; import { obstacles, shareObstacles } from '$lib/lineage/edge-routes'; import type { ComponentProps, Snippet } from 'svelte'; import FlowController from '$lib/lineage/flow-controller.svelte'; import FitControls from '$lib/lineage/fit-controls.svelte'; import CountEdge from '$lib/lineage/count-edge.svelte'; - import { LABEL_MIN_ZOOM, READABLE_ZOOM, compactLevel } from '$lib/lineage/fit'; + import { LABEL_MIN_ZOOM, READABLE_ZOOM, cardStage, compactLevel } from '$lib/lineage/fit'; // Every graph in the UI is drawn here, so they share one canvas: the same background, fit controls // and readable fit (a large graph opens on its cards at a zoom where they read, never as dots), and @@ -121,25 +121,28 @@ } press = null; } - // Semantic zoom: zoomed out past the point where the cards' lines would no longer read, each card - // shows its compact form instead (CompactFace: a one-line pill, its state's ring and its name), by - // one class on the canvas; `data-compact` picks the name's fit for the level of zoom, and - // `--sb-title-unzoom` keeps the pill's size on screen. Cards keep their size, so edges don't move. - // Card controls grow with `--sb-unzoom` so they keep their size. + // Semantic zoom in stages (`cardStage`): zoomed out past the point where the cards' status lines would + // no longer read, node cards show their name alone, enlarged; further out every card shows its compact + // form (CompactFace: a one-line pill, its state's dot and its name), then the dot alone. One class + // and `data-stage` on the canvas pick the stage, and `--sb-title-unzoom` keeps the pill's size on + // screen. Cards keep their size, so edges don't move. Card controls grow with `--sb-unzoom`. const level = $derived(compactLevel(settledZoom)); + const stage = $derived(cardStage(settledZoom)); // Each card's pill name: the part of its title none of its siblings ends with. Worked out from the // cards' titles and boxes alone, so moving or selecting cards doesn't change it. const cardKey = $derived(nodes.map((n) => `${n.id}\t${n.parentId ?? ''}\t${compactTitleOf(n.data as Record) ?? ''}`).join('\n')); const titled = $derived(cardKey ? cardKey.split('\n').map((line) => line.split('\t')).filter(([, , title]) => title).map(([id, parent, title]) => ({ id, parent, title })) : []); const tails = $derived(siblingTails(titled)); const parents = $derived(new Map(titled.map((c) => [c.id, c.parent]))); - setContext(COMPACT_TAILS, { tail: (id) => tails.get(id), parent: (id) => parents.get(id) }); + // The prefix each pill name shares with a sibling's, dropped first when it doesn't fit. + const leads = $derived(siblingLeads(titled, tails)); + setContext(COMPACT_TAILS, { tail: (id) => tails.get(id), parent: (id) => parents.get(id), lead: (id) => leads.get(id) ?? 0, zoom: () => settledZoom }); const compact = $derived(level > 0); const titleUnzoom = $derived(compact ? 1 / Math.max(settledZoom, LABEL_MIN_ZOOM) : 1); const controlScale = $derived(unzoom(settledZoom)); -
0} data-compact={level || undefined} style:--sb-title-unzoom={titleUnzoom} style:--sb-unzoom={controlScale} bind:this={element} onpointerdowncapture={onpointerdown} onpointermovecapture={onpointermove} onclickcapture={onclick}> +
0} data-compact={level || undefined} data-stage={stage} style:--sb-inv={1 / settledZoom} style:--sb-title-unzoom={titleUnzoom} style:--sb-unzoom={controlScale} bind:this={element} onpointerdowncapture={onpointerdown} onpointermovecapture={onpointermove} onclickcapture={onclick}> diff --git a/ui/src/lib/components/lineage/asset-node.svelte b/ui/src/lib/components/lineage/asset-node.svelte index f74f9fd09e..4fd57fe082 100644 --- a/ui/src/lib/components/lineage/asset-node.svelte +++ b/ui/src/lib/components/lineage/asset-node.svelte @@ -5,7 +5,7 @@ Database, Table2, Eye, - Layers, + ChartGantt, FunctionSquare, Sprout, Download, @@ -22,6 +22,11 @@ import CompactFace from '$lib/components/graph/compact-face.svelte'; import { fonts } from '$lib/components/graph/fonts.svelte'; import { fitStatus } from '$lib/lineage/status-line'; + import { getContext } from 'svelte'; + import { COMPACT_TAILS, type CompactTails } from '$lib/components/graph/compact-tails'; + import { measureText, nameOnlyText } from '$lib/components/graph/compact-title'; + import { cardStage } from '$lib/lineage/fit'; + import { discoveredStep } from '$lib/lineage/discovered-labels'; type AssetData = { name: string; @@ -87,15 +92,27 @@ table: Table2, merge: GitMerge, delete_insert: Repeat, - microbatch: Layers, + microbatch: ChartGantt, asset: Package, udf: FunctionSquare, table_fn: TableProperties, fn: FunctionSquare }; + // No kind word on the card: the icon tells the kinds and incremental strategies apart, and the full + // materialization is in the tooltip and the side panel. const Glyph = $derived(icons[d.icon ?? ''] ?? Table2); + // Zoomed out to the name-only stage, the name is fitted to the card at its enlarged size: a + // discovered step's shared prefix gives way first, any other name loses its end. + const tails = getContext(COMPACT_TAILS); + const shownName = $derived.by(() => { + const label = d.label ?? d.name; + const zoom = tails?.zoom(); + if (zoom === undefined || cardStage(zoom) !== 'name') return label; + void fonts.ready; + void fonts.version; + return nameOnlyText(label, zoom, discoveredStep(id) ? (tails?.lead(id) ?? 0) : 0, measureText); + }); const tone = $derived(statusColor[d.status] ?? statusColor.none); - const kindShort = $derived(d.kind.split(' · ')[0]); const when = $derived(d.lastBuiltAt ? (d.status === 'src' ? `loaded ${formatAgo(d.lastBuiltAt, app.now)}` : formatAgo(d.lastBuiltAt, app.now)) : ''); // Zoomed out, the card's state is its colour: a failure or a run first, then staleness, then the outcome. @@ -124,13 +141,12 @@ ); -
+
- {d.label ?? d.name} - {#if f.kind}{kindShort}{/if} + {shownName}
{#if hasDetail} @@ -200,15 +216,31 @@ min-width: 0; flex: 1; overflow: hidden; + font-family: var(--font-mono); font-size: 12.5px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; } - .kind { - flex: 0 0 auto; - color: var(--sb-text-faint); - font-size: 11px; + /* Name-only stage: the same card, its other lines hidden and its name enlarged to stay about 10 px + on screen; the card keeps its size, so nothing moves. Its state shows as a stripe and the icon's colour. */ + :global(.graph-canvas[data-stage='name']) .node:not(.selected) { + box-shadow: inset 3px 0 0 var(--face); + } + :global(.graph-canvas[data-stage='name']) .detail, + :global(.graph-canvas[data-stage='name']) .status { + visibility: hidden; + } + :global(.graph-canvas[data-stage='name']) .head { + transform: translateY(13px); + } + :global(.graph-canvas[data-stage='name']) .head :global(.glyph) { + width: calc(14px * min(var(--sb-inv, 1), 1.8)); + height: calc(14px * min(var(--sb-inv, 1), 1.8)); + color: var(--face); + } + :global(.graph-canvas[data-stage='name']) .name { + font-size: clamp(12.5px, calc(10px * var(--sb-inv, 1)), 26px); } /* drift is a cause of staleness, so it shares the stale colour */ .drift { @@ -262,6 +294,7 @@ padding: 0 10px; border-top: 1px solid var(--border); background: color-mix(in srgb, var(--tone) 9%, var(--card)); + font-family: var(--font-mono); font-size: 11px; /* One line, whatever the parts: they are fitted to it (status-line.ts); none wraps or shrinks. */ white-space: nowrap; diff --git a/ui/src/lib/components/list/data-table.svelte b/ui/src/lib/components/list/data-table.svelte index 7f5a7b67c4..e77c821e18 100644 --- a/ui/src/lib/components/list/data-table.svelte +++ b/ui/src/lib/components/list/data-table.svelte @@ -25,6 +25,7 @@ class: className = '', label, windowAbove = WINDOW_ABOVE, + overscan = 8, onwindow, after, emptyRow @@ -48,6 +49,8 @@ label?: string; /** Window lists longer than this; 0 windows every list, as an endless list does. */ windowAbove?: number; + /** Rows drawn beyond the view on either side of a windowed list. */ + overscan?: number; /** The rows drawn, as indices into `rows`; an endless list loads more as the end comes into view. */ onwindow?: (range: { first: number; last: number }) => void; /** Rows after the list, such as "Loading more…". */ @@ -60,7 +63,7 @@ // Rows drawn, and the height they took: the average sizes the spacers for rows not drawn. let average = $state(44); const fixed = untrack(() => rowHeight); - const win = createVirtualRows(fixed ?? (() => average), () => rows.length); + const win = createVirtualRows(fixed ?? (() => average), () => rows.length, untrack(() => overscan)); const first = $derived(isWindowed ? win.first : 0); const last = $derived(isWindowed ? win.last : rows.length); const shown = $derived(rows.slice(first, last)); diff --git a/ui/src/lib/components/list/fitting-items.svelte b/ui/src/lib/components/list/fitting-items.svelte new file mode 100644 index 0000000000..27f66d2672 --- /dev/null +++ b/ui/src/lib/components/list/fitting-items.svelte @@ -0,0 +1,144 @@ + + +
+ {#each items as entry, i (i)} + + {/each} + {#if shown < items.length} + + e.stopPropagation()}>+{items.length - shown} + + {#each items as entry, i (i)}
{@render item(entry)}
{/each} +
+
+ {/if} +
+ + + diff --git a/ui/src/lib/components/names/breakable-name.svelte b/ui/src/lib/components/names/breakable-name.svelte new file mode 100644 index 0000000000..5b47ce332d --- /dev/null +++ b/ui/src/lib/components/names/breakable-name.svelte @@ -0,0 +1,16 @@ + + +{#each parts as part, i (i)}{#if i}{/if}{part}{/each} + + diff --git a/ui/src/lib/components/names/path-tail.svelte b/ui/src/lib/components/names/path-tail.svelte new file mode 100644 index 0000000000..23c4beeeff --- /dev/null +++ b/ui/src/lib/components/names/path-tail.svelte @@ -0,0 +1,25 @@ + + +{path} + + diff --git a/ui/src/lib/components/platform/issued-secret.svelte b/ui/src/lib/components/platform/issued-secret.svelte index b6379f16aa..e9e04371d7 100644 --- a/ui/src/lib/components/platform/issued-secret.svelte +++ b/ui/src/lib/components/platform/issued-secret.svelte @@ -1,20 +1,20 @@ diff --git a/ui/src/lib/components/platform/location-tokens.svelte b/ui/src/lib/components/platform/location-tokens.svelte index 2ee0c6b1de..f53b44e2f9 100644 --- a/ui/src/lib/components/platform/location-tokens.svelte +++ b/ui/src/lib/components/platform/location-tokens.svelte @@ -79,7 +79,7 @@ {/if} {:else} -
  • {#if tokens}No tokens yet. Create one and give it to the location so it can connect.{:else}{/if}
  • +
  • {#if tokens}No tokens yet.{:else}{/if}
  • {/each}
    diff --git a/ui/src/lib/components/selection/selection-bar.svelte b/ui/src/lib/components/selection/selection-bar.svelte index afe2d58eee..01ca14d29b 100644 --- a/ui/src/lib/components/selection/selection-bar.svelte +++ b/ui/src/lib/components/selection/selection-bar.svelte @@ -1,12 +1,11 @@ -
    +
    {#if folder} @@ -36,6 +38,22 @@ {folder.label} · {plural(folder.nodeCount, folder.noun ?? 'node')}{#if folder.stale} · {folder.stale} stale{/if}{#if folder.failed} · {folder.failed} failed{/if} + {:else if d.discovered} + {@const set = d.discovered} + + + {:else}
    {#if d.ontoggle} @@ -66,6 +84,25 @@ border-radius: 3px; background: color-mix(in srgb, var(--card) 45%, transparent); } + /* An open discovered set's title sits on its frame, at a size that reads at any zoom. */ + .discovered { + border-style: dashed; + border-color: color-mix(in srgb, var(--primary) 45%, var(--border-strong)); + background: color-mix(in srgb, var(--primary) 4%, transparent); + } + .discovered .head { + position: absolute; + bottom: 100%; + left: -1px; + width: max-content; + max-width: calc(100% / var(--sb-unzoom, 1)); + border: 1px solid color-mix(in srgb, var(--primary) 45%, var(--border-strong)); + border-bottom: 0; + border-radius: 3px 3px 0 0; + background: var(--card); + transform: scale(var(--sb-unzoom, 1)); + transform-origin: bottom left; + } .collapsed .head { border-bottom: 0; } @@ -127,6 +164,31 @@ .failed { color: var(--sb-error); } + .set-head { + width: 100%; + gap: 6px; + padding-left: 8px; + cursor: pointer; + text-align: left; + } + .set-head:hover { + background: var(--sb-hover); + } + .set-head:focus-visible { + outline: 2px solid var(--primary); + outline-offset: -2px; + } + .set-head :global(.chevron) { + flex: 0 0 auto; + color: var(--muted-foreground); + } + .set-head .name:hover { + color: inherit; + } + .mono-faint { + font-family: var(--font-mono); + font-size: 11.5px; + } .name:hover, .last:hover { color: var(--primary); diff --git a/ui/src/lib/lineage/job-graph.ts b/ui/src/lib/lineage/job-graph.ts index 986319224b..1855a5cc3a 100644 --- a/ui/src/lib/lineage/job-graph.ts +++ b/ui/src/lib/lineage/job-graph.ts @@ -16,6 +16,8 @@ const EMPTY_HEIGHT = 44; const COLLAPSED_HEIGHT = HEADER + 2; /** Wide enough for a header's name, node count and last run on one line. */ const COLLAPSED_WIDTH = 380; +/** A collapsed discovered set's header also names its release and status. */ +const DISCOVERED_COLLAPSED_WIDTH = 560; /** Space between cards stacked in one column. */ const STACK_GAP = 20; /** Space dagre leaves between cards, and between boxes and cards outside them. */ @@ -23,7 +25,9 @@ const CARD_GAP = 24; const BOX_GAP = 24 + HEADER; const MARGIN = 24; -export type JobBox = { jobKey: string; nodes: string[]; lastRun?: RunRef | null }; +/** A box framing a discovered set's steps, under their asset's name. */ +export type DiscoveredBox = { set: string; status: 'ok' | 'failed' | 'never'; release: string | null; releaseFull: string | null; error: string | null }; +export type JobBox = { jobKey: string; nodes: string[]; lastRun?: RunRef | null; discovered?: DiscoveredBox }; const edgeStyle = 'stroke: var(--sb-edge); stroke-width: 1.5;'; const waitStyle = 'stroke: var(--sb-edge); stroke-width: 1.5; stroke-dasharray: 5 4;'; @@ -63,7 +67,7 @@ export function jobGraph( id: boxId(b.jobKey), type: 'job', position: { x: 0, y: 0 }, - width: collapsed.has(b.jobKey) ? COLLAPSED_WIDTH : NODE_WIDTH + 2 * PAD, + width: collapsed.has(b.jobKey) ? (b.discovered ? DISCOVERED_COLLAPSED_WIDTH : COLLAPSED_WIDTH) : NODE_WIDTH + 2 * PAD, height: collapsed.has(b.jobKey) ? COLLAPSED_HEIGHT : EMPTY_HEIGHT, selectable: false, data: { @@ -71,7 +75,8 @@ export function jobGraph( lastRun: b.lastRun ?? null, nodeCount: built.get(b.jobKey)!.length, drawnElsewhere: built.get(b.jobKey)!.filter((n) => owner.get(n) !== b.jobKey).length, - collapsed: collapsed.has(b.jobKey) + collapsed: collapsed.has(b.jobKey), + ...(b.discovered ? { discovered: b.discovered } : {}) } })); const cards: Node[] = nodes.filter((key) => shownAs(key) === key).map((key) => { diff --git a/ui/src/lib/lineage/node-fields.svelte.ts b/ui/src/lib/lineage/node-fields.svelte.ts index 3e9cbb9555..880e3bf74c 100644 --- a/ui/src/lib/lineage/node-fields.svelte.ts +++ b/ui/src/lib/lineage/node-fields.svelte.ts @@ -3,7 +3,6 @@ // choice of what to show on nodes survives reloads. export type NodeFieldKey = - | 'kind' | 'status' | 'checks' | 'lastBuilt' @@ -14,7 +13,6 @@ export type NodeFieldKey = export type NodeField = { key: NodeFieldKey; label: string }; export const NODE_FIELDS: NodeField[] = [ - { key: 'kind', label: 'Kind' }, { key: 'status', label: 'Status' }, { key: 'checks', label: 'Checks' }, { key: 'lastBuilt', label: 'Last built' }, @@ -24,7 +22,6 @@ export const NODE_FIELDS: NodeField[] = [ ]; const DEFAULTS: Record = { - kind: true, status: true, checks: true, lastBuilt: true, diff --git a/ui/src/lib/nav.ts b/ui/src/lib/nav.ts index 0cef4bc332..84dd7b36a1 100644 --- a/ui/src/lib/nav.ts +++ b/ui/src/lib/nav.ts @@ -1,4 +1,6 @@ import CheckCircleIcon from '@lucide/svelte/icons/circle-check'; +import CircleDollarSignIcon from '@lucide/svelte/icons/circle-dollar-sign'; +import { reportsCost } from '$lib/operate/cost'; import ClockIcon from '@lucide/svelte/icons/clock-3'; import DatabaseIcon from '@lucide/svelte/icons/database'; import GitBranchIcon from '@lucide/svelte/icons/git-branch'; @@ -21,7 +23,8 @@ export type NavBadge = { value: (counts: NavCounts) => number; tone: 'muted' | ' * `loads` is the client method the page cannot work without; the entry hides when the server lacks it. * `wholeTarget` pages list the selected target, which needs view on every node in it. */ -export type NavItem = { label: string; href: string; icon: Component; loads: keyof ApiClient; badge?: NavBadge; requires?: readonly Capability[]; wholeTarget?: true }; +/** `reportsCost`: shown only for locations whose adapter reports query cost. */ +export type NavItem = { label: string; href: string; icon: Component; loads: keyof ApiClient; badge?: NavBadge; requires?: readonly Capability[]; wholeTarget?: true; reportsCost?: true }; export type NavGroup = { section: string | null; items: NavItem[]; requires?: readonly Capability[] }; export const NAV: readonly NavGroup[] = [ @@ -40,7 +43,8 @@ export const NAV: readonly NavGroup[] = [ items: [ { label: 'Runs', href: '/runs', icon: ListIcon, loads: 'listRunRows', badge: { value: (c) => c.activeRuns, tone: 'live' }, wholeTarget: true }, { label: 'Jobs', href: '/jobs', icon: PlayIcon, loads: 'listJobs', wholeTarget: true }, - { label: 'Triggers', href: '/triggers', icon: ClockIcon, loads: 'listTriggers', badge: { value: (c) => c.pausedTriggers, tone: 'muted' }, wholeTarget: true } + { label: 'Triggers', href: '/triggers', icon: ClockIcon, loads: 'listTriggers', badge: { value: (c) => c.pausedTriggers, tone: 'muted' }, wholeTarget: true }, + { label: 'Cost', href: '/cost', icon: CircleDollarSignIcon, loads: 'readCostSelection', wholeTarget: true, reportsCost: true } ] }, { @@ -64,11 +68,11 @@ export const NAV: readonly NavGroup[] = [ ]; /** Entries the person may use and the server can load; groups left empty disappear. */ -export function visibleNav(client: Pick, capabilities: readonly Capability[]): NavGroup[] { +export function visibleNav(client: Pick, capabilities: readonly Capability[], adapter?: string | null): NavGroup[] { return NAV.filter((g) => !g.requires || hasAnyCapability(capabilities, g.requires)) .map((g) => ({ ...g, - items: g.items.filter((i) => client.supports(i.loads) && (!i.requires || hasAnyCapability(capabilities, i.requires))) + items: g.items.filter((i) => client.supports(i.loads) && (!i.requires || hasAnyCapability(capabilities, i.requires)) && (!i.reportsCost || reportsCost(adapter))) })) .filter((g) => g.items.length > 0); } diff --git a/ui/src/lib/operate/cost.test.ts b/ui/src/lib/operate/cost.test.ts index b42d193f77..9099bb9d86 100644 --- a/ui/src/lib/operate/cost.test.ts +++ b/ui/src/lib/operate/cost.test.ts @@ -1,8 +1,9 @@ import { describe, expect, it } from 'vitest'; -import type { CatalogNode, RunCostRow } from '$lib/api'; -import { costByFolder, costSummary, formatQueryCost, runCostOf } from './cost'; +import type { RunCostRow } from '$lib/api'; +import { combinedSource, costSummary, costTitle, formatQueryCost, runCostOf } from './cost'; const row = (overrides: Partial): RunCostRow => ({ + priceSource: overrides.usd === null ? null : 'config', nodeKey: `${overrides.resourceType ?? 'model'}:${overrides.resourceName ?? 'orders'}`, buildRunId: 'b1', resourceType: 'model', @@ -77,25 +78,20 @@ describe('what the cost figure says', () => { }); }); -describe('cost by folder', () => { - const node = (key: string, path: string, group: string | null = null) => ({ key, kind: 'model', path, group }) as unknown as CatalogNode; - const nodes = [node('model:stg_orders', 'models/staging/orders/stg_orders.sql'), node('model:stg_items', 'models/staging/stg_items.sql'), node('model:fct_revenue', 'models/finance/fct_revenue.sql', 'marts/finance')]; - - it('sums nodes under their outermost folder, honours declared groups and keeps removed nodes', () => { - const folders = costByFolder( - [ - { key: 'model:fct_revenue', credits: 0.5, usd: 1.5, seconds: 900, runs: 2 }, - { key: 'model:stg_orders', credits: 0.3, usd: 0.9, seconds: 540, runs: 3 }, - { key: 'model:stg_items', credits: 0.4, usd: null, seconds: 720, runs: 3 }, - { key: 'model:dropped', credits: 0.05, usd: 0.15, seconds: 90, runs: 1 } - ], - nodes - ); - expect(folders.map((f) => [f.key, f.nodes, f.usd])).toEqual([ - ['staging', 2, null], - ['marts', 1, 1.5], - ['other', 1, 0.15] - ]); - expect(folders[0].credits).toBeCloseTo(0.7); +describe('prices and their sources', () => { + it('marks dollars at a list price as an estimate, and names the source in the tooltip', () => { + expect(formatQueryCost({ credits: 1, usd: 3.9, priceSource: 'list_price' })).toBe('$3.90 est.'); + expect(formatQueryCost({ credits: 1, usd: 2.73, priceSource: 'rate_sheet' })).toBe('$2.73'); + expect(costTitle({ credits: 2, usd: 7.8, priceSource: 'list_price' })).toBe("2.000 credits × $3.90 per credit (Snowflake's list price for the account's region (an estimate))"); + expect(costTitle({ credits: 2, usd: null, priceSource: null })).toBeUndefined(); + }); + it('reads several sources as one: theirs, the list price when any is one, else mixed', () => { + expect(combinedSource(['config', 'config', null])).toBe('config'); + expect(combinedSource(['config', 'list_price'])).toBe('list_price'); + expect(combinedSource(['config', 'rate_sheet'])).toBe('mixed'); + expect(combinedSource([null])).toBeNull(); + }); + it("gives a run's breakdown its rows' source", () => { + expect(runCostOf([row({ resourceType: '_total', resourceName: 'b1', nodeKey: null, priceSource: 'list_price' }), row({ priceSource: 'list_price' })]).priceSource).toBe('list_price'); }); }); diff --git a/ui/src/lib/operate/cost.ts b/ui/src/lib/operate/cost.ts index d59a6f2507..1426bca130 100644 --- a/ui/src/lib/operate/cost.ts +++ b/ui/src/lib/operate/cost.ts @@ -1,26 +1,16 @@ -import type { CatalogNode, CostGroup, RunCostBreakdown, RunCostRow, RunCostStatus } from '$lib/api'; -import { topFolder } from '$lib/lineage/catalog-graph'; +import type { PriceSource, RunCostBreakdown, RunCostRow, RunCostStatus } from '$lib/api'; /** The resource type of the row carrying a collection's totals. */ export const TOTAL = '_total'; -/** Shown wherever figures read in credits, because the project set no credit price. */ +/** The help tip wherever figures read in credits, because the project set no credit price. */ export const CREDIT_PRICE_HINT = 'Set usd_per_credit under [cost] in sqlbuild_project.toml to see dollars.'; -/** Node costs summed per top-level folder, most expensive first; nodes no longer deployed count as `other`. */ -export function costByFolder(byNode: CostGroup[], nodes: CatalogNode[]): { key: string; credits: number; usd: number | null; nodes: number }[] { - const folders = new Map(nodes.map((n) => [n.key, topFolder(n)])); - const totals = new Map(); - for (const g of byNode) { - const key = (g.key && folders.get(g.key)) ?? 'other'; - const t = totals.get(key) ?? { key, credits: 0, usd: 0, nodes: 0 }; - t.credits += g.credits; - t.usd = sumUsd(t.usd, g.usd); - t.nodes += 1; - totals.set(key, t); - } - return [...totals.values()].sort((a, b) => b.credits - a.credits); -} +/** Adapters whose runs report query cost; the Overview's cost card and the Cost page show only for these. */ +const COST_ADAPTERS: ReadonlySet = new Set(['snowflake']); + +/** Whether a location on `adapter` reports query cost. */ +export const reportsCost = (adapter: string | null | undefined): boolean => !!adapter && COST_ADAPTERS.has(adapter); /** Least complete first, so a group run shows the weakest of its job runs' collections. */ const STATUS_RANK: Record = { none: 0, collection_failed: 1, unavailable: 2, pending: 3, partial: 4, complete: 5 }; @@ -36,18 +26,20 @@ export function runCostOf(rows: RunCostRow[]): RunCostBreakdown { const warehouses = new Map(); for (const r of parts) { const nodeKey = r.nodeKey ?? r.resourceName; - const resource = resources.get(nodeKey) ?? { nodeKey, credits: 0, usd: 0, seconds: 0, queryCount: 0, bytesScanned: 0, warehouses: [] }; + const resource = resources.get(nodeKey) ?? { nodeKey, credits: 0, usd: 0, priceSource: null, seconds: 0, queryCount: 0, bytesScanned: 0, warehouses: [] }; resource.credits += r.credits; resource.usd = sumUsd(resource.usd, r.usd); + resource.priceSource = combinedSource([resource.priceSource, r.priceSource]); resource.seconds += r.seconds; resource.queryCount += r.queryCount; resource.bytesScanned += r.bytesScanned; if (r.warehouseName && !resource.warehouses.includes(r.warehouseName)) resource.warehouses.push(r.warehouseName); resources.set(nodeKey, resource); const warehouseKey = `${r.warehouseName}|${r.warehouseSize}`; - const warehouse = warehouses.get(warehouseKey) ?? { name: r.warehouseName, size: r.warehouseSize, credits: 0, usd: 0, seconds: 0, queryCount: 0 }; + const warehouse = warehouses.get(warehouseKey) ?? { name: r.warehouseName, size: r.warehouseSize, credits: 0, usd: 0, priceSource: null, seconds: 0, queryCount: 0 }; warehouse.credits += r.credits; warehouse.usd = sumUsd(warehouse.usd, r.usd); + warehouse.priceSource = combinedSource([warehouse.priceSource, r.priceSource]); warehouse.seconds += r.seconds; warehouse.queryCount += r.queryCount; warehouses.set(warehouseKey, warehouse); @@ -57,6 +49,7 @@ export function runCostOf(rows: RunCostRow[]): RunCostBreakdown { status, credits: runs.reduce((total, r) => total + r.credits, 0), usd: runs.length === 0 ? null : runs.map((r) => r.usd).reduce(sumUsd), + priceSource: combinedSource(runs.map((r) => r.priceSource)), seconds: runs.reduce((total, r) => total + r.seconds, 0), queryCount: runs.reduce((total, r) => total + r.queryCount, 0), statementsExpected: runs.reduce((total, r) => total + r.statementsExpected, 0), @@ -66,9 +59,37 @@ export function runCostOf(rows: RunCostRow[]): RunCostBreakdown { }; } -/** Dollars when the project priced credits; otherwise credits, so no price is ever guessed. */ -export function formatQueryCost(cost: { credits: number; usd: number | null }): string { - if (cost.usd != null) return cost.usd < 0.01 && cost.usd > 0 ? '< $0.01' : `$${cost.usd.toFixed(2)}`; +/** Where a price per credit came from, as a tooltip says it. */ +export const PRICE_SOURCE_TEXT: Record = { + config: "the project's usd_per_credit", + rate_sheet: "the account's Snowflake rate sheet", + list_price: "Snowflake's list price for the account's region (an estimate)", + mixed: 'several prices' +}; + +/** A price's source as a short label beside it. */ +export const PRICE_SOURCE_LABEL: Record = { config: 'Project price', rate_sheet: 'Rate sheet', list_price: 'List price', mixed: 'Several prices' }; + +/** A list price is an estimate, so its dollars say so. */ +export const isEstimate = (source: PriceSource | null | undefined) => source === 'list_price'; + +/** One source for several: theirs when they agree, the list price when any is one, else `mixed`. */ +export function combinedSource(sources: Iterable): PriceSource | null { + const set = new Set([...sources].filter((s): s is PriceSource => s !== null)); + if (set.size <= 1) return set.values().next().value ?? null; + return set.has('list_price') ? 'list_price' : 'mixed'; +} + +/** A cost figure's tooltip: its credits and the price that made them dollars, with its source. */ +export function costTitle(cost: { credits: number; usd: number | null; priceSource?: PriceSource | null }): string | undefined { + if (cost.usd == null || !cost.credits) return undefined; + const source = cost.priceSource ? ` (${PRICE_SOURCE_TEXT[cost.priceSource]})` : ''; + return `${cost.credits.toFixed(3)} credits × $${(cost.usd / cost.credits).toFixed(2)} per credit${source}`; +} + +/** Dollars when credits have a price, marked `est.` for a list price; otherwise credits, so no price is ever guessed. */ +export function formatQueryCost(cost: { credits: number; usd: number | null; priceSource?: PriceSource | null }): string { + if (cost.usd != null) return `${cost.usd < 0.01 && cost.usd > 0 ? '< $0.01' : `$${cost.usd.toFixed(2)}`}${isEstimate(cost.priceSource) ? ' est.' : ''}`; return `${cost.credits < 0.001 && cost.credits > 0 ? '< 0.001' : cost.credits.toFixed(3)} credits`; } diff --git a/ui/src/lib/operate/labels.test.ts b/ui/src/lib/operate/labels.test.ts index 184e9b6276..ee6f1b6b63 100644 --- a/ui/src/lib/operate/labels.test.ts +++ b/ui/src/lib/operate/labels.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { describeWait, onFailureText, overlapPlain, overlapWhileRunning, poolText, runConcurrencyText, triggerKindLabel, waitTechnical } from './labels'; +import { describeWait, onFailureText, overlapPlain, poolText, runConcurrencyHelp, triggerKindLabel, waitTechnical } from './labels'; import type { QueueWait } from '$lib/api'; const text = (w: QueueWait) => describeWait(w).map((p) => p.text).join(''); @@ -49,14 +49,13 @@ describe('concurrency in plain words', () => { expect(`${clamped.text} (${clamped.detail})`).toBe('Takes the whole warehouse_heavy pool on this server (capped at 1; the project asks for 3)'); }); - it("states a run's concurrency as the limit it applies, for a job and for a group's members", () => { - expect(runConcurrencyText(4, 'job')).toBe("Inside a run: at most 4 of this job's nodes at once"); - expect(runConcurrencyText(1, 'job')).toBe("Inside a run: at most 1 of this job's nodes at once"); - expect(runConcurrencyText(6, 'group')).toBe('Members without their own limit: at most 6 nodes at once'); + it("explains a run's node limit for a job and for a group's members", () => { + expect(runConcurrencyHelp('job')).toBe("At most this many of the job's nodes run together in one run."); + expect(runConcurrencyHelp('group')).toBe('Members without their own limit run at most this many nodes together.'); }); - it('says what a job triggered while it runs does', () => { - expect(overlapWhileRunning).toEqual({ queue: 'waits', skip: 'is skipped' }); + it('names what a job triggered while it runs does', () => { + expect(overlapPlain).toEqual({ queue: 'Queue', skip: 'Skip' }); }); }); diff --git a/ui/src/lib/operate/labels.ts b/ui/src/lib/operate/labels.ts index d82f56c2e3..4f3c9c846f 100644 --- a/ui/src/lib/operate/labels.ts +++ b/ui/src/lib/operate/labels.ts @@ -115,18 +115,13 @@ export const SHARED_SHOWN = 3; export const CONCURRENCY_DOCS = 'https://sqlbuild.com/docs/concepts/concurrency/'; /** - * A run's concurrency as the panel states it. A group's limit is the target's, which each member - * job's run uses unless the job sets its own. + * What the "Nodes at once" limit means. A group's limit is the target's, which each member job's run + * uses unless the job sets its own. */ -export function runConcurrencyText(limit: number, kind: 'job' | 'group'): string { - return kind === 'group' - ? `Members without their own limit: at most ${limit} nodes at once` - : `Inside a run: at most ${limit} of this job's nodes at once`; +export function runConcurrencyHelp(kind: 'job' | 'group'): string { + return kind === 'group' ? 'Members without their own limit run at most this many nodes together.' : "At most this many of the job's nodes run together in one run."; } -/** What a job does when triggered while a run of it is active, finishing "If triggered while running: …". */ -export const overlapWhileRunning: Record = { queue: 'waits', skip: 'is skipped' }; - /** * A pool the job takes, in plain words. Normally "supplier_api: takes 1 of 2", against the limit on * this server, with the cap as a quiet detail when the server lowered the project's limit. When the diff --git a/ui/src/lib/platform/labels.ts b/ui/src/lib/platform/labels.ts index ee659d6832..d248dfaf51 100644 --- a/ui/src/lib/platform/labels.ts +++ b/ui/src/lib/platform/labels.ts @@ -170,3 +170,15 @@ export function eventLinkLabel(link: PlatformEventLink, locations: readonly Loca export function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } + +/** How a discovered set's newest fetch went (`DiscoveredSetStatus`). */ +export const discoveredStatusLabel: Record<'ok' | 'failed' | 'never', string> = { + ok: 'Fetched', + failed: 'Fetch failed', + never: 'Never fetched' +}; +export const discoveredStatusTone: Record<'ok' | 'failed' | 'never', string> = { + ok: 'var(--sb-success)', + failed: 'var(--sb-warning)', + never: 'var(--sb-text-faint)' +}; diff --git a/ui/src/lib/state/resource.svelte.ts b/ui/src/lib/state/resource.svelte.ts index 365d5322f0..dd4189d24f 100644 --- a/ui/src/lib/state/resource.svelte.ts +++ b/ui/src/lib/state/resource.svelte.ts @@ -43,10 +43,19 @@ export type Resource = { export function createResource( load: (client: ApiClient, scope: Scope) => Promise, topics: readonly string[] = [], - /** `every`: the least time between reloads a stream of change signals starts, for a large read. */ - options: { every?: number } = {} + /** + * `every`: the least time between reloads a stream of change signals starts, for a large read. + * `raw`: the answer is kept as it came, not made deeply reactive, for large reads replaced whole. + */ + options: { every?: number; raw?: boolean } = {} ): Resource { - let data = $state(undefined); + let deep = $state(undefined); + let flat = $state.raw(undefined); + const read = (): T | undefined => (options.raw ? flat : deep); + const write = (value: T | undefined) => { + if (options.raw) flat = value; + else deep = value; + }; let error = $state(null); let loading = $state(true); let shownKey = ''; @@ -61,7 +70,7 @@ export function createResource( started = Date.now(); // The page's path and query tell apart reads of different jobs, runs and filters made by the same code. const key = `${app.user?.name ?? ''}|${scope.locationId}|${browser ? window.location.pathname + window.location.search : ''}|${load}`; - if (key !== shownKey && remembered.has(key)) data = remembered.get(key) as T; + if (key !== shownKey && remembered.has(key)) write(remembered.get(key) as T); shownKey = key; loading = true; const done = () => { @@ -75,7 +84,7 @@ export function createResource( (value) => { if (request !== latest) return; remember(key, value); - data = value; + write(value); error = null; loading = false; done(); @@ -85,7 +94,7 @@ export function createResource( // A refusal also drops the earlier answer, so a person whose access went sees the refusal, not old data. if (isRefusal(reason)) { remembered.delete(key); - data = undefined; + write(undefined); } error = reason instanceof Error ? reason.message : String(reason); loading = false; @@ -127,7 +136,7 @@ export function createResource( return { get data() { - return data; + return read(); }, get error() { return error; diff --git a/ui/src/lib/state/selection.svelte.ts b/ui/src/lib/state/selection.svelte.ts index d152baa53c..06576028f9 100644 --- a/ui/src/lib/state/selection.svelte.ts +++ b/ui/src/lib/state/selection.svelte.ts @@ -7,8 +7,12 @@ import { goto } from '$app/navigation'; import { page } from '$app/state'; import type { ApiClient, Scope, SelectionEvaluation, SelectionVocabulary } from '$lib/api'; import { readSelectionParams, writeSelectionParams, type Selection } from '$lib/selection/command'; +import { untrack } from 'svelte'; import { app } from './app.svelte'; +/** A selection's text with its spacing evened out, for comparing. */ +const squash = (text: string) => text.split(/\s+/).filter(Boolean).join(' '); + /** Typing pauses this long before a selection is evaluated. */ export const EVALUATE_DELAY_MS = 150; /** Keys read per request; the server allows up to 10,000. */ @@ -62,8 +66,9 @@ export type SelectionState = ReturnType; * A selection bar's state. Must be created during component initialisation. With `url`, the * selection starts from (unless `initial` is given) and is kept in the page's `?select=…&exclude=…`; * the older parameters in `replaces`, read into `initial` by the page, are dropped from the URL. + * With `follow`, links and Back that change the URL's selection change it here too. */ -export function createSelection(options: { url?: boolean; initial?: Selection; replaces?: string[] } = {}) { +export function createSelection(options: { url?: boolean; follow?: boolean; initial?: Selection; replaces?: string[] } = {}) { const start = options.initial ?? (options.url ? readSelectionParams(page.url.searchParams) : { select: '', exclude: '' }); let select = $state(start.select); let exclude = $state(start.exclude); @@ -141,6 +146,20 @@ export function createSelection(options: { url?: boolean; initial?: Selection; r return () => clearTimeout(timer); }); + if (options.follow) { + // Links and Back change the URL: take the selection from it, unless it already says the same. + let seen = page.url.search; + $effect(() => { + const search = page.url.search; + if (search === seen) return; + seen = search; + const linked = readSelectionParams(page.url.searchParams); + untrack(() => { + if (squash(linked.select) !== squash(select)) select = linked.select; + if (squash(linked.exclude) !== squash(exclude)) exclude = linked.exclude; + }); + }); + } if (options.url) { $effect(() => { const params = writeSelectionParams(page.url.searchParams, { select, exclude }); diff --git a/ui/src/routes/+page.svelte b/ui/src/routes/+page.svelte index 9044711f2f..d1b8d5f0a4 100644 --- a/ui/src/routes/+page.svelte +++ b/ui/src/routes/+page.svelte @@ -28,11 +28,10 @@ import { attentionViews, type AttentionTone } from '$lib/build-area/attention'; import type { AttentionItem, Overview } from '$lib/api'; import { CLEARED_REASON, acknowledgementOf, clearedWithdrawalId, judgedRead, snoozeWords, withdrawalsDue, type JudgedRead } from '$lib/build-area/attention-conditions'; - import { formatCredits } from '$lib/build-area/labels'; import { nodeChangeLine, summarizeChange } from '$lib/build-area/changes'; import { cappedFolders, quietDeployLine, recentDeployRows } from '$lib/build-area/overview-panels'; import { pagesBeyondTarget } from '$lib/nav'; - import OverviewCost from './overview-cost.svelte'; + import { CREDIT_PRICE_HINT, costTitle, formatQueryCost, reportsCost } from '$lib/operate/cost'; const catalog = useCatalogNodes(); /** Each top-level folder as a selection, for the folder rows' links to the catalog. */ @@ -165,7 +164,10 @@ const m = $derived(data?.metrics); const finished = $derived(m ? m.runs24h.success + m.runs24h.warn + m.runs24h.partial + m.runs24h.failed : 0); const successRate = $derived(m && finished ? Math.round(((m.runs24h.success + m.runs24h.warn) / finished) * 100) : null); - const costChange = $derived(m?.cost && m.cost.baseline ? Math.round(((m.cost.last24h - m.cost.baseline) / m.cost.baseline) * 100) : null); + // The last 7 days' query cost, for locations whose adapter reports cost and once any run has some. + const showCost = $derived(reportsCost(app.location?.target.adapter) && app.client.supports('getCostSummary')); + const costWeek = createResource((client, scope) => (showCost ? client.getCostSummary(scope, 7).catch(() => null) : Promise.resolve(null)), ['runs', 'warehouse_sync', 'snapshot']); + const weekCost = $derived(costWeek.data?.runs ? costWeek.data : null); const groups = $derived(data?.groups ?? []); // At most eight folders, most urgent first; the catalog's folder view lists them all. const folders = $derived(cappedFolders(groups)); @@ -309,7 +311,7 @@

    {acknowledgeError}

    {/if} -
    +
    {#if m}
    Models @@ -333,11 +335,11 @@ {m.stale.changed} changed · {m.stale.behind} behind{#if m.stale.sources !== null} · {plural(m.stale.sources, 'source')} late{/if}
    {/if} - {#if m.cost} -
    - Cost · 24h -
    {formatCredits(m.cost.last24h)}
    - = 20}>{costChange === null ? '—' : `${costChange >= 0 ? '+' : ''}${costChange}%`} vs {m.cost.baselineDays}-day average + {#if weekCost} +
    + Cost · 7 days{#if weekCost.usd === null}{/if} +
    {formatQueryCost(weekCost)}
    + {plural(weekCost.runs, 'run')} · By job and folder
    {/if} {/if} @@ -405,11 +407,10 @@

    Activity

    Past and upcoming
    Open full timeline →
    - +
    {/if} -
    {/if} diff --git a/ui/src/routes/admin/people/key-reveal.svelte b/ui/src/routes/admin/people/key-reveal.svelte index 7d5758c7be..c7bdd0a435 100644 --- a/ui/src/routes/admin/people/key-reveal.svelte +++ b/ui/src/routes/admin/people/key-reveal.svelte @@ -1,18 +1,18 @@ diff --git a/ui/src/routes/admin/people/service-account-panel.svelte b/ui/src/routes/admin/people/service-account-panel.svelte index a6fe5a8639..bcfdb86791 100644 --- a/ui/src/routes/admin/people/service-account-panel.svelte +++ b/ui/src/routes/admin/people/service-account-panel.svelte @@ -139,7 +139,7 @@ {/if} {:else} -
  • No working key. Rotate to create one.
  • +
  • No working key.
  • {/each} {#if canManage} diff --git a/ui/src/routes/admin/people/service-accounts-tab.svelte b/ui/src/routes/admin/people/service-accounts-tab.svelte index 3e32180b67..278b626b43 100644 --- a/ui/src/routes/admin/people/service-accounts-tab.svelte +++ b/ui/src/routes/admin/people/service-accounts-tab.svelte @@ -8,6 +8,7 @@ import RelativeTime from '$lib/components/list/relative-time.svelte'; import StatusLabel from '$lib/components/list/status-label.svelte'; import Button from '$lib/components/ui/button/button.svelte'; + import HelpTip from '$lib/components/help-tip.svelte'; import { formatAgo, formatIn, formatStamp } from '$lib/format/time'; import { app } from '$lib/state/app.svelte'; import AddServiceAccountDialog from './add-service-account-dialog.svelte'; @@ -18,6 +19,8 @@ let { sa }: { sa: ServiceAccountsState } = $props(); + const SERVICE_ACCOUNT_DOCS = 'https://sqlbuild.com/docs/cli/server/#call-the-server-from-scripts-with-service-accounts'; + const canAdd = $derived(app.can('user.manage') && app.can('role.assign')); let query = $state(''); const shown = $derived.by(() => { @@ -62,12 +65,16 @@
    -
    No service accounts yet
    -

    A service account lets a script or system call SQLBuild with an API key, such as a deploy that republishes after each release. Its actions appear in the audit log under its own name.

    +
    + No service accounts yet. + +

    A service account lets a script or system call SQLBuild with an API key, such as a deploy that republishes after each release. Its actions appear in the audit log under its own name.

    +

    CLI: sqb admin create-service-account <name> --role <role>

    +
    +
    {#if canAdd} {/if} -

    From a terminal: sqb admin create-service-account <name> --role <role>

    @@ -165,11 +172,11 @@ white-space: normal; } .empty-title { + display: inline-flex; + align-items: center; + gap: 6px; color: var(--foreground); font-size: 14px; font-weight: 600; } - .empty p { - margin: 0; - } diff --git a/ui/src/routes/catalog/[name]/runs-tab.svelte b/ui/src/routes/catalog/[name]/runs-tab.svelte index 14429447c0..40207bd08c 100644 --- a/ui/src/routes/catalog/[name]/runs-tab.svelte +++ b/ui/src/routes/catalog/[name]/runs-tab.svelte @@ -5,6 +5,7 @@ import type { CatalogNodeDetail, NodeBuildCost } from '$lib/api'; import { CREDIT_PRICE_HINT, formatQueryCost } from '$lib/operate/cost'; import CostChart from './cost-chart.svelte'; + import HelpTip from '$lib/components/help-tip.svelte'; import StatusLabel from '$lib/components/list/status-label.svelte'; import RelativeTime from '$lib/components/list/relative-time.svelte'; import { app } from '$lib/state/app.svelte'; @@ -31,7 +32,7 @@ {#if costs.length} - {#if costs.some((c) => c.usd === null)}

    {CREDIT_PRICE_HINT}

    {/if} + {#if costs.some((c) => c.usd === null)}

    In credits

    {/if} {/if} ({ ...r, i }))} key={(r) => `${r.runId ?? r.fingerprintRunId}-${r.i}`} empty="No builds yet."> diff --git a/ui/src/routes/connections/+page.svelte b/ui/src/routes/connections/+page.svelte index 3784ddeadb..ceaf520673 100644 --- a/ui/src/routes/connections/+page.svelte +++ b/ui/src/routes/connections/+page.svelte @@ -1,202 +1,160 @@ - connections.refresh()} /> + - - {#if connections.error} -

    Couldn't load connections: {connections.error}

    - {/if} - - {#each groups as g (g.key)} - -
    -
    - - {g.users.length === 1 ? `${g.users[0].location} · ${g.users[0].target}` : `${g.users.length} targets`} -
    -
    - {#each detailRows(g.details) as row (row.label)} -
    {row.label}
    {row.value ?? '—'}
    - {/each} -
    - {#if !g.details}

    Settings not published

    {/if} - c.id} empty="No location uses this connection."> - {#snippet row(c)} - - {c.location} · {c.target} - {#if c.stateLocation}{where(c.stateLocation)}{:else}Not reported yet{/if} - - {#if c.lastTest} - - {:else} - Not checked yet - {/if} - - connections.refresh()} /> - - {/snippet} - -
    -
    + - {#each g.users as c (c.id)} - {@const failing = failingTables(c.tables)} - 1 ? `${c.location} · ${c.target}` : undefined}> -
    - {#if c.tables.length} - (openSyncs[c.id] = !openSyncs[c.id])} class="w-full gap-2 text-[12.5px]"> - {syncSummary(c, app.now)} - {#if failing}{/if} - - {#if openSyncs[c.id]} - t.table} empty="No state tables reported."> - {#snippet row(t)} - - {t.table} - - - {#if t.failure}{:else}{/if} - - {#if t.error}

    {t.error}

    {/if} - - {formatNumber(t.mirroredTotal)} - {formatNumber(t.recordsSent)} - {formatMs(t.elapsedMs)} - {t.lastSyncedAt ? formatAgo(t.lastSyncedAt, app.now) : 'never'} - - {/snippet} -
    - {/if} - {:else} -

    No warehouse sync reported yet.

    - {/if} + c.id} resource={conn.resource} empty={all.length ? 'No connections match the search.' : 'Nothing reported yet.'}> + {#snippet row(c)} + {@const bad = failing(c.tables)} + {@const fullAt = lastFullSync(c.tables)} + toggle(c)}> + +
    + +
    + {targetName(c)} +
    {subtitle(c.group)}
    +
    +
    - - {/each} - {:else} - {#if connections.data}

    Nothing reported yet.

    {:else if !connections.error}{/if} - {/each} - + + + + {#if !c.tables.length} + + {:else if bad} + + {:else} + + {/if} + {#if fullAt}
    full sync {formatAgo(fullAt, app.now)}
    {/if} + + e.stopPropagation()}> +
    + + + {#if isOpen(c)} + + +
    +
    + + {#snippet location()}{targetName(c)}{/snippet} + +
    +
    +

    State history sync

    + +
    +
    + + + {/if} + {/snippet} +
    diff --git a/ui/src/routes/connections/check-status.svelte b/ui/src/routes/connections/check-status.svelte new file mode 100644 index 0000000000..d191b23585 --- /dev/null +++ b/ui/src/routes/connections/check-status.svelte @@ -0,0 +1,36 @@ + + +{#if test} + + + {checkOrigin(test)} + +{:else} + +{/if} + + diff --git a/ui/src/routes/connections/state.svelte.ts b/ui/src/routes/connections/state.svelte.ts new file mode 100644 index 0000000000..6ec8ac06f2 --- /dev/null +++ b/ui/src/routes/connections/state.svelte.ts @@ -0,0 +1,17 @@ +import { groupConnections } from '$lib/platform/connections'; +import { createResource } from '$lib/state/resource.svelte'; + +/** The connections, grouped by their published settings. */ +export function createConnectionsState() { + const resource = createResource((client) => client.listWarehouseConnections(), ['warehouse_sync']); + const groups = $derived(groupConnections(resource.data ?? [])); + return { + get resource() { + return resource; + }, + get groups() { + return groups; + }, + refresh: () => resource.refresh() + }; +} diff --git a/ui/src/routes/connections/sync-tables.svelte b/ui/src/routes/connections/sync-tables.svelte new file mode 100644 index 0000000000..ed9c1a065a --- /dev/null +++ b/ui/src/routes/connections/sync-tables.svelte @@ -0,0 +1,122 @@ + + +
    + {#if rows.length} + t.table} empty="No tables reported."> + {#snippet row(t)} + + {t.table} + + {#if t.waiting}{:else if t.failure}{:else}{/if} + + {formatNumber(t.mirroredTotal)} + {formatNumber(t.recordsSent)} + {formatMs(t.elapsedMs)} + {t.lastSyncedAt ? formatAgo(t.lastSyncedAt, app.now) : 'Never'} + + {#if t.failure} + + + {t.failure} + {#if t.error}{t.error}{/if} + + + {/if} + {/snippet} + + {/if} + {#if clean.length} + (open = !open)} class="more text-[12.5px]"> + {plural(clean.length, problems.length ? 'more table' : 'table')}{#if cleanAt} synced {formatAgo(cleanAt, app.now)}{/if} + + {:else if !tables.length} +

    No sync reported yet.

    + {/if} +
    + + diff --git a/ui/src/routes/connections/utils/connections.ts b/ui/src/routes/connections/utils/connections.ts new file mode 100644 index 0000000000..ef9b61b5a6 --- /dev/null +++ b/ui/src/routes/connections/utils/connections.ts @@ -0,0 +1,62 @@ +// The Connections page's facts about checks, tables and sync. Pure. + +import type { ConnectionTest, WarehouseConnection } from '$lib/api'; +import { formatCount, lastFullSync } from '$lib/platform/connections'; +import { formatAgo, formatIn, formatStamp } from '$lib/format/time'; + +export type Table = WarehouseConnection['tables'][number]; + +/** e.g. `WAFFLE_SHOP.sqlbuild`. */ +export const where = (s: { database: string | null; schema: string }) => (s.database ? `${s.database}.${s.schema}` : s.schema); + +/** e.g. "waffle-shop · prod". */ +export const targetName = (c: Pick) => `${c.location} · ${c.target}`; + +const TRIGGER: Record = { startup: 'on startup', publish: 'after deploy', manual: 'manual' }; + +/** e.g. "Passed 3h ago". */ +export const checkWords = (t: ConnectionTest, now: number) => `${t.outcome === 'ok' ? 'Passed' : 'Failed'} ${formatAgo(t.at, now)}`; + +/** e.g. "after deploy · 820 ms". */ +export const checkOrigin = (t: ConnectionTest) => [TRIGGER[t.trigger], t.durationMs > 0 ? `${t.durationMs.toLocaleString('en')} ms` : null].filter(Boolean).join(' · '); + +/** The tooltip: exact time and the location's own message. */ +export const checkTitle = (t: ConnectionTest) => `${formatStamp(t.at)}\n${t.message}`; + +/** A table whose newest sync failed or waits for a build. */ +export const isProblem = (t: Table) => !!t.failure; +export const failing = (tables: readonly Table[]) => tables.filter((t) => t.failure && !t.waiting).length; + +/** Problems first, then by name. */ +export const bySeverity = (tables: readonly Table[]) => + [...tables].sort((a, b) => Number(isProblem(b)) - Number(isProblem(a)) || Number(!b.waiting) - Number(!a.waiting) || a.table.localeCompare(b.table)); + +/** The oldest newest-sync among tables that synced cleanly, e.g. for "13 synced 4m ago". */ +export function oldestClean(tables: readonly Table[]): string | null { + const ok = tables.filter((t) => !t.failure).map((t) => t.at); + return ok.length ? ok.reduce((a, b) => (Date.parse(a) <= Date.parse(b) ? a : b)) : null; +} + +/** Records mirrored in total; null when any table has not reported. */ +export function mirrored(tables: readonly Table[]): string | null { + if (!tables.length || tables.some((t) => t.mirroredTotal === null)) return null; + return formatCount(tables.reduce((sum, t) => sum + t.mirroredTotal!, 0)); +} + +export type Fact = { label: string; value: string; title?: string; tone?: string; help?: string }; + +/** The sync's facts as key-value rows, one fact each. */ +export function syncFacts(c: WarehouseConnection, now: number): Fact[] { + const full = lastFullSync(c.tables); + const total = mirrored(c.tables); + const facts: (Fact | null)[] = [ + { label: 'Last full sync', value: full ? formatAgo(full, now) : 'None yet', title: full ? formatStamp(full) : undefined, help: 'When every table last synced cleanly' }, + total ? { label: 'Records mirrored', value: total } : null, + c.halted + ? { label: 'Next sync', value: c.nextSyncAt ? `Stopped · retry ${formatIn(c.nextSyncAt, now)}` : 'Stopped', tone: 'var(--sb-error)', help: 'Failed reads in a row stopped the sync. It resumes at the retry time, or after the next run, a sync request or a deploy.' } + : c.nextSyncAt + ? { label: 'Next sync', value: formatIn(c.nextSyncAt, now), title: formatStamp(c.nextSyncAt) } + : null + ]; + return facts.filter((f): f is Fact => !!f); +} diff --git a/ui/src/routes/cost/+page.svelte b/ui/src/routes/cost/+page.svelte new file mode 100644 index 0000000000..35f6ef3b78 --- /dev/null +++ b/ui/src/routes/cost/+page.svelte @@ -0,0 +1,64 @@ + + + + {#if reports} + ({ value: String(d), label: `${d} days` }))} onselect={setDays} /> + cost.refresh()} /> + {/if} + + +{#if !reports} +
    Query cost is reported for Snowflake only.
    +{:else if cost.data} +
    +{:else if cost.error} + +{:else} + +{/if} + + diff --git a/ui/src/routes/cost/cost-view.svelte b/ui/src/routes/cost/cost-view.svelte new file mode 100644 index 0000000000..9b02e4da62 --- /dev/null +++ b/ui/src/routes/cost/cost-view.svelte @@ -0,0 +1,250 @@ + + + + + +
    + + {#if !refused} +
    +
    +
    {#if levelTrend}{/if}
    +
    + {/if} +
    +
    + {#if !place.job && !place.folder && !place.base.length} nav(href(selection.select, { by: v === 'folder' ? 'folder' : null }))} />{/if} + {#if inJob} nav(href(selection.select, { flat: v === 'flat' ? '1' : null }))} />{/if} + {count(topRows)} {topRows === 1 ? 'row' : 'rows'} + {#if series.failed}Daily cost failed to load: {series.failed}{/if} + + + +
    +
    + href(selection.select, { flat: '1' }) : undefined} ontoggle={toggle} selected={modelKey} {trend} onadd={add} {dayTitle} onwindow={(r) => (range = r)} onfollow={follow} empty={refused ? 'No nodes selected.' : 'No cost in this period.'} /> + {#if modelKey && modelTotal && !refused} + + {/if} +
    + + diff --git a/ui/src/routes/cost/drill/drill-table.svelte b/ui/src/routes/cost/drill/drill-table.svelte new file mode 100644 index 0000000000..ac1522e69e --- /dev/null +++ b/ui/src/routes/cost/drill/drill-table.svelte @@ -0,0 +1,191 @@ + + + + slots.get(r) ?? r.id} rowHeight={36} windowAbove={embedded ? undefined : 0} overscan={4} {empty} {onwindow}> + {#snippet row(t)} + {#if 'more' in t} + +
    {#if moreHref}{count(t.more)} more models →{:else}{count(t.more)} more models{/if}
    + {#each columns.slice(1) as col (col.id)}{/each} + + {:else} + {@const r = t.row} + {@const c = change(r.credits, r.previous)} + {@const href = hrefOf(r, t.id)} + {@const opens = !!ontoggle && r.deeper} + {@const days = trend?.(r, t.id) ?? null} + {@const spark = days ? sparkPaths(days) : NO_SPARK} + + + rowClick(e, t)} onkeydown={(e) => rowKey(e, t)}> + +
    + + + + + href && onfollow?.(e, href)}>{r.label} + {r.sub ?? (r.kind === 'model' ? '' : count(r.models))} + + +
    + + {money(r.credits, price)} + + {count(r.runs)} + {#if !narrow} + {count(r.queries)} + {c?.text ?? '—'} + {/if} + {#if trend} + + days && dayTip(e, days)}> + Cost per day of {r.label} + + + + + {/if} + + {/if} + {/snippet} +
    + + diff --git a/ui/src/routes/cost/drill/level-strip.svelte b/ui/src/routes/cost/drill/level-strip.svelte new file mode 100644 index 0000000000..326f4270e5 --- /dev/null +++ b/ui/src/routes/cost/drill/level-strip.svelte @@ -0,0 +1,46 @@ + + +
    +
    +
    Cost · {days} days
    +
    {money(totals.credits, price)}{#if isEstimate(price?.source)}est.{/if}
    +
    +
    Share of total
    {sharePct(totals.credits, whole)}
    +
    Change
    {c?.text ?? '—'}
    +
    Runs
    {count(totals.runs)}
    +
    Queries
    {count(totals.queries)}
    +
    Models
    {count(totals.models)}
    +
    Warehouse time
    {hours(totals.seconds)}
    +
    + {#if price} +
    Price
    +
    ${price.usdPerCredit.toFixed(2)} per credit{#if isEstimate(price.source)}est.{/if} {PRICE_SOURCE_LABEL[price.source]}
    + {:else} +
    Price
    +
    Not set
    + {/if} +
    +
    + + diff --git a/ui/src/routes/cost/drill/model-detail.svelte b/ui/src/routes/cost/drill/model-detail.svelte new file mode 100644 index 0000000000..ca23497ff0 --- /dev/null +++ b/ui/src/routes/cost/drill/model-detail.svelte @@ -0,0 +1,72 @@ + + +
    + + {#if daily}{:else}
    {/if} +
    + + jobHref(r)} embedded selected={job} narrow /> + + + r.buildRunId} resource={runs} empty="No runs in this period."> + {#snippet row(r)} + + {#if r.runId}{r.runId.slice(0, 8)}{:else}{MANUAL_LABEL}{/if} + {money(r.credits, price)} + {hours(r.seconds)} + + + {/snippet} + + {#if sorted.length > 8}{/if} + + Open in the catalog → +
    + + diff --git a/ui/src/routes/cost/drill/trend-area.svelte b/ui/src/routes/cost/drill/trend-area.svelte new file mode 100644 index 0000000000..0394984b5e --- /dev/null +++ b/ui/src/routes/cost/drill/trend-area.svelte @@ -0,0 +1,42 @@ + + + + + diff --git a/ui/src/routes/cost/series.svelte.ts b/ui/src/routes/cost/series.svelte.ts new file mode 100644 index 0000000000..52f1882127 --- /dev/null +++ b/ui/src/routes/cost/series.svelte.ts @@ -0,0 +1,56 @@ +// Daily series for rows deeper than jobs and top-level folders, read in batches of up to 200 groups +// as rows come into view, and kept until the read they belong to changes. + +import type { ApiClient, CostSelectionQuery, CostSeriesGroup, Scope } from '$lib/api'; + +/** The most groups one read asks for; the server's limit. */ +const BATCH = 200; + +export const groupKey = (g: CostSeriesGroup) => `${g.manual ? '\u0001' : (g.job ?? '')}\u0000${g.folder ?? ''}\u0000${g.nodeKey ?? ''}`; + +export function createSeries() { + let held = new Map(); + let asked = new Set(); + let read = ''; + let version = $state(0); + let failed = $state(null); + + return { + /** A group's series, once read; null while unknown. */ + get(group: CostSeriesGroup): readonly number[] | null { + void version; + return held.get(groupKey(group)) ?? null; + }, + get failed() { + return failed; + }, + /** Reads the groups not yet read or asked for, for `query` at `scope`; a new query drops what was held. */ + want(client: ApiClient, scope: Scope, query: CostSelectionQuery, groups: CostSeriesGroup[]) { + const at = `${scope.locationId}\u0000${query.days}\u0000${query.select}\u0000${query.exclude}`; + if (at !== read) { + read = at; + held = new Map(); + asked = new Set(); + failed = null; + version += 1; + } + const missing = groups.filter((g) => !asked.has(groupKey(g))); + for (const g of missing) asked.add(groupKey(g)); + for (let i = 0; i < missing.length; i += BATCH) { + const batch = missing.slice(i, i + BATCH); + client.readCostSeries(scope, query, batch).then( + (series) => { + if (read !== at) return; + batch.forEach((g, n) => held.set(groupKey(g), series[n] ?? [])); + version += 1; + }, + (error: unknown) => { + if (read !== at) return; + for (const g of batch) asked.delete(groupKey(g)); + failed = error instanceof Error ? error.message : String(error); + } + ); + } + } + }; +} diff --git a/ui/src/routes/cost/utils/format.ts b/ui/src/routes/cost/utils/format.ts new file mode 100644 index 0000000000..50adb5714f --- /dev/null +++ b/ui/src/routes/cost/utils/format.ts @@ -0,0 +1,72 @@ +// Cost figures: dollars when the read has a price, else credits, so no price is ever guessed; the +// credits and the price in tooltips. Number formats are made once. Pure; no side effects. + +import type { CostPrice, PriceSource } from '$lib/api'; +import { PRICE_SOURCE_TEXT } from '$lib/operate/cost'; + +const whole = new Intl.NumberFormat('en', { maximumFractionDigits: 0 }); +const cents = new Intl.NumberFormat('en', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); +const tenths = new Intl.NumberFormat('en', { minimumFractionDigits: 1, maximumFractionDigits: 1 }); +const shortDay = new Intl.DateTimeFormat('en-GB', { day: 'numeric', timeZone: 'UTC' }); +const longDay = new Intl.DateTimeFormat('en-GB', { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }); + +/** A count, such as runs or queries. */ +export const count = (n: number) => whole.format(n); + +export function creditsText(credits: number): string { + if (credits > 0 && credits < 0.01) return '< 0.01 credits'; + return `${credits < 10 ? cents.format(credits) : credits < 1000 ? tenths.format(credits) : whole.format(credits)} credits`; +} + +/** The figure: dollars (cents below $100, whole dollars above) with a price, else credits. */ +export function money(credits: number, price: CostPrice | null): string { + if (!price) return creditsText(credits); + const v = credits * price.usdPerCredit; + if (v > 0 && v < 0.01) return '< $0.01'; + return `$${v < 100 ? cents.format(v) : whole.format(v)}`; +} + +/** A figure's tooltip: its credits and the price that made it dollars. */ +export function costTitle(credits: number, price: CostPrice | null): string { + return price ? `${creditsText(credits)} × $${cents.format(price.usdPerCredit)} per credit (${PRICE_SOURCE_TEXT[price.source]})` : creditsText(credits); +} + +/** Where a price came from, for its help tip. */ +export const priceHelp = (price: CostPrice): string => PRICE_SOURCE_HELP[price.source]; + +const PRICE_SOURCE_HELP: Record = { + config: 'Set by usd_per_credit under [cost] in sqlbuild_project.toml.', + rate_sheet: "Your contract's price per credit, from Snowflake's rate sheet (ORGANIZATION_USAGE.RATE_SHEET_DAILY).", + list_price: + "An estimate: Snowflake's public on-demand price for the account's region, at Enterprise edition. Set usd_per_credit under [cost] in sqlbuild_project.toml, or let the connection's role read ORGANIZATION_USAGE, for your contract's price.", + mixed: 'Builds in this period were priced from more than one source.' +}; + +/** Change against the period before, or null without a previous figure. */ +export function change(credits: number, previous: number): { text: string; tone: 'up' | 'down' | 'flat' } | null { + if (previous <= 0) return null; + const pct = Math.round(((credits - previous) / previous) * 100); + if (Math.abs(pct) < 3) return { text: '±0%', tone: 'flat' }; + return { text: `${pct > 0 ? '+' : '−'}${whole.format(Math.abs(pct))}%`, tone: pct > 0 ? 'up' : 'down' }; +} + +export const sharePct = (part: number, total: number) => (total <= 0 ? '—' : part > 0 && part / total < 0.005 ? '<1%' : `${Math.round((part / total) * 100)}%`); + +/** Warehouse time: minutes below an hour, then hours. */ +export function hours(seconds: number): string { + if (seconds <= 0) return '—'; + if (seconds < 3600) return `${Math.max(1, Math.round(seconds / 60))}m`; + return seconds < 36_000 ? `${tenths.format(seconds / 3600)}h` : `${whole.format(seconds / 3600)}h`; +} + +export function bytes(n: number): string { + if (n >= 1e12) return `${tenths.format(n / 1e12)} TB`; + if (n >= 1e9) return `${tenths.format(n / 1e9)} GB`; + return `${whole.format(n / 1e6)} MB`; +} + +/** "17" for a chart's day axis, or "Mon, 17 Nov" in full. */ +export function dayLabel(date: string, long = false): string { + if (!date) return ''; + return (long ? longDay : shortDay).format(new Date(`${date}T00:00:00Z`)); +} diff --git a/ui/src/routes/cost/utils/selector.test.ts b/ui/src/routes/cost/utils/selector.test.ts new file mode 100644 index 0000000000..d732c473bb --- /dev/null +++ b/ui/src/routes/cost/utils/selector.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; +import { folderOfPath, pathOfFolder, placeCrumbs, placeOf, selectorOf, union } from './selector'; + +describe('the Cost page’s selection as a place', () => { + it('reads a job, a folder and a model shared by every token', () => { + expect(placeOf('job:nightly,path:sql/models/staging/orders,stg_orders')).toEqual({ base: [], job: 'nightly', folder: 'staging/orders', model: 'stg_orders' }); + expect(placeOf('tag:finance,job:nightly')).toEqual({ base: ['tag:finance'], job: 'nightly', folder: null, model: null }); + }); + + it('keeps what the tree can’t break down as the base: unions, upstream, and any except', () => { + expect(placeOf('+orders')).toEqual({ base: ['+orders'], job: null, folder: null, model: null }); + expect(placeOf('job:nightly', 'tag:pii').base).toEqual(['job:nightly']); + expect(placeOf('job:a job:b').base).toEqual(['job:a', 'job:b']); + }); + + it('writes folders as path selectors under the project layout, and back', () => { + expect(pathOfFolder('staging/orders')).toBe('sql/models/staging/orders'); + expect(pathOfFolder('python/nodes/loaders')).toBe('python/nodes/loaders'); + expect(folderOfPath('sql/models/staging/')).toBe('staging'); + expect(selectorOf({ base: ['tag:finance'], job: 'nightly', folder: 'marts', model: null })).toBe('tag:finance,job:nightly,path:sql/models/marts'); + expect(union('job:a', 'job:b')).toBe('job:a job:b'); + }); + + it('gives a breadcrumb for each step up, each the selection there', () => { + expect(placeCrumbs({ base: [], job: 'nightly', folder: 'staging/orders', model: null }).map((c) => [c.label, c.select])).toEqual([ + ['All', ''], + ['nightly', 'job:nightly'], + ['staging', 'job:nightly,path:sql/models/staging'], + ['orders', 'job:nightly,path:sql/models/staging/orders'] + ]); + }); +}); diff --git a/ui/src/routes/cost/utils/selector.ts b/ui/src/routes/cost/utils/selector.ts new file mode 100644 index 0000000000..e424a76d4f --- /dev/null +++ b/ui/src/routes/cost/utils/selector.ts @@ -0,0 +1,81 @@ +// The Cost page's selection read as a place to stand: a free-form base (anything the tree can't +// break down), then a job, a folder and a model, each a comma part SQLBuild intersects. Drilling +// adds a part to every token; breadcrumbs take parts away. Pure. +import { parseSelection, type Part } from '$lib/selection/syntax'; + +/** A cost folder as `path:` selects it: SQL models under `sql/models/`, other roots (`python/…`, `sql/…`) as they are. */ +export const pathOfFolder = (folder: string) => (/^(python|sql)\//.test(folder) ? folder : `sql/models/${folder}`); +/** A `path:` value as a cost folder: without `sql/models/` and a trailing slash. */ +export const folderOfPath = (path: string) => path.replace(/^sql\/models(\/|$)/, '').replace(/\/$/, ''); + +export type Place = { + /** The free-form tokens, each without the structured parts; empty when the tree covers it all. */ + base: string[]; + job: string | null; + folder: string | null; + model: string | null; +}; + +type Kind = 'job' | 'path' | 'name'; +function kindOf(p: Part): Kind | null { + if (p.up || p.down || p.between) return null; + if (p.type === 'job') return 'job'; + if (p.type === 'path' || (p.type === null && p.value.includes('/'))) return 'path'; + if (p.type === null && !/[*?[]/.test(p.value)) return 'name'; + return null; +} + +/** Splits a selection into its free-form base and the job, folder and model every token shares. */ +export function placeOf(select: string, exclude = ''): Place { + const tokens = parseSelection(select); + const place: Place = { base: [], job: null, folder: null, model: null }; + if (!tokens.length) return place; + if (exclude.trim()) return { ...place, base: tokens.map((t) => t.raw) }; + // The structured parts at the end of every token, the same in each. + const tails = tokens.map((t) => { + const parts = t.parts; + let i = parts.length; + while (i > 0 && kindOf(parts[i - 1])) i--; + return { head: parts.slice(0, i), tail: parts.slice(i) }; + }); + const shared = tails[0].tail.filter((p) => tails.every((t) => t.tail.some((q) => q.raw === p.raw))); + const kinds = shared.map((p) => kindOf(p)!); + if (new Set(kinds).size !== kinds.length) return { ...place, base: tokens.map((t) => t.raw) }; + for (const p of shared) { + const k = kindOf(p); + if (k === 'job') place.job = p.value; + else if (k === 'path') place.folder = folderOfPath(p.value); + else place.model = p.value; + } + place.base = tails.map((t) => [...t.head, ...t.tail.filter((p) => !shared.some((s) => s.raw === p.raw))].map((p) => p.raw).join(',')).filter(Boolean); + // A token that is nothing but the shared parts selects all of them, so nothing is shared after all. + if (place.base.length !== tokens.length && (place.base.length || tokens.length > 1)) return { base: tokens.map((t) => t.raw), job: null, folder: null, model: null }; + return place; +} + +/** The selection for a place: its parts joined to every base token, or on their own. */ +export function selectorOf(place: Place): string { + const parts = [place.job ? `job:${place.job}` : '', place.folder ? `path:${pathOfFolder(place.folder)}` : '', place.model ?? ''].filter(Boolean); + if (!place.base.length) return parts.join(','); + return place.base.map((b) => [b, ...parts].join(',')).join(' '); +} + +/** `select` with another selection unioned in, as `sqb` reads space-separated tokens. */ +export const union = (select: string, more: string) => [select.trim(), more].filter(Boolean).join(' '); + +export type SelectorCrumb = { label: string; select: string; code?: boolean }; + +/** Breadcrumbs: All, the base, the job, each folder down, and the model, each the selection there. */ +export function placeCrumbs(place: Place): SelectorCrumb[] { + const out: SelectorCrumb[] = [{ label: 'All', select: '' }]; + let at: Place = { base: place.base, job: null, folder: null, model: null }; + if (place.base.length) out.push({ label: place.base.join(' '), select: selectorOf(at), code: true }); + if (place.job) out.push({ label: place.job, select: selectorOf((at = { ...at, job: place.job })) }); + if (place.folder) { + const parts = place.folder.split('/'); + parts.forEach((p, i) => out.push({ label: p, select: selectorOf((at = { ...at, folder: parts.slice(0, i + 1).join('/') })) })); + } + if (place.model) out.push({ label: place.model, select: selectorOf({ ...at, model: place.model }) }); + return out; +} + diff --git a/ui/src/routes/cost/utils/smooth.ts b/ui/src/routes/cost/utils/smooth.ts new file mode 100644 index 0000000000..49839b2030 --- /dev/null +++ b/ui/src/routes/cost/utils/smooth.ts @@ -0,0 +1,49 @@ +// Smooth lines through daily points: monotone cubic interpolation (Fritsch–Carlson), which passes +// through every point and never overshoots between them, so a day is never drawn below zero or +// above its neighbours. Pure. + +/** An SVG path through `points`, sorted by x. */ +export function monotonePath(points: readonly [number, number][]): string { + const n = points.length; + if (n === 0) return ''; + if (n === 1) return `M${points[0][0]},${points[0][1]}`; + const dx: number[] = []; + const slope: number[] = []; + for (let i = 0; i < n - 1; i++) { + dx.push(points[i + 1][0] - points[i][0]); + slope.push(dx[i] === 0 ? 0 : (points[i + 1][1] - points[i][1]) / dx[i]); + } + const t: number[] = [slope[0]]; + for (let i = 1; i < n - 1; i++) t.push(slope[i - 1] * slope[i] <= 0 ? 0 : (slope[i - 1] + slope[i]) / 2); + t.push(slope[n - 2]); + for (let i = 0; i < n - 1; i++) { + if (slope[i] === 0) { + t[i] = 0; + t[i + 1] = 0; + continue; + } + const a = t[i] / slope[i]; + const b = t[i + 1] / slope[i]; + const s = a * a + b * b; + if (s > 9) { + const tau = 3 / Math.sqrt(s); + t[i] = tau * a * slope[i]; + t[i + 1] = tau * b * slope[i]; + } + } + let d = `M${points[0][0]},${points[0][1]}`; + for (let i = 0; i < n - 1; i++) { + const [x0, y0] = points[i]; + const [x1, y1] = points[i + 1]; + const h = dx[i] / 3; + d += ` C${x0 + h},${y0 + t[i] * h} ${x1 - h},${y1 - t[i + 1] * h} ${x1},${y1}`; + } + return d; +} + +/** Points for `values` across a `width` × `height` box, the largest at the top less `pad`. */ +export function plot(values: readonly number[], width: number, height: number, pad = 1): [number, number][] { + const max = Math.max(...values, 0) || 1; + const step = values.length > 1 ? width / (values.length - 1) : 0; + return values.map((v, i) => [values.length > 1 ? i * step : width / 2, height - (v / max) * (height - pad * 2) - pad / 2]); +} diff --git a/ui/src/routes/cost/utils/spark.ts b/ui/src/routes/cost/utils/spark.ts new file mode 100644 index 0000000000..023215233f --- /dev/null +++ b/ui/src/routes/cost/utils/spark.ts @@ -0,0 +1,20 @@ +// A row's cost per day as a smooth filled line, its SVG paths worked out once per series. Pure apart +// from the cache, which holds each series' paths while the series is alive. + +import { monotonePath, plot } from './smooth'; + +/** The trend's height in its viewBox; its width is 100. */ +export const SPARK_H = 20; + +const held = new WeakMap(); + +/** The line through `values` and the area under it. */ +export function sparkPaths(values: readonly number[]): { area: string; line: string } { + let paths = held.get(values); + if (!paths) { + const line = monotonePath(plot(values, 100, SPARK_H, 2)); + paths = { line, area: values.length ? `${line} L100,${SPARK_H} L0,${SPARK_H} Z` : '' }; + held.set(values, paths); + } + return paths; +} diff --git a/ui/src/routes/cost/utils/tree.test.ts b/ui/src/routes/cost/utils/tree.test.ts new file mode 100644 index 0000000000..8976088c24 --- /dev/null +++ b/ui/src/routes/cost/utils/tree.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest'; +import type { CostFact } from '$lib/api'; +import { MANUAL, folderIds, indexCost, type Level } from './tree'; + +const fact = (job: string | null, nodeKey: string, folder: string, credits: number, runs = 2): CostFact => ({ + job, + nodeKey, + folder, + credits, + previousCredits: credits / 2, + usd: null, + previousUsd: null, + seconds: credits * 100, + runs, + queries: 3, + bytesScanned: 0 +}); + +const facts = [ + fact('nightly', 'model:stg_orders', 'staging/orders', 4), + fact('nightly', 'model:stg_customers', 'staging/customers', 2), + fact('nightly', 'model:revenue', '', 3), + fact('hourly', 'model:stg_orders', 'staging/orders', 1, 24), + fact(null, 'model:revenue', '', 0.5, 1) +]; +const index = indexCost({ facts }); +const root: Level = { by: 'job', job: null, folder: null, flat: false }; + +describe('the cost tree', () => { + it('lists jobs most expensive first, builds by hand under their own key', () => { + expect(index.children(root).map((r) => [r.key, r.label, r.credits])).toEqual([ + ['nightly', 'nightly', 9], + ['hourly', 'hourly', 1], + [MANUAL, 'By hand or CLI', 0.5] + ]); + }); + + it("lists a job's folders and its top-level models, and a folder's subfolders", () => { + const job: Level = { by: 'job', job: 'nightly', folder: null, flat: false }; + expect(index.children(job).map((r) => [r.kind, r.key, r.credits])).toEqual([ + ['folder', 'staging', 6], + ['model', 'model:revenue', 3] + ]); + expect(index.children({ ...job, folder: 'staging' }).map((r) => r.key)).toEqual(['staging/orders', 'staging/customers']); + expect(index.children({ ...job, flat: true }).map((r) => [r.label, r.sub])).toEqual([ + ['stg_orders', 'staging/orders'], + ['revenue', undefined], + ['stg_customers', 'staging/customers'] + ]); + }); + + it('sums every job by folder, counting each job’s builds once', () => { + const byFolder: Level = { by: 'folder', job: null, folder: null, flat: false }; + const [staging] = index.children(byFolder); + expect([staging.key, staging.credits, staging.runs, staging.models]).toEqual(['staging', 7, 2 + 24, 2]); + expect(index.totals(null, null)).toMatchObject({ credits: 10.5, previous: 5.25, models: 3 }); + expect(index.totals('nightly', 'staging/orders').credits).toBe(4); + expect(index.totals(null, null, 'model:revenue').credits).toBe(3.5); + }); + + it('draws opened rows under theirs, and Expand all opens to a depth', () => { + const open = new Set(['/job:nightly', '/job:nightly/folder:staging']); + const rows = index.rows(root, open); + expect(rows.map((r) => ('row' in r ? `${r.depth}:${r.row.label}` : 'more'))).toEqual(['0:nightly', '1:staging', '2:orders', '2:customers', '1:revenue', '0:hourly', '0:By hand or CLI']); + expect(index.ids(root, 2)).toEqual(['/job:nightly', '/job:nightly/folder:staging', '/job:hourly', '/job:hourly/folder:staging', `/job:${MANUAL}`]); + expect(index.rows({ ...root, by: 'job', job: 'nightly', flat: true }, new Set(), 1).map((r) => ('more' in r ? `+${r.more}` : r.row.label))).toEqual(['stg_orders', '+2']); + }); + + it('names the jobs that spent a model’s cost, and the rows down to its folder', () => { + expect(index.jobsOf('model:stg_orders').map((r) => [r.key, r.credits])).toEqual([ + ['nightly', 4], + ['hourly', 1] + ]); + // Row ids are the path of ids from the level down, as the tree draws them. + expect(folderIds('staging/orders/web', 'staging')).toEqual(['/folder:staging/orders', '/folder:staging/orders/folder:staging/orders/web']); + }); +}); diff --git a/ui/src/routes/cost/utils/tree.ts b/ui/src/routes/cost/utils/tree.ts new file mode 100644 index 0000000000..66a58130f8 --- /dev/null +++ b/ui/src/routes/cost/utils/tree.ts @@ -0,0 +1,225 @@ +// The Cost page's tree: a selection's job-by-model facts indexed once into jobs and folders, so a +// level's children, a row's totals and the rows of a tree opened in place are lookups, not scans. +// Pure; no side effects. + +import type { CostFact, CostSelection } from '$lib/api'; + +/** The job key of builds no server run started, which have no job to select. */ +export const MANUAL = ''; +export const MANUAL_LABEL = 'By hand or CLI'; + +export type Totals = { credits: number; previous: number; seconds: number; runs: number; queries: number; models: number }; + +export type RowKind = 'job' | 'folder' | 'model'; + +/** One row of a level: a job, a folder or a model, with its totals. */ +export type DrillRow = Totals & { + kind: RowKind; + /** The job (`MANUAL` for builds by hand), folder path or model's node key. */ + key: string; + label: string; + /** Whether the row opens onto another level. */ + deeper: boolean; + /** A muted fact after the name, such as a model's folder in a flat list. */ + sub?: string; + /** The job the row is in, if any; `MANUAL` for builds by hand. */ + job: string | null; + /** The folder the row is, or is in. */ + folder: string | null; +}; + +/** A model's name as people read it: its node key without the kind. */ +export const nameOf = (nodeKey: string) => nodeKey.slice(nodeKey.indexOf(':') + 1); + +type Acc = { credits: number; previous: number; seconds: number; queries: number; runs: Map; models: Set }; +const acc = (): Acc => ({ credits: 0, previous: 0, seconds: 0, queries: 0, runs: new Map(), models: new Set() }); + +function add(a: Acc, f: CostFact, job: string) { + a.credits += f.credits; + a.previous += f.previousCredits; + a.seconds += f.seconds; + a.queries += f.queries; + // A job's builds count once however many of its models a group holds. + a.runs.set(job, Math.max(a.runs.get(job) ?? 0, f.runs)); + a.models.add(f.nodeKey); +} + +function totalsOf(a: Acc): Totals { + let runs = 0; + for (const n of a.runs.values()) runs += n; + return { credits: a.credits, previous: a.previous, seconds: a.seconds, queries: a.queries, runs, models: a.models.size }; +} + +type FolderNode = { path: string; acc: Acc; folders: Map; models: Map; rows?: DrillRow[] }; +const folderNode = (path: string): FolderNode => ({ path, acc: acc(), folders: new Map(), models: new Map() }); + +type JobNode = { key: string; acc: Acc; tree: FolderNode; flat?: DrillRow[] }; + +/** Where the table stands: the job and folder it lists, and whether a job's models show without folders. */ +export type Level = { by: 'job' | 'folder'; job: string | null; folder: string | null; flat: boolean }; + +export type TreeRow = { row: DrillRow; depth: number; id: string; open: boolean; parent: number; peak: number } | { more: number; depth: number; id: string }; + +export type CostIndex = { + /** The totals of everything in the read, or of a job, folder or model in it. */ + totals(job: string | null, folder: string | null, model?: string | null): Totals; + children(level: Level): DrillRow[]; + rows(level: Level, open: ReadonlySet, limit?: number): TreeRow[]; + /** Every row id that opens, to a depth, for Expand all. */ + ids(level: Level, depth: number): string[]; + /** The jobs that spent a model's cost, most expensive first. */ + jobsOf(nodeKey: string): DrillRow[]; + /** A model's folder, if the read has it. */ + folderOf(nodeKey: string): string | undefined; +}; + +const segments = (folder: string) => (folder ? folder.split('/') : []); +const inside = (folder: string, base: string | null) => !base || folder === base || folder.startsWith(`${base}/`); +const byCost = (a: DrillRow, b: DrillRow) => b.credits - a.credits; + +/** Indexes a read's facts once: by job, then by folder down to models, and by folder alone. */ +export function indexCost(read: Pick, job: string | null = null): CostIndex { + const all = folderNode(''); + const jobs = new Map(); + const models = new Map>(); + const folders = new Map(); + const everything = acc(); + for (const f of read.facts) { + const jobKey = f.job ?? MANUAL; + // A drilled job narrows the read to its own builds. + if (job !== null && jobKey !== job) continue; + add(everything, f, jobKey); + folders.set(f.nodeKey, f.folder); + let j = jobs.get(jobKey); + if (!j) jobs.set(jobKey, (j = { key: jobKey, acc: acc(), tree: folderNode('') })); + add(j.acc, f, jobKey); + for (const tree of [all, j.tree]) { + let node = tree; + add(node.acc, f, jobKey); + let path = ''; + for (const part of segments(f.folder)) { + path = path ? `${path}/${part}` : part; + let next = node.folders.get(part); + if (!next) node.folders.set(part, (next = folderNode(path))); + node = next; + add(node.acc, f, jobKey); + } + const m = node.models.get(f.nodeKey) ?? node.models.set(f.nodeKey, { acc: acc(), folder: f.folder }).get(f.nodeKey)!; + add(m.acc, f, jobKey); + } + const per = models.get(f.nodeKey) ?? models.set(f.nodeKey, new Map()).get(f.nodeKey)!; + add(per.get(jobKey) ?? per.set(jobKey, acc()).get(jobKey)!, f, jobKey); + } + + const find = (tree: FolderNode, folder: string | null): FolderNode | undefined => { + let node: FolderNode | undefined = tree; + for (const part of segments(folder ?? '')) node = node?.folders.get(part); + return node; + }; + const treeOf = (job: string | null) => (job === null ? all : jobs.get(job)?.tree); + const jobRow = (j: JobNode): DrillRow => ({ kind: 'job', key: j.key, label: j.key === MANUAL ? MANUAL_LABEL : j.key, deeper: true, job: j.key, folder: null, ...totalsOf(j.acc) }); + const folderRows = (node: FolderNode, job: string | null): DrillRow[] => + (node.rows ??= [ + ...[...node.folders.values()].map((n): DrillRow => ({ kind: 'folder', key: n.path, label: n.path.split('/').at(-1)!, deeper: true, job, folder: n.path, ...totalsOf(n.acc) })), + ...[...node.models].map(([key, m]): DrillRow => ({ kind: 'model', key, label: nameOf(key), deeper: false, job, folder: m.folder, ...totalsOf(m.acc) })) + ].sort(byCost)); + const flatRows = (j: JobNode): DrillRow[] => { + if (j.flat) return j.flat; + const out: DrillRow[] = []; + const walk = (node: FolderNode) => { + for (const [key, m] of node.models) out.push({ kind: 'model', key, label: nameOf(key), deeper: false, sub: m.folder || undefined, job: j.key, folder: m.folder, ...totalsOf(m.acc) }); + for (const n of node.folders.values()) walk(n); + }; + walk(j.tree); + return (j.flat = out.sort(byCost)); + }; + let jobRows: DrillRow[] | undefined; + const children = (level: Level): DrillRow[] => { + if (level.by === 'job' && level.job === null) return (jobRows ??= [...jobs.values()].map(jobRow).sort(byCost)); + if (level.flat && level.job !== null) { + const j = jobs.get(level.job); + return j ? flatRows(j).filter((r) => inside(r.folder ?? '', level.folder)) : []; + } + const tree = treeOf(level.by === 'job' ? level.job : null); + const node = tree && find(tree, level.folder); + return node ? folderRows(node, level.by === 'job' ? level.job : null) : []; + }; + /** The level a row opens onto. */ + const below = (level: Level, row: DrillRow): Level => (row.kind === 'job' ? { by: 'job', job: row.key, folder: null, flat: false } : { ...level, folder: row.key, flat: false }); + + return { + totals(job, folder, model = null) { + if (model) { + const per = models.get(model); + const a = acc(); + for (const [j, m] of per ?? []) { + if (job !== null && j !== job) continue; + a.credits += m.credits; + a.previous += m.previous; + a.seconds += m.seconds; + a.queries += m.queries; + for (const [k, n] of m.runs) a.runs.set(k, n); + a.models.add(model); + } + return totalsOf(a); + } + if (job === null && folder === null) return totalsOf(everything); + const tree = treeOf(job); + const node = tree && find(tree, folder); + return node ? totalsOf(node.acc) : totalsOf(acc()); + }, + children, + rows(level, open, limit = 25) { + const out: TreeRow[] = []; + const walk = (at: Level, parent: number, depth: number, path: string) => { + const kids = children(at); + const peak = kids[0]?.credits ?? 0; + let shown = 0; + let hidden = 0; + for (const row of kids) { + if (row.kind === 'model' && ++shown > limit) { + hidden += 1; + continue; + } + const id = `${path}/${row.kind}:${row.key}`; + const isOpen = row.deeper && open.has(id); + out.push({ row, depth, id, open: isOpen, parent, peak }); + if (isOpen) walk(below(at, row), row.credits, depth + 1, id); + } + if (hidden) out.push({ more: hidden, depth, id: `${path}/more` }); + }; + walk(level, this.totals(level.by === 'job' ? level.job : null, level.folder).credits, 0, ''); + return out; + }, + ids(level, depth) { + const ids: string[] = []; + const walk = (at: Level, d: number, path: string) => { + if (d >= depth) return; + for (const row of children(at)) { + if (!row.deeper) continue; + const id = `${path}/${row.kind}:${row.key}`; + ids.push(id); + walk(below(at, row), d + 1, id); + } + }; + walk(level, 0, ''); + return ids; + }, + jobsOf(nodeKey) { + const per = models.get(nodeKey); + if (!per) return []; + return [...per].map(([j, a]): DrillRow => ({ kind: 'job', key: j, label: j === MANUAL ? MANUAL_LABEL : j, deeper: false, job: j, folder: null, ...totalsOf(a) })).sort(byCost); + }, + folderOf: (nodeKey) => folders.get(nodeKey) + }; +} + +/** The tree row ids from the top down to a model's folder, for opening its ancestors. */ +export function folderIds(folder: string, from: string | null): string[] { + const parts = segments(folder); + const start = segments(from ?? '').length; + const ids: string[] = []; + let path = ''; + for (let i = start; i < parts.length; i++) ids.push((path += `/folder:${parts.slice(0, i + 1).join('/')}`)); + return ids; +} diff --git a/ui/src/routes/jobs/+page.svelte b/ui/src/routes/jobs/+page.svelte index c5667d8cc7..c22428cfc1 100644 --- a/ui/src/routes/jobs/+page.svelte +++ b/ui/src/routes/jobs/+page.svelte @@ -19,12 +19,8 @@ import { formatAgo, formatStamp } from '$lib/format/time'; import { isActiveRun, isProblemRun, runStatusLabel, runStatusTone } from '$lib/status'; import { jobPolicyText, overlapHelp } from '$lib/operate/labels'; - import { capItems, capLines, ownerChip, selectionTokens } from './utils'; - - /** Group members drawn on the first line; the rest fold into "+N more" on the second. */ - const MEMBERS_SHOWN = 3; - /** Selection tokens drawn as pills; the rest fold into "+N more". */ - const TOKENS_SHOWN = 4; + import FittingItems from '$lib/components/list/fitting-items.svelte'; + import { ownerChip, selectionTokens } from './utils'; const jobs = createResource((client, scope) => client.listJobs(scope), ['jobs', 'runs', 'snapshot']); const triggers = createResource((client, scope) => client.listTriggers(scope), ['triggers', 'ticks']); @@ -132,21 +128,13 @@ {#if showSelection} {#if j.kind === 'group'} - {@const members = capItems(j.members ?? [], MEMBERS_SHOWN)} -
    Group{#if members.shown.length} · {members.shown.join(', ')}{/if}
    - {#if members.hidden.length} - e.stopPropagation()}>+{members.hidden.length} more - {/if} + + {#snippet item(member)}{member}{/snippet} + {:else} - {@const tokens = capItems(selectionTokens(j.select), TOKENS_SHOWN)} -
    - {#each tokens.shown as tok, i (i)} - {#if tok.prefix}{tok.prefix}{/if}{tok.name} - {/each} - {#if tokens.hidden.length} - t.token).join('\n')}>+{tokens.hidden.length} more - {/if} -
    + + {#snippet item(tok)}{#if tok.prefix}{tok.prefix}{/if}{tok.name}{/snippet} + {/if} {/if} @@ -156,10 +144,9 @@ {#if jobTriggers.length === 0} Manual {:else} - {@const capped = capLines(jobTriggers)} -
    - {#each capped.shown as t (t.id)} -
    + + {#snippet item(t)} + {t.name} -
    - {/each} - {#if capped.hidden.length} - `${t.name}${t.state === 'paused' ? ' (paused)' : ''}`).join('\n')} onclick={(e) => e.stopPropagation()}>+{capped.hidden.length} more - {/if} -
    + + {/snippet} + {/if} {#if showOwner} @@ -213,12 +197,12 @@ .job-name { max-width: 420px; } - .pills { - display: flex; - max-width: 460px; - flex-wrap: wrap; + .trigger { + display: inline-flex; + min-width: 0; align-items: center; - gap: 4px; + gap: 10px; + margin-right: 8px; } /* The shared tag, in mono, with the name standing out from its dimmed `tag:` prefix. */ .pill { @@ -229,10 +213,6 @@ font-family: var(--font-mono); text-overflow: ellipsis; } - .pills .more:hover { - color: var(--muted-foreground); - text-decoration: none; - } .pill .pfx { color: var(--sb-text-faint); } @@ -267,14 +247,6 @@ text-overflow: ellipsis; white-space: nowrap; } - .more { - color: var(--muted-foreground); - font-size: 12px; - } - .more:hover { - color: var(--primary); - text-decoration: underline; - } .nowrap { white-space: nowrap; } diff --git a/ui/src/routes/jobs/[name]/discovered/discovered-facts.svelte b/ui/src/routes/jobs/[name]/discovered/discovered-facts.svelte new file mode 100644 index 0000000000..2620291b06 --- /dev/null +++ b/ui/src/routes/jobs/[name]/discovered/discovered-facts.svelte @@ -0,0 +1,86 @@ + + +
    +
    Name
    + {#if set.assets.length}
    Asset
    {set.assets.join(', ')}
    {/if} +
    +
    Status
    +
    {discoveredStatusLabel[set.status]}{set.fetchedAt ? ` · ${formatAgo(set.fetchedAt, app.now)}` : ''}
    +
    + {#if failed}
    Serving
    {set.lastGoodAt ? `Last good · ${formatAgo(set.lastGoodAt, app.now)}` : 'No steps'}
    {/if} + {#if release}
    Release
    {release}
    {/if} + {#if digest}
    Plan digest
    {digest}
    {/if} +
    Steps
    {set.items}
    + {#if set.tags.max_parallel}
    Max parallel
    {set.tags.max_parallel}
    {/if} + {#if set.checkEverySeconds}
    Checked
    Every {set.checkEverySeconds / 60} min
    {/if} +
    +{#if otherTags.length} +
    {#each otherTags as [k, v] (k)}{k}={v}{/each}
    +{/if} +{#if failed && set.error}

    {set.error}

    {/if} + + diff --git a/ui/src/routes/jobs/[name]/discovered/utils.ts b/ui/src/routes/jobs/[name]/discovered/utils.ts new file mode 100644 index 0000000000..7eb7e99afa --- /dev/null +++ b/ui/src/routes/jobs/[name]/discovered/utils.ts @@ -0,0 +1,36 @@ +// A job's discovered sets and how its graph frames them. Pure. + +import type { DiscoveredSet } from '$lib/api'; +import type { JobBox } from '$lib/lineage/job-graph'; + +/** The sets with at least one node in the job. */ +export function setsInJob(sets: DiscoveredSet[], keys: string[]): DiscoveredSet[] { + const inJob = new Set(keys); + return sets.filter((s) => s.nodes.some((n) => inJob.has(n.key))); +} + +/** A hash as people quote it: its first 7 characters, without an algorithm prefix. */ +export function shortHash(hash: string | null | undefined): string | null { + return hash ? hash.replace(/^[a-z0-9]+:/, '').slice(0, 7) : null; +} + +/** One box per asset of each set, around the asset's steps in the job. */ +export function discoveredBoxes(sets: DiscoveredSet[], keys: string[]): JobBox[] { + const inJob = new Set(keys); + return sets.flatMap((s) => + s.assets.map((asset) => ({ + jobKey: asset, + nodes: s.nodes.filter((n) => n.asset === asset && inJob.has(n.key)).map((n) => n.key), + discovered: { set: s.name, status: s.status, release: shortHash(s.tags.release), releaseFull: s.tags.release ?? null, error: s.error } + })) + ); +} + +/** The set and item behind a node, or null for a node no set made. */ +export function itemOf(sets: DiscoveredSet[], key: string): { set: DiscoveredSet; item: DiscoveredSet['nodes'][number] } | null { + for (const set of sets) { + const item = set.nodes.find((n) => n.key === key); + if (item) return { set, item }; + } + return null; +} diff --git a/ui/src/routes/jobs/[name]/job-view.svelte b/ui/src/routes/jobs/[name]/job-view.svelte index 26e63b03c2..a25231f72e 100644 --- a/ui/src/routes/jobs/[name]/job-view.svelte +++ b/ui/src/routes/jobs/[name]/job-view.svelte @@ -23,14 +23,20 @@ import { formatNodeCounts, isActiveRun, nodeOutcomeLabel, nodeOutcomeTone, runOriginLabel, runStatusLabel, runStatusTone } from '$lib/status'; import { kindLine, shortName } from '$lib/build-area/labels'; import { planHref } from '$lib/run/command'; - import { CONCURRENCY_DOCS, formatCost, narrowingText, onFailureText, overlapHelp, overlapWhileRunning, poolText, runConcurrencyText, shortRunId } from '$lib/operate/labels'; + import { CONCURRENCY_DOCS, formatCost, narrowingText, onFailureText, overlapHelp, overlapPlain, poolText, runConcurrencyHelp, shortRunId } from '$lib/operate/labels'; import ScopeGraph from '$lib/lineage/scope-graph.svelte'; import MemberGraph from '$lib/lineage/member-graph.svelte'; import { memberLinks, publishedLinks, waitReasons, type MemberInfo, type MemberSelection } from '$lib/lineage/member-graph'; import InspectorHead from '$lib/components/lineage/inspector-head.svelte'; import InspectorSection from '$lib/components/lineage/inspector-section.svelte'; + import HelpTip from '$lib/components/help-tip.svelte'; + import KeyValues from '$lib/components/platform/key-values.svelte'; import OutcomeStrip from '$lib/components/build-area/outcome-strip.svelte'; import { formatMs } from '$lib/build-area/labels'; + import BreakableName from '$lib/components/names/breakable-name.svelte'; + import PathTail from '$lib/components/names/path-tail.svelte'; + import DiscoveredFacts from './discovered/discovered-facts.svelte'; + import { discoveredBoxes, itemOf, setsInJob } from './discovered/utils'; let { name }: { name: string } = $props(); @@ -47,6 +53,10 @@ }, ['jobs', 'runs', 'snapshot']); const def = $derived(job.data ?? null); + // The discovered sets with steps in this job, each framed in the graph under its asset. + const discovered = createResource((client, scope) => client.readDiscovered(scope), ['snapshot']); + const jobSets = $derived(def ? setsInJob(discovered.data ?? [], def.resolvedNodes) : []); + const boxes = $derived(discoveredBoxes(jobSets, def?.resolvedNodes ?? [])); // Why each member waits for another, node by node, from the catalog's lineage. // Why members wait, node by node: as the server publishes it, or worked out from lineage for a // snapshot that predates published reasons. @@ -180,7 +190,7 @@ {#if job.error}
    Couldn't load this job: {job.error}
    {:else if job.data === null} -
    There's no job or group named {name} in the version deployed to {app.location?.name}.
    +
    No job or group {name} in {app.location?.name}.
    {/if} {#if actionError}
    {actionError}
    {/if} @@ -199,7 +209,9 @@ {:else if catalog.data} - (picked = keys)} /> + {#key boxes.length} + (picked = keys)} /> + {/key} {:else} {#if catalog.error}

    {catalog.error}

    {:else}
    {/if} {/if} @@ -253,21 +265,33 @@ {:else if pickedNodes.length === 1} {@const n = pickedNodes[0]} + {@const found = itemOf(jobSets, n.key)}

    {kindLine(n)}

    -

    {n.key}

    +

    Open in Catalog ↗ {#if n.description}

    {n.description}

    {/if}
    {#if n.lastOutcome || n.lastBuild}
    Last build
    {n.lastOutcome ? nodeOutcomeLabel[n.lastOutcome] : 'Built'}{n.lastBuild ? ` · ${formatAgo(n.lastBuild.builtAt, app.now)}` : ''}
    {/if} {#if n.relation}
    Writes
    {[n.relation.database, n.relation.schema, n.relation.name].filter(Boolean).join('.')}
    {/if} - {#if n.path}
    Defined in
    {n.path}
    {/if} + {#if n.path}
    Defined in
    {/if}
    + {#if found} +

    Item

    +
    +
    Step
    {found.item.step}
    +
    Asset
    + {#each Object.entries(found.item.args).filter(([k]) => k !== 'step') as [k, v] (k)}
    {k}
    {v}
    {/each} +
    +

    Discovered set

    + + {/if} {:else if pickedNodes.length > 1}

    {pickedNodes.length} nodes selected

      {#each pickedNodes as n (n.key)}
    • {n.key}
    • {/each}
    {:else} + {#each jobSets as set (set.name)}{/each} {#if def.description}

    {def.description}

    {/if} {#snippet meta()}{#if runs.length}{/if}{/snippet} @@ -302,41 +326,42 @@ {#if def.select || def.exclude.length}

    Selection

    {/if}
    {#if def.owner}
    Owner
    {def.owner}
    {/if} - {#if def.sourceFile}
    Defined in
    {def.sourceFile}
    {/if} + {#if def.sourceFile}
    Defined in
    {/if} {#if def.memberOf?.length}
    In groups
    {#each def.memberOf as g, i (g)}{i ? ', ' : ''}{g}{/each}
    {/if}
    - + + {#snippet meta()}{/snippet} {@const resolved = def.resolvedConcurrency} -
      - {#if resolved} -
    • {runConcurrencyText(resolved.limit, def.kind)}
    • - {/if} -
    • Never alongside runs writing the same tables (automatic)
    • - {#if def.overlap} -
    • If triggered while running: {overlapWhileRunning[def.overlap]}
    • - {/if} - {#if !pools.length} -
    • Pools: none
    • - {:else} - {#each pools as use (use.pool)} - {@const text = poolText(use)} - {@const holders = holdersOf(use.pool)} -
    • - {#if text.clamped}{/if}{text.text}{#if text.detail} ({text.detail}){/if}{#if text.shared.length}, shared with {#each text.shared as other, i (other)}{i ? ', ' : ''}{other}{/each}{#if text.more} +{text.more} more{/if}{/if} - {#if holders.length} - Running now: {#each holders as h, i (h)}{i ? ', ' : ''}{shortRunId(h)}{/each} - {/if} -
    • - {/each} - {/if} -
    - How concurrency works ↗ +
    + {#snippet poolList()} +
      + {#each pools as use (use.pool)} + {@const text = poolText(use)} + {@const holders = holdersOf(use.pool)} +
    • + {#if text.clamped}{/if}{text.text}{#if text.detail} ({text.detail}){/if}{#if text.shared.length}, shared with {#each text.shared as other, i (other)}{i ? ', ' : ''}{other}{/each}{#if text.more} +{text.more} more{/if}{/if} + {#if holders.length} + Running now: {#each holders as h, i (h)}{i ? ', ' : ''}{shortRunId(h)}{/each} + {/if} +
    • + {/each} +
    + {/snippet} + +
    {#if hasSettings} @@ -468,6 +493,20 @@ font-weight: 600; word-break: break-all; } + /* Names wrap between their words only. */ + .rail h2.wrap-name { + word-break: normal; + overflow-wrap: normal; + } + dd.path { + flex: 1; + min-width: 0; + } + .label.sub { + margin: 14px 0 4px; + padding-top: 10px; + border-top: 1px solid var(--border); + } .rail.sections { padding: 0; } @@ -531,48 +570,44 @@ .picked li { padding: 2px 0; } - /* The Concurrency panel: one plain fact per line, any detail quieter beside it. */ - .concurrency { + /* The Concurrency panel: key-value facts; pools list one per line, any detail quieter beside it. */ + .concurrency :global(dd) { + white-space: normal; + } + .pools { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 0; list-style: none; - font-size: 12.5px; line-height: 1.4; } - .concurrency .muted { + .pools .muted { color: var(--muted-foreground); } - .concurrency .pool { + .pools .pool { display: flex; flex-direction: column; gap: 2px; } /* A pool this server caps below what the job asks: it takes the whole pool, so it runs alone there. */ - .concurrency .pool.clamped { + .pools .pool.clamped { padding: 4px 8px; border-left: 3px solid var(--sb-warning); border-radius: 2px; background: color-mix(in srgb, var(--sb-warning) 10%, transparent); color: var(--sb-warning); } - .concurrency .pool.clamped a { + .pools .pool.clamped a { color: inherit; text-decoration: underline; } - .concurrency :global(.inline-icon) { + .pools :global(.inline-icon) { display: inline; margin-right: 4px; vertical-align: -1px; } - .docs { - display: inline-block; - margin-top: 10px; - color: var(--primary); - font-size: 12px; - } code, .mono { font-family: var(--font-mono); diff --git a/ui/src/routes/jobs/utils.test.ts b/ui/src/routes/jobs/utils.test.ts index a5f934a7d9..6753565f13 100644 --- a/ui/src/routes/jobs/utils.test.ts +++ b/ui/src/routes/jobs/utils.test.ts @@ -1,29 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { capItems, capLines, ownerChip, selectionTokens } from './utils'; - -describe('capLines', () => { - it('shows every item when they fit in the lines', () => { - expect(capLines(['orders_hourly', 'orders_daily'])).toEqual({ shown: ['orders_hourly', 'orders_daily'], hidden: [] }); - }); - - it('keeps the last line for "+N more" when they do not fit', () => { - expect(capLines(['orders_hourly', 'orders_daily', 'inventory_sensor'])).toEqual({ shown: ['orders_hourly'], hidden: ['orders_daily', 'inventory_sensor'] }); - }); - - it('handles an empty list', () => { - expect(capLines([])).toEqual({ shown: [], hidden: [] }); - }); -}); - -describe('capItems', () => { - it('keeps the first items and returns the rest', () => { - expect(capItems(['orders', 'customers', 'inventory', 'returns'], 3)).toEqual({ shown: ['orders', 'customers', 'inventory'], hidden: ['returns'] }); - }); - - it('hides nothing when the list is short', () => { - expect(capItems(['orders'], 3)).toEqual({ shown: ['orders'], hidden: [] }); - }); -}); +import { ownerChip, selectionTokens } from './utils'; describe('selectionTokens', () => { it('splits on whitespace and separates the method prefix', () => { @@ -46,10 +22,8 @@ describe('selectionTokens', () => { expect(selectionTokens(null)).toEqual([]); }); - it('caps at four pills with the rest hidden', () => { - const capped = capItems(selectionTokens('tag:a tag:b tag:c tag:d source:e'), 4); - expect(capped.shown.map((t) => t.token)).toEqual(['tag:a', 'tag:b', 'tag:c', 'tag:d']); - expect(capped.hidden.map((t) => t.token)).toEqual(['source:e']); + it('gives each comma-joined selector its own chip', () => { + expect(selectionTokens('tag:orders,tag:daily_orders customers').map((t) => t.token)).toEqual(['tag:orders', 'tag:daily_orders', 'customers']); }); }); diff --git a/ui/src/routes/jobs/utils.ts b/ui/src/routes/jobs/utils.ts index 386eb87b4f..513bfa8f2a 100644 --- a/ui/src/routes/jobs/utils.ts +++ b/ui/src/routes/jobs/utils.ts @@ -1,25 +1,5 @@ // Pure helpers for the Jobs list. -export interface Capped { - shown: T[]; - /** The items left out, for the "+N more" tooltip. */ - hidden: T[]; -} - -/** - * Items drawn one per line, at most `lines` lines: all of them when they fit, otherwise - * `lines - 1` items and a "+N more" line. - */ -export function capLines(items: readonly T[], lines = 2): Capped { - const keep = items.length <= lines ? items.length : Math.max(0, lines - 1); - return { shown: items.slice(0, keep), hidden: items.slice(keep) }; -} - -/** The first `max` items, and the rest for a "+N more" line. */ -export function capItems(items: readonly T[], max: number): Capped { - return { shown: items.slice(0, max), hidden: items.slice(max) }; -} - /** One selection token split for display: a dimmed `tag:`-style prefix and the name that stands out. */ export interface SelectionToken { /** The whole token, e.g. `+tag:orders`. */ @@ -29,11 +9,11 @@ export interface SelectionToken { name: string; } -/** Splits a job's selection (space-separated tokens) into tokens with their method prefix. */ +/** Splits a job's selection into one token per selector, at spaces and commas, with its method prefix. */ export function selectionTokens(select: string | null | undefined): SelectionToken[] { return (select ?? '') .trim() - .split(/\s+/) + .split(/[\s,]+/) .filter(Boolean) .map((token) => { const m = /^([@+\d]*[a-z][a-z0-9_]*:)(.+)$/i.exec(token); diff --git a/ui/src/routes/layout.css b/ui/src/routes/layout.css index a08b9f4af6..6eef1123a9 100644 --- a/ui/src/routes/layout.css +++ b/ui/src/routes/layout.css @@ -5,6 +5,7 @@ @import "@fontsource-variable/space-grotesk"; @import "@fontsource/ibm-plex-mono/400.css"; @import "@fontsource/ibm-plex-mono/500.css"; +@import "@fontsource/ibm-plex-mono/600.css"; @custom-variant dark (&:is(.dark *)); @plugin '@tailwindcss/typography'; @@ -306,6 +307,21 @@ .sb-list.static tbody tr { cursor: default; } +/* A row that opens in place: a click anywhere on it toggles it, its chevron brightens on hover, + and a name that drills in underlines. */ +.sb-list tbody tr.expandable { + cursor: pointer; +} +.sb-list tbody tr.expandable:hover { + background: var(--sb-hover); +} +.sb-list tbody tr.expandable:hover .chevron, +.sb-list tbody tr.expandable:hover .chev { + color: var(--foreground); +} +.sb-list tbody tr.expandable:hover .row-name:not(.plain) { + text-decoration: underline; +} /* A short list inside a page section, such as a plan's nodes: tighter rows. */ .sb-list.compact tbody td { padding-top: 5px; diff --git a/ui/src/routes/overview-cost.svelte b/ui/src/routes/overview-cost.svelte deleted file mode 100644 index c7d43d3ca9..0000000000 --- a/ui/src/routes/overview-cost.svelte +++ /dev/null @@ -1,115 +0,0 @@ - - -{#if app.client.supports('getCostSummary') && (cost?.runs || summary.error)} -
    -
    -
    -

    Estimated query cost

    -
    - ({ value: String(w), label: `${w} days` }))} onselect={(v) => (days = Number(v) as (typeof WINDOWS)[number])} /> -
    - - {#if summary.error && !cost} -

    Couldn't load cost: {summary.error}

    - {:else if cost} -
    - {formatQueryCost(cost)} - {plural(cost.runs, 'run')} in the last {days} days{#if cost.incompleteRuns} · {cost.incompleteRuns} incomplete{/if} - {#if cost.usd === null}{CREDIT_PRICE_HINT}{/if} -
    -
    - {#each columns as c (c.title)} - {@const top = c.rows[0]?.credits || 1} -
    -

    {c.title}

    - {#each c.rows.slice(0, TOP) as r (r.key)} - - {r.label} - {formatQueryCost(r)} - - {r.detail} - - {/each} - {#if c.rows.length > TOP}and {c.rows.length - TOP} more{/if} -
    - {/each} -
    - {/if} -
    -{/if} - - diff --git a/ui/src/routes/plan/+page.svelte b/ui/src/routes/plan/+page.svelte index 7638873674..48b65e38f2 100644 --- a/ui/src/routes/plan/+page.svelte +++ b/ui/src/routes/plan/+page.svelte @@ -1,5 +1,5 @@