Compare commits

..

215 Commits

Author SHA1 Message Date
Jeremy Cohen
feb37c55c7 demo: OperationRefResolver for SqlOperation 2022-03-10 06:59:44 -05:00
Emily Rockman
9a0abc1bfc Automate changelog (#4743)
* initial setup to use changie

* added `dbt-core` to version line

* fix formatting

* rename to be more accurate

* remove extra file

* add stug for contributing section

* updated docs for contributing and changelog

* first pass at changelog check

* Fix workflow name

* comment on handling failure

* add automatic contributors section via footer

* removed unused initialization

* add script to automate entire changelog creation and handle prereleases

* stub out README

* add changelog entry!

* no longer need to add contributors ourselves

* fixed formatted and excluded core team

* fix typo and collapse if statement

* updated to reflect automatic pre-release handling

Removed custom script in favor of built in pre-release functionality in new version of changie.

* update contributing doc

* pass at GHA

* fix path

* all changed files

* more GHA work

* continued GHA work

* try another approach

* testing

* adding comment via GHA

* added uses for GHA

* more debugging

* fixed formatting

* another comment attempt

* remove read permission

* add label check

* fix quotes

* checking label logic

* test forcing failure

* remove extra script tag

* removed logic for having changelog

* Revert "removed logic for having changelog"

This reverts commit 490bda8256.

* remove unused workflow section

* update header and readme

* update with current version of changelog

* add step failure for missing changelog file

* fix typos and formatting

* small tweaks per feedback

* Update so changelog end up onlywith current version, not past

* update changelog to recent contents

* added the rest of our releases to previous release list

* clarifying the readme

* updated to reflect current changelog state

* updated so only 1.1 changes are on main
2022-03-07 20:12:33 -06:00
Gerda Shank
490d68e076 Switch to using class scope fixtures (#4835)
* Switch to using class scope fixtures

* Reorganize some graph selection tests because of ci errors
2022-03-07 14:38:36 -05:00
Stu Kilgore
c45147fe6d Fix macro modified from previous state (#4820)
* Fix macro modified from previous state

Previously, if the first node selected by state:modified had multiple
dependencies, the first of which had not been changed, the rest of the
macro dependencies of the node would not be checked for changes. This
commit fixes this behavior, so the remainder of the macro dependencies
of the node will be checked as well.
2022-03-07 08:23:59 -06:00
Gerda Shank
bc3468e649 Convert tests in dbt-adapter-tests to use new pytest framework (#4815)
* Convert tests in dbt-adapter-tests to use new pytest framework

* Filter out ResourceWarning for log file

* Move run_sql to dbt.tests.util, fix check_cols definition

* Convert jaffle_shop fixture and test to use classes

* Tweak run_sql methods, rename some adapter file pieces, add comment
to dbt.tests.adapter.

* Add some more comments
2022-03-03 16:53:41 -05:00
Kyle Wigley
8fff6729a2 simplify and cleanup gha workflow (#4803) 2022-03-02 10:21:39 -05:00
varun-dc
08f50acb9e Fix stdout piped colored output on MacOS and Linux (#4792)
* Fix stdout pipe output coloring

* Update CHANGELOG.md

Co-authored-by: Chenyu Li <chenyulee777@gmail.com>

Co-authored-by: Chenyu Li <chenyulee777@gmail.com>
2022-03-01 17:23:51 -05:00
Chenyu Li
436a5f5cd4 add coverage (#4791) 2022-02-28 09:17:33 -05:00
Emily Rockman
aca710048f ct-237 test conversion 002_varchar_widening_tests (#4795)
* convert 002 integration test

* remove original test

* moved varchar test under basic folder
2022-02-25 14:25:22 -06:00
Emily Rockman
673ad50e21 updated index file to fix DAG errors for operations & work around null columns (#4763)
* updated index file to fix DAG errors for operations

* update index file to reflect dbt-docs fixes

* add changelog
2022-02-25 13:02:26 -06:00
Chenyu Li
8ee86a61a0 rewrite graph selection (#4783)
* rewrite graph selection
2022-02-25 12:09:11 -05:00
Gerda Shank
0dda0a90cf Fix errors on Windows tests in new tests/functional (#4767)
* [#4781] Convert reads and writes in project fixture to text/utf-8 encoding

* Switch to using write_file and read_file functions

* Add comment
2022-02-25 11:13:15 -05:00
Gerda Shank
220d8b888c Fix "dbt found two resources" error with multiple snapshot blocks in one file (#4773)
* Fix handling of multiple snapshot blocks in partial parsing

* Update tests for partial parsing snapshots
2022-02-25 10:54:07 -05:00
dependabot[bot]
42d5812577 Bump black from 21.12b0 to 22.1.0 (#4718)
Bumps [black](https://github.com/psf/black) from 21.12b0 to 22.1.0.
- [Release notes](https://github.com/psf/black/releases)
- [Changelog](https://github.com/psf/black/blob/main/CHANGES.md)
- [Commits](https://github.com/psf/black/commits/22.1.0)

---
updated-dependencies:
- dependency-name: black
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-02-24 13:28:23 -05:00
Ian Knox
dea4f5f8ff update flake8 to remove line length req (#4779) 2022-02-24 11:22:25 -06:00
Dmytro Kazanzhy
8f50eee330 Fixed misspellings, typos, and duplicated words (#4545) 2022-02-22 18:05:43 -05:00
Gerda Shank
8fd8dfcf74 Initial pass at switching integration tests to pytest (#4691)
Author: Emily Rockman <emily.rockman@dbtlabs.com>
    route logs to dbt-core/logs instead of each test folder (#4711)

 * Initial pass at switching integration tests to pytest

* Reorganize dbt.tests.tables. Cleanup adapter handling

* Move run_sql to TestProjInfo and TableComparison.
Add comments, cleanup adapter schema setup

* Tweak unique_schema name generation

* Update CHANGELOG.md
2022-02-22 15:34:14 -05:00
Hein Bekker
10b27b9633 Deduplicate postgres relations (#3058) (#4521)
* Deduplicate postgres relations (#3058)

* Add changelog entry for #3058, #4521
2022-02-21 16:48:15 -06:00
Gerda Shank
5808ee6dd7 Fix bug accessing target in deps and clean commands (#4758)
* Create DictDefaultNone for to_target_dict in deps and clean commands

* Update test case to handle

* update CHANGELOG.md

* Switch to DictDefaultEmptyStr for to_target_dict
2022-02-21 13:26:29 -05:00
Jeremy Cohen
a66fe7f467 Pin MarkupSafe==2.0.1 (#4746) 2022-02-18 14:35:27 +01:00
Gerda Shank
18fef38702 Ensure meta is both at node top level and in node.config. Fix snapshots with schema config. (#4726)
* Do not overwrite node.meta with empty patch.meta

* Restore config_call_dict in snapshot node transform

* Test for snapshot with schema file config

* Test for meta in both toplevel node and node config
2022-02-17 12:15:11 -05:00
Ian Knox
3ad61d5d81 ignore markdown files for trim-trailing-whitespace hook (#4727) 2022-02-16 10:25:52 -06:00
Emily Rockman
bb1f5b43be Initital pass at deps README (#4686)
* Initital pass at README

* Finished the sentence

* fixed typo and added changelog
2022-02-15 13:58:22 -06:00
Michiel De Smet
a642b20abc Allow override of Column string and numeric type by classes inheritin… (#4604)
* Allow override of Column string and numeric type by classes inheriting from the Column class

* updating based on new black formatter

Co-authored-by: Matthew McKnight <91097623+McKnight-42@users.noreply.github.com>
Co-authored-by: Matthew McKnight <matthew.mcknight@dbtlabs.com>
2022-02-14 15:22:43 -06:00
Ian Knox
c112050455 Pre commit Hooks (black, flake8, mypy, etc) [CT-105] (#4639)
Added pre-commit and configured hooks (black, flake8, mypy, white space formatters)
Removed code checks from tox
updated CI
2022-02-11 12:57:16 -06:00
Ian Knox
43e3fc22c4 Reformat core [CT-104 CT-105] (#4697)
Reformatting dbt-core via black, flake8, mypy, and assorted pre-commit hooks.
2022-02-11 12:17:31 -06:00
elizabeth martens
41c6177ae2 Add --quiet flag and print Jinja function (#4701)
* Add `--quiet` flag

* Add print() macro

* Update tests for --quiet and print()

* Updating changelog

* Apply suggestions from PR review
2022-02-10 13:24:42 -06:00
Tristan Willy
72ecd1ce74 task init: support older click v7.0 (#4681)
* task init: support older click v7.0

`dbt init` uses click for interactively setting up a project. The
version constraints currently ask for click >= 8 but v7.0 has nearly the
same prompt/confirm/echo API. prompt added a feature that isn't used.
confirm has a behavior change if the default is None, but
confirm(..., default=None) is not used. Long story short, we can relax
the version constraint to allow installing with an older click library.

Ref: Issue #4566

* Update CHANGELOG.md

Co-authored-by: Chenyu Li <chenyulee777@gmail.com>

Co-authored-by: Chenyu Li <chenyulee777@gmail.com>
2022-02-07 14:14:22 -05:00
Nathaniel May
2d0b975b6c fix test to use a secret username (#4682) 2022-02-04 14:57:03 -05:00
Rachel
8a0bc39a66 Set flags from args in lib module for dbt-server (#4623) 2022-02-04 10:14:41 -05:00
nkyuray
f3c7b6bfd1 adapter compability messaging added. (#4565)
* adapter compability messaging added.

* edited plugin version compatibility message

* edited test version for plugin compability

* compare using only major and minor

* Add checking PYPI and update changelog

Co-authored-by: Chenyu Li <chenyulee777@gmail.com>
Co-authored-by: ChenyuLi <chenyu.li@dbtlabs.com>
2022-02-03 17:27:31 -05:00
Nathaniel May
0391e4e53a add changelog entry for #4665 (#4673) 2022-02-03 15:48:05 -05:00
Gerda Shank
3ad3c21886 [#2479] Allow unique_id to take a list (#4618)
* Add unique_key to NodeConfig

`unique_key` can be a string or a list.

* merge.sql update to work with unique_key as list

extend the functionality to support both single and multiple keys

Signed-off-by: triedandtested-dev (Bryan Dunkley) <bryan@triedandtested.dev>

* Updated test to include unique_key

Signed-off-by: triedandtested-dev (Bryan Dunkley) <bryan@triedandtested.dev>

* updated tests

Signed-off-by: triedandtested-dev (Bryan Dunkley) <bryan@triedandtested.dev>

* Fix unit and integration tests

* Update Changelog for 2479/4618

Co-authored-by: triedandtested-dev (Bryan Dunkley) <bryan@triedandtested.dev>
2022-02-03 12:55:06 -05:00
Nathaniel May
6e0ed751e1 Avoid saving secrets in SecretContext (#4665) 2022-02-03 12:54:45 -05:00
Gerda Shank
c43c79a995 Initial file creation of code documentation READMEs (#4654) 2022-02-02 18:29:47 -05:00
Ian Knox
d6cc8b3042 Docker release CT-3 (#4616)
* new docker setup

* formatting

* Updated spark: support for extras

* Added third-party adapter support

* More selective lib installs for spark

* added docker to bumpversion

* Updated refs to be tag-based because bumpversion doesn't understand 'latest'

* Updated docs per PR feedback

* reducing RUNs and formatting/pip best practices changes

* Added multi-architecture support and small test script, updated docs

* typo

* Added a few more tests

* fixed tests output, clarified dbt-postgres special case-ness

* Fix merge conflicts

* formatting

* Updated spark: support for extras

* Added third-party adapter support

* More selective lib installs for spark

* added docker to bumpversion

* Updated refs to be tag-based because bumpversion doesn't understand 'latest'

* Updated docs per PR feedback

* reducing RUNs and formatting/pip best practices changes

* Added multi-architecture support and small test script, updated docs

* typo

* Added a few more tests

* fixed tests output, clarified dbt-postgres special case-ness

* changelog

* basic framework

* PR ready excepts docs

* PR feedback
2022-02-01 16:49:33 -06:00
Chenyu Li
2f4a6e33ec fix changelog for a community pr (#4659) 2022-02-01 13:50:58 -05:00
Alec Wang
b9867e89cb added semver official regex pattern (#4644)
* added semver official regex pattern

* removed extra character

* added comma

* added contribution

* fixed contribution

* Update CHANGELOG.md

Co-authored-by: leahwicz <60146280+leahwicz@users.noreply.github.com>

Co-authored-by: leahwicz <60146280+leahwicz@users.noreply.github.com>
2022-02-01 08:19:37 -05:00
Nathaniel May
13b18654f0 Guard against unnecessarily calling dump_graph in logging (#4619)
* add lazy type and apply to cache events
2022-01-31 14:14:34 -05:00
Jeremy Cohen
aafa1c7f47 Change InvalidRefInTestNode level to DEBUG (#4647)
* Debug-level test depends on disabled

* Add PR link to Changelog
2022-01-31 18:28:43 +01:00
Jeremy Cohen
638e3ad299 Drop support for Python <3.7.2 (#4643)
* Drop support for 3.7.1 + 3.7.2

* Rm root level setup.py

* Rm 'dbt' pkg from build-dist script

* Fixup changelog
2022-01-31 17:31:20 +01:00
Emily Rockman
d9cfeb1ea3 Retry after failure to download or failure to open files (#4609)
* add retry logic, tests when extracting tarfile fails

* fixed bug with not catching empty responses

* specify compression type

* WIP test

* more testing work

* fixed up unit test

* add changelog

* Add more comments!

* clarify why we do the json() check for None
2022-01-31 10:26:51 -06:00
Chenyu Li
e6786a2bc3 fix comparision for new model/body (#4631)
* fix comparison for new model/body
2022-01-31 10:33:35 -05:00
leahwicz
13571435a3 Initial addition of CODEOWNERS file (#4620)
* Initial addition of CODEOWNERS file

* Proposed sub-team ownership (#4632)

* Updating for the events module to be both language and execution

* Adding more comment details

Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2022-01-27 16:23:55 -05:00
Gerda Shank
efb890db2d [#4504] Use mashumaro for serializing logging events (#4505) 2022-01-27 14:43:26 -05:00
Niall Woodward
f3735187a6 Run check_if_can_write_profile before create_profile_using_project_profile_template [CT-67] [Backport 1.0.latest] (#4447)
* Run check_if_can_write_profile before create_profile_using_project_profile_template

* Changelog

Co-authored-by: Ian Knox <81931810+iknox-fa@users.noreply.github.com>
2022-01-27 11:17:28 -06:00
Gerda Shank
3032594b26 [#4554] Don't require a profile for dbt deps and clean commands (#4610) 2022-01-25 12:26:44 -05:00
Joel Labes
1df7a029b4 Clarify "incompatible package version" error msg (#4587)
* Clarify "incompatible package version" error msg

* Clarify error message when they shouldn't fall fwd
2022-01-24 18:33:45 -05:00
leahwicz
f467fba151 Changing Jira mirroring workflows to point to shared Actions (#4615) 2022-01-24 12:20:12 -05:00
Amir Kadivar
8791313ec5 Validate project names in interactive dbt init (#4536)
* Validate project names in interactive dbt init

- workflow: ask the user to provide a valid project name until they do.
- new integration tests
- supported scenarios:
  - dbt init
  - dbt init -s
  - dbt init [name]
  - dbt init [name] -s

* Update Changelog.md

* Add full URLs to CHANGELOG.md

Co-authored-by: Chenyu Li <chenyulee777@gmail.com>

Co-authored-by: Chenyu Li <chenyulee777@gmail.com>
2022-01-21 18:24:26 -05:00
leahwicz
7798f932a0 Add Backport Action (#4605) 2022-01-21 12:40:55 -05:00
Nathaniel May
a588607ec6 drop support for Python 3.7.0 and 3.7.1 (#4585) 2022-01-19 12:24:37 -05:00
Joel Labes
348764d99d Rename data directory to seeds (#4589)
* Rename data directory to seeds

* Update CHANGELOG.md
2022-01-19 10:04:35 -06:00
Gerda Shank
5aeb088a73 [#3988] Fix test deprecation warnings (#4556) 2022-01-12 17:03:11 -05:00
leahwicz
e943b9fc84 Mirror labels to Jira (#4550)
* Adding Jira label mirroring

* Fixing bad step name
2022-01-05 09:29:52 -05:00
leahwicz
892426eecb Mirroring issues to Jira (#4548)
* Adding issue creation Jira Action

* Adding issue closing Jira Action

* Add labeling logic
2022-01-04 17:00:03 -05:00
Emily Rockman
1d25b2b046 test name standardization (#4509)
* rename tests for standardization

* more renaming

* rename tests to remove duplicate numbers

* removed unused file

* removed unused files in 016

* removed unused files in 017

* fixed schema number mismatch 027

* fixed to be actual directory name 025

* remove unused dir 029

* remove unused files 039

* remove unused files 053

* updated changelog
2022-01-04 11:36:47 -06:00
github-actions[bot]
da70840be8 Bumping version to 1.0.1 (#4543)
* Bumping version to 1.0.1

* Update CHANGELOG.md

* Update CHANGELOG.md

Co-authored-by: Github Build Bot <buildbot@fishtownanalytics.com>
Co-authored-by: leahwicz <60146280+leahwicz@users.noreply.github.com>
2022-01-03 13:04:50 -05:00
leahwicz
7632782ecd Removing Docker from bumpversion script (#4542) 2022-01-03 12:48:03 -05:00
Nathaniel May
6fae647097 copy over windows compat logic for colored log output (#4474) 2022-01-03 12:37:36 -05:00
leahwicz
fc8b8c11d5 Commenting our Docker portion of Version Bump (#4541) 2022-01-03 12:37:20 -05:00
Topherhindman
26a7922a34 Fix small typo in architecture doc (#4533) 2022-01-03 12:00:04 +01:00
Emily Rockman
c18b4f1f1a removed unused code in unit tests (#4496)
* removed unused code

* add changelog

* moved changelog entry
2021-12-23 08:26:22 -06:00
Nathaniel May
fa31a67499 Add Structured Logging ADR (#4308) 2021-12-22 10:26:14 -05:00
Ian Knox
742cd990ee New Dockerfile (#4487)
New Dockerfile supporting individual db adapters and architectures
2021-12-22 08:29:21 -06:00
Gerda Shank
8463af35c3 [#4523] Fix error with env_var in hook (#4524) 2021-12-20 14:19:05 -05:00
github-actions[bot]
b34a4ab493 Bumping version to 1.0.1rc1 (#4517)
* Bumping version to 1.0.1rc1

* Update CHANGELOG.md

Co-authored-by: Github Build Bot <buildbot@fishtownanalytics.com>
Co-authored-by: leahwicz <60146280+leahwicz@users.noreply.github.com>
2021-12-19 15:33:38 -05:00
Jeremy Cohen
417ccdc3b4 Fix bool coercion to 0/1 (#4512)
* Fix bool coercion

* Fix unit test
2021-12-19 10:30:25 -05:00
Emily Rockman
7c46b784ef scrub message of secrets (#4507)
* scrub message of secrets

* update changelog

* use new scrubbing and scrub more places using git

* fixed small miss of string conv and missing raise

* fix bug with cloning error

* resolving message issues

* better, more specific scrubbing
2021-12-17 16:05:57 -06:00
Gerda Shank
067b861d30 Improve checking of schema version for pre-1.0.0 manifests (#4497)
* [#4470] Improve checking of schema version for pre-1.0.0 manifests

* Check exception code instead of message in test
2021-12-16 13:30:52 -05:00
Emily Rockman
9f6ed3cec3 update log message to use adapter name (#4501)
* update log message to use adapter name

* add changelog
2021-12-16 11:46:28 -06:00
Nathaniel May
43edc887f9 Simplify Log Destinations (#4483) 2021-12-16 11:40:05 -05:00
Emily Rockman
6d4c64a436 compile new index file for docs (#4484)
* compile new index file for docs

* Add changelog

* move changleog entries for docs changes
2021-12-16 10:09:02 -06:00
Gerda Shank
0ed14fa236 [#4464] Check specifically for generic node type for some partial parsing actions (#4465)
* [#4464] Check specifically for generic node type for some partial parsing actions

* Add check for existence of macro file in saved_files

* Check for existence of patch file in saved_files
2021-12-14 16:28:40 -05:00
Emily Rockman
51f2daf4b0 updated DepsStartPackageInstall event to use package name (#4482)
* updated event to user package name

* add changelog
2021-12-14 14:25:29 -06:00
Matthew McKnight
76f7bf9900 made change to test of str (#4463)
* made change to test of str

* changelog update
2021-12-13 11:55:19 -06:00
Matthew McKnight
3fc715f066 updating contributing.md based on suggestions from updates to adapter… (#4356)
* updating contributing.md based on suggestions from updates to adapter contributing files.

* removed section refering to non-postgres databases for core contributing.md

* making suggested changes to contributing.md based on kyle's initial lookover

* Update CONTRIBUTING.md

Co-authored-by: Kyle Wigley <kyle@fishtownanalytics.com>

Co-authored-by: Kyle Wigley <kyle@fishtownanalytics.com>
2021-12-10 13:14:49 -06:00
Rebekka Moyson
b6811da84f Fix dbt docs overview to working url (#4442)
* Fix to working url

* add fix to changelog
2021-12-08 10:30:41 -06:00
Nathaniel May
1dffccd9da point latest version check to dbt-core package (#4434) 2021-12-03 16:13:38 -05:00
github-actions[bot]
9ed9936c84 Bumping version to 1.0.0 (#4431)
Co-authored-by: Github Build Bot <buildbot@fishtownanalytics.com>
2021-12-03 13:27:46 -05:00
Jeremy Cohen
e75ae8c754 Changelog entries for rc3 -> final (#4389)
* Changelog entries for rc3 -> final

* More updates

* Final entry

* Last fix, and the date

* These few, these happy few
2021-12-03 19:16:46 +01:00
Nathaniel May
b68535b8cb relax version specifier for dbt-extractor (#4427) 2021-12-03 12:56:03 -05:00
Nathaniel May
5310498647 add new interop tests for black-box json log schema testing (#4327) 2021-12-03 12:51:28 -05:00
Ian Knox
22b1a09aa2 stringify generic exceptions (#4424) 2021-12-03 10:32:22 -06:00
Jeremy Cohen
6855fe06a7 Info vs debug text formatting (#4418) 2021-12-03 14:36:42 +01:00
Jeremy Cohen
affd8619c2 Sources aren't materialized (#4417) 2021-12-03 14:36:35 +01:00
Jeremy Cohen
b67d5f396b Add flag to main.py. Reinstantiate after flags (#4416) 2021-12-03 14:36:25 +01:00
Emily Rockman
b3039fdc76 add node type codes to more events + more hook log data (#4378)
* add node type codes to more events + more hook log

* minor fixes

* renames started/finished keys

* made process more clear

* fixed errors

* Put back report_node_data in fresshness.py

Co-authored-by: Gerda Shank <gerda@dbtlabs.com>
2021-12-02 19:25:57 -05:00
Nathaniel May
9bdf5fe74a use reference keys instead of relations (#4410) 2021-12-02 18:35:51 -05:00
Emily Rockman
c675c2d318 Logging README (#4395)
* WIP

* more README cleanup

* readme tweaks

* small tweaks

* wording updates
2021-12-02 17:04:23 -06:00
Ian Knox
2cd1f7d98e user configurable event buffer size (#4411) 2021-12-02 16:47:31 -06:00
Jeremy Cohen
ce9ac8ea10 Rollover + backup for dbt.log (#4405) 2021-12-02 22:10:11 +01:00
Jeremy Cohen
b90ab74975 A few final logging touch-ups (#4388)
* Rm unused events, per #4104

* More structured ConcurrencyLine

* Replace \n prefixes with EmptyLine

* Reimplement ui.warning_tag to centralize logic

* Use warning_tag for deprecations too

* Rm more unused event types

* Exclude EmptyLine from json logs

* loglines are not always created by events (#4406)

Co-authored-by: Nathaniel May <nathaniel.may@fishtownanalytics.com>
2021-12-02 22:09:46 +01:00
Emily Rockman
6d3c3f1995 update file name (#4402) 2021-12-02 15:04:29 -06:00
Nathaniel May
74fbaa18cd change json override strategy (#4396) 2021-12-02 15:04:52 -05:00
Emily Rockman
fc7c073691 allow log_format to be set in profile configs (#4394) 2021-12-02 13:51:45 -06:00
leahwicz
29f504e201 Fix release process (#4385) 2021-12-02 11:18:49 -05:00
Nathaniel May
eeb490ed15 use rfc3339 format for log time stamps (#4384) 2021-12-02 09:44:10 -05:00
Gerda Shank
c220b1e42c [#4354] Different output for console and file logs (#4379)
* [#4354] Different output for console and file logs

* Tweak some log formats

* Change loging of thread names
2021-12-02 08:23:25 -05:00
Jeremy Cohen
d973ae9ec6 Tiny touchups for deps, clean (#4366)
* Use actual profile name for log msg

* Raise clean dep warning iff configured path missing
2021-12-02 12:12:49 +01:00
Ian Knox
f461683df5 Add windows OS error supressing for temp dir cleanups (#4380) 2021-12-01 17:25:56 -06:00
Nathaniel May
41ed976941 move event code up a level (#4381)
move event code up a level plus minor fixes
2021-12-01 17:30:19 -05:00
Gerda Shank
e93ad5f118 Make the stdout logger actually go to stdout (#4368) 2021-11-30 17:48:23 -05:00
Emily Rockman
d75ed964f8 only log events in cache.py when flag is set set (#4369)
flag is --log-cache-events
2021-11-30 15:17:08 -06:00
Nathaniel May
284ac9b138 better dataclass field handling (#4361)
fix serializing dataclass fields so they show up at all
2021-11-30 13:34:57 -05:00
github-actions[bot]
7448ec5adb Bumping version to 1.0.0rc3 (#4363)
* Bumping version to 1.0.0rc3

* Updating Changelog for release

Co-authored-by: Github Build Bot <buildbot@fishtownanalytics.com>
Co-authored-by: leahwicz <60146280+leahwicz@users.noreply.github.com>
2021-11-30 09:35:03 -05:00
Emily Rockman
caa6269bc7 add node_info to relevant logs (#4336)
* WIP

* fixed some merg issues

* WIP

* first pass with node_status logging

* add node details to one more

* another pass at node info

* fixed failures

* convert to classes

* more tweaks to basic implementation

* added in ststus, organized a bit

* saving broken state

* working state with lots of todos

* formatting

* add start/end tiemstamps

* adding node_status logging to more events

* adding node_status to more events

* Add RunningStatus and set in node

* Add NodeCompiling and NodeExecuting events, switch to _event_status dict

* add _event_status to SourceDefinition

* small tweaks to NodeInfo

* fixed misnamed attr

* small fix to validation

* rename logging timestamps to minimize name collision

* fixed flake failure

* move str formatting to events

* incorporate serialization changes

* add node_status to event_to_serializable_dict

* convert nodeInfo to dict with dataclass builtin

* Try to fix failing unit, flake8, mypy tests (#4362)

* fixed leftover merge conflict

Co-authored-by: Gerda Shank <gerda@dbtlabs.com>
2021-11-30 09:34:28 -05:00
Gerda Shank
31691c3b88 Events with graph_func include actual output of graph_func (#4360) 2021-11-29 20:20:22 -05:00
Ian Knox
3a904a811f Event buffer for structlog (#4358)
Add Internal event buffer

Co-authored-by: Nathaniel May <nathaniel.may@fishtownanalytics.com>
2021-11-29 20:12:20 -05:00
Nathaniel May
b927a31a53 make json serialization overridable for events (#4326)
* simplify scrubbing

* add overridable serialize method to events

* add imperfect test for json serialization of events

Co-authored-by: Ian Knox <ian.knox@fishtownanalytics.com>
Co-authored-by: Kyle Wigley <kyle@fishtownanalytics.com>
2021-11-29 18:19:34 -05:00
Kyle Wigley
d8dd75320c set invocation id when generating psuedo config (#4359) 2021-11-29 17:29:12 -05:00
Nathaniel May
a613556246 add thread_name to json output (#4353) 2021-11-29 14:01:50 -05:00
Jeremy Cohen
8d2351d541 Logging: restore previous (small) behaviors (#4341)
* Log formatting from flags earlier

* WARN-level stdout for list task

* Readd tracking events to File

* PR feedback, annotate hacks

* Revert "PR feedback, annotate hacks"

This reverts commit 5508fa230b.

* This is maybe better

* Annotate main.py

* One more comment in base.py

* Update changelog
2021-11-29 19:05:39 +01:00
leahwicz
f72b603196 Adding release workflow (#4288) 2021-11-29 10:37:14 -05:00
Gerda Shank
4eb17b57fb Provide function to set the invocation_id (#4351) 2021-11-29 10:15:19 -05:00
Cor
85a4b87267 Use cls in classmethod (#4345)
Instead of calling the class explicitly, use the `cls` variable instead.
2021-11-29 09:57:52 -05:00
jan zens
0d320c58da fix typo in UnparsedSourceDefinition.__post_serialize_ (#4349)
* fix typo in UnparsedSourceDefinition.__post_serialize_

fix typo in UnparsedSourceDefinition.__post_serialize_

* update CHANGELOG.md

update CHANGELOG.md

add #4349

* Update changelog

Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-11-29 11:36:11 +01:00
Emilie Lima Schario
ed1ff2caac Adjust logic when finding approx matches for model or test matching (#4076)
* adjust logic when finding approx matches

* update changelog

* Update core/dbt/adapters/base/relation.py

Co-authored-by: Jeremy Cohen <jtcohen6@gmail.com>

* Update changelog

Co-authored-by: Jeremy Cohen <jtcohen6@gmail.com>
Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-11-29 11:20:01 +01:00
sarah-weatherbee
d80646c258 adds additional augmented assignment statements (#4315) (#4331)
* adds additional augmented assignment statements (#4315)

* Per PR comments, revised CHANGELOG.md to note change and contributor info
2021-11-27 09:04:40 -06:00
Matthew McKnight
a9b4316346 Mc knight 42/test event codes (#4338)
* pushing up to get eye on from Nate

* updating to compare

* latest push

* finished test for duplicate codes with a lot of help from Nate

* resolving suggestions

* removed duplicated code in types.py, made minor changes to test_events.py

* added missing func call
2021-11-24 16:03:43 -06:00
Gerda Shank
36776b96e7 [#4337] Always create an invocation_id, even when not tracking (#4340) 2021-11-24 16:54:17 -05:00
Jeremy Cohen
7f2d3cd24f Fix static parser tracking logic (#4332)
* Fix static parser tracking logic

* Add changelog note
2021-11-24 17:26:56 +01:00
Gerda Shank
d046ae0606 [#4253] Support partial parsing of env_vars in metrics definitions (#4322) 2021-11-23 15:02:47 -05:00
Gerda Shank
e8c267275e [#4254] Change some CompilationExceptions to ParsingException in the parser (#4328) 2021-11-23 13:50:00 -05:00
github-actions[bot]
a4951749a8 Bumping version to 1.0.0rc2 (#4321)
* Bumping version to 1.0.0rc2

* Update changelog

Co-authored-by: Github Build Bot <buildbot@fishtownanalytics.com>
Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-11-22 21:26:15 +01:00
Ian Knox
e1a2e8d9f5 Add codes to all log events (re-work of PR #4268) (#4319)
* re-work of old branch
2021-11-22 13:14:33 -06:00
Emily Rockman
f80c78e3a5 add logic to scrub more than str types (#4317) 2021-11-22 12:58:10 -06:00
Emily Rockman
c541eca592 structured logging: add data attributes to json log output (#4301)
* simplified data construction

* fixed missed scrubbing of secrets

* switched to vars()

* scrub entire log line, update how attributes get pulled

* get ahead of serialization errors

* store if data is serialized and modify values instead of a copy of values

* fixed unused import from merge
2021-11-19 15:43:26 -06:00
Nathaniel May
726aba0586 version logging (#4289)
* start adding version logging, noticed some wrong stuff

* fix bad pid and ts

* remove level format on json logs

Co-authored-by: Emily Rockman <emily.rockman@dbtlabs.com>
2021-11-19 14:53:50 -06:00
Jeremy Cohen
d300addee1 SecretContext for secret env vars, profiles + packages only (#4311)
* SecretContext for secret env vars

* Cleanup exception. Add + edit tests

* Add changelog entry
2021-11-19 19:36:19 +01:00
Kyle Wigley
d5d16f01f4 Fix flags import (#4307) 2021-11-18 14:59:49 -05:00
Kyle Wigley
2cb26e2699 Add supported dbt tasks (#4200) 2021-11-18 14:05:00 -05:00
Nathaniel May
b4793b4f9b Fix adapter failures due to string formatting issues (#4305)
fix adapter failures due to string formatting issues
2021-11-18 12:54:20 -05:00
Gerda Shank
045e70ccf1 [#4298] Fix 'created_at' in ParsedMetric to allow recalculating metrics depends_on refs (#4299) 2021-11-18 09:29:09 -05:00
Jeremy Cohen
ba23395c8e Fix metrics count in compile stats (#4292)
* Fix metrics count in compile stats

* Add changelog entry
2021-11-18 09:28:13 +01:00
Joel Labes
0aacd99168 Get prerelease packages when specifically requested (#4295)
* Get prerelease packages when specifically required. Add test validating it works

* Update CHANGELOG.md
2021-11-18 09:11:49 +01:00
Nathaniel May
e4b5d73dc4 adjust level length for text only (#4303)
adjust level length for text log lines only
2021-11-17 17:32:15 -05:00
Gerda Shank
bd950f687a [#4252] Serialization error when missing quotes in metrics model ref() call (#4287) 2021-11-17 17:14:32 -05:00
Gerda Shank
aea23a488b [#4272] Move validator keyword argument in jinja 'config.get' to after 'default' (#4297) 2021-11-17 17:12:26 -05:00
Jeremy Cohen
22731df07b Fix: default log formatting (#4302)
* Respect log formatting

* PR feedback
2021-11-17 21:10:14 +01:00
Jeremy Cohen
c55be164e6 Separate warnings. Fix duplication (#4291) 2021-11-17 18:01:28 +01:00
kadero
9d73304c1a Alow snapshot defer (#4296)
* Alow snapshot defer

* Update changelog
2021-11-17 16:56:37 +01:00
Nathaniel May
719b2026ab Minor Cleanup of Structured Logging Module (#4266)
* cleanup structured logging module

* update adapter logger to preserve new-style logging formatting
2021-11-16 20:22:11 -05:00
kadero
22416980d1 Avoid errors when missing column in yaml doc (#4285)
* Update postgres__alter_column_comment

* Update changelog

* Add integration test
2021-11-16 13:22:18 +01:00
Gerda Shank
3d28b6704c [#3689] Fix filesystem searcher and tests that mock it (#4271) 2021-11-15 09:46:17 -05:00
Mila Page
5d1b104e1f Feature/3997 profiles test selection flag (#4270)
* Address 3997. Test selection flag can be in profile.yml.

* Per Jerco's 4104 PR unresolved comments, unify i.s. predicate and add env var.

* Couple of flake8 touchups.

* Classier error handling using enum semantics.

* Cherry-pick in part of Gerda's commit to hopefully avoid a future merge conflict.

* Add 3997 to changelog.

Co-authored-by: Mila Page <versusfacit@users.noreply.github.com>
2021-11-15 14:07:22 +01:00
Jeremy Cohen
4a8a68049d Try removing dupe logging during integration tests (#4275) 2021-11-15 11:00:29 +01:00
Jeremy Cohen
4b7fd1d46a Update dbt-postgres readme (#4263)
* Update dbt-postgres readme

* Rm redshift references

* Update plugins/postgres/README.md

Co-authored-by: leahwicz <60146280+leahwicz@users.noreply.github.com>

* Update plugins/postgres/README.md

Co-authored-by: leahwicz <60146280+leahwicz@users.noreply.github.com>

Co-authored-by: leahwicz <60146280+leahwicz@users.noreply.github.com>
2021-11-12 17:12:00 +01:00
github-actions[bot]
0722922c03 Bumping version to 1.0.0rc1 (#4234)
* Bumping version to 1.0.0rc1

* Update changelog

* Add Dockerfile to bumpversion, update reqs

Co-authored-by: Github Build Bot <buildbot@fishtownanalytics.com>
Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-11-10 14:24:40 +01:00
kadero
40321d7966 Dbt init with provided project name (#4249)
* Dbt init with provided project name

* Update changelog.md

* Fix changelog.md

* Fix typo in help

Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-11-10 11:58:49 +01:00
Nathaniel May
434f3d2678 Merge pull request #4055 from dbt-labs/feature/structured-logging
Add Structured Logging
2021-11-09 17:42:19 -05:00
Jeremy Cohen
6dd9c2c5ba Env var shim to enable legacy logger (#4255)
* Env var shim to reenable logbook

* Rename to ENABLE_LEGACY_LOGGER
2021-11-09 23:04:47 +01:00
Nathaniel May
5e6be1660e configure event logger for integration tests (#4257)
* apply test fixes

* remove presto test
2021-11-09 16:13:13 -05:00
Nathaniel May
31acb95d7a rebased on main and added new partial parsing event 2021-11-09 11:40:18 -05:00
Nathaniel May
683190b711 fixes 2021-11-09 11:26:01 -05:00
Nathaniel May
ebb84c404f postgres adapter to use new logger 2021-11-09 11:26:01 -05:00
Nathaniel May
2ca6ce688b whitespace change 2021-11-09 11:26:01 -05:00
Nathaniel May
a40550b89d std logger for structured logging (#4231)
structured logging powered by the stdlib logger

Co-authored-by: Emily Rockman <emily.rockman@dbtlabs.com>
Co-authored-by: Ian Knox <81931810+iknox-fa@users.noreply.github.com>
2021-11-09 11:26:01 -05:00
Ian Knox
b2aea11cdb Struct log for adapter call sites (#4189)
graph call sites for structured logging

Co-authored-by: Nathaniel May <nathaniel.may@fishtownanalytics.com>
Co-authored-by: Emily Rockman <emily.rockman@dbtlabs.com>
2021-11-09 11:26:01 -05:00
Emily Rockman
43b39fd1aa removed redundant timestamp (#4239) 2021-11-09 11:26:01 -05:00
Emily Rockman
5cc8626e96 updates associated with merging main
- removed 3 new log call sites and replaced with structured logs
- removed 2 unused struc logs
2021-11-09 11:26:01 -05:00
Nathaniel May
f95e9efbc0 use event types in main even before the logger is set up. (#4219) 2021-11-09 11:26:01 -05:00
Nathaniel May
25c974af8c lazy logging in event module (#4210)
* switches on debug level to guard against expensive messages

* adds memoization to msg construction
2021-11-09 11:26:01 -05:00
Emily Rockman
b5c6f09a9e remove unused import (#4217) 2021-11-09 11:26:01 -05:00
Emily Rockman
bd3e623240 test/integration call sites (#4209)
* added struct logging to base

* fixed merge wierdness

* convert to use single type for integration tests

* converted to 3 reusable test types in sep module

* tweak message

* clean up and making test_types complete for future

* fix missed import
2021-11-09 11:26:01 -05:00
Emily Rockman
63343653a9 trivial logger removal (#4216) 2021-11-09 11:26:01 -05:00
Emily Rockman
d8b97c1077 call sites in core/dbt (excluding main.py) (#4202)
* add struct logging to compilation

* add struct logging to tracking

* add struct logging to utils

* add struct logging to exceptions

* fixed some misc errors

* updated to send raw ex, removed resulting circ dep
2021-11-09 11:26:01 -05:00
Emily Rockman
e0b0edaeed deps call sites (#4199)
* add struct logging to base

* add struct logging to git

* add struct logging to deps

* remove blank line

* fixed stray merge error
2021-11-09 11:26:01 -05:00
Emily Rockman
3cafc9e13f task callsites: part 2 (#4188)
* add struct logging to docs serve

* remove merge fluff

* struct logging to seed command

* converting print to use structured logging

* more structured logging print conversion

* pulling apart formatting more

* added struct logging by disecting printer.py

* add struct logging to runnable

* add struct logging to task init

* fixed formatting

* more formatting and moving things around
2021-11-09 11:26:01 -05:00
Nathaniel May
13f31aed90 scrub the secrets (#4203)
scrub secrets in event module
2021-11-09 11:26:01 -05:00
Nathaniel May
d513491046 Show Exception should trigger a stack trace (#4190) 2021-11-09 11:26:01 -05:00
Emily Rockman
281d2491a5 task call sites part 1 (#4183)
* add struct logging to base.py

* struct logging in run_operation

* add struct logging to base

* add struct logging to clean

* add struct logging to debug

* add struct logging to deps

* fix errors

* add struct logging to run.py

* fixed flake error

* add struct logging to geneerate

* added debug level stack trace

* fixed flake error

* added struct logging to compile

* added struct logging to freshness

* cleaned up errors

* resolved bug that broke everything

* removed accidental import

* fixed bug with unused args
2021-11-09 11:26:01 -05:00
Emily Rockman
9857e1dd83 parser call sites (#4177)
* convert generic_test to structured logging

* convert macros to structured logging

* add struc logging to most of manifest.py

* add struct logging to models.py

* added struct logging to partial.py

* finished conversion of manifest

* fixing errors

* fixed 1 todo and added another

* fixed bugs from merge
2021-11-09 11:26:01 -05:00
Emily Rockman
6b36b18029 config call sites (#4169)
* update config use structured logging

* WIP

* minor cleanup

* fixed merge error

* added in ShowException

* added todo to remove defaults after dropping 3.6

* removed todo that is obsolete
2021-11-09 11:26:01 -05:00
Ian Knox
d8868c5197 Dataclass compatibility (#4180)
* use __post_init__() instead of fake dataclass member vars
2021-11-09 11:26:01 -05:00
Emily Rockman
b141620125 contracts call sites (#4166)
* first pass adding structured logging
2021-11-09 11:26:01 -05:00
Emily Rockman
51d8440dd4 Change Graph logger call sites (#4165)
graph call sites for structured logging
2021-11-09 11:26:01 -05:00
Nathaniel May
5b2562a919 Client call sites (#4163)
update log call sites with new event system
2021-11-09 11:26:01 -05:00
Nathaniel May
44a9da621e Handle exec info (#4168)
handle exec info
2021-11-09 11:26:01 -05:00
Emily Rockman
69aa6bf964 context call sites (#4164)
* updated context dir to new structured logging
2021-11-09 11:26:01 -05:00
Nathaniel May
f9ef9da110 Initial structured logging work with fire_event (#4137)
add event type modeling and fire_event calls
2021-11-09 11:26:01 -05:00
Nathaniel May
57ae9180c2 init 2021-11-09 11:26:01 -05:00
Jeremy Cohen
efe926d20c Change user instead of pass (#4250) 2021-11-09 13:10:34 +01:00
Jeremy Cohen
1081b8e720 Improve error msg on pip install dbt (#4244) 2021-11-09 10:40:45 +01:00
Kyle Wigley
8205921c4b Update docs (#4241)
Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-11-08 19:47:28 -05:00
Jeremy Cohen
da6c211611 Wrap get_batch_size() in return() (#4240) 2021-11-09 00:46:15 +01:00
Jeremy Cohen
354c1e0d4d Rm py36 tests, pkg metadata, bump reqs (#4223) 2021-11-09 00:19:09 +01:00
Gerda Shank
855419d698 [#4071] Add metrics feature (#4235)
* first cut at supporting metrics definitions

* teach dbt about metrics

* wip

* support partial parsing for metrics

* working on tests

* Fix some tests

* Add partial parsing metrics test

* Fix some more tests

* Update CHANGELOG.md

* Fix partial parsing yaml file to correct model syntax

Co-authored-by: Drew Banin <drew@fishtownanalytics.com>
2021-11-08 17:44:01 -05:00
Gerda Shank
e94fd61b24 Issue message instead of exception when patch does not have a matching (#4236) node 2021-11-08 15:35:14 -05:00
Kyle Wigley
4cf9b73c3d Raise parsing error instead of compilation when extracting test args (#4237) 2021-11-08 14:51:52 -05:00
Jeremy Cohen
8442fb66a5 Reorganize global project (macros) (#4154)
* Add integration tests

* Reorganize + dispatch more global macros

* Reorg materializations subdir

* Move around + document generic tests

* Fix failing tests

* Fix merge conflict

* Grab fix from #4148

* PR feedback

* Fixup

* Add load_relation back, it was nice

* Last few test fixes

* Rm incremental_upsert, now unused

* Add changelog entry
2021-11-08 19:09:54 +01:00
dependabot[bot]
f8cefa3eff Update agate requirement from <1.6.2,>=1.6 to >=1.6,<1.6.4 in /core (#3585)
Updates the requirements on [agate](https://github.com/wireservice/agate) to permit the latest version.
- [Release notes](https://github.com/wireservice/agate/releases)
- [Changelog](https://github.com/wireservice/agate/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/wireservice/agate/compare/1.6.0...1.6.3)

---
updated-dependencies:
- dependency-name: agate
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-11-08 18:41:04 +01:00
dependabot[bot]
d83e0fb8d8 Bump mashumaro from 2.5 to 2.9 in /core (#4193)
Bumps [mashumaro](https://github.com/Fatal1ty/mashumaro) from 2.5 to 2.9.
- [Release notes](https://github.com/Fatal1ty/mashumaro/releases)
- [Commits](https://github.com/Fatal1ty/mashumaro/compare/v2.5...v2.9)

---
updated-dependencies:
- dependency-name: mashumaro
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-11-08 18:40:25 +01:00
Gerda Shank
3e9da06365 [#3885] Skip partial parsing if project env vars change (#4212)
* [#3885] Skip partial parsing if project env vars change

* Support env_vars in the profile
2021-11-08 11:51:38 -05:00
Gerda Shank
bda70c988e [#3885] Partially parse when environment variables in schema files change (#4162)
* [#3885] Partially parse when environment variables in schema files
change

* Add documentation for test kwargs

* Add test and fix for schema configs with env_var
2021-11-08 11:28:43 -05:00
Rachel
229e897070 Clears adapters before registering to fix dbt-server cacheing behavior (#4218) 2021-11-08 10:33:39 -05:00
Benoit Perigaud
f20e83a32b Fix/dbt deps retry none answer (#4225)
* Fix issue #4178
Allow retries when the answer is None

* Include fix for #4178
Allow retries when the answer from dbt deps is None

* Add link to the PR

* Update exception and shorten line size

* Add test when dbt deps returns None
2021-11-08 12:30:38 +01:00
Jeremy Cohen
dd84f9a896 Raise error on pip install dbt (#4133)
* Raise error on pip install dbt

* Fix relative path logic

* Do not build dist for dbt

* Fix long descriptions

* Trigger code checks

* Using root readme more trouble than good

* only fail on install, not build

* Edit dist script. Avoid README duplication

* jk, be less clever

* Ignore 'dbt' source distribution when testing

* Add changelog entry

Co-authored-by: Kyle Wigley <kyle@dbtlabs.com>
2021-11-07 17:55:30 +01:00
Mila Page
e6df4266f6 Parser no longer takes greedy. Accepts indirect selection, a bool. (#4104)
* Parser no longer takes greedy. Accepts indirect selection, a bool.

* Remove references to greedy and supporting functions.

* 1. Set testing flag default to True. 2. Improve arg parsing.

* Update tests and add new case for when flag unset.

* Update names and styling to fit test requirements. Add default value for option.

* Correct several failing tests now that default behavior was flipped.

* Tests expect eager on by default.

* All but selector test passing.

* Get integration tests working, add them, and mix in selector syntax.

* Clean code and correct test.

* Add changelog entry

Co-authored-by: Mila Page <versusfacit@users.noreply.github.com>
Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-11-07 17:41:56 +01:00
Christophe Oudar
b591e1a2b7 Use common columns for incremental schema changes (#4170)
* Use common columns for incremental schema changes

* on_schema_change:append_new_columns should gracefully handle column removal

* review changes

* Lean approach for `process_schema_changes` to simplify

Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-11-07 17:31:30 +01:00
Jeremy Cohen
3dab058c73 incorporate_indirect_nodes should pass if not needed (#4214)
* Pass incorporate_indirect_nodes if not needed

* Fix flake8

* Add changelog entry
2021-11-05 16:55:58 +01:00
Robert
c7bc6eb812 Add error surfacing for git cloning errors (#4124)
* Add error surfacing for git cloning errors

* Update CHANGELOG.md

* Fix formatting and remove redundant except: raise

* Turn error handling for duplicate packages back on
2021-11-05 10:12:07 +01:00
Jeremy Cohen
c690ecc1fd Fixup changelog (#4206) 2021-11-04 13:54:23 +01:00
Jeremy Cohen
73e272f06e Add get_where_subquery to test namespace (#4197)
* Add get_where_subquery to test namespace

* Add integration test

* Fix test, add comment, smarter approach

* Fix unit tests

* Add changelog entry
2021-11-04 11:53:28 +01:00
leahwicz
95d087b51b Bumping artifact versions for v1 (#4191)
* Bumping artifact versions for v1

* Adding schema in Changelog

* Update CHANGELOG.md

* Update changelog entry

Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-11-04 11:19:36 +01:00
Jeremy Cohen
40ae6b6bc8 Any subset, strict or not (#4160) 2021-11-02 17:59:46 +01:00
Jeremy Cohen
fe20534a98 Add extra graph edges for build only (#4143)
* Resolve extra graph edges for build only

* Fix flake8

* Change test to reflect functional change

* Rename method + args. Add changelog entry
2021-11-02 17:41:14 +01:00
leahwicz
dd7af477ac Perf improvement to subgraph selection (#4155)
Perf improvement to get_subset_graph
Co-authored-by: Ian Knox <ian.knox@fishtownanalytics.com>
2021-10-29 16:06:09 -05:00
Jeremy Cohen
178f74b753 Fix comma if only removing columns in on_schema_change: sync_all_columns (#4148)
* Fix comma if only removing in on_schema_change: sync

* Add changelog entry
2021-10-28 10:19:05 +02:00
Emily Rockman
a14f563ec8 port error scrub from 0.21.latests up for main (#4145) 2021-10-27 14:06:22 -05:00
Kyle Wigley
ff109e1806 Expose lib to to run tasks and compile/execute sql (#4111) 2021-10-27 13:30:46 -04:00
Frank Cash
5e46694b68 assertRaisesRegexp => assertRaisesRegex (#4136)
* assertRaisesRegexp => assertRaisesRegex

* Update CHANGELOG.md

* Update CHANGELOG.md
2021-10-27 13:05:24 +02:00
Gerda Shank
73af9a56e5 [#3885] Handle env_vars in partial parsing of SQL files (#4101)
* [#3885] Handle env_vars in partial parsing

* Comment method to build env_vars_to_source_files
2021-10-26 11:16:36 -04:00
kadero
d2aa920275 Feature: nullable error_after in source (#3955)
* Add nullable error after feature

* add merge_error_after method

* Fix FreshnessThreshold merged test

* Fix other tests

* Fix merge error after

* Fix test docs generate integration test

* Fix source integration test

* Typo and fix linting.

* Fix mypy test

* More terse way to express merge_freshness_time_thresholds

* Update Changelog.md

* Add integration test

* Fix conflict

* Fix contributing.md

* Fix integration tests

* Move up changelog entry

Co-authored-by: Jeremy Cohen <jeremy@dbtlabs.com>
2021-10-26 15:23:57 +02:00
Gerda Shank
c34f3530c8 Use platform agnostic code when searching generic test directory (#4131) 2021-10-25 22:46:36 -04:00
3003 changed files with 25897 additions and 18528 deletions

View File

@@ -1,5 +1,5 @@
[bumpversion] [bumpversion]
current_version = 1.0.0b2 current_version = 1.0.1
parse = (?P<major>\d+) parse = (?P<major>\d+)
\.(?P<minor>\d+) \.(?P<minor>\d+)
\.(?P<patch>\d+) \.(?P<patch>\d+)
@@ -35,3 +35,5 @@ first_value = 1
[bumpversion:file:plugins/postgres/setup.py] [bumpversion:file:plugins/postgres/setup.py]
[bumpversion:file:plugins/postgres/dbt/adapters/postgres/__version__.py] [bumpversion:file:plugins/postgres/dbt/adapters/postgres/__version__.py]
[bumpversion:file:docker/Dockerfile]

16
.changes/0.0.0.md Normal file
View File

@@ -0,0 +1,16 @@
## Previous Releases
For information on prior major and minor releases, see their changelogs:
* [1.0](https://github.com/dbt-labs/dbt-core/blob/1.0.latest/CHANGELOG.md)
* [0.21](https://github.com/dbt-labs/dbt-core/blob/0.21.latest/CHANGELOG.md)
* [0.20](https://github.com/dbt-labs/dbt-core/blob/0.20.latest/CHANGELOG.md)
* [0.19](https://github.com/dbt-labs/dbt-core/blob/0.19.latest/CHANGELOG.md)
* [0.18](https://github.com/dbt-labs/dbt-core/blob/0.18.latest/CHANGELOG.md)
* [0.17](https://github.com/dbt-labs/dbt-core/blob/0.17.latest/CHANGELOG.md)
* [0.16](https://github.com/dbt-labs/dbt-core/blob/0.16.latest/CHANGELOG.md)
* [0.15](https://github.com/dbt-labs/dbt-core/blob/0.15.latest/CHANGELOG.md)
* [0.14](https://github.com/dbt-labs/dbt-core/blob/0.14.latest/CHANGELOG.md)
* [0.13](https://github.com/dbt-labs/dbt-core/blob/0.13.latest/CHANGELOG.md)
* [0.12](https://github.com/dbt-labs/dbt-core/blob/0.12.latest/CHANGELOG.md)
* [0.11 and earlier](https://github.com/dbt-labs/dbt-core/blob/0.11.latest/CHANGELOG.md)

31
.changes/1.0.1.md Normal file
View File

@@ -0,0 +1,31 @@
## dbt-core 1.1.0 (TBD)
### Features
- Added Support for Semantic Versioning ([#4644](https://github.com/dbt-labs/dbt-core/pull/4644))
- New Dockerfile to support specific db adapters and platforms. See docker/README.md for details ([#4495](https://github.com/dbt-labs/dbt-core/issues/4495), [#4487](https://github.com/dbt-labs/dbt-core/pull/4487))
- Allow unique_key to take a list ([#2479](https://github.com/dbt-labs/dbt-core/issues/2479), [#4618](https://github.com/dbt-labs/dbt-core/pull/4618))
- Add `--quiet` global flag and `print` Jinja function ([#3451](https://github.com/dbt-labs/dbt-core/issues/3451), [#4701](https://github.com/dbt-labs/dbt-core/pull/4701))
### Fixes
- User wasn't asked for permission to overwite a profile entry when running init inside an existing project ([#4375](https://github.com/dbt-labs/dbt-core/issues/4375), [#4447](https://github.com/dbt-labs/dbt-core/pull/4447))
- Add project name validation to `dbt init` ([#4490](https://github.com/dbt-labs/dbt-core/issues/4490),[#4536](https://github.com/dbt-labs/dbt-core/pull/4536))
- Allow override of string and numeric types for adapters. ([#4603](https://github.com/dbt-labs/dbt-core/issues/4603))
- A change in secret environment variables won't trigger a full reparse [#4650](https://github.com/dbt-labs/dbt-core/issues/4650) [4665](https://github.com/dbt-labs/dbt-core/pull/4665)
- Fix misspellings and typos in docstrings ([#4545](https://github.com/dbt-labs/dbt-core/pull/4545))
### Under the hood
- Testing cleanup ([#4496](https://github.com/dbt-labs/dbt-core/pull/4496), [#4509](https://github.com/dbt-labs/dbt-core/pull/4509))
- Clean up test deprecation warnings ([#3988](https://github.com/dbt-labs/dbt-core/issue/3988), [#4556](https://github.com/dbt-labs/dbt-core/pull/4556))
- Use mashumaro for serialization in event logging ([#4504](https://github.com/dbt-labs/dbt-core/issues/4504), [#4505](https://github.com/dbt-labs/dbt-core/pull/4505))
- Drop support for Python 3.7.0 + 3.7.1 ([#4584](https://github.com/dbt-labs/dbt-core/issues/4584), [#4585](https://github.com/dbt-labs/dbt-core/pull/4585), [#4643](https://github.com/dbt-labs/dbt-core/pull/4643))
- Re-format codebase (except tests) using pre-commit hooks ([#3195](https://github.com/dbt-labs/dbt-core/issues/3195), [#4697](https://github.com/dbt-labs/dbt-core/pull/4697))
- Add deps module README ([#4686](https://github.com/dbt-labs/dbt-core/pull/4686/))
- Initial conversion of tests to pytest ([#4690](https://github.com/dbt-labs/dbt-core/issues/4690), [#4691](https://github.com/dbt-labs/dbt-core/pull/4691))
- Fix errors in Windows for tests/functions ([#4781](https://github.com/dbt-labs/dbt-core/issues/4781), [#4767](https://github.com/dbt-labs/dbt-core/pull/4767))
Contributors:
- [@NiallRees](https://github.com/NiallRees) ([#4447](https://github.com/dbt-labs/dbt-core/pull/4447))
- [@alswang18](https://github.com/alswang18) ([#4644](https://github.com/dbt-labs/dbt-core/pull/4644))
- [@emartens](https://github.com/ehmartens) ([#4701](https://github.com/dbt-labs/dbt-core/pull/4701))
- [@mdesmet](https://github.com/mdesmet) ([#4604](https://github.com/dbt-labs/dbt-core/pull/4604))
- [@kazanzhy](https://github.com/kazanzhy) ([#4545](https://github.com/dbt-labs/dbt-core/pull/4545))

40
.changes/README.md Normal file
View File

@@ -0,0 +1,40 @@
# CHANGELOG Automation
We use [changie](https://changie.dev/) to automate `CHANGELOG` generation. For installation and format/command specifics, see the documentation.
### Quick Tour
- All new change entries get generated under `/.changes/unreleased` as a yaml file
- `header.tpl.md` contains the contents of the entire CHANGELOG file
- `0.0.0.md` contains the contents of the footer for the entire CHANGELOG file. changie looks to be in the process of supporting a footer file the same as it supports a header file. Switch to that when available. For now, the 0.0.0 in the file name forces it to the bottom of the changelog no matter what version we are releasing.
- `.changie.yaml` contains the fields in a change, the format of a single change, as well as the format of the Contributors section for each version.
### Workflow
#### Daily workflow
Almost every code change we make associated with an issue will require a `CHANGELOG` entry. After you have created the PR in GitHub, run `changie new` and follow the command prompts to generate a yaml file with your change details. This only needs to be done once per PR.
The `changie new` command will ensure correct file format and file name. There is a one to one mapping of issues to changes. Multiple issues cannot be lumped into a single entry. If you make a mistake, the yaml file may be directly modified and saved as long as the format is preserved.
Note: If your PR has been cleared by the Core Team as not needing a changelog entry, the `Skip Changelog` label may be put on the PR to bypass the GitHub action that blacks PRs from being merged when they are missing a `CHANGELOG` entry.
#### Prerelease Workflow
These commands batch up changes in `/.changes/unreleased` to be included in this prerelease and move those files to a directory named for the release version. The `--move-dir` will be created if it does not exist and is created in `/.changes`.
```
changie batch <version> --move-dir '<version>' --prerelease 'rc1'
changie merge
```
#### Final Release Workflow
These commands batch up changes in `/.changes/unreleased` as well as `/.changes/<version>` to be included in this final release and delete all prereleases. This rolls all prereleases up into a single final release. All `yaml` files in `/unreleased` and `<version>` will be deleted at this point.
```
changie batch <version> --include '<version>' --remove-prereleases
changie merge
```
### A Note on Manual Edits & Gotchas
- Changie generates markdown files in the `.changes` directory that are parsed together with the `changie merge` command. Every time `changie merge` is run, it regenerates the entire file. For this reason, any changes made directly to `CHANGELOG.md` will be overwritten on the next run of `changie merge`.
- If changes need to be made to the `CHANGELOG.md`, make the changes to the relevant `<version>.md` file located in the `/.changes` directory. You will then run `changie merge` to regenerate the `CHANGELOG.MD`.
- Do not run `changie batch` again on released versions. Our final release workflow deletes all of the yaml files associated with individual changes. If for some reason modifications to the `CHANGELOG.md` are required after we've generated the final release `CHANGELOG.md`, the modifications need to be done manually to the `<version>.md` file in the `/.changes` directory.

6
.changes/header.tpl.md Executable file
View File

@@ -0,0 +1,6 @@
# dbt Core Changelog
- This file provides a full account of all changes to `dbt-core` and `dbt-postgres`
- Changes are listed under the (pre)release in which they first appear. Subsequent releases include changes from previous releases.
- "Breaking changes" listed under a version may require action from end users or external maintainers when upgrading to that version.
- Do not edit this file directly. This file is auto-generated using [changie](https://github.com/miniscruff/changie). For details on how to document a change, see [the contributing guide](CONTRIBUTING.md)

View File

@@ -0,0 +1,7 @@
kind: Under the Hood
body: Automate changelog generation with changie
time: 2022-02-18T16:13:19.882436-06:00
custom:
Author: emmyoop
Issue: "4652"
PR: "4743"

50
.changie.yaml Executable file
View File

@@ -0,0 +1,50 @@
changesDir: .changes
unreleasedDir: unreleased
headerPath: header.tpl.md
versionHeaderPath: ""
changelogPath: CHANGELOG.md
versionExt: md
versionFormat: '## dbt-core {{.Version}} - {{.Time.Format "January 02, 2006"}}'
kindFormat: '### {{.Kind}}'
changeFormat: '- {{.Body}} ([#{{.Custom.Issue}}](https://github.com/dbt-labs/dbt-core/issues/{{.Custom.Issue}}), [#{{.Custom.PR}}](https://github.com/dbt-labs/dbt-core/pull/{{.Custom.PR}}))'
kinds:
- label: Fixes
- label: Features
- label: Under the Hood
- label: Breaking Changes
- label: Docs
- label: Dependencies
custom:
- key: Author
label: GitHub Name
type: string
minLength: 3
- key: Issue
label: GitHub Issue Number
type: int
minLength: 4
- key: PR
label: GitHub Pull Request Number
type: int
minLength: 4
footerFormat: |
Contributors:
{{- $contributorDict := dict }}
{{- $core_team := list "emmyoop" "nathaniel-may" "gshank" "leahwicz" "ChenyuLInx" "stu-k" "iknox-fa" "VersusFacit" "McKnight-42" "jtcohen6" }}
{{- range $change := .Changes }}
{{- $author := $change.Custom.Author }}
{{- if not (has $author $core_team)}}
{{- $pr := $change.Custom.PR }}
{{- if hasKey $contributorDict $author }}
{{- $prList := get $contributorDict $author }}
{{- $prList = append $prList $pr }}
{{- $contributorDict := set $contributorDict $author $prList }}
{{- else }}
{{- $prList := list $change.Custom.PR }}
{{- $contributorDict := set $contributorDict $author $prList }}
{{- end }}
{{- end}}
{{- end }}
{{- range $k,$v := $contributorDict }}
- [{{$k}}](https://github.com/{{$k}}) ({{ range $index, $element := $v }}{{if $index}}, {{end}}[#{{$element}}](https://github.com/dbt-labs/dbt-core/pull/{{$element}}){{end}})
{{- end }}

12
.flake8 Normal file
View File

@@ -0,0 +1,12 @@
[flake8]
select =
E
W
F
ignore =
W503 # makes Flake8 work like black
W504
E203 # makes Flake8 work like black
E741
E501 # long line checking is done in black
exclude = test

43
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1,43 @@
# This file contains the code owners for the dbt-core repo.
# PRs will be automatically assigned for review to the associated
# team(s) or person(s) that touches any files that are mapped to them.
#
# A statement takes precedence over the statements above it so more general
# assignments are found at the top with specific assignments being lower in
# the ordering (i.e. catch all assignment should be the first item)
#
# Consult GitHub documentation for formatting guidelines:
# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners#example-of-a-codeowners-file
# As a default for areas with no assignment,
# the core team as a whole will be assigned
* @dbt-labs/core
# Changes to GitHub configurations including Actions
/.github/ @leahwicz
# Language core modules
/core/dbt/config/ @dbt-labs/core-language
/core/dbt/context/ @dbt-labs/core-language
/core/dbt/contracts/ @dbt-labs/core-language
/core/dbt/deps/ @dbt-labs/core-language
/core/dbt/parser/ @dbt-labs/core-language
# Execution core modules
/core/dbt/events/ @dbt-labs/core-execution @dbt-labs/core-language # eventually remove language but they have knowledge here now
/core/dbt/graph/ @dbt-labs/core-execution
/core/dbt/task/ @dbt-labs/core-execution
# Adapter interface, scaffold, Postgres plugin
/core/dbt/adapters @dbt-labs/core-adapters
/core/scripts/create_adapter_plugin.py @dbt-labs/core-adapters
/plugins/ @dbt-labs/core-adapters
# Global project: default macros, including generic tests + materializations
/core/dbt/include/global_project @dbt-labs/core-execution @dbt-labs/core-adapters
# Perf regression testing framework
# This excludes the test project files itself since those aren't specific
# framework changes (excluded by not setting an owner next to it- no owner)
/performance @nathaniel-may
/performance/projects

View File

@@ -0,0 +1,14 @@
FROM python:3-slim AS builder
ADD . /app
WORKDIR /app
# We are installing a dependency here directly into our app source dir
RUN pip install --target=/app requests packaging
# A distroless container image with Python and some basics like SSL certificates
# https://github.com/GoogleContainerTools/distroless
FROM gcr.io/distroless/python3-debian10
COPY --from=builder /app /app
WORKDIR /app
ENV PYTHONPATH /app
CMD ["/app/main.py"]

View File

@@ -0,0 +1,50 @@
# Github package 'latest' tag wrangler for containers
## Usage
Plug in the necessary inputs to determine if the container being built should be tagged 'latest; at the package level, for example `dbt-redshift:latest`.
## Inputs
| Input | Description |
| - | - |
| `package` | Name of the GH package to check against |
| `new_version` | Semver of new container |
| `gh_token` | GH token with package read scope|
| `halt_on_missing` | Return non-zero exit code if requested package does not exist. (defaults to false)|
## Outputs
| Output | Description |
| - | - |
| `latest` | Wether or not the new container should be tagged 'latest'|
| `minor_latest` | Wether or not the new container should be tagged major.minor.latest |
## Example workflow
```yaml
name: Ship it!
on:
workflow_dispatch:
inputs:
package:
description: The package to publish
required: true
version_number:
description: The version number
required: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Wrangle latest tag
id: is_latest
uses: ./.github/actions/latest-wrangler
with:
package: ${{ github.event.inputs.package }}
new_version: ${{ github.event.inputs.new_version }}
gh_token: ${{ secrets.GITHUB_TOKEN }}
- name: Print the results
run: |
echo "Is it latest? Survey says: ${{ steps.is_latest.outputs.latest }} !"
echo "Is it minor.latest? Survey says: ${{ steps.is_latest.outputs.minor_latest }} !"
```

View File

@@ -0,0 +1,20 @@
name: "Github package 'latest' tag wrangler for containers"
description: "Determines wether or not a given dbt container should be given a bare 'latest' tag (I.E. dbt-core:latest)"
inputs:
package_name:
description: "Package to check (I.E. dbt-core, dbt-redshift, etc)"
required: true
new_version:
description: "Semver of the container being built (I.E. 1.0.4)"
required: true
gh_token:
description: "Auth token for github (must have view packages scope)"
required: true
outputs:
latest:
description: "Wether or not built container should be tagged latest (bool)"
minor_latest:
description: "Wether or not built container should be tagged minor.latest (bool)"
runs:
using: "docker"
image: "Dockerfile"

View File

@@ -0,0 +1,26 @@
name: Ship it!
on:
workflow_dispatch:
inputs:
package:
description: The package to publish
required: true
version_number:
description: The version number
required: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Wrangle latest tag
id: is_latest
uses: ./.github/actions/latest-wrangler
with:
package: ${{ github.event.inputs.package }}
new_version: ${{ github.event.inputs.new_version }}
gh_token: ${{ secrets.GITHUB_TOKEN }}
- name: Print the results
run: |
echo "Is it latest? Survey says: ${{ steps.is_latest.outputs.latest }} !"

View File

@@ -0,0 +1,6 @@
{
"inputs": {
"version_number": "1.0.1",
"package": "dbt-redshift"
}
}

95
.github/actions/latest-wrangler/main.py vendored Normal file
View File

@@ -0,0 +1,95 @@
import os
import sys
import requests
from distutils.util import strtobool
from typing import Union
from packaging.version import parse, Version
if __name__ == "__main__":
# get inputs
package = os.environ["INPUT_PACKAGE"]
new_version = parse(os.environ["INPUT_NEW_VERSION"])
gh_token = os.environ["INPUT_GH_TOKEN"]
halt_on_missing = strtobool(os.environ.get("INPUT_HALT_ON_MISSING", "False"))
# get package metadata from github
package_request = requests.get(
f"https://api.github.com/orgs/dbt-labs/packages/container/{package}/versions",
auth=("", gh_token),
)
package_meta = package_request.json()
# Log info if we don't get a 200
if package_request.status_code != 200:
print(f"Call to GH API failed: {package_request.status_code} {package_meta['message']}")
# Make an early exit if there is no matching package in github
if package_request.status_code == 404:
if halt_on_missing:
sys.exit(1)
else:
# everything is the latest if the package doesn't exist
print(f"::set-output name=latest::{True}")
print(f"::set-output name=minor_latest::{True}")
sys.exit(0)
# TODO: verify package meta is "correct"
# https://github.com/dbt-labs/dbt-core/issues/4640
# map versions and tags
version_tag_map = {
version["id"]: version["metadata"]["container"]["tags"] for version in package_meta
}
# is pre-release
pre_rel = True if any(x in str(new_version) for x in ["a", "b", "rc"]) else False
# semver of current latest
for version, tags in version_tag_map.items():
if "latest" in tags:
# N.B. This seems counterintuitive, but we expect any version tagged
# 'latest' to have exactly three associated tags:
# latest, major.minor.latest, and major.minor.patch.
# Subtracting everything that contains the string 'latest' gets us
# the major.minor.patch which is what's needed for comparison.
current_latest = parse([tag for tag in tags if "latest" not in tag][0])
else:
current_latest = False
# semver of current_minor_latest
for version, tags in version_tag_map.items():
if f"{new_version.major}.{new_version.minor}.latest" in tags:
# Similar to above, only now we expect exactly two tags:
# major.minor.patch and major.minor.latest
current_minor_latest = parse([tag for tag in tags if "latest" not in tag][0])
else:
current_minor_latest = False
def is_latest(
pre_rel: bool, new_version: Version, remote_latest: Union[bool, Version]
) -> bool:
"""Determine if a given contaier should be tagged 'latest' based on:
- it's pre-release status
- it's version
- the version of a previously identified container tagged 'latest'
:param pre_rel: Wether or not the version of the new container is a pre-release
:param new_version: The version of the new container
:param remote_latest: The version of the previously identified container that's
already tagged latest or False
"""
# is a pre-release = not latest
if pre_rel:
return False
# + no latest tag found = is latest
if not remote_latest:
return True
# + if remote version is lower than current = is latest, else not latest
return True if remote_latest <= new_version else False
latest = is_latest(pre_rel, new_version, current_latest)
minor_latest = is_latest(pre_rel, new_version, current_minor_latest)
print(f"::set-output name=latest::{latest}")
print(f"::set-output name=minor_latest::{minor_latest}")

View File

@@ -18,4 +18,4 @@ resolves #
- [ ] I have signed the [CLA](https://docs.getdbt.com/docs/contributor-license-agreements) - [ ] I have signed the [CLA](https://docs.getdbt.com/docs/contributor-license-agreements)
- [ ] I have run this code in development and it appears to resolve the stated issue - [ ] I have run this code in development and it appears to resolve the stated issue
- [ ] This PR includes tests, or tests are not required/relevant for this PR - [ ] This PR includes tests, or tests are not required/relevant for this PR
- [ ] I have updated the `CHANGELOG.md` and added information about my change - [ ] I have added information about my change to be included in the [CHANGELOG](https://github.com/dbt-labs/dbt-core/blob/main/CONTRIBUTING.md#Adding-CHANGELOG-Entry).

View File

@@ -1,95 +0,0 @@
module.exports = ({ context }) => {
const defaultPythonVersion = "3.8";
const supportedPythonVersions = ["3.6", "3.7", "3.8", "3.9"];
const supportedAdapters = ["postgres"];
// if PR, generate matrix based on files changed and PR labels
if (context.eventName.includes("pull_request")) {
// `changes` is a list of adapter names that have related
// file changes in the PR
// ex: ['postgres', 'snowflake']
const changes = JSON.parse(process.env.CHANGES);
const labels = context.payload.pull_request.labels.map(({ name }) => name);
console.log("labels", labels);
console.log("changes", changes);
const testAllLabel = labels.includes("test all");
const include = [];
for (const adapter of supportedAdapters) {
if (
changes.includes(adapter) ||
testAllLabel ||
labels.includes(`test ${adapter}`)
) {
for (const pythonVersion of supportedPythonVersions) {
if (
pythonVersion === defaultPythonVersion ||
labels.includes(`test python${pythonVersion}`) ||
testAllLabel
) {
// always run tests on ubuntu by default
include.push({
os: "ubuntu-latest",
adapter,
"python-version": pythonVersion,
});
if (labels.includes("test windows") || testAllLabel) {
include.push({
os: "windows-latest",
adapter,
"python-version": pythonVersion,
});
}
if (labels.includes("test macos") || testAllLabel) {
include.push({
os: "macos-latest",
adapter,
"python-version": pythonVersion,
});
}
}
}
}
}
console.log("matrix", { include });
return {
include,
};
}
// if not PR, generate matrix of python version, adapter, and operating
// system to run integration tests on
const include = [];
// run for all adapters and python versions on ubuntu
for (const adapter of supportedAdapters) {
for (const pythonVersion of supportedPythonVersions) {
include.push({
os: 'ubuntu-latest',
adapter: adapter,
"python-version": pythonVersion,
});
}
}
// additionally include runs for all adapters, on macos and windows,
// but only for the default python version
for (const adapter of supportedAdapters) {
for (const operatingSystem of ["windows-latest", "macos-latest"]) {
include.push({
os: operatingSystem,
adapter: adapter,
"python-version": defaultPythonVersion,
});
}
}
console.log("matrix", { include });
return {
include,
};
};

34
.github/workflows/backport.yml vendored Normal file
View File

@@ -0,0 +1,34 @@
# **what?**
# When a PR is merged, if it has the backport label, it will create
# a new PR to backport those changes to the given branch. If it can't
# cleanly do a backport, it will comment on the merged PR of the failure.
#
# Label naming convention: "backport <branch name to backport to>"
# Example: backport 1.0.latest
#
# You MUST "Squash and merge" the original PR or this won't work.
# **why?**
# Changes sometimes need to be backported to release branches.
# This automates the backporting process
# **when?**
# Once a PR is "Squash and merge"'d and it has been correctly labeled
# according to the naming convention.
name: Backport
on:
pull_request:
types:
- closed
- labeled
jobs:
backport:
runs-on: ubuntu-18.04
name: Backport
steps:
- name: Backport
uses: tibdex/backport@v1.1.1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}

62
.github/workflows/changelog-check.yml vendored Normal file
View File

@@ -0,0 +1,62 @@
# **what?**
# Checks that a file has been committed under the /.changes directory
# as a new CHANGELOG entry. Cannot check for a specific filename as
# it is dynamically generated by change type and timestamp.
# This workflow should not require any secrets since it runs for PRs
# from forked repos.
# By default, secrets are not passed to workflows running from
# a forked repo.
# **why?**
# Ensure code change gets reflected in the CHANGELOG.
# **when?**
# This will run for all PRs going into main and *.latest.
name: Check Changelog Entry
on:
pull_request:
workflow_dispatch:
defaults:
run:
shell: bash
permissions:
contents: read
pull-requests: write
jobs:
changelog:
name: changelog
runs-on: ubuntu-latest
steps:
- name: Check if changelog file was added
# https://github.com/marketplace/actions/paths-changes-filter
# For each filter, it sets output variable named by the filter to the text:
# 'true' - if any of changed files matches any of filter rules
# 'false' - if none of changed files matches any of filter rules
# also, returns:
# `changes` - JSON array with names of all filters matching any of the changed files
uses: dorny/paths-filter@v2
id: filter
with:
token: ${{ secrets.GITHUB_TOKEN }}
filters: |
changelog:
- added: '.changes/unreleased/**.yaml'
- name: Check a file has been added to .changes/unreleased if required
uses: actions/github-script@v6
if: steps.filter.outputs.changelog == 'false' && !contains( github.event.pull_request.labels.*.name, 'Skip Changelog')
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: "Thank you for your pull request! We could not find a changelog entry for this change. For details on how to document a change, see [the contributing guide](CONTRIBUTING.md)."
})
core.setFailed('Changelog entry required to merge.')

View File

@@ -1,222 +0,0 @@
# **what?**
# This workflow runs all integration tests for supported OS
# and python versions and core adapters. If triggered by PR,
# the workflow will only run tests for adapters related
# to code changes. Use the `test all` and `test ${adapter}`
# label to run all or additional tests. Use `ok to test`
# label to mark PRs from forked repositories that are safe
# to run integration tests for. Requires secrets to run
# against different warehouses.
# **why?**
# This checks the functionality of dbt from a user's perspective
# and attempts to catch functional regressions.
# **when?**
# This workflow will run on every push to a protected branch
# and when manually triggered. It will also run for all PRs, including
# PRs from forks. The workflow will be skipped until there is a label
# to mark the PR as safe to run.
name: Adapter Integration Tests
on:
# pushes to release branches
push:
branches:
- "main"
- "develop"
- "*.latest"
- "releases/*"
# all PRs, important to note that `pull_request_target` workflows
# will run in the context of the target branch of a PR
pull_request_target:
# manual tigger
workflow_dispatch:
# explicitly turn off permissions for `GITHUB_TOKEN`
permissions: read-all
# will cancel previous workflows triggered by the same event and for the same ref for PRs or same SHA otherwise
concurrency:
group: ${{ github.workflow }}-${{ github.event_name }}-${{ contains(github.event_name, 'pull_request') && github.event.pull_request.head.ref || github.sha }}
cancel-in-progress: true
# sets default shell to bash, for all operating systems
defaults:
run:
shell: bash
jobs:
# generate test metadata about what files changed and the testing matrix to use
test-metadata:
# run if not a PR from a forked repository or has a label to mark as safe to test
if: >-
github.event_name != 'pull_request_target' ||
github.event.pull_request.head.repo.full_name == github.repository ||
contains(github.event.pull_request.labels.*.name, 'ok to test')
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.generate-matrix.outputs.result }}
steps:
- name: Check out the repository (non-PR)
if: github.event_name != 'pull_request_target'
uses: actions/checkout@v2
with:
persist-credentials: false
- name: Check out the repository (PR)
if: github.event_name == 'pull_request_target'
uses: actions/checkout@v2
with:
persist-credentials: false
ref: ${{ github.event.pull_request.head.sha }}
- name: Check if relevant files changed
# https://github.com/marketplace/actions/paths-changes-filter
# For each filter, it sets output variable named by the filter to the text:
# 'true' - if any of changed files matches any of filter rules
# 'false' - if none of changed files matches any of filter rules
# also, returns:
# `changes` - JSON array with names of all filters matching any of the changed files
uses: dorny/paths-filter@v2
id: get-changes
with:
token: ${{ secrets.GITHUB_TOKEN }}
filters: |
postgres:
- 'core/**'
- 'plugins/postgres/**'
- 'dev-requirements.txt'
- name: Generate integration test matrix
id: generate-matrix
uses: actions/github-script@v4
env:
CHANGES: ${{ steps.get-changes.outputs.changes }}
with:
script: |
const script = require('./.github/scripts/integration-test-matrix.js')
const matrix = script({ context })
console.log(matrix)
return matrix
test:
name: ${{ matrix.adapter }} / python ${{ matrix.python-version }} / ${{ matrix.os }}
# run if not a PR from a forked repository or has a label to mark as safe to test
# also checks that the matrix generated is not empty
if: >-
needs.test-metadata.outputs.matrix &&
fromJSON( needs.test-metadata.outputs.matrix ).include[0] &&
(
github.event_name != 'pull_request_target' ||
github.event.pull_request.head.repo.full_name == github.repository ||
contains(github.event.pull_request.labels.*.name, 'ok to test')
)
runs-on: ${{ matrix.os }}
needs: test-metadata
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.test-metadata.outputs.matrix) }}
env:
TOXENV: integration-${{ matrix.adapter }}
PYTEST_ADDOPTS: "-v --color=yes -n4 --csv integration_results.csv"
DBT_INVOCATION_ENV: github-actions
steps:
- name: Check out the repository
if: github.event_name != 'pull_request_target'
uses: actions/checkout@v2
with:
persist-credentials: false
# explicity checkout the branch for the PR,
# this is necessary for the `pull_request_target` event
- name: Check out the repository (PR)
if: github.event_name == 'pull_request_target'
uses: actions/checkout@v2
with:
persist-credentials: false
ref: ${{ github.event.pull_request.head.sha }}
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Set up postgres (linux)
if: |
matrix.adapter == 'postgres' &&
runner.os == 'Linux'
uses: ./.github/actions/setup-postgres-linux
- name: Set up postgres (macos)
if: |
matrix.adapter == 'postgres' &&
runner.os == 'macOS'
uses: ./.github/actions/setup-postgres-macos
- name: Set up postgres (windows)
if: |
matrix.adapter == 'postgres' &&
runner.os == 'Windows'
uses: ./.github/actions/setup-postgres-windows
- name: Install python dependencies
run: |
pip install --user --upgrade pip
pip install tox
pip --version
tox --version
- name: Run tox (postgres)
if: matrix.adapter == 'postgres'
run: tox
- uses: actions/upload-artifact@v2
if: always()
with:
name: logs
path: ./logs
- name: Get current date
if: always()
id: date
run: echo "::set-output name=date::$(date +'%Y-%m-%dT%H_%M_%S')" #no colons allowed for artifacts
- uses: actions/upload-artifact@v2
if: always()
with:
name: integration_results_${{ matrix.python-version }}_${{ matrix.os }}_${{ matrix.adapter }}-${{ steps.date.outputs.date }}.csv
path: integration_results.csv
require-label-comment:
runs-on: ubuntu-latest
needs: test
permissions:
pull-requests: write
steps:
- name: Needs permission PR comment
if: >-
needs.test.result == 'skipped' &&
github.event_name == 'pull_request_target' &&
github.event.pull_request.head.repo.full_name != github.repository
uses: unsplash/comment-on-pr@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
msg: |
"You do not have permissions to run integration tests, @dbt-labs/core "\
"needs to label this PR with `ok to test` in order to run integration tests!"
check_for_duplicate_msg: true

26
.github/workflows/jira-creation.yml vendored Normal file
View File

@@ -0,0 +1,26 @@
# **what?**
# Mirrors issues into Jira. Includes the information: title,
# GitHub Issue ID and URL
# **why?**
# Jira is our tool for tracking and we need to see these issues in there
# **when?**
# On issue creation or when an issue is labeled `Jira`
name: Jira Issue Creation
on:
issues:
types: [opened, labeled]
permissions:
issues: write
jobs:
call-label-action:
uses: dbt-labs/jira-actions/.github/workflows/jira-creation.yml@main
secrets:
JIRA_BASE_URL: ${{ secrets.JIRA_BASE_URL }}
JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }}
JIRA_API_TOKEN: ${{ secrets.JIRA_API_TOKEN }}

26
.github/workflows/jira-label.yml vendored Normal file
View File

@@ -0,0 +1,26 @@
# **what?**
# Calls mirroring Jira label Action. Includes adding a new label
# to an existing issue or removing a label as well
# **why?**
# Jira is our tool for tracking and we need to see these labels in there
# **when?**
# On labels being added or removed from issues
name: Jira Label Mirroring
on:
issues:
types: [labeled, unlabeled]
permissions:
issues: read
jobs:
call-label-action:
uses: dbt-labs/jira-actions/.github/workflows/jira-label.yml@main
secrets:
JIRA_BASE_URL: ${{ secrets.JIRA_BASE_URL }}
JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }}
JIRA_API_TOKEN: ${{ secrets.JIRA_API_TOKEN }}

24
.github/workflows/jira-transition.yml vendored Normal file
View File

@@ -0,0 +1,24 @@
# **what?**
# Transition a Jira issue to a new state
# Only supports these GitHub Issue transitions:
# closed, deleted, reopened
# **why?**
# Jira needs to be kept up-to-date
# **when?**
# On issue closing, deletion, reopened
name: Jira Issue Transition
on:
issues:
types: [closed, deleted, reopened]
jobs:
call-label-action:
uses: dbt-labs/jira-actions/.github/workflows/jira-transition.yml@main
secrets:
JIRA_BASE_URL: ${{ secrets.JIRA_BASE_URL }}
JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }}
JIRA_API_TOKEN: ${{ secrets.JIRA_API_TOKEN }}

View File

@@ -1,9 +1,8 @@
# **what?** # **what?**
# Runs code quality checks, unit tests, and verifies python build on # Runs code quality checks, unit tests, integration tests and
# all code commited to the repository. This workflow should not # verifies python build on all code commited to the repository. This workflow
# require any secrets since it runs for PRs from forked repos. # should not require any secrets since it runs for PRs from forked repos. By
# By default, secrets are not passed to workflows running from # default, secrets are not passed to workflows running from a forked repos.
# a forked repo.
# **why?** # **why?**
# Ensure code for dbt meets a certain quality standard. # Ensure code for dbt meets a certain quality standard.
@@ -18,7 +17,6 @@ on:
push: push:
branches: branches:
- "main" - "main"
- "develop"
- "*.latest" - "*.latest"
- "releases/*" - "releases/*"
pull_request: pull_request:
@@ -37,24 +35,13 @@ defaults:
jobs: jobs:
code-quality: code-quality:
name: ${{ matrix.toxenv }} name: code-quality
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
toxenv: [flake8, mypy]
env:
TOXENV: ${{ matrix.toxenv }}
PYTEST_ADDOPTS: "-v --color=yes"
steps: steps:
- name: Check out the repository - name: Check out the repository
uses: actions/checkout@v2 uses: actions/checkout@v2
with:
persist-credentials: false
- name: Set up Python - name: Set up Python
uses: actions/setup-python@v2 uses: actions/setup-python@v2
@@ -62,12 +49,16 @@ jobs:
- name: Install python dependencies - name: Install python dependencies
run: | run: |
pip install --user --upgrade pip pip install --user --upgrade pip
pip install tox
pip --version pip --version
tox --version pip install pre-commit
pre-commit --version
pip install mypy==0.782
mypy --version
pip install -r editable-requirements.txt
dbt --version
- name: Run tox - name: Run pre-commit hooks
run: tox run: pre-commit run --all-files --show-diff-on-failure
unit: unit:
name: unit test / python ${{ matrix.python-version }} name: unit test / python ${{ matrix.python-version }}
@@ -77,7 +68,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
python-version: [3.6, 3.7, 3.8] # TODO: support unit testing for python 3.9 (https://github.com/dbt-labs/dbt/issues/3689) python-version: [3.7, 3.8, 3.9]
env: env:
TOXENV: "unit" TOXENV: "unit"
@@ -86,8 +77,6 @@ jobs:
steps: steps:
- name: Check out the repository - name: Check out the repository
uses: actions/checkout@v2 uses: actions/checkout@v2
with:
persist-credentials: false
- name: Set up Python ${{ matrix.python-version }} - name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2 uses: actions/setup-python@v2
@@ -97,8 +86,8 @@ jobs:
- name: Install python dependencies - name: Install python dependencies
run: | run: |
pip install --user --upgrade pip pip install --user --upgrade pip
pip install tox
pip --version pip --version
pip install tox
tox --version tox --version
- name: Run tox - name: Run tox
@@ -115,6 +104,75 @@ jobs:
name: unit_results_${{ matrix.python-version }}-${{ steps.date.outputs.date }}.csv name: unit_results_${{ matrix.python-version }}-${{ steps.date.outputs.date }}.csv
path: unit_results.csv path: unit_results.csv
integration:
name: integration test / python ${{ matrix.python-version }} / ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
python-version: [3.7, 3.8, 3.9]
os: [ubuntu-latest]
include:
- python-version: 3.8
os: windows-latest
- python-version: 3.8
os: macos-latest
env:
TOXENV: integration
PYTEST_ADDOPTS: "-v --color=yes -n4 --csv integration_results.csv"
DBT_INVOCATION_ENV: github-actions
steps:
- name: Check out the repository
uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Set up postgres (linux)
if: runner.os == 'Linux'
uses: ./.github/actions/setup-postgres-linux
- name: Set up postgres (macos)
if: runner.os == 'macOS'
uses: ./.github/actions/setup-postgres-macos
- name: Set up postgres (windows)
if: runner.os == 'Windows'
uses: ./.github/actions/setup-postgres-windows
- name: Install python tools
run: |
pip install --user --upgrade pip
pip --version
pip install tox
tox --version
- name: Run tests
run: tox
- name: Get current date
if: always()
id: date
run: echo "::set-output name=date::$(date +'%Y_%m_%dT%H_%M_%S')" #no colons allowed for artifacts
- uses: actions/upload-artifact@v2
if: always()
with:
name: logs_${{ matrix.python-version }}_${{ matrix.os }}_${{ steps.date.outputs.date }}
path: ./logs
- uses: actions/upload-artifact@v2
if: always()
with:
name: integration_results_${{ matrix.python-version }}_${{ matrix.os }}_${{ steps.date.outputs.date }}.csv
path: integration_results.csv
build: build:
name: build packages name: build packages
@@ -123,8 +181,6 @@ jobs:
steps: steps:
- name: Check out the repository - name: Check out the repository
uses: actions/checkout@v2 uses: actions/checkout@v2
with:
persist-credentials: false
- name: Set up Python - name: Set up Python
uses: actions/setup-python@v2 uses: actions/setup-python@v2
@@ -151,44 +207,6 @@ jobs:
run: | run: |
check-wheel-contents dist/*.whl --ignore W007,W008 check-wheel-contents dist/*.whl --ignore W007,W008
- uses: actions/upload-artifact@v2
with:
name: dist
path: dist/
test-build:
name: verify packages / python ${{ matrix.python-version }} / ${{ matrix.os }}
needs: build
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: [3.6, 3.7, 3.8, 3.9]
steps:
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install python dependencies
run: |
pip install --user --upgrade pip
pip install --upgrade wheel
pip --version
- uses: actions/download-artifact@v2
with:
name: dist
path: dist/
- name: Show distributions
run: ls -lh dist/
- name: Install wheel distributions - name: Install wheel distributions
run: | run: |
find ./dist/*.whl -maxdepth 1 -type f | xargs pip install --force-reinstall --find-links=dist/ find ./dist/*.whl -maxdepth 1 -type f | xargs pip install --force-reinstall --find-links=dist/
@@ -198,8 +216,9 @@ jobs:
dbt --version dbt --version
- name: Install source distributions - name: Install source distributions
# ignore dbt-1.0.0, which intentionally raises an error when installed from source
run: | run: |
find ./dist/*.gz -maxdepth 1 -type f | xargs pip install --force-reinstall --find-links=dist/ find ./dist/dbt-[a-z]*.gz -maxdepth 1 -type f | xargs pip install --force-reinstall --find-links=dist/
- name: Check source distributions - name: Check source distributions
run: | run: |

113
.github/workflows/release-docker.yml vendored Normal file
View File

@@ -0,0 +1,113 @@
# **what?**
# This workflow will generate a series of docker images for dbt and push them to the github container registry
# **why?**
# Docker images for dbt are used in a number of important places throughout the dbt ecosystem. This is how we keep those images up-to-date.
# **when?**
# This is triggered manually
# **next steps**
# - build this into the release workflow (or conversly, break out the different release methods into their own workflow files)
name: Docker release
on:
workflow_dispatch:
inputs:
package:
description: The package to release. _One_ of [dbt-core, dbt-redshift, dbt-bigquery, dbt-snowflake, dbt-spark, dbt-postgres]
required: true
version_number:
description: The release version number (i.e. 1.0.0b1). Do not include `latest` tags or a leading `v`!
required: true
jobs:
get_version_meta:
name: Get version meta
runs-on: ubuntu-latest
outputs:
major: ${{ steps.version.outputs.major }}
minor: ${{ steps.version.outputs.minor }}
patch: ${{ steps.version.outputs.patch }}
latest: ${{ steps.latest.outputs.latest }}
minor_latest: ${{ steps.latest.outputs.minor_latest }}
steps:
- uses: actions/checkout@v1
- name: Split version
id: version
run: |
IFS="." read -r MAJOR MINOR PATCH <<< ${{ github.event.inputs.version_number }}
echo "::set-output name=major::$MAJOR"
echo "::set-output name=minor::$MINOR"
echo "::set-output name=patch::$PATCH"
- name: Is pkg 'latest'
id: latest
uses: ./.github/actions/latest-wrangler
with:
package: ${{ github.event.inputs.package }}
new_version: ${{ github.event.inputs.version_number }}
gh_token: ${{ secrets.GITHUB_TOKEN }}
halt_on_missing: False
setup_image_builder:
name: Set up docker image builder
runs-on: ubuntu-latest
needs: [get_version_meta]
steps:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
build_and_push:
name: Build images and push to GHCR
runs-on: ubuntu-latest
needs: [setup_image_builder, get_version_meta]
steps:
- name: Get docker build arg
id: build_arg
run: |
echo "::set-output name=build_arg_name::"$(echo ${{ github.event.inputs.package }} | sed 's/\-/_/g')
echo "::set-output name=build_arg_value::"$(echo ${{ github.event.inputs.package }} | sed 's/postgres/core/g')
- name: Log in to the GHCR
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push MAJOR.MINOR.PATCH tag
uses: docker/build-push-action@v2
with:
file: docker/Dockerfile
push: True
target: ${{ github.event.inputs.package }}
build-args: |
${{ steps.build_arg.outputs.build_arg_name }}_ref=${{ steps.build_arg.outputs.build_arg_value }}@v${{ github.event.inputs.version_number }}
tags: |
ghcr.io/dbt-labs/${{ github.event.inputs.package }}:${{ github.event.inputs.version_number }}
- name: Build and push MINOR.latest tag
uses: docker/build-push-action@v2
if: ${{ needs.get_version_meta.outputs.minor_latest == 'True' }}
with:
file: docker/Dockerfile
push: True
target: ${{ github.event.inputs.package }}
build-args: |
${{ steps.build_arg.outputs.build_arg_name }}_ref=${{ steps.build_arg.outputs.build_arg_value }}@v${{ github.event.inputs.version_number }}
tags: |
ghcr.io/dbt-labs/${{ github.event.inputs.package }}:${{ needs.get_version_meta.outputs.major }}.${{ needs.get_version_meta.outputs.minor }}.latest
- name: Build and push latest tag
uses: docker/build-push-action@v2
if: ${{ needs.get_version_meta.outputs.latest == 'True' }}
with:
file: docker/Dockerfile
push: True
target: ${{ github.event.inputs.package }}
build-args: |
${{ steps.build_arg.outputs.build_arg_name }}_ref=${{ steps.build_arg.outputs.build_arg_value }}@v${{ github.event.inputs.version_number }}
tags: |
ghcr.io/dbt-labs/${{ github.event.inputs.package }}:latest

199
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,199 @@
# **what?**
# Take the given commit, run unit tests specifically on that sha, build and
# package it, and then release to GitHub and PyPi with that specific build
# **why?**
# Ensure an automated and tested release process
# **when?**
# This will only run manually with a given sha and version
name: Release to GitHub and PyPi
on:
workflow_dispatch:
inputs:
sha:
description: 'The last commit sha in the release'
required: true
version_number:
description: 'The release version number (i.e. 1.0.0b1)'
required: true
defaults:
run:
shell: bash
jobs:
unit:
name: Unit test
runs-on: ubuntu-latest
env:
TOXENV: "unit"
steps:
- name: Check out the repository
uses: actions/checkout@v2
with:
persist-credentials: false
ref: ${{ github.event.inputs.sha }}
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Install python dependencies
run: |
pip install --user --upgrade pip
pip install tox
pip --version
tox --version
- name: Run tox
run: tox
build:
name: build packages
runs-on: ubuntu-latest
steps:
- name: Check out the repository
uses: actions/checkout@v2
with:
persist-credentials: false
ref: ${{ github.event.inputs.sha }}
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Install python dependencies
run: |
pip install --user --upgrade pip
pip install --upgrade setuptools wheel twine check-wheel-contents
pip --version
- name: Build distributions
run: ./scripts/build-dist.sh
- name: Show distributions
run: ls -lh dist/
- name: Check distribution descriptions
run: |
twine check dist/*
- name: Check wheel contents
run: |
check-wheel-contents dist/*.whl --ignore W007,W008
- uses: actions/upload-artifact@v2
with:
name: dist
path: |
dist/
!dist/dbt-${{github.event.inputs.version_number}}.tar.gz
test-build:
name: verify packages
needs: [build, unit]
runs-on: ubuntu-latest
steps:
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Install python dependencies
run: |
pip install --user --upgrade pip
pip install --upgrade wheel
pip --version
- uses: actions/download-artifact@v2
with:
name: dist
path: dist/
- name: Show distributions
run: ls -lh dist/
- name: Install wheel distributions
run: |
find ./dist/*.whl -maxdepth 1 -type f | xargs pip install --force-reinstall --find-links=dist/
- name: Check wheel distributions
run: |
dbt --version
- name: Install source distributions
run: |
find ./dist/*.gz -maxdepth 1 -type f | xargs pip install --force-reinstall --find-links=dist/
- name: Check source distributions
run: |
dbt --version
github-release:
name: GitHub Release
needs: test-build
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v2
with:
name: dist
path: '.'
# Need to set an output variable because env variables can't be taken as input
# This is needed for the next step with releasing to GitHub
- name: Find release type
id: release_type
env:
IS_PRERELEASE: ${{ contains(github.event.inputs.version_number, 'rc') || contains(github.event.inputs.version_number, 'b') }}
run: |
echo ::set-output name=isPrerelease::$IS_PRERELEASE
- name: Creating GitHub Release
uses: softprops/action-gh-release@v1
with:
name: dbt-core v${{github.event.inputs.version_number}}
tag_name: v${{github.event.inputs.version_number}}
prerelease: ${{ steps.release_type.outputs.isPrerelease }}
target_commitish: ${{github.event.inputs.sha}}
body: |
[Release notes](https://github.com/dbt-labs/dbt-core/blob/main/CHANGELOG.md)
files: |
dbt_postgres-${{github.event.inputs.version_number}}-py3-none-any.whl
dbt_core-${{github.event.inputs.version_number}}-py3-none-any.whl
dbt-postgres-${{github.event.inputs.version_number}}.tar.gz
dbt-core-${{github.event.inputs.version_number}}.tar.gz
pypi-release:
name: Pypi release
runs-on: ubuntu-latest
needs: github-release
environment: PypiProd
steps:
- uses: actions/download-artifact@v2
with:
name: dist
path: 'dist'
- name: Publish distribution to PyPI
uses: pypa/gh-action-pypi-publish@v1.4.2
with:
password: ${{ secrets.PYPI_API_TOKEN }}

View File

@@ -0,0 +1,73 @@
# This Action checks makes a dbt run to sample json structured logs
# and checks that they conform to the currently documented schema.
#
# If this action fails it either means we have unintentionally deviated
# from our documented structured logging schema, or we need to bump the
# version of our structured logging and add new documentation to
# communicate these changes.
name: Structured Logging Schema Check
on:
push:
branches:
- "main"
- "*.latest"
- "releases/*"
pull_request:
workflow_dispatch:
permissions: read-all
jobs:
# run the performance measurements on the current or default branch
test-schema:
name: Test Log Schema
runs-on: ubuntu-latest
env:
# turns warnings into errors
RUSTFLAGS: "-D warnings"
# points tests to the log file
LOG_DIR: "/home/runner/work/dbt-core/dbt-core/logs"
# tells integration tests to output into json format
DBT_LOG_FORMAT: "json"
steps:
- name: checkout dev
uses: actions/checkout@v2
with:
persist-credentials: false
- name: Setup Python
uses: actions/setup-python@v2.2.2
with:
python-version: "3.8"
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Install python dependencies
run: |
pip install --user --upgrade pip
pip --version
pip install tox
tox --version
- name: Set up postgres
uses: ./.github/actions/setup-postgres-linux
- name: ls
run: ls
# integration tests generate a ton of logs in different files. the next step will find them all.
# we actually care if these pass, because the normal test run doesn't usually include many json log outputs
- name: Run integration tests
run: tox -e integration -- -nauto
# apply our schema tests to every log event from the previous step
# skips any output that isn't valid json
- uses: actions-rs/cargo@v1
with:
command: run
args: --manifest-path test/interop/log_parsing/Cargo.toml

1
.github/workflows/test/.actrc vendored Normal file
View File

@@ -0,0 +1 @@
-P ubuntu-latest=ghcr.io/catthehacker/ubuntu:act-latest

1
.github/workflows/test/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.secrets

View File

@@ -0,0 +1 @@
GITHUB_TOKEN=GH_PERSONAL_ACCESS_TOKEN_GOES_HERE

View File

@@ -0,0 +1,6 @@
{
"inputs": {
"version_number": "1.0.1",
"package": "dbt-postgres"
}
}

View File

@@ -66,12 +66,12 @@ jobs:
git push origin bumping-version/${{steps.variables.outputs.VERSION_NUMBER}}_$GITHUB_RUN_ID git push origin bumping-version/${{steps.variables.outputs.VERSION_NUMBER}}_$GITHUB_RUN_ID
git branch --set-upstream-to=origin/bumping-version/${{steps.variables.outputs.VERSION_NUMBER}}_$GITHUB_RUN_ID bumping-version/${{steps.variables.outputs.VERSION_NUMBER}}_$GITHUB_RUN_ID git branch --set-upstream-to=origin/bumping-version/${{steps.variables.outputs.VERSION_NUMBER}}_$GITHUB_RUN_ID bumping-version/${{steps.variables.outputs.VERSION_NUMBER}}_$GITHUB_RUN_ID
- name: Generate Docker requirements # - name: Generate Docker requirements
run: | # run: |
source env/bin/activate # source env/bin/activate
pip install -r requirements.txt # pip install -r requirements.txt
pip freeze -l > docker/requirements/requirements.txt # pip freeze -l > docker/requirements/requirements.txt
git status # git status
- name: Bump version - name: Bump version
run: | run: |

9
.gitignore vendored
View File

@@ -49,9 +49,8 @@ coverage.xml
*,cover *,cover
.hypothesis/ .hypothesis/
test.env test.env
*.pytest_cache/
# Mypy
.mypy_cache/
# Translations # Translations
*.mo *.mo
@@ -66,10 +65,10 @@ docs/_build/
# PyBuilder # PyBuilder
target/ target/
#Ipython Notebook # Ipython Notebook
.ipynb_checkpoints .ipynb_checkpoints
#Emacs # Emacs
*~ *~
# Sublime Text # Sublime Text
@@ -78,6 +77,7 @@ target/
# Vim # Vim
*.sw* *.sw*
# Pyenv
.python-version .python-version
# Vim # Vim
@@ -90,6 +90,7 @@ venv/
# AWS credentials # AWS credentials
.aws/ .aws/
# MacOS
.DS_Store .DS_Store
# vscode # vscode

68
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,68 @@
# Configuration for pre-commit hooks (see https://pre-commit.com/).
# Eventually the hooks described here will be run as tests before merging each PR.
# TODO: remove global exclusion of tests when testing overhaul is complete
exclude: ^test/
# Force all unspecified python hooks to run python 3.8
default_language_version:
python: python3.8
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: check-yaml
args: [--unsafe]
- id: check-json
- id: end-of-file-fixer
- id: trailing-whitespace
exclude_types:
- "markdown"
- id: check-case-conflict
- repo: https://github.com/psf/black
rev: 21.12b0
hooks:
- id: black
args:
- "--line-length=99"
- "--target-version=py38"
- id: black
alias: black-check
stages: [manual]
args:
- "--line-length=99"
- "--target-version=py38"
- "--check"
- "--diff"
- repo: https://gitlab.com/pycqa/flake8
rev: 4.0.1
hooks:
- id: flake8
- id: flake8
alias: flake8-check
stages: [manual]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.782
hooks:
- id: mypy
# N.B.: Mypy is... a bit fragile.
#
# By using `language: system` we run this hook in the local
# environment instead of a pre-commit isolated one. This is needed
# to ensure mypy correctly parses the project.
# It may cause trouble
# in that it adds environmental variables out of our control to the
# mix. Unfortunately, there's nothing we can do about per pre-commit's
# author.
# See https://github.com/pre-commit/pre-commit/issues/730 for details.
args: [--show-error-codes]
files: ^core/dbt/
language: system
- id: mypy
alias: mypy-check
stages: [manual]
args: [--show-error-codes, --pretty]
files: ^core/dbt/
language: system

View File

@@ -2,18 +2,25 @@ The core function of dbt is SQL compilation and execution. Users create projects
## dbt-core ## dbt-core
Most of the python code in the repository is within the `core/dbt` directory. Currently the main subdirectories are: Most of the python code in the repository is within the `core/dbt` directory.
- [`single python files`](core/dbt/README.md): A number of individual files, such as 'compilation.py' and 'exceptions.py'
- [`adapters`](core/dbt/adapters): Define base classes for behavior that is likely to differ across databases The main subdirectories of core/dbt:
- [`clients`](core/dbt/clients): Interface with dependencies (agate, jinja) or across operating systems - [`adapters`](core/dbt/adapters/README.md): Define base classes for behavior that is likely to differ across databases
- [`config`](core/dbt/config): Reconcile user-supplied configuration from connection profiles, project files, and Jinja macros - [`clients`](core/dbt/clients/README.md): Interface with dependencies (agate, jinja) or across operating systems
- [`context`](core/dbt/context): Build and expose dbt-specific Jinja functionality - [`config`](core/dbt/config/README.md): Reconcile user-supplied configuration from connection profiles, project files, and Jinja macros
- [`contracts`](core/dbt/contracts): Define Python objects (dataclasses) that dbt expects to create and validate - [`context`](core/dbt/context/README.md): Build and expose dbt-specific Jinja functionality
- [`deps`](core/dbt/deps): Package installation and dependency resolution - [`contracts`](core/dbt/contracts/README.md): Define Python objects (dataclasses) that dbt expects to create and validate
- [`graph`](core/dbt/graph): Produce a `networkx` DAG of project resources, and selecting those resources given user-supplied criteria - [`deps`](core/dbt/deps/README.md): Package installation and dependency resolution
- [`include`](core/dbt/include): The dbt "global project," which defines default implementations of Jinja2 macros - [`events`](core/dbt/events/README.md): Logging events
- [`parser`](core/dbt/parser): Read project files, validate, construct python objects - [`graph`](core/dbt/graph/README.md): Produce a `networkx` DAG of project resources, and selecting those resources given user-supplied criteria
- [`task`](core/dbt/task): Set forth the actions that dbt can perform when invoked - [`include`](core/dbt/include/README.md): The dbt "global project," which defines default implementations of Jinja2 macros
- [`parser`](core/dbt/parser/README.md): Read project files, validate, construct python objects
- [`task`](core/dbt/task/README.md): Set forth the actions that dbt can perform when invoked
Legacy tests are found in the 'test' directory:
- [`unit tests`](core/dbt/test/unit/README.md): Unit tests
- [`integration tests`](core/dbt/test/integration/README.md): Integration tests
### Invoking dbt ### Invoking dbt
@@ -44,4 +51,4 @@ The [`test/`](test/) subdirectory includes unit and integration tests that run a
- [docker](docker/): All dbt versions are published as Docker images on DockerHub. This subfolder contains the `Dockerfile` (constant) and `requirements.txt` (one for each version). - [docker](docker/): All dbt versions are published as Docker images on DockerHub. This subfolder contains the `Dockerfile` (constant) and `requirements.txt` (one for each version).
- [etc](etc/): Images for README - [etc](etc/): Images for README
- [scripts](scripts/): Helper scripts for testing, releasing, and producing JSON schemas. These are not included in distributions of dbt, not are they rigorously tested—they're just handy tools for the dbt maintainers :) - [scripts](scripts/): Helper scripts for testing, releasing, and producing JSON schemas. These are not included in distributions of dbt, nor are they rigorously tested—they're just handy tools for the dbt maintainers :)

3492
CHANGELOG.md Normal file → Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
## About this document ## About this document
This document is a guide intended for folks interested in contributing to `dbt`. Below, we document the process by which members of the community should create issues and submit pull requests (PRs) in this repository. It is not intended as a guide for using `dbt`, and it assumes a certain level of familiarity with Python concepts such as virtualenvs, `pip`, python modules, filesystems, and so on. This guide assumes you are using macOS or Linux and are comfortable with the command line. This document is a guide intended for folks interested in contributing to `dbt-core`. Below, we document the process by which members of the community should create issues and submit pull requests (PRs) in this repository. It is not intended as a guide for using `dbt-core`, and it assumes a certain level of familiarity with Python concepts such as virtualenvs, `pip`, python modules, filesystems, and so on. This guide assumes you are using macOS or Linux and are comfortable with the command line.
If you're new to python development or contributing to open-source software, we encourage you to read this document from start to finish. If you get stuck, drop us a line in the `#dbt-core-development` channel on [slack](https://community.getdbt.com). If you're new to python development or contributing to open-source software, we encourage you to read this document from start to finish. If you get stuck, drop us a line in the `#dbt-core-development` channel on [slack](https://community.getdbt.com).
@@ -20,101 +20,103 @@ If you have an issue or code change suggestion related to a specific database [a
### Signing the CLA ### Signing the CLA
Please note that all contributors to `dbt` must sign the [Contributor License Agreement](https://docs.getdbt.com/docs/contributor-license-agreements) to have their Pull Request merged into the `dbt` codebase. If you are unable to sign the CLA, then the `dbt` maintainers will unfortunately be unable to merge your Pull Request. You are, however, welcome to open issues and comment on existing ones. Please note that all contributors to `dbt-core` must sign the [Contributor License Agreement](https://docs.getdbt.com/docs/contributor-license-agreements) to have their Pull Request merged into the `dbt-core` codebase. If you are unable to sign the CLA, then the `dbt-core` maintainers will unfortunately be unable to merge your Pull Request. You are, however, welcome to open issues and comment on existing ones.
## Proposing a change ## Proposing a change
`dbt` is Apache 2.0-licensed open source software. `dbt` is what it is today because community members like you have opened issues, provided feedback, and contributed to the knowledge loop for the entire communtiy. Whether you are a seasoned open source contributor or a first-time committer, we welcome and encourage you to contribute code, documentation, ideas, or problem statements to this project. `dbt-core` is Apache 2.0-licensed open source software. `dbt-core` is what it is today because community members like you have opened issues, provided feedback, and contributed to the knowledge loop for the entire communtiy. Whether you are a seasoned open source contributor or a first-time committer, we welcome and encourage you to contribute code, documentation, ideas, or problem statements to this project.
### Defining the problem ### Defining the problem
If you have an idea for a new feature or if you've discovered a bug in `dbt`, the first step is to open an issue. Please check the list of [open issues](https://github.com/dbt-labs/dbt-core/issues) before creating a new one. If you find a relevant issue, please add a comment to the open issue instead of creating a new one. There are hundreds of open issues in this repository and it can be hard to know where to look for a relevant open issue. **The `dbt` maintainers are always happy to point contributors in the right direction**, so please err on the side of documenting your idea in a new issue if you are unsure where a problem statement belongs. If you have an idea for a new feature or if you've discovered a bug in `dbt-core`, the first step is to open an issue. Please check the list of [open issues](https://github.com/dbt-labs/dbt-core/issues) before creating a new one. If you find a relevant issue, please add a comment to the open issue instead of creating a new one. There are hundreds of open issues in this repository and it can be hard to know where to look for a relevant open issue. **The `dbt-core` maintainers are always happy to point contributors in the right direction**, so please err on the side of documenting your idea in a new issue if you are unsure where a problem statement belongs.
> **Note:** All community-contributed Pull Requests _must_ be associated with an open issue. If you submit a Pull Request that does not pertain to an open issue, you will be asked to create an issue describing the problem before the Pull Request can be reviewed. > **Note:** All community-contributed Pull Requests _must_ be associated with an open issue. If you submit a Pull Request that does not pertain to an open issue, you will be asked to create an issue describing the problem before the Pull Request can be reviewed.
### Discussing the idea ### Discussing the idea
After you open an issue, a `dbt` maintainer will follow up by commenting on your issue (usually within 1-3 days) to explore your idea further and advise on how to implement the suggested changes. In many cases, community members will chime in with their own thoughts on the problem statement. If you as the issue creator are interested in submitting a Pull Request to address the issue, you should indicate this in the body of the issue. The `dbt` maintainers are _always_ happy to help contributors with the implementation of fixes and features, so please also indicate if there's anything you're unsure about or could use guidance around in the issue. After you open an issue, a `dbt-core` maintainer will follow up by commenting on your issue (usually within 1-3 days) to explore your idea further and advise on how to implement the suggested changes. In many cases, community members will chime in with their own thoughts on the problem statement. If you as the issue creator are interested in submitting a Pull Request to address the issue, you should indicate this in the body of the issue. The `dbt-core` maintainers are _always_ happy to help contributors with the implementation of fixes and features, so please also indicate if there's anything you're unsure about or could use guidance around in the issue.
### Submitting a change ### Submitting a change
If an issue is appropriately well scoped and describes a beneficial change to the `dbt` codebase, then anyone may submit a Pull Request to implement the functionality described in the issue. See the sections below on how to do this. If an issue is appropriately well scoped and describes a beneficial change to the `dbt-core` codebase, then anyone may submit a Pull Request to implement the functionality described in the issue. See the sections below on how to do this.
The `dbt` maintainers will add a `good first issue` label if an issue is suitable for a first-time contributor. This label often means that the required code change is small, limited to one database adapter, or a net-new addition that does not impact existing functionality. You can see the list of currently open issues on the [Contribute](https://github.com/dbt-labs/dbt-core/contribute) page. The `dbt-core` maintainers will add a `good first issue` label if an issue is suitable for a first-time contributor. This label often means that the required code change is small, limited to one database adapter, or a net-new addition that does not impact existing functionality. You can see the list of currently open issues on the [Contribute](https://github.com/dbt-labs/dbt-core/contribute) page.
Here's a good workflow: Here's a good workflow:
- Comment on the open issue, expressing your interest in contributing the required code change - Comment on the open issue, expressing your interest in contributing the required code change
- Outline your planned implementation. If you want help getting started, ask! - Outline your planned implementation. If you want help getting started, ask!
- Follow the steps outlined below to develop locally. Once you have opened a PR, one of the `dbt` maintainers will work with you to review your code. - Follow the steps outlined below to develop locally. Once you have opened a PR, one of the `dbt-core` maintainers will work with you to review your code.
- Add a test! Tests are crucial for both fixes and new features alike. We want to make sure that code works as intended, and that it avoids any bugs previously encountered. Currently, the best resource for understanding `dbt`'s [unit](test/unit) and [integration](test/integration) tests is the tests themselves. One of the maintainers can help by pointing out relevant examples. - Add a test! Tests are crucial for both fixes and new features alike. We want to make sure that code works as intended, and that it avoids any bugs previously encountered. Currently, the best resource for understanding `dbt-core`'s [unit](test/unit) and [integration](test/integration) tests is the tests themselves. One of the maintainers can help by pointing out relevant examples.
- Check your formatting and linting with [Flake8](https://flake8.pycqa.org/en/latest/#), [Black](https://github.com/psf/black), and the rest of the hooks we have in our [pre-commit](https://pre-commit.com/) [config](https://github.com/dbt-labs/dbt-core/blob/75201be9db1cb2c6c01fa7e71a314f5e5beb060a/.pre-commit-config.yaml).
In some cases, the right resolution to an open issue might be tangential to the `dbt` codebase. The right path forward might be a documentation update or a change that can be made in user-space. In other cases, the issue might describe functionality that the `dbt` maintainers are unwilling or unable to incorporate into the `dbt` codebase. When it is determined that an open issue describes functionality that will not translate to a code change in the `dbt` repository, the issue will be tagged with the `wontfix` label (see below) and closed. In some cases, the right resolution to an open issue might be tangential to the `dbt-core` codebase. The right path forward might be a documentation update or a change that can be made in user-space. In other cases, the issue might describe functionality that the `dbt-core` maintainers are unwilling or unable to incorporate into the `dbt-core` codebase. When it is determined that an open issue describes functionality that will not translate to a code change in the `dbt-core` repository, the issue will be tagged with the `wontfix` label (see below) and closed.
### Using issue labels ### Using issue labels
The `dbt` maintainers use labels to categorize open issues. Some labels indicate the databases impacted by the issue, while others describe the domain in the `dbt` codebase germane to the discussion. While most of these labels are self-explanatory (eg. `snowflake` or `bigquery`), there are others that are worth describing. The `dbt-core` maintainers use labels to categorize open issues. Most labels describe the domain in the `dbt-core` codebase germane to the discussion.
| tag | description | | tag | description |
| --- | ----------- | | --- | ----------- |
| [triage](https://github.com/dbt-labs/dbt-core/labels/triage) | This is a new issue which has not yet been reviewed by a `dbt` maintainer. This label is removed when a maintainer reviews and responds to the issue. | | [triage](https://github.com/dbt-labs/dbt-core/labels/triage) | This is a new issue which has not yet been reviewed by a `dbt-core` maintainer. This label is removed when a maintainer reviews and responds to the issue. |
| [bug](https://github.com/dbt-labs/dbt-core/labels/bug) | This issue represents a defect or regression in `dbt` | | [bug](https://github.com/dbt-labs/dbt-core/labels/bug) | This issue represents a defect or regression in `dbt-core` |
| [enhancement](https://github.com/dbt-labs/dbt-core/labels/enhancement) | This issue represents net-new functionality in `dbt` | | [enhancement](https://github.com/dbt-labs/dbt-core/labels/enhancement) | This issue represents net-new functionality in `dbt-core` |
| [good first issue](https://github.com/dbt-labs/dbt-core/labels/good%20first%20issue) | This issue does not require deep knowledge of the `dbt` codebase to implement. This issue is appropriate for a first-time contributor. | | [good first issue](https://github.com/dbt-labs/dbt-core/labels/good%20first%20issue) | This issue does not require deep knowledge of the `dbt-core` codebase to implement. This issue is appropriate for a first-time contributor. |
| [help wanted](https://github.com/dbt-labs/dbt-core/labels/help%20wanted) / [discussion](https://github.com/dbt-labs/dbt-core/labels/discussion) | Conversation around this issue in ongoing, and there isn't yet a clear path forward. Input from community members is most welcome. | | [help wanted](https://github.com/dbt-labs/dbt-core/labels/help%20wanted) / [discussion](https://github.com/dbt-labs/dbt-core/labels/discussion) | Conversation around this issue in ongoing, and there isn't yet a clear path forward. Input from community members is most welcome. |
| [duplicate](https://github.com/dbt-labs/dbt-core/issues/duplicate) | This issue is functionally identical to another open issue. The `dbt` maintainers will close this issue and encourage community members to focus conversation on the other one. | | [duplicate](https://github.com/dbt-labs/dbt-core/issues/duplicate) | This issue is functionally identical to another open issue. The `dbt-core` maintainers will close this issue and encourage community members to focus conversation on the other one. |
| [snoozed](https://github.com/dbt-labs/dbt-core/labels/snoozed) | This issue describes a good idea, but one which will probably not be addressed in a six-month time horizon. The `dbt` maintainers will revist these issues periodically and re-prioritize them accordingly. | | [snoozed](https://github.com/dbt-labs/dbt-core/labels/snoozed) | This issue describes a good idea, but one which will probably not be addressed in a six-month time horizon. The `dbt-core` maintainers will revist these issues periodically and re-prioritize them accordingly. |
| [stale](https://github.com/dbt-labs/dbt-core/labels/stale) | This is an old issue which has not recently been updated. Stale issues will periodically be closed by `dbt` maintainers, but they can be re-opened if the discussion is restarted. | | [stale](https://github.com/dbt-labs/dbt-core/labels/stale) | This is an old issue which has not recently been updated. Stale issues will periodically be closed by `dbt-core` maintainers, but they can be re-opened if the discussion is restarted. |
| [wontfix](https://github.com/dbt-labs/dbt-core/labels/wontfix) | This issue does not require a code change in the `dbt` repository, or the maintainers are unwilling/unable to merge a Pull Request which implements the behavior described in the issue. | | [wontfix](https://github.com/dbt-labs/dbt-core/labels/wontfix) | This issue does not require a code change in the `dbt-core` repository, or the maintainers are unwilling/unable to merge a Pull Request which implements the behavior described in the issue. |
#### Branching Strategy #### Branching Strategy
`dbt` has three types of branches: `dbt-core` has three types of branches:
- **Trunks** are where active development of the next release takes place. There is one trunk named `develop` at the time of writing this, and will be the default branch of the repository. - **Trunks** are where active development of the next release takes place. There is one trunk named `main` at the time of writing this, and will be the default branch of the repository.
- **Release Branches** track a specific, not yet complete release of `dbt`. Each minor version release has a corresponding release branch. For example, the `0.11.x` series of releases has a branch called `0.11.latest`. This allows us to release new patch versions under `0.11` without necessarily needing to pull them into the latest version of `dbt`. - **Release Branches** track a specific, not yet complete release of `dbt-core`. Each minor version release has a corresponding release branch. For example, the `0.11.x` series of releases has a branch called `0.11.latest`. This allows us to release new patch versions under `0.11` without necessarily needing to pull them into the latest version of `dbt-core`.
- **Feature Branches** track individual features and fixes. On completion they should be merged into the trunk branch or a specific release branch. - **Feature Branches** track individual features and fixes. On completion they should be merged into the trunk branch or a specific release branch.
## Getting the code ## Getting the code
### Installing git ### Installing git
You will need `git` in order to download and modify the `dbt` source code. On macOS, the best way to download git is to just install [Xcode](https://developer.apple.com/support/xcode/). You will need `git` in order to download and modify the `dbt-core` source code. On macOS, the best way to download git is to just install [Xcode](https://developer.apple.com/support/xcode/).
### External contributors ### External contributors
If you are not a member of the `dbt-labs` GitHub organization, you can contribute to `dbt` by forking the `dbt` repository. For a detailed overview on forking, check out the [GitHub docs on forking](https://help.github.com/en/articles/fork-a-repo). In short, you will need to: If you are not a member of the `dbt-labs` GitHub organization, you can contribute to `dbt-core` by forking the `dbt-core` repository. For a detailed overview on forking, check out the [GitHub docs on forking](https://help.github.com/en/articles/fork-a-repo). In short, you will need to:
1. fork the `dbt` repository 1. fork the `dbt-core` repository
2. clone your fork locally 2. clone your fork locally
3. check out a new branch for your proposed changes 3. check out a new branch for your proposed changes
4. push changes to your fork 4. push changes to your fork
5. open a pull request against `dbt-labs/dbt` from your forked repository 5. open a pull request against `dbt-labs/dbt` from your forked repository
### Core contributors ### dbt Labs contributors
If you are a member of the `dbt-labs` GitHub organization, you will have push access to the `dbt` repo. Rather than forking `dbt` to make your changes, just clone the repository, check out a new branch, and push directly to that branch. If you are a member of the `dbt-labs` GitHub organization, you will have push access to the `dbt-core` repo. Rather than forking `dbt-core` to make your changes, just clone the repository, check out a new branch, and push directly to that branch.
## Setting up an environment ## Setting up an environment
There are some tools that will be helpful to you in developing locally. While this is the list relevant for `dbt` development, many of these tools are used commonly across open-source python projects. There are some tools that will be helpful to you in developing locally. While this is the list relevant for `dbt-core` development, many of these tools are used commonly across open-source python projects.
### Tools ### Tools
A short list of tools used in `dbt` testing that will be helpful to your understanding: A short list of tools used in `dbt-core` testing that will be helpful to your understanding:
- [`tox`](https://tox.readthedocs.io/en/latest/) to manage virtualenvs across python versions. We currently target the latest patch releases for Python 3.6, Python 3.7, Python 3.8, and Python 3.9 - [`tox`](https://tox.readthedocs.io/en/latest/) to manage virtualenvs across python versions. We currently target the latest patch releases for Python 3.7, Python 3.8, and Python 3.9
- [`pytest`](https://docs.pytest.org/en/latest/) to discover/run tests - [`pytest`](https://docs.pytest.org/en/latest/) to discover/run tests
- [`make`](https://users.cs.duke.edu/~ola/courses/programming/Makefiles/Makefiles.html) - but don't worry too much, nobody _really_ understands how make works and our Makefile is super simple - [`make`](https://users.cs.duke.edu/~ola/courses/programming/Makefiles/Makefiles.html) - but don't worry too much, nobody _really_ understands how make works and our Makefile is super simple
- [`flake8`](https://flake8.pycqa.org/en/latest/) for code linting - [`flake8`](https://flake8.pycqa.org/en/latest/) for code linting
- [`black`](https://github.com/psf/black) for code formatting
- [`mypy`](https://mypy.readthedocs.io/en/stable/) for static type checking - [`mypy`](https://mypy.readthedocs.io/en/stable/) for static type checking
- [Github Actions](https://github.com/features/actions) - [Github Actions](https://github.com/features/actions)
A deep understanding of these tools in not required to effectively contribute to `dbt`, but we recommend checking out the attached documentation if you're interested in learning more about them. A deep understanding of these tools in not required to effectively contribute to `dbt-core`, but we recommend checking out the attached documentation if you're interested in learning more about them.
#### virtual environments #### virtual environments
We strongly recommend using virtual environments when developing code in `dbt`. We recommend creating this virtualenv We strongly recommend using virtual environments when developing code in `dbt-core`. We recommend creating this virtualenv
in the root of the `dbt` repository. To create a new virtualenv, run: in the root of the `dbt-core` repository. To create a new virtualenv, run:
```sh ```sh
python3 -m venv env python3 -m venv env
source env/bin/activate source env/bin/activate
@@ -135,11 +137,11 @@ For testing, and later in the examples in this document, you may want to have `p
brew install postgresql brew install postgresql
``` ```
## Running `dbt` in development ## Running `dbt-core` in development
### Installation ### Installation
First make sure that you set up your `virtualenv` as described in [Setting up an environment](#setting-up-an-environment). Also ensure you have the latest version of pip installed with `pip install --upgrade pip`. Next, install `dbt` (and its dependencies) with: First make sure that you set up your `virtualenv` as described in [Setting up an environment](#setting-up-an-environment). Also ensure you have the latest version of pip installed with `pip install --upgrade pip`. Next, install `dbt-core` (and its dependencies) with:
```sh ```sh
make dev make dev
@@ -147,23 +149,24 @@ make dev
pip install -r dev-requirements.txt -r editable-requirements.txt pip install -r dev-requirements.txt -r editable-requirements.txt
``` ```
When `dbt` is installed this way, any changes you make to the `dbt` source code will be reflected immediately in your next `dbt` run. When `dbt-core` is installed this way, any changes you make to the `dbt-core` source code will be reflected immediately in your next `dbt-core` run.
### Running `dbt`
With your virtualenv activated, the `dbt` script should point back to the source code you've cloned on your machine. You can verify this by running `which dbt`. This command should show you a path to an executable in your virtualenv. ### Running `dbt-core`
With your virtualenv activated, the `dbt-core` script should point back to the source code you've cloned on your machine. You can verify this by running `which dbt`. This command should show you a path to an executable in your virtualenv.
Configure your [profile](https://docs.getdbt.com/docs/configure-your-profile) as necessary to connect to your target databases. It may be a good idea to add a new profile pointing to a local postgres instance, or a specific test sandbox within your data warehouse if appropriate. Configure your [profile](https://docs.getdbt.com/docs/configure-your-profile) as necessary to connect to your target databases. It may be a good idea to add a new profile pointing to a local postgres instance, or a specific test sandbox within your data warehouse if appropriate.
## Testing ## Testing
Getting the `dbt` integration tests set up in your local environment will be very helpful as you start to make changes to your local version of `dbt`. The section that follows outlines some helpful tips for setting up the test environment. Getting the `dbt-core` integration tests set up in your local environment will be very helpful as you start to make changes to your local version of `dbt-core`. The section that follows outlines some helpful tips for setting up the test environment.
Although `dbt` works with a number of different databases, you won't need to supply credentials for every one of these databases in your test environment. Instead you can test all dbt-core code changes with Python and Postgres. Although `dbt-core` works with a number of different databases, you won't need to supply credentials for every one of these databases in your test environment. Instead you can test all dbt-core code changes with Python and Postgres.
### Initial setup ### Initial setup
We recommend starting with `dbt`'s Postgres tests. These tests cover most of the functionality in `dbt`, are the fastest to run, and are the easiest to set up. To run the Postgres integration tests, you'll have to do one extra step of setting up the test database: We recommend starting with `dbt-core`'s Postgres tests. These tests cover most of the functionality in `dbt-core`, are the fastest to run, and are the easiest to set up. To run the Postgres integration tests, you'll have to do one extra step of setting up the test database:
```sh ```sh
make setup-db make setup-db
@@ -174,15 +177,6 @@ docker-compose up -d database
PGHOST=localhost PGUSER=root PGPASSWORD=password PGDATABASE=postgres bash test/setup_db.sh PGHOST=localhost PGUSER=root PGPASSWORD=password PGDATABASE=postgres bash test/setup_db.sh
``` ```
`dbt` uses test credentials specified in a `test.env` file in the root of the repository for non-Postgres databases. This `test.env` file is git-ignored, but please be _extra_ careful to never check in credentials or other sensitive information when developing against `dbt`. To create your `test.env` file, copy the provided sample file, then supply your relevant credentials. This step is only required to use non-Postgres databases.
```
cp test.env.sample test.env
$EDITOR test.env
```
> In general, it's most important to have successful unit and Postgres tests. Once you open a PR, `dbt` will automatically run integration tests for the other three core database adapters. Of course, if you are a BigQuery user, contributing a BigQuery-only feature, it's important to run BigQuery tests as well.
### Test commands ### Test commands
There are a few methods for running tests locally. There are a few methods for running tests locally.
@@ -198,19 +192,18 @@ make test
# Runs postgres integration tests with py38 in "fail fast" mode. # Runs postgres integration tests with py38 in "fail fast" mode.
make integration make integration
``` ```
> These make targets assume you have a recent version of [`tox`](https://tox.readthedocs.io/en/latest/) installed locally, > These make targets assume you have a local install of a recent version of [`tox`](https://tox.readthedocs.io/en/latest/) for unit/integration testing and pre-commit for code quality checks,
> unless you use choose a Docker container to run tests. Run `make help` for more info. > unless you use choose a Docker container to run tests. Run `make help` for more info.
Check out the other targets in the Makefile to see other commonly used test Check out the other targets in the Makefile to see other commonly used test
suites. suites.
#### `pre-commit`
[`pre-commit`](https.pre-commit.com) takes care of running all code-checks for formatting and linting. Run `make dev` to install `pre-commit` in your local environment. Once this is done you can use any of the linter-based make targets as well as a git pre-commit hook that will ensure proper formatting and linting.
#### `tox` #### `tox`
[`tox`](https://tox.readthedocs.io/en/latest/) takes care of managing virtualenvs and install dependencies in order to run [`tox`](https://tox.readthedocs.io/en/latest/) takes care of managing virtualenvs and install dependencies in order to run tests. You can also run tests in parallel, for example, you can run unit tests for Python 3.7, Python 3.8, and Python 3.9 checks in parallel with `tox -p`. Also, you can run unit tests for specific python versions with `tox -e py37`. The configuration for these tests in located in `tox.ini`.
tests. You can also run tests in parallel, for example, you can run unit tests
for Python 3.6, Python 3.7, Python 3.8, `flake8` checks, and `mypy` checks in
parallel with `tox -p`. Also, you can run unit tests for specific python versions
with `tox -e py36`. The configuration for these tests in located in `tox.ini`.
#### `pytest` #### `pytest`
@@ -226,10 +219,21 @@ python -m pytest test/unit/test_graph.py::GraphTest::test__dependency_list
``` ```
> [Here](https://docs.pytest.org/en/reorganize-docs/new-docs/user/commandlineuseful.html) > [Here](https://docs.pytest.org/en/reorganize-docs/new-docs/user/commandlineuseful.html)
> is a list of useful command-line options for `pytest` to use while developing. > is a list of useful command-line options for `pytest` to use while developing.
## Adding CHANGELOG Entry
We use [changie](https://changie.dev) to generate `CHANGELOG` entries. Do not edit the `CHANGELOG.md` directly. Your modifications will be lost.
Follow the steps to [install `changie`](https://changie.dev/guide/installation/) for your system.
Once changie is installed and your PR is created, simply run `changie new` and changie will walk you through the process of creating a changelog entry. Commit the file that's created and your changelog entry is complete!
## Submitting a Pull Request ## Submitting a Pull Request
dbt Labs provides a CI environment to test changes to specific adapters, and periodic maintenance checks of `dbt-core` through Github Actions. For example, if you submit a pull request to the `dbt-redshift` repo, GitHub will trigger automated code checks and tests against Redshift. dbt Labs provides a CI environment to test changes to specific adapters, and periodic maintenance checks of `dbt-core` through Github Actions. For example, if you submit a pull request to the `dbt-redshift` repo, GitHub will trigger automated code checks and tests against Redshift.
A `dbt` maintainer will review your PR. They may suggest code revision for style or clarity, or request that you add unit or integration test(s). These are good things! We believe that, with a little bit of help, anyone can contribute high-quality code. A `dbt-core` maintainer will review your PR. They may suggest code revision for style or clarity, or request that you add unit or integration test(s). These are good things! We believe that, with a little bit of help, anyone can contribute high-quality code.
- First time contributors should note code checks + unit tests require a maintainer to approve.
Once all tests are passing and your PR has been approved, a `dbt` maintainer will merge your changes into the active development branch. And that's it! Happy developing :tada:
Once all tests are passing and your PR has been approved, a `dbt-core` maintainer will merge your changes into the active development branch. And that's it! Happy developing :tada:

View File

@@ -1,3 +1,8 @@
##
# This dockerfile is used for local development and adapter testing only.
# See `/docker` for a generic and production-ready docker file
##
FROM ubuntu:20.04 FROM ubuntu:20.04
ENV DEBIAN_FRONTEND noninteractive ENV DEBIAN_FRONTEND noninteractive

View File

@@ -8,45 +8,58 @@ endif
.PHONY: dev .PHONY: dev
dev: ## Installs dbt-* packages in develop mode along with development dependencies. dev: ## Installs dbt-* packages in develop mode along with development dependencies.
pip install -r dev-requirements.txt -r editable-requirements.txt @\
pip install -r dev-requirements.txt -r editable-requirements.txt && \
pre-commit install
.PHONY: mypy .PHONY: mypy
mypy: .env ## Runs mypy for static type checking. mypy: .env ## Runs mypy against staged changes for static type checking.
$(DOCKER_CMD) tox -e mypy @\
$(DOCKER_CMD) pre-commit run --hook-stage manual mypy-check | grep -v "INFO"
.PHONY: flake8 .PHONY: flake8
flake8: .env ## Runs flake8 to enforce style guide. flake8: .env ## Runs flake8 against staged changes to enforce style guide.
$(DOCKER_CMD) tox -e flake8 @\
$(DOCKER_CMD) pre-commit run --hook-stage manual flake8-check | grep -v "INFO"
.PHONY: black
black: .env ## Runs black against staged changes to enforce style guide.
@\
$(DOCKER_CMD) pre-commit run --hook-stage manual black-check -v | grep -v "INFO"
.PHONY: lint .PHONY: lint
lint: .env ## Runs all code checks in parallel. lint: .env ## Runs flake8 and mypy code checks against staged changes.
$(DOCKER_CMD) tox -p -e flake8,mypy @\
$(DOCKER_CMD) pre-commit run flake8-check --hook-stage manual | grep -v "INFO"; \
$(DOCKER_CMD) pre-commit run mypy-check --hook-stage manual | grep -v "INFO"
.PHONY: unit .PHONY: unit
unit: .env ## Runs unit tests with py38. unit: .env ## Runs unit tests with py38.
@\
$(DOCKER_CMD) tox -e py38 $(DOCKER_CMD) tox -e py38
.PHONY: test .PHONY: test
test: .env ## Runs unit tests with py38 and code checks in parallel. test: .env ## Runs unit tests with py38 and code checks against staged changes.
$(DOCKER_CMD) tox -p -e py38,flake8,mypy @\
$(DOCKER_CMD) tox -e py38; \
$(DOCKER_CMD) pre-commit run black-check --hook-stage manual | grep -v "INFO"; \
$(DOCKER_CMD) pre-commit run flake8-check --hook-stage manual | grep -v "INFO"; \
$(DOCKER_CMD) pre-commit run mypy-check --hook-stage manual | grep -v "INFO"
.PHONY: integration .PHONY: integration
integration: .env integration-postgres ## Alias for integration-postgres. integration: .env ## Runs postgres integration tests with py38.
@\
$(DOCKER_CMD) tox -e py38-integration -- -nauto
.PHONY: integration-fail-fast .PHONY: integration-fail-fast
integration-fail-fast: .env integration-postgres-fail-fast ## Alias for integration-postgres-fail-fast. integration-fail-fast: .env ## Runs postgres integration tests with py38 in "fail fast" mode.
@\
.PHONY: integration-postgres $(DOCKER_CMD) tox -e py38-integration -- -x -nauto
integration-postgres: .env ## Runs postgres integration tests with py38.
$(DOCKER_CMD) tox -e py38-postgres -- -nauto
.PHONY: integration-postgres-fail-fast
integration-postgres-fail-fast: .env ## Runs postgres integration tests with py38 in "fail fast" mode.
$(DOCKER_CMD) tox -e py38-postgres -- -x -nauto
.PHONY: setup-db .PHONY: setup-db
setup-db: ## Setup Postgres database with docker-compose for system testing. setup-db: ## Setup Postgres database with docker-compose for system testing.
docker-compose up -d database @\
docker-compose up -d database && \
PGHOST=localhost PGUSER=root PGPASSWORD=password PGDATABASE=postgres bash test/setup_db.sh PGHOST=localhost PGUSER=root PGPASSWORD=password PGDATABASE=postgres bash test/setup_db.sh
# This rule creates a file named .env that is used by docker-compose for passing # This rule creates a file named .env that is used by docker-compose for passing
@@ -62,27 +75,29 @@ endif
.PHONY: clean .PHONY: clean
clean: ## Resets development environment. clean: ## Resets development environment.
rm -f .coverage @echo 'cleaning repo...'
rm -rf .eggs/ @rm -f .coverage
rm -f .env @rm -rf .eggs/
rm -rf .tox/ @rm -f .env
rm -rf build/ @rm -rf .tox/
rm -rf dbt.egg-info/ @rm -rf build/
rm -f dbt_project.yml @rm -rf dbt.egg-info/
rm -rf dist/ @rm -f dbt_project.yml
rm -f htmlcov/*.{css,html,js,json,png} @rm -rf dist/
rm -rf logs/ @rm -f htmlcov/*.{css,html,js,json,png}
rm -rf target/ @rm -rf logs/
find . -type f -name '*.pyc' -delete @rm -rf target/
find . -type d -name '__pycache__' -depth -delete @find . -type f -name '*.pyc' -delete
@find . -type d -name '__pycache__' -depth -delete
@echo 'done.'
.PHONY: help .PHONY: help
help: ## Show this help message. help: ## Show this help message.
@echo 'usage: make [target] [USE_DOCKER=true]' @echo 'usage: make [target] [USE_DOCKER=true]'
@echo @echo
@echo 'targets:' @echo 'targets:'
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' @grep -E '^[8+a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
@echo @echo
@echo 'options:' @echo 'options:'
@echo 'use USE_DOCKER=true to run target in a docker container' @echo 'use USE_DOCKER=true to run target in a docker container'

View File

@@ -3,10 +3,7 @@
</p> </p>
<p align="center"> <p align="center">
<a href="https://github.com/dbt-labs/dbt-core/actions/workflows/main.yml"> <a href="https://github.com/dbt-labs/dbt-core/actions/workflows/main.yml">
<img src="https://github.com/dbt-labs/dbt-core/actions/workflows/main.yml/badge.svg?event=push" alt="Unit Tests Badge"/> <img src="https://github.com/dbt-labs/dbt-core/actions/workflows/main.yml/badge.svg?event=push" alt="CI Badge"/>
</a>
<a href="https://github.com/dbt-labs/dbt-core/actions/workflows/integration.yml">
<img src="https://github.com/dbt-labs/dbt-core/actions/workflows/integration.yml/badge.svg?event=push" alt="Integration Tests Badge"/>
</a> </a>
</p> </p>

39
core/README.md Normal file
View File

@@ -0,0 +1,39 @@
<p align="center">
<img src="https://raw.githubusercontent.com/dbt-labs/dbt-core/fa1ea14ddfb1d5ae319d5141844910dd53ab2834/etc/dbt-core.svg" alt="dbt logo" width="750"/>
</p>
<p align="center">
<a href="https://github.com/dbt-labs/dbt-core/actions/workflows/main.yml">
<img src="https://github.com/dbt-labs/dbt-core/actions/workflows/main.yml/badge.svg?event=push" alt="CI Badge"/>
</a>
</p>
**[dbt](https://www.getdbt.com/)** enables data analysts and engineers to transform their data using the same practices that software engineers use to build applications.
![architecture](https://raw.githubusercontent.com/dbt-labs/dbt-core/6c6649f9129d5d108aa3b0526f634cd8f3a9d1ed/etc/dbt-arch.png)
## Understanding dbt
Analysts using dbt can transform their data by simply writing select statements, while dbt handles turning these statements into tables and views in a data warehouse.
These select statements, or "models", form a dbt project. Models frequently build on top of one another dbt makes it easy to [manage relationships](https://docs.getdbt.com/docs/ref) between models, and [visualize these relationships](https://docs.getdbt.com/docs/documentation), as well as assure the quality of your transformations through [testing](https://docs.getdbt.com/docs/testing).
![dbt dag](https://raw.githubusercontent.com/dbt-labs/dbt-core/6c6649f9129d5d108aa3b0526f634cd8f3a9d1ed/etc/dbt-dag.png)
## Getting started
- [Install dbt](https://docs.getdbt.com/docs/installation)
- Read the [introduction](https://docs.getdbt.com/docs/introduction/) and [viewpoint](https://docs.getdbt.com/docs/about/viewpoint/)
## Join the dbt Community
- Be part of the conversation in the [dbt Community Slack](http://community.getdbt.com/)
- Read more on the [dbt Community Discourse](https://discourse.getdbt.com)
## Reporting bugs and contributing code
- Want to report a bug or request a feature? Let us know on [Slack](http://community.getdbt.com/), or open [an issue](https://github.com/dbt-labs/dbt-core/issues/new)
- Want to help us build dbt? Check out the [Contributing Guide](https://github.com/dbt-labs/dbt-core/blob/HEAD/CONTRIBUTING.md)
## Code of Conduct
Everyone interacting in the dbt project's codebases, issue trackers, chat rooms, and mailing lists is expected to follow the [dbt Code of Conduct](https://community.getdbt.com/code-of-conduct).

51
core/dbt/README.md Normal file
View File

@@ -0,0 +1,51 @@
# core/dbt directory README
## The following are individual files in this directory.
### deprecations.py
### flags.py
### main.py
### tracking.py
### version.py
### lib.py
### node_types.py
### helper_types.py
### links.py
### semver.py
### ui.py
### compilation.py
### dataclass_schema.py
### exceptions.py
### hooks.py
### logger.py
### profiler.py
### utils.py
## The subdirectories will be documented in a README in the subdirectory
* config
* include
* adapters
* context
* deps
* graph
* task
* clients
* events

View File

@@ -0,0 +1 @@
# Adapters README

View File

@@ -8,10 +8,10 @@ from dbt.exceptions import RuntimeException
@dataclass @dataclass
class Column: class Column:
TYPE_LABELS: ClassVar[Dict[str, str]] = { TYPE_LABELS: ClassVar[Dict[str, str]] = {
'STRING': 'TEXT', "STRING": "TEXT",
'TIMESTAMP': 'TIMESTAMP', "TIMESTAMP": "TIMESTAMP",
'FLOAT': 'FLOAT', "FLOAT": "FLOAT",
'INTEGER': 'INT' "INTEGER": "INT",
} }
column: str column: str
dtype: str dtype: str
@@ -24,7 +24,7 @@ class Column:
return cls.TYPE_LABELS.get(dtype.upper(), dtype) return cls.TYPE_LABELS.get(dtype.upper(), dtype)
@classmethod @classmethod
def create(cls, name, label_or_dtype: str) -> 'Column': def create(cls, name, label_or_dtype: str) -> "Column":
column_type = cls.translate_type(label_or_dtype) column_type = cls.translate_type(label_or_dtype)
return cls(name, column_type) return cls(name, column_type)
@@ -39,16 +39,14 @@ class Column:
@property @property
def data_type(self) -> str: def data_type(self) -> str:
if self.is_string(): if self.is_string():
return Column.string_type(self.string_size()) return self.string_type(self.string_size())
elif self.is_numeric(): elif self.is_numeric():
return Column.numeric_type(self.dtype, self.numeric_precision, return self.numeric_type(self.dtype, self.numeric_precision, self.numeric_scale)
self.numeric_scale)
else: else:
return self.dtype return self.dtype
def is_string(self) -> bool: def is_string(self) -> bool:
return self.dtype.lower() in ['text', 'character varying', 'character', return self.dtype.lower() in ["text", "character varying", "character", "varchar"]
'varchar']
def is_number(self): def is_number(self):
return any([self.is_integer(), self.is_numeric(), self.is_float()]) return any([self.is_integer(), self.is_numeric(), self.is_float()])
@@ -56,33 +54,45 @@ class Column:
def is_float(self): def is_float(self):
return self.dtype.lower() in [ return self.dtype.lower() in [
# floats # floats
'real', 'float4', 'float', 'double precision', 'float8' "real",
"float4",
"float",
"double precision",
"float8",
] ]
def is_integer(self) -> bool: def is_integer(self) -> bool:
return self.dtype.lower() in [ return self.dtype.lower() in [
# real types # real types
'smallint', 'integer', 'bigint', "smallint",
'smallserial', 'serial', 'bigserial', "integer",
"bigint",
"smallserial",
"serial",
"bigserial",
# aliases # aliases
'int2', 'int4', 'int8', "int2",
'serial2', 'serial4', 'serial8', "int4",
"int8",
"serial2",
"serial4",
"serial8",
] ]
def is_numeric(self) -> bool: def is_numeric(self) -> bool:
return self.dtype.lower() in ['numeric', 'decimal'] return self.dtype.lower() in ["numeric", "decimal"]
def string_size(self) -> int: def string_size(self) -> int:
if not self.is_string(): if not self.is_string():
raise RuntimeException("Called string_size() on non-string field!") raise RuntimeException("Called string_size() on non-string field!")
if self.dtype == 'text' or self.char_size is None: if self.dtype == "text" or self.char_size is None:
# char_size should never be None. Handle it reasonably just in case # char_size should never be None. Handle it reasonably just in case
return 256 return 256
else: else:
return int(self.char_size) return int(self.char_size)
def can_expand_to(self, other_column: 'Column') -> bool: def can_expand_to(self, other_column: "Column") -> bool:
"""returns True if this column can be expanded to the size of the """returns True if this column can be expanded to the size of the
other column""" other column"""
if not self.is_string() or not other_column.is_string(): if not self.is_string() or not other_column.is_string():
@@ -110,12 +120,10 @@ class Column:
return "<Column {} ({})>".format(self.name, self.data_type) return "<Column {} ({})>".format(self.name, self.data_type)
@classmethod @classmethod
def from_description(cls, name: str, raw_data_type: str) -> 'Column': def from_description(cls, name: str, raw_data_type: str) -> "Column":
match = re.match(r'([^(]+)(\([^)]+\))?', raw_data_type) match = re.match(r"([^(]+)(\([^)]+\))?", raw_data_type)
if match is None: if match is None:
raise RuntimeException( raise RuntimeException(f'Could not interpret data type "{raw_data_type}"')
f'Could not interpret data type "{raw_data_type}"'
)
data_type, size_info = match.groups() data_type, size_info = match.groups()
char_size = None char_size = None
numeric_precision = None numeric_precision = None
@@ -123,7 +131,7 @@ class Column:
if size_info is not None: if size_info is not None:
# strip out the parentheses # strip out the parentheses
size_info = size_info[1:-1] size_info = size_info[1:-1]
parts = size_info.split(',') parts = size_info.split(",")
if len(parts) == 1: if len(parts) == 1:
try: try:
char_size = int(parts[0]) char_size = int(parts[0])
@@ -148,6 +156,4 @@ class Column:
f'could not convert "{parts[1]}" to an integer' f'could not convert "{parts[1]}" to an integer'
) )
return cls( return cls(name, data_type, char_size, numeric_precision, numeric_scale)
name, data_type, char_size, numeric_precision, numeric_scale
)

View File

@@ -1,24 +1,37 @@
import abc import abc
import os import os
# multiprocessing.RLock is a function returning this type # multiprocessing.RLock is a function returning this type
from multiprocessing.synchronize import RLock from multiprocessing.synchronize import RLock
from threading import get_ident from threading import get_ident
from typing import ( from typing import Dict, Tuple, Hashable, Optional, ContextManager, List, Union
Dict, Tuple, Hashable, Optional, ContextManager, List, Union
)
import agate import agate
import dbt.exceptions import dbt.exceptions
from dbt.contracts.connection import ( from dbt.contracts.connection import (
Connection, Identifier, ConnectionState, Connection,
AdapterRequiredConfig, LazyHandle, AdapterResponse Identifier,
ConnectionState,
AdapterRequiredConfig,
LazyHandle,
AdapterResponse,
) )
from dbt.contracts.graph.manifest import Manifest from dbt.contracts.graph.manifest import Manifest
from dbt.adapters.base.query_headers import ( from dbt.adapters.base.query_headers import (
MacroQueryStringSetter, MacroQueryStringSetter,
) )
from dbt.logger import GLOBAL_LOGGER as logger from dbt.events.functions import fire_event
from dbt.events.types import (
NewConnection,
ConnectionReused,
ConnectionLeftOpen,
ConnectionLeftOpen2,
ConnectionClosed,
ConnectionClosed2,
Rollback,
RollbackFailed,
)
from dbt import flags from dbt import flags
@@ -35,6 +48,7 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
You must also set the 'TYPE' class attribute with a class-unique constant You must also set the 'TYPE' class attribute with a class-unique constant
string. string.
""" """
TYPE: str = NotImplemented TYPE: str = NotImplemented
def __init__(self, profile: AdapterRequiredConfig): def __init__(self, profile: AdapterRequiredConfig):
@@ -56,16 +70,14 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
key = self.get_thread_identifier() key = self.get_thread_identifier()
with self.lock: with self.lock:
if key not in self.thread_connections: if key not in self.thread_connections:
raise dbt.exceptions.InvalidConnectionException( raise dbt.exceptions.InvalidConnectionException(key, list(self.thread_connections))
key, list(self.thread_connections)
)
return self.thread_connections[key] return self.thread_connections[key]
def set_thread_connection(self, conn: Connection) -> None: def set_thread_connection(self, conn: Connection) -> None:
key = self.get_thread_identifier() key = self.get_thread_identifier()
if key in self.thread_connections: if key in self.thread_connections:
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
'In set_thread_connection, existing connection exists for {}' "In set_thread_connection, existing connection exists for {}"
) )
self.thread_connections[key] = conn self.thread_connections[key] = conn
@@ -105,18 +117,19 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
underlying database. underlying database.
""" """
raise dbt.exceptions.NotImplementedException( raise dbt.exceptions.NotImplementedException(
'`exception_handler` is not implemented for this adapter!') "`exception_handler` is not implemented for this adapter!"
)
def set_connection_name(self, name: Optional[str] = None) -> Connection: def set_connection_name(self, name: Optional[str] = None) -> Connection:
conn_name: str conn_name: str
if name is None: if name is None:
# if a name isn't specified, we'll re-use a single handle # if a name isn't specified, we'll re-use a single handle
# named 'master' # named 'master'
conn_name = 'master' conn_name = "master"
else: else:
if not isinstance(name, str): if not isinstance(name, str):
raise dbt.exceptions.CompilerException( raise dbt.exceptions.CompilerException(
f'For connection name, got {name} - not a string!' f"For connection name, got {name} - not a string!"
) )
assert isinstance(name, str) assert isinstance(name, str)
conn_name = name conn_name = name
@@ -129,21 +142,17 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
state=ConnectionState.INIT, state=ConnectionState.INIT,
transaction_open=False, transaction_open=False,
handle=None, handle=None,
credentials=self.profile.credentials credentials=self.profile.credentials,
) )
self.set_thread_connection(conn) self.set_thread_connection(conn)
if conn.name == conn_name and conn.state == 'open': if conn.name == conn_name and conn.state == "open":
return conn return conn
logger.debug( fire_event(NewConnection(conn_name=conn_name, conn_type=self.TYPE))
'Acquiring new {} connection "{}".'.format(self.TYPE, conn_name))
if conn.state == 'open': if conn.state == "open":
logger.debug( fire_event(ConnectionReused(conn_name=conn_name))
'Re-using an available connection from the pool (formerly {}).'
.format(conn.name)
)
else: else:
conn.handle = LazyHandle(self.open) conn.handle = LazyHandle(self.open)
@@ -154,7 +163,7 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
def cancel_open(self) -> Optional[List[str]]: def cancel_open(self) -> Optional[List[str]]:
"""Cancel all open connections on the adapter. (passable)""" """Cancel all open connections on the adapter. (passable)"""
raise dbt.exceptions.NotImplementedException( raise dbt.exceptions.NotImplementedException(
'`cancel_open` is not implemented for this adapter!' "`cancel_open` is not implemented for this adapter!"
) )
@abc.abstractclassmethod @abc.abstractclassmethod
@@ -167,9 +176,7 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
This should be thread-safe, or hold the lock if necessary. The given This should be thread-safe, or hold the lock if necessary. The given
connection should not be in either in_use or available. connection should not be in either in_use or available.
""" """
raise dbt.exceptions.NotImplementedException( raise dbt.exceptions.NotImplementedException("`open` is not implemented for this adapter!")
'`open` is not implemented for this adapter!'
)
def release(self) -> None: def release(self) -> None:
with self.lock: with self.lock:
@@ -189,12 +196,10 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
def cleanup_all(self) -> None: def cleanup_all(self) -> None:
with self.lock: with self.lock:
for connection in self.thread_connections.values(): for connection in self.thread_connections.values():
if connection.state not in {'closed', 'init'}: if connection.state not in {"closed", "init"}:
logger.debug("Connection '{}' was left open." fire_event(ConnectionLeftOpen(conn_name=connection.name))
.format(connection.name))
else: else:
logger.debug("Connection '{}' was properly closed." fire_event(ConnectionClosed(conn_name=connection.name))
.format(connection.name))
self.close(connection) self.close(connection)
# garbage collect these connections # garbage collect these connections
@@ -204,14 +209,14 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
def begin(self) -> None: def begin(self) -> None:
"""Begin a transaction. (passable)""" """Begin a transaction. (passable)"""
raise dbt.exceptions.NotImplementedException( raise dbt.exceptions.NotImplementedException(
'`begin` is not implemented for this adapter!' "`begin` is not implemented for this adapter!"
) )
@abc.abstractmethod @abc.abstractmethod
def commit(self) -> None: def commit(self) -> None:
"""Commit a transaction. (passable)""" """Commit a transaction. (passable)"""
raise dbt.exceptions.NotImplementedException( raise dbt.exceptions.NotImplementedException(
'`commit` is not implemented for this adapter!' "`commit` is not implemented for this adapter!"
) )
@classmethod @classmethod
@@ -220,31 +225,28 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
try: try:
connection.handle.rollback() connection.handle.rollback()
except Exception: except Exception:
logger.debug( fire_event(RollbackFailed(conn_name=connection.name))
'Failed to rollback {}'.format(connection.name),
exc_info=True
)
@classmethod @classmethod
def _close_handle(cls, connection: Connection) -> None: def _close_handle(cls, connection: Connection) -> None:
"""Perform the actual close operation.""" """Perform the actual close operation."""
# On windows, sometimes connection handles don't have a close() attr. # On windows, sometimes connection handles don't have a close() attr.
if hasattr(connection.handle, 'close'): if hasattr(connection.handle, "close"):
logger.debug(f'On {connection.name}: Close') fire_event(ConnectionClosed2(conn_name=connection.name))
connection.handle.close() connection.handle.close()
else: else:
logger.debug(f'On {connection.name}: No close available on handle') fire_event(ConnectionLeftOpen2(conn_name=connection.name))
@classmethod @classmethod
def _rollback(cls, connection: Connection) -> None: def _rollback(cls, connection: Connection) -> None:
"""Roll back the given connection.""" """Roll back the given connection."""
if connection.transaction_open is False: if connection.transaction_open is False:
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
f'Tried to rollback transaction on connection ' f"Tried to rollback transaction on connection "
f'"{connection.name}", but it does not have one open!' f'"{connection.name}", but it does not have one open!'
) )
logger.debug(f'On {connection.name}: ROLLBACK') fire_event(Rollback(conn_name=connection.name))
cls._rollback_handle(connection) cls._rollback_handle(connection)
connection.transaction_open = False connection.transaction_open = False
@@ -256,7 +258,7 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
return connection return connection
if connection.transaction_open and connection.handle: if connection.transaction_open and connection.handle:
logger.debug('On {}: ROLLBACK'.format(connection.name)) fire_event(Rollback(conn_name=connection.name))
cls._rollback_handle(connection) cls._rollback_handle(connection)
connection.transaction_open = False connection.transaction_open = False
@@ -290,5 +292,5 @@ class BaseConnectionManager(metaclass=abc.ABCMeta):
:rtype: Tuple[Union[str, AdapterResponse], agate.Table] :rtype: Tuple[Union[str, AdapterResponse], agate.Table]
""" """
raise dbt.exceptions.NotImplementedException( raise dbt.exceptions.NotImplementedException(
'`execute` is not implemented for this adapter!' "`execute` is not implemented for this adapter!"
) )

File diff suppressed because it is too large Load Diff

View File

@@ -30,9 +30,11 @@ class _Available:
x.update(big_expensive_db_query()) x.update(big_expensive_db_query())
return x return x
""" """
def inner(func): def inner(func):
func._parse_replacement_ = parse_replacement func._parse_replacement_ = parse_replacement
return self(func) return self(func)
return inner return inner
def deprecated( def deprecated(
@@ -57,13 +59,14 @@ class _Available:
The optional parse_replacement, if provided, will provide a parse-time The optional parse_replacement, if provided, will provide a parse-time
replacement for the actual method (see `available.parse`). replacement for the actual method (see `available.parse`).
""" """
def wrapper(func): def wrapper(func):
func_name = func.__name__ func_name = func.__name__
renamed_method(func_name, supported_name) renamed_method(func_name, supported_name)
@wraps(func) @wraps(func)
def inner(*args, **kwargs): def inner(*args, **kwargs):
warn('adapter:{}'.format(func_name)) warn("adapter:{}".format(func_name))
return func(*args, **kwargs) return func(*args, **kwargs)
if parse_replacement: if parse_replacement:
@@ -71,6 +74,7 @@ class _Available:
else: else:
available_function = self available_function = self
return available_function(inner) return available_function(inner)
return wrapper return wrapper
def parse_none(self, func: Callable) -> Callable: def parse_none(self, func: Callable) -> Callable:
@@ -95,9 +99,7 @@ class AdapterMeta(abc.ABCMeta):
# I'm not sure there is any benefit to it after poking around a bit, # I'm not sure there is any benefit to it after poking around a bit,
# but having it doesn't hurt on the python side (and omitting it could # but having it doesn't hurt on the python side (and omitting it could
# hurt for obscure metaclass reasons, for all I know) # hurt for obscure metaclass reasons, for all I know)
cls = abc.ABCMeta.__new__( # type: ignore cls = abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs) # type: ignore
mcls, name, bases, namespace, **kwargs
)
# this is very much inspired by ABCMeta's own implementation # this is very much inspired by ABCMeta's own implementation
@@ -109,14 +111,14 @@ class AdapterMeta(abc.ABCMeta):
# collect base class data first # collect base class data first
for base in bases: for base in bases:
available.update(getattr(base, '_available_', set())) available.update(getattr(base, "_available_", set()))
replacements.update(getattr(base, '_parse_replacements_', set())) replacements.update(getattr(base, "_parse_replacements_", set()))
# override with local data if it exists # override with local data if it exists
for name, value in namespace.items(): for name, value in namespace.items():
if getattr(value, '_is_available_', False): if getattr(value, "_is_available_", False):
available.add(name) available.add(name)
parse_replacement = getattr(value, '_parse_replacement_', None) parse_replacement = getattr(value, "_parse_replacement_", None)
if parse_replacement is not None: if parse_replacement is not None:
replacements[name] = parse_replacement replacements[name] = parse_replacement

View File

@@ -8,11 +8,10 @@ from dbt.adapters.protocol import AdapterProtocol
def project_name_from_path(include_path: str) -> str: def project_name_from_path(include_path: str) -> str:
# avoid an import cycle # avoid an import cycle
from dbt.config.project import Project from dbt.config.project import Project
partial = Project.partial_load(include_path) partial = Project.partial_load(include_path)
if partial.project_name is None: if partial.project_name is None:
raise CompilationException( raise CompilationException(f"Invalid project at {include_path}: name not set!")
f'Invalid project at {include_path}: name not set!'
)
return partial.project_name return partial.project_name
@@ -23,12 +22,13 @@ class AdapterPlugin:
:param dependencies: A list of adapter names that this adapter depends :param dependencies: A list of adapter names that this adapter depends
upon. upon.
""" """
def __init__( def __init__(
self, self,
adapter: Type[AdapterProtocol], adapter: Type[AdapterProtocol],
credentials: Type[Credentials], credentials: Type[Credentials],
include_path: str, include_path: str,
dependencies: Optional[List[str]] = None dependencies: Optional[List[str]] = None,
): ):
self.adapter: Type[AdapterProtocol] = adapter self.adapter: Type[AdapterProtocol] = adapter

View File

@@ -15,7 +15,7 @@ class NodeWrapper:
self._inner_node = node self._inner_node = node
def __getattr__(self, name): def __getattr__(self, name):
return getattr(self._inner_node, name, '') return getattr(self._inner_node, name, "")
class _QueryComment(local): class _QueryComment(local):
@@ -24,6 +24,7 @@ class _QueryComment(local):
- the current thread's query comment. - the current thread's query comment.
- a source_name indicating what set the current thread's query comment - a source_name indicating what set the current thread's query comment
""" """
def __init__(self, initial): def __init__(self, initial):
self.query_comment: Optional[str] = initial self.query_comment: Optional[str] = initial
self.append = False self.append = False
@@ -35,21 +36,19 @@ class _QueryComment(local):
if self.append: if self.append:
# replace last ';' with '<comment>;' # replace last ';' with '<comment>;'
sql = sql.rstrip() sql = sql.rstrip()
if sql[-1] == ';': if sql[-1] == ";":
sql = sql[:-1] sql = sql[:-1]
return '{}\n/* {} */;'.format(sql, self.query_comment.strip()) return "{}\n/* {} */;".format(sql, self.query_comment.strip())
return '{}\n/* {} */'.format(sql, self.query_comment.strip()) return "{}\n/* {} */".format(sql, self.query_comment.strip())
return '/* {} */\n{}'.format(self.query_comment.strip(), sql) return "/* {} */\n{}".format(self.query_comment.strip(), sql)
def set(self, comment: Optional[str], append: bool): def set(self, comment: Optional[str], append: bool):
if isinstance(comment, str) and '*/' in comment: if isinstance(comment, str) and "*/" in comment:
# tell the user "no" so they don't hurt themselves by writing # tell the user "no" so they don't hurt themselves by writing
# garbage # garbage
raise RuntimeException( raise RuntimeException(f'query comment contains illegal value "*/": {comment}')
f'query comment contains illegal value "*/": {comment}'
)
self.query_comment = comment self.query_comment = comment
self.append = append self.append = append
@@ -63,15 +62,17 @@ class MacroQueryStringSetter:
self.config = config self.config = config
comment_macro = self._get_comment_macro() comment_macro = self._get_comment_macro()
self.generator: QueryStringFunc = lambda name, model: '' self.generator: QueryStringFunc = lambda name, model: ""
# if the comment value was None or the empty string, just skip it # if the comment value was None or the empty string, just skip it
if comment_macro: if comment_macro:
assert isinstance(comment_macro, str) assert isinstance(comment_macro, str)
macro = '\n'.join(( macro = "\n".join(
'{%- macro query_comment_macro(connection_name, node) -%}', (
"{%- macro query_comment_macro(connection_name, node) -%}",
comment_macro, comment_macro,
'{% endmacro %}' "{% endmacro %}",
)) )
)
ctx = self._get_context() ctx = self._get_context()
self.generator = QueryStringGenerator(macro, ctx) self.generator = QueryStringGenerator(macro, ctx)
self.comment = _QueryComment(None) self.comment = _QueryComment(None)
@@ -87,7 +88,7 @@ class MacroQueryStringSetter:
return self.comment.add(sql) return self.comment.add(sql)
def reset(self): def reset(self):
self.set('master', None) self.set("master", None)
def set(self, name: str, node: Optional[CompileResultNode]): def set(self, name: str, node: Optional[CompileResultNode]):
wrapped: Optional[NodeWrapper] = None wrapped: Optional[NodeWrapper] = None

View File

@@ -1,13 +1,16 @@
from collections.abc import Hashable from collections.abc import Hashable
from dataclasses import dataclass from dataclasses import dataclass
from typing import ( from typing import Optional, TypeVar, Any, Type, Dict, Union, Iterator, Tuple, Set
Optional, TypeVar, Any, Type, Dict, Union, Iterator, Tuple, Set
)
from dbt.contracts.graph.compiled import CompiledNode from dbt.contracts.graph.compiled import CompiledNode
from dbt.contracts.graph.parsed import ParsedSourceDefinition, ParsedNode from dbt.contracts.graph.parsed import ParsedSourceDefinition, ParsedNode
from dbt.contracts.relation import ( from dbt.contracts.relation import (
RelationType, ComponentName, HasQuoting, FakeAPIObject, Policy, Path RelationType,
ComponentName,
HasQuoting,
FakeAPIObject,
Policy,
Path,
) )
from dbt.exceptions import InternalException from dbt.exceptions import InternalException
from dbt.node_types import NodeType from dbt.node_types import NodeType
@@ -16,7 +19,7 @@ from dbt.utils import filter_null_values, deep_merge, classproperty
import dbt.exceptions import dbt.exceptions
Self = TypeVar('Self', bound='BaseRelation') Self = TypeVar("Self", bound="BaseRelation")
@dataclass(frozen=True, eq=False, repr=False) @dataclass(frozen=True, eq=False, repr=False)
@@ -40,7 +43,7 @@ class BaseRelation(FakeAPIObject, Hashable):
if field.name == field_name: if field.name == field_name:
return field return field
# this should be unreachable # this should be unreachable
raise ValueError(f'BaseRelation has no {field_name} field!') raise ValueError(f"BaseRelation has no {field_name} field!")
def __eq__(self, other): def __eq__(self, other):
if not isinstance(other, self.__class__): if not isinstance(other, self.__class__):
@@ -49,20 +52,18 @@ class BaseRelation(FakeAPIObject, Hashable):
@classmethod @classmethod
def get_default_quote_policy(cls) -> Policy: def get_default_quote_policy(cls) -> Policy:
return cls._get_field_named('quote_policy').default return cls._get_field_named("quote_policy").default
@classmethod @classmethod
def get_default_include_policy(cls) -> Policy: def get_default_include_policy(cls) -> Policy:
return cls._get_field_named('include_policy').default return cls._get_field_named("include_policy").default
def get(self, key, default=None): def get(self, key, default=None):
"""Override `.get` to return a metadata object so we don't break """Override `.get` to return a metadata object so we don't break
dbt_utils. dbt_utils.
""" """
if key == 'metadata': if key == "metadata":
return { return {"type": self.__class__.__name__}
'type': self.__class__.__name__
}
return super().get(key, default) return super().get(key, default)
def matches( def matches(
@@ -71,16 +72,19 @@ class BaseRelation(FakeAPIObject, Hashable):
schema: Optional[str] = None, schema: Optional[str] = None,
identifier: Optional[str] = None, identifier: Optional[str] = None,
) -> bool: ) -> bool:
search = filter_null_values({ search = filter_null_values(
{
ComponentName.Database: database, ComponentName.Database: database,
ComponentName.Schema: schema, ComponentName.Schema: schema,
ComponentName.Identifier: identifier ComponentName.Identifier: identifier,
}) }
)
if not search: if not search:
# nothing was passed in # nothing was passed in
raise dbt.exceptions.RuntimeException( raise dbt.exceptions.RuntimeException(
"Tried to match relation, but no search path was passed!") "Tried to match relation, but no search path was passed!"
)
exact_match = True exact_match = True
approximate_match = True approximate_match = True
@@ -88,14 +92,13 @@ class BaseRelation(FakeAPIObject, Hashable):
for k, v in search.items(): for k, v in search.items():
if not self._is_exactish_match(k, v): if not self._is_exactish_match(k, v):
exact_match = False exact_match = False
if str(self.path.get_lowered_part(k)).strip(self.quote_character) != v.lower().strip(
if self.path.get_lowered_part(k) != v.lower(): self.quote_character
approximate_match = False ):
approximate_match = False # type: ignore[union-attr]
if approximate_match and not exact_match: if approximate_match and not exact_match:
target = self.create( target = self.create(database=database, schema=schema, identifier=identifier)
database=database, schema=schema, identifier=identifier
)
dbt.exceptions.approximate_relation_match(target, self) dbt.exceptions.approximate_relation_match(target, self)
return exact_match return exact_match
@@ -109,11 +112,13 @@ class BaseRelation(FakeAPIObject, Hashable):
schema: Optional[bool] = None, schema: Optional[bool] = None,
identifier: Optional[bool] = None, identifier: Optional[bool] = None,
) -> Self: ) -> Self:
policy = filter_null_values({ policy = filter_null_values(
{
ComponentName.Database: database, ComponentName.Database: database,
ComponentName.Schema: schema, ComponentName.Schema: schema,
ComponentName.Identifier: identifier ComponentName.Identifier: identifier,
}) }
)
new_quote_policy = self.quote_policy.replace_dict(policy) new_quote_policy = self.quote_policy.replace_dict(policy)
return self.replace(quote_policy=new_quote_policy) return self.replace(quote_policy=new_quote_policy)
@@ -124,16 +129,18 @@ class BaseRelation(FakeAPIObject, Hashable):
schema: Optional[bool] = None, schema: Optional[bool] = None,
identifier: Optional[bool] = None, identifier: Optional[bool] = None,
) -> Self: ) -> Self:
policy = filter_null_values({ policy = filter_null_values(
{
ComponentName.Database: database, ComponentName.Database: database,
ComponentName.Schema: schema, ComponentName.Schema: schema,
ComponentName.Identifier: identifier ComponentName.Identifier: identifier,
}) }
)
new_include_policy = self.include_policy.replace_dict(policy) new_include_policy = self.include_policy.replace_dict(policy)
return self.replace(include_policy=new_include_policy) return self.replace(include_policy=new_include_policy)
def information_schema(self, view_name=None) -> 'InformationSchema': def information_schema(self, view_name=None) -> "InformationSchema":
# some of our data comes from jinja, where things can be `Undefined`. # some of our data comes from jinja, where things can be `Undefined`.
if not isinstance(view_name, str): if not isinstance(view_name, str):
view_name = None view_name = None
@@ -143,10 +150,10 @@ class BaseRelation(FakeAPIObject, Hashable):
info_schema = InformationSchema.from_relation(self, view_name) info_schema = InformationSchema.from_relation(self, view_name)
return info_schema.incorporate(path={"schema": None}) return info_schema.incorporate(path={"schema": None})
def information_schema_only(self) -> 'InformationSchema': def information_schema_only(self) -> "InformationSchema":
return self.information_schema() return self.information_schema()
def without_identifier(self) -> 'BaseRelation': def without_identifier(self) -> "BaseRelation":
"""Return a form of this relation that only has the database and schema """Return a form of this relation that only has the database and schema
set to included. To get the appropriately-quoted form the schema out of set to included. To get the appropriately-quoted form the schema out of
the result (for use as part of a query), use `.render()`. To get the the result (for use as part of a query), use `.render()`. To get the
@@ -156,9 +163,7 @@ class BaseRelation(FakeAPIObject, Hashable):
""" """
return self.include(identifier=False).replace_path(identifier=None) return self.include(identifier=False).replace_path(identifier=None)
def _render_iterator( def _render_iterator(self) -> Iterator[Tuple[Optional[ComponentName], Optional[str]]]:
self
) -> Iterator[Tuple[Optional[ComponentName], Optional[str]]]:
for key in ComponentName: for key in ComponentName:
path_part: Optional[str] = None path_part: Optional[str] = None
@@ -170,27 +175,22 @@ class BaseRelation(FakeAPIObject, Hashable):
def render(self) -> str: def render(self) -> str:
# if there is nothing set, this will return the empty string. # if there is nothing set, this will return the empty string.
return '.'.join( return ".".join(part for _, part in self._render_iterator() if part is not None)
part for _, part in self._render_iterator()
if part is not None
)
def quoted(self, identifier): def quoted(self, identifier):
return '{quote_char}{identifier}{quote_char}'.format( return "{quote_char}{identifier}{quote_char}".format(
quote_char=self.quote_character, quote_char=self.quote_character,
identifier=identifier, identifier=identifier,
) )
@classmethod @classmethod
def create_from_source( def create_from_source(cls: Type[Self], source: ParsedSourceDefinition, **kwargs: Any) -> Self:
cls: Type[Self], source: ParsedSourceDefinition, **kwargs: Any
) -> Self:
source_quoting = source.quoting.to_dict(omit_none=True) source_quoting = source.quoting.to_dict(omit_none=True)
source_quoting.pop('column', None) source_quoting.pop("column", None)
quote_policy = deep_merge( quote_policy = deep_merge(
cls.get_default_quote_policy().to_dict(omit_none=True), cls.get_default_quote_policy().to_dict(omit_none=True),
source_quoting, source_quoting,
kwargs.get('quote_policy', {}), kwargs.get("quote_policy", {}),
) )
return cls.create( return cls.create(
@@ -198,12 +198,12 @@ class BaseRelation(FakeAPIObject, Hashable):
schema=source.schema, schema=source.schema,
identifier=source.identifier, identifier=source.identifier,
quote_policy=quote_policy, quote_policy=quote_policy,
**kwargs **kwargs,
) )
@staticmethod @staticmethod
def add_ephemeral_prefix(name: str): def add_ephemeral_prefix(name: str):
return f'__dbt__cte__{name}' return f"__dbt__cte__{name}"
@classmethod @classmethod
def create_ephemeral_from_node( def create_ephemeral_from_node(
@@ -236,7 +236,8 @@ class BaseRelation(FakeAPIObject, Hashable):
schema=node.schema, schema=node.schema,
identifier=node.alias, identifier=node.alias,
quote_policy=quote_policy, quote_policy=quote_policy,
**kwargs) **kwargs,
)
@classmethod @classmethod
def create_from( def create_from(
@@ -248,15 +249,14 @@ class BaseRelation(FakeAPIObject, Hashable):
if node.resource_type == NodeType.Source: if node.resource_type == NodeType.Source:
if not isinstance(node, ParsedSourceDefinition): if not isinstance(node, ParsedSourceDefinition):
raise InternalException( raise InternalException(
'type mismatch, expected ParsedSourceDefinition but got {}' "type mismatch, expected ParsedSourceDefinition but got {}".format(type(node))
.format(type(node))
) )
return cls.create_from_source(node, **kwargs) return cls.create_from_source(node, **kwargs)
else: else:
if not isinstance(node, (ParsedNode, CompiledNode)): if not isinstance(node, (ParsedNode, CompiledNode)):
raise InternalException( raise InternalException(
'type mismatch, expected ParsedNode or CompiledNode but ' "type mismatch, expected ParsedNode or CompiledNode but "
'got {}'.format(type(node)) "got {}".format(type(node))
) )
return cls.create_from_node(config, node, **kwargs) return cls.create_from_node(config, node, **kwargs)
@@ -269,14 +269,16 @@ class BaseRelation(FakeAPIObject, Hashable):
type: Optional[RelationType] = None, type: Optional[RelationType] = None,
**kwargs, **kwargs,
) -> Self: ) -> Self:
kwargs.update({ kwargs.update(
'path': { {
'database': database, "path": {
'schema': schema, "database": database,
'identifier': identifier, "schema": schema,
"identifier": identifier,
}, },
'type': type, "type": type,
}) }
)
return cls.from_dict(kwargs) return cls.from_dict(kwargs)
def __repr__(self) -> str: def __repr__(self) -> str:
@@ -342,7 +344,7 @@ class BaseRelation(FakeAPIObject, Hashable):
return RelationType return RelationType
Info = TypeVar('Info', bound='InformationSchema') Info = TypeVar("Info", bound="InformationSchema")
@dataclass(frozen=True, eq=False, repr=False) @dataclass(frozen=True, eq=False, repr=False)
@@ -352,17 +354,15 @@ class InformationSchema(BaseRelation):
def __post_init__(self): def __post_init__(self):
if not isinstance(self.information_schema_view, (type(None), str)): if not isinstance(self.information_schema_view, (type(None), str)):
raise dbt.exceptions.CompilationException( raise dbt.exceptions.CompilationException(
'Got an invalid name: {}'.format(self.information_schema_view) "Got an invalid name: {}".format(self.information_schema_view)
) )
@classmethod @classmethod
def get_path( def get_path(cls, relation: BaseRelation, information_schema_view: Optional[str]) -> Path:
cls, relation: BaseRelation, information_schema_view: Optional[str]
) -> Path:
return Path( return Path(
database=relation.database, database=relation.database,
schema=relation.schema, schema=relation.schema,
identifier='INFORMATION_SCHEMA', identifier="INFORMATION_SCHEMA",
) )
@classmethod @classmethod
@@ -393,9 +393,7 @@ class InformationSchema(BaseRelation):
relation: BaseRelation, relation: BaseRelation,
information_schema_view: Optional[str], information_schema_view: Optional[str],
) -> Info: ) -> Info:
include_policy = cls.get_include_policy( include_policy = cls.get_include_policy(relation, information_schema_view)
relation, information_schema_view
)
quote_policy = cls.get_quote_policy(relation, information_schema_view) quote_policy = cls.get_quote_policy(relation, information_schema_view)
path = cls.get_path(relation, information_schema_view) path = cls.get_path(relation, information_schema_view)
return cls( return cls(
@@ -417,6 +415,7 @@ class SchemaSearchMap(Dict[InformationSchema, Set[Optional[str]]]):
search for what schemas. The schema values are all lowercased to avoid search for what schemas. The schema values are all lowercased to avoid
duplication. duplication.
""" """
def add(self, relation: BaseRelation): def add(self, relation: BaseRelation):
key = relation.information_schema_only() key = relation.information_schema_only()
if key not in self: if key not in self:
@@ -426,9 +425,7 @@ class SchemaSearchMap(Dict[InformationSchema, Set[Optional[str]]]):
schema = relation.schema.lower() schema = relation.schema.lower()
self[key].add(schema) self[key].add(schema)
def search( def search(self) -> Iterator[Tuple[InformationSchema, Optional[str]]]:
self
) -> Iterator[Tuple[InformationSchema, Optional[str]]]:
for information_schema_name, schemas in self.items(): for information_schema_name, schemas in self.items():
for schema in schemas: for schema in schemas:
yield information_schema_name, schema yield information_schema_name, schema
@@ -443,14 +440,13 @@ class SchemaSearchMap(Dict[InformationSchema, Set[Optional[str]]]):
dbt.exceptions.raise_compiler_error(str(seen)) dbt.exceptions.raise_compiler_error(str(seen))
for information_schema_name, schema in self.search(): for information_schema_name, schema in self.search():
path = { path = {"database": information_schema_name.database, "schema": schema}
'database': information_schema_name.database, new.add(
'schema': schema information_schema_name.incorporate(
}
new.add(information_schema_name.incorporate(
path=path, path=path,
quote_policy={'database': False}, quote_policy={"database": False},
include_policy={'database': False}, include_policy={"database": False},
)) )
)
return new return new

View File

@@ -1,23 +1,27 @@
from collections import namedtuple
from copy import deepcopy
from typing import List, Iterable, Optional, Dict, Set, Tuple, Any
import threading import threading
from copy import deepcopy
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
from dbt.logger import CACHE_LOGGER as logger from dbt.adapters.reference_keys import _make_key, _ReferenceKey
from dbt.utils import lowercase
import dbt.exceptions import dbt.exceptions
from dbt.events.functions import fire_event
_ReferenceKey = namedtuple('_ReferenceKey', 'database schema identifier') from dbt.events.types import (
AddLink,
AddRelation,
def _make_key(relation) -> _ReferenceKey: DropCascade,
"""Make _ReferenceKeys with lowercase values for the cache so we don't have DropMissingRelation,
to keep track of quoting DropRelation,
""" DumpAfterAddGraph,
# databases and schemas can both be None DumpAfterRenameSchema,
return _ReferenceKey(lowercase(relation.database), DumpBeforeAddGraph,
lowercase(relation.schema), DumpBeforeRenameSchema,
lowercase(relation.identifier)) RenameSchema,
TemporaryRelation,
UncachedRelation,
UpdateReference,
)
from dbt.utils import lowercase
from dbt.helper_types import Lazy
def dot_separated(key: _ReferenceKey) -> str: def dot_separated(key: _ReferenceKey) -> str:
@@ -25,7 +29,7 @@ def dot_separated(key: _ReferenceKey) -> str:
:param _ReferenceKey key: The key to stringify. :param _ReferenceKey key: The key to stringify.
""" """
return '.'.join(map(str, key)) return ".".join(map(str, key))
class _CachedRelation: class _CachedRelation:
@@ -37,14 +41,15 @@ class _CachedRelation:
that refer to this relation. that refer to this relation.
:attr BaseRelation inner: The underlying dbt relation. :attr BaseRelation inner: The underlying dbt relation.
""" """
def __init__(self, inner): def __init__(self, inner):
self.referenced_by = {} self.referenced_by = {}
self.inner = inner self.inner = inner
def __str__(self) -> str: def __str__(self) -> str:
return ( return ("_CachedRelation(database={}, schema={}, identifier={}, inner={})").format(
'_CachedRelation(database={}, schema={}, identifier={}, inner={})' self.database, self.schema, self.identifier, self.inner
).format(self.database, self.schema, self.identifier, self.inner) )
@property @property
def database(self) -> Optional[str]: def database(self) -> Optional[str]:
@@ -78,7 +83,7 @@ class _CachedRelation:
""" """
return _make_key(self) return _make_key(self)
def add_reference(self, referrer: '_CachedRelation'): def add_reference(self, referrer: "_CachedRelation"):
"""Add a reference from referrer to self, indicating that if this node """Add a reference from referrer to self, indicating that if this node
were drop...cascaded, the referrer would be dropped as well. were drop...cascaded, the referrer would be dropped as well.
@@ -122,9 +127,9 @@ class _CachedRelation:
# table_name is ever anything but the identifier (via .create()) # table_name is ever anything but the identifier (via .create())
self.inner = self.inner.incorporate( self.inner = self.inner.incorporate(
path={ path={
'database': new_relation.inner.database, "database": new_relation.inner.database,
'schema': new_relation.inner.schema, "schema": new_relation.inner.schema,
'identifier': new_relation.inner.identifier "identifier": new_relation.inner.identifier,
}, },
) )
@@ -140,8 +145,9 @@ class _CachedRelation:
""" """
if new_key in self.referenced_by: if new_key in self.referenced_by:
dbt.exceptions.raise_cache_inconsistent( dbt.exceptions.raise_cache_inconsistent(
'in rename of "{}" -> "{}", new name is in the cache already' 'in rename of "{}" -> "{}", new name is in the cache already'.format(
.format(old_key, new_key) old_key, new_key
)
) )
if old_key not in self.referenced_by: if old_key not in self.referenced_by:
@@ -157,12 +163,6 @@ class _CachedRelation:
return [dot_separated(r) for r in self.referenced_by] return [dot_separated(r) for r in self.referenced_by]
def lazy_log(msg, func):
if logger.disabled:
return
logger.debug(msg.format(func()))
class RelationsCache: class RelationsCache:
"""A cache of the relations known to dbt. Keeps track of relationships """A cache of the relations known to dbt. Keeps track of relationships
declared between tables and handles renames/drops as a real database would. declared between tables and handles renames/drops as a real database would.
@@ -172,13 +172,16 @@ class RelationsCache:
The adapters also hold this lock while filling the cache. The adapters also hold this lock while filling the cache.
:attr Set[str] schemas: The set of known/cached schemas, all lowercased. :attr Set[str] schemas: The set of known/cached schemas, all lowercased.
""" """
def __init__(self) -> None: def __init__(self) -> None:
self.relations: Dict[_ReferenceKey, _CachedRelation] = {} self.relations: Dict[_ReferenceKey, _CachedRelation] = {}
self.lock = threading.RLock() self.lock = threading.RLock()
self.schemas: Set[Tuple[Optional[str], Optional[str]]] = set() self.schemas: Set[Tuple[Optional[str], Optional[str]]] = set()
def add_schema( def add_schema(
self, database: Optional[str], schema: Optional[str], self,
database: Optional[str],
schema: Optional[str],
) -> None: ) -> None:
"""Add a schema to the set of known schemas (case-insensitive) """Add a schema to the set of known schemas (case-insensitive)
@@ -188,7 +191,9 @@ class RelationsCache:
self.schemas.add((lowercase(database), lowercase(schema))) self.schemas.add((lowercase(database), lowercase(schema)))
def drop_schema( def drop_schema(
self, database: Optional[str], schema: Optional[str], self,
database: Optional[str],
schema: Optional[str],
) -> None: ) -> None:
"""Drop the given schema and remove it from the set of known schemas. """Drop the given schema and remove it from the set of known schemas.
@@ -232,10 +237,7 @@ class RelationsCache:
# self.relations or any cache entry's referenced_by during iteration # self.relations or any cache entry's referenced_by during iteration
# it's a runtime error! # it's a runtime error!
with self.lock: with self.lock:
return { return {dot_separated(k): v.dump_graph_entry() for k, v in self.relations.items()}
dot_separated(k): v.dump_graph_entry()
for k, v in self.relations.items()
}
def _setdefault(self, relation: _CachedRelation): def _setdefault(self, relation: _CachedRelation):
"""Add a relation to the cache, or return it if it already exists. """Add a relation to the cache, or return it if it already exists.
@@ -263,21 +265,20 @@ class RelationsCache:
return return
if referenced is None: if referenced is None:
dbt.exceptions.raise_cache_inconsistent( dbt.exceptions.raise_cache_inconsistent(
'in add_link, referenced link key {} not in cache!' "in add_link, referenced link key {} not in cache!".format(referenced_key)
.format(referenced_key)
) )
dependent = self.relations.get(dependent_key) dependent = self.relations.get(dependent_key)
if dependent is None: if dependent is None:
dbt.exceptions.raise_cache_inconsistent( dbt.exceptions.raise_cache_inconsistent(
'in add_link, dependent link key {} not in cache!' "in add_link, dependent link key {} not in cache!".format(dependent_key)
.format(dependent_key)
) )
assert dependent is not None # we just raised! assert dependent is not None # we just raised!
referenced.add_reference(dependent) referenced.add_reference(dependent)
# TODO: Is this dead code? I can't seem to find it grepping the codebase.
def add_link(self, referenced, dependent): def add_link(self, referenced, dependent):
"""Add a link between two relations to the database. If either relation """Add a link between two relations to the database. If either relation
does not exist, it will be added as an "external" relation. does not exist, it will be added as an "external" relation.
@@ -293,33 +294,22 @@ class RelationsCache:
:raises InternalError: If either entry does not exist. :raises InternalError: If either entry does not exist.
""" """
ref_key = _make_key(referenced) ref_key = _make_key(referenced)
dep_key = _make_key(dependent)
if (ref_key.database, ref_key.schema) not in self: if (ref_key.database, ref_key.schema) not in self:
# if we have not cached the referenced schema at all, we must be # if we have not cached the referenced schema at all, we must be
# referring to a table outside our control. There's no need to make # referring to a table outside our control. There's no need to make
# a link - we will never drop the referenced relation during a run. # a link - we will never drop the referenced relation during a run.
logger.debug( fire_event(UncachedRelation(dep_key=dep_key, ref_key=ref_key))
'{dep!s} references {ref!s} but {ref.database}.{ref.schema} '
'is not in the cache, skipping assumed external relation'
.format(dep=dependent, ref=ref_key)
)
return return
if ref_key not in self.relations: if ref_key not in self.relations:
# Insert a dummy "external" relation. # Insert a dummy "external" relation.
referenced = referenced.replace( referenced = referenced.replace(type=referenced.External)
type=referenced.External
)
self.add(referenced) self.add(referenced)
dep_key = _make_key(dependent)
if dep_key not in self.relations: if dep_key not in self.relations:
# Insert a dummy "external" relation. # Insert a dummy "external" relation.
dependent = dependent.replace( dependent = dependent.replace(type=referenced.External)
type=referenced.External
)
self.add(dependent) self.add(dependent)
logger.debug( fire_event(AddLink(dep_key=dep_key, ref_key=ref_key))
'adding link, {!s} references {!s}'.format(dep_key, ref_key)
)
with self.lock: with self.lock:
self._add_link(ref_key, dep_key) self._add_link(ref_key, dep_key)
@@ -330,14 +320,12 @@ class RelationsCache:
:param BaseRelation relation: The underlying relation. :param BaseRelation relation: The underlying relation.
""" """
cached = _CachedRelation(relation) cached = _CachedRelation(relation)
logger.debug('Adding relation: {!s}'.format(cached)) fire_event(AddRelation(relation=_make_key(cached)))
fire_event(DumpBeforeAddGraph(dump=Lazy.defer(lambda: self.dump_graph())))
lazy_log('before adding: {!s}', self.dump_graph)
with self.lock: with self.lock:
self._setdefault(cached) self._setdefault(cached)
fire_event(DumpAfterAddGraph(dump=Lazy.defer(lambda: self.dump_graph())))
lazy_log('after adding: {!s}', self.dump_graph)
def _remove_refs(self, keys): def _remove_refs(self, keys):
"""Removes all references to all entries in keys. This does not """Removes all references to all entries in keys. This does not
@@ -352,20 +340,17 @@ class RelationsCache:
for cached in self.relations.values(): for cached in self.relations.values():
cached.release_references(keys) cached.release_references(keys)
def _drop_cascade_relation(self, dropped): def _drop_cascade_relation(self, dropped_key):
"""Drop the given relation and cascade it appropriately to all """Drop the given relation and cascade it appropriately to all
dependent relations. dependent relations.
:param _CachedRelation dropped: An existing _CachedRelation to drop. :param _CachedRelation dropped: An existing _CachedRelation to drop.
""" """
if dropped not in self.relations: if dropped_key not in self.relations:
logger.debug('dropped a nonexistent relationship: {!s}' fire_event(DropMissingRelation(relation=dropped_key))
.format(dropped))
return return
consequences = self.relations[dropped].collect_consequences() consequences = self.relations[dropped_key].collect_consequences()
logger.debug( fire_event(DropCascade(dropped=dropped_key, consequences=consequences))
'drop {} is cascading to {}'.format(dropped, consequences)
)
self._remove_refs(consequences) self._remove_refs(consequences)
def drop(self, relation): def drop(self, relation):
@@ -379,10 +364,10 @@ class RelationsCache:
:param str schema: The schema of the relation to drop. :param str schema: The schema of the relation to drop.
:param str identifier: The identifier of the relation to drop. :param str identifier: The identifier of the relation to drop.
""" """
dropped = _make_key(relation) dropped_key = _make_key(relation)
logger.debug('Dropping relation: {!s}'.format(dropped)) fire_event(DropRelation(dropped=dropped_key))
with self.lock: with self.lock:
self._drop_cascade_relation(dropped) self._drop_cascade_relation(dropped_key)
def _rename_relation(self, old_key, new_relation): def _rename_relation(self, old_key, new_relation):
"""Rename a relation named old_key to new_key, updating references. """Rename a relation named old_key to new_key, updating references.
@@ -403,9 +388,8 @@ class RelationsCache:
# update all the relations that refer to it # update all the relations that refer to it
for cached in self.relations.values(): for cached in self.relations.values():
if cached.is_referenced_by(old_key): if cached.is_referenced_by(old_key):
logger.debug( fire_event(
'updated reference from {0} -> {2} to {1} -> {2}' UpdateReference(old_key=old_key, new_key=new_key, cached_key=cached.key())
.format(old_key, new_key, cached.key())
) )
cached.rename_key(old_key, new_key) cached.rename_key(old_key, new_key)
@@ -430,15 +414,13 @@ class RelationsCache:
""" """
if new_key in self.relations: if new_key in self.relations:
dbt.exceptions.raise_cache_inconsistent( dbt.exceptions.raise_cache_inconsistent(
'in rename, new key {} already in cache: {}' "in rename, new key {} already in cache: {}".format(
.format(new_key, list(self.relations.keys())) new_key, list(self.relations.keys())
)
) )
if old_key not in self.relations: if old_key not in self.relations:
logger.debug( fire_event(TemporaryRelation(key=old_key))
'old key {} not found in self.relations, assuming temporary'
.format(old_key)
)
return False return False
return True return True
@@ -456,11 +438,9 @@ class RelationsCache:
""" """
old_key = _make_key(old) old_key = _make_key(old)
new_key = _make_key(new) new_key = _make_key(new)
logger.debug('Renaming relation {!s} to {!s}'.format( fire_event(RenameSchema(old_key=old_key, new_key=new_key))
old_key, new_key
))
lazy_log('before rename: {!s}', self.dump_graph) fire_event(DumpBeforeRenameSchema(dump=Lazy.defer(lambda: self.dump_graph())))
with self.lock: with self.lock:
if self._check_rename_constraints(old_key, new_key): if self._check_rename_constraints(old_key, new_key):
@@ -468,11 +448,9 @@ class RelationsCache:
else: else:
self._setdefault(_CachedRelation(new)) self._setdefault(_CachedRelation(new))
lazy_log('after rename: {!s}', self.dump_graph) fire_event(DumpAfterRenameSchema(dump=Lazy.defer(lambda: self.dump_graph())))
def get_relations( def get_relations(self, database: Optional[str], schema: Optional[str]) -> List[Any]:
self, database: Optional[str], schema: Optional[str]
) -> List[Any]:
"""Case-insensitively yield all relations matching the given schema. """Case-insensitively yield all relations matching the given schema.
:param str schema: The case-insensitive schema name to list from. :param str schema: The case-insensitive schema name to list from.
@@ -483,14 +461,14 @@ class RelationsCache:
schema = lowercase(schema) schema = lowercase(schema)
with self.lock: with self.lock:
results = [ results = [
r.inner for r in self.relations.values() r.inner
if (lowercase(r.schema) == schema and for r in self.relations.values()
lowercase(r.database) == database) if (lowercase(r.schema) == schema and lowercase(r.database) == database)
] ]
if None in results: if None in results:
dbt.exceptions.raise_cache_inconsistent( dbt.exceptions.raise_cache_inconsistent(
'in get_relations, a None relation was found in the cache!' "in get_relations, a None relation was found in the cache!"
) )
return results return results

View File

@@ -8,10 +8,9 @@ from dbt.include.global_project import (
PACKAGE_PATH as GLOBAL_PROJECT_PATH, PACKAGE_PATH as GLOBAL_PROJECT_PATH,
PROJECT_NAME as GLOBAL_PROJECT_NAME, PROJECT_NAME as GLOBAL_PROJECT_NAME,
) )
from dbt.logger import GLOBAL_LOGGER as logger from dbt.events.functions import fire_event
from dbt.events.types import AdapterImportError, PluginLoadError
from dbt.contracts.connection import Credentials, AdapterRequiredConfig from dbt.contracts.connection import Credentials, AdapterRequiredConfig
from dbt.adapters.protocol import ( from dbt.adapters.protocol import (
AdapterProtocol, AdapterProtocol,
AdapterConfig, AdapterConfig,
@@ -50,9 +49,7 @@ class AdapterContainer:
adapter = self.get_adapter_class_by_name(name) adapter = self.get_adapter_class_by_name(name)
return adapter.Relation return adapter.Relation
def get_config_class_by_name( def get_config_class_by_name(self, name: str) -> Type[AdapterConfig]:
self, name: str
) -> Type[AdapterConfig]:
adapter = self.get_adapter_class_by_name(name) adapter = self.get_adapter_class_by_name(name)
return adapter.AdapterSpecificConfigs return adapter.AdapterSpecificConfigs
@@ -62,24 +59,25 @@ class AdapterContainer:
# singletons # singletons
try: try:
# mypy doesn't think modules have any attributes. # mypy doesn't think modules have any attributes.
mod: Any = import_module('.' + name, 'dbt.adapters') mod: Any = import_module("." + name, "dbt.adapters")
except ModuleNotFoundError as exc: except ModuleNotFoundError as exc:
# if we failed to import the target module in particular, inform # if we failed to import the target module in particular, inform
# the user about it via a runtime error # the user about it via a runtime error
if exc.name == 'dbt.adapters.' + name: if exc.name == "dbt.adapters." + name:
raise RuntimeException(f'Could not find adapter type {name}!') fire_event(AdapterImportError(exc=exc))
logger.info(f'Error importing adapter: {exc}') raise RuntimeException(f"Could not find adapter type {name}!")
# otherwise, the error had to have come from some underlying # otherwise, the error had to have come from some underlying
# library. Log the stack trace. # library. Log the stack trace.
logger.debug('', exc_info=True)
fire_event(PluginLoadError())
raise raise
plugin: AdapterPlugin = mod.Plugin plugin: AdapterPlugin = mod.Plugin
plugin_type = plugin.adapter.type() plugin_type = plugin.adapter.type()
if plugin_type != name: if plugin_type != name:
raise RuntimeException( raise RuntimeException(
f'Expected to find adapter with type named {name}, got ' f"Expected to find adapter with type named {name}, got "
f'adapter with type {plugin_type}' f"adapter with type {plugin_type}"
) )
with self.lock: with self.lock:
@@ -109,8 +107,7 @@ class AdapterContainer:
return self.adapters[adapter_name] return self.adapters[adapter_name]
def reset_adapters(self): def reset_adapters(self):
"""Clear the adapters. This is useful for tests, which change configs. """Clear the adapters. This is useful for tests, which change configs."""
"""
with self.lock: with self.lock:
for adapter in self.adapters.values(): for adapter in self.adapters.values():
adapter.cleanup_connections() adapter.cleanup_connections()
@@ -140,9 +137,7 @@ class AdapterContainer:
try: try:
plugin = self.plugins[plugin_name] plugin = self.plugins[plugin_name]
except KeyError: except KeyError:
raise InternalException( raise InternalException(f"No plugin found for {plugin_name}") from None
f'No plugin found for {plugin_name}'
) from None
plugins.append(plugin) plugins.append(plugin)
seen.add(plugin_name) seen.add(plugin_name)
if plugin.dependencies is None: if plugin.dependencies is None:
@@ -153,9 +148,7 @@ class AdapterContainer:
return plugins return plugins
def get_adapter_package_names(self, name: Optional[str]) -> List[str]: def get_adapter_package_names(self, name: Optional[str]) -> List[str]:
package_names: List[str] = [ package_names: List[str] = [p.project_name for p in self.get_adapter_plugins(name)]
p.project_name for p in self.get_adapter_plugins(name)
]
package_names.append(GLOBAL_PROJECT_NAME) package_names.append(GLOBAL_PROJECT_NAME)
return package_names return package_names
@@ -165,9 +158,7 @@ class AdapterContainer:
try: try:
path = self.packages[package_name] path = self.packages[package_name]
except KeyError: except KeyError:
raise InternalException( raise InternalException(f"No internal package listing found for {package_name}")
f'No internal package listing found for {package_name}'
)
paths.append(path) paths.append(path)
return paths return paths
@@ -186,9 +177,12 @@ def get_adapter(config: AdapterRequiredConfig):
return FACTORY.lookup_adapter(config.credentials.type) return FACTORY.lookup_adapter(config.credentials.type)
def get_adapter_by_type(adapter_type):
return FACTORY.lookup_adapter(adapter_type)
def reset_adapters(): def reset_adapters():
"""Clear the adapters. This is useful for tests, which change configs. """Clear the adapters. This is useful for tests, which change configs."""
"""
FACTORY.reset_adapters() FACTORY.reset_adapters()

View File

@@ -1,18 +1,24 @@
from dataclasses import dataclass from dataclasses import dataclass
from typing import ( from typing import (
Type, Hashable, Optional, ContextManager, List, Generic, TypeVar, ClassVar, Type,
Tuple, Union, Dict, Any Hashable,
Optional,
ContextManager,
List,
Generic,
TypeVar,
ClassVar,
Tuple,
Union,
Dict,
Any,
) )
from typing_extensions import Protocol from typing_extensions import Protocol
import agate import agate
from dbt.contracts.connection import ( from dbt.contracts.connection import Connection, AdapterRequiredConfig, AdapterResponse
Connection, AdapterRequiredConfig, AdapterResponse from dbt.contracts.graph.compiled import CompiledNode, ManifestNode, NonSourceCompiledNode
)
from dbt.contracts.graph.compiled import (
CompiledNode, ManifestNode, NonSourceCompiledNode
)
from dbt.contracts.graph.parsed import ParsedNode, ParsedSourceDefinition from dbt.contracts.graph.parsed import ParsedNode, ParsedSourceDefinition
from dbt.contracts.graph.model_config import BaseConfig from dbt.contracts.graph.model_config import BaseConfig
from dbt.contracts.graph.manifest import Manifest from dbt.contracts.graph.manifest import Manifest
@@ -34,7 +40,7 @@ class ColumnProtocol(Protocol):
pass pass
Self = TypeVar('Self', bound='RelationProtocol') Self = TypeVar("Self", bound="RelationProtocol")
class RelationProtocol(Protocol): class RelationProtocol(Protocol):
@@ -64,22 +70,15 @@ class CompilerProtocol(Protocol):
... ...
AdapterConfig_T = TypeVar( AdapterConfig_T = TypeVar("AdapterConfig_T", bound=AdapterConfig)
'AdapterConfig_T', bound=AdapterConfig ConnectionManager_T = TypeVar("ConnectionManager_T", bound=ConnectionManagerProtocol)
) Relation_T = TypeVar("Relation_T", bound=RelationProtocol)
ConnectionManager_T = TypeVar( Column_T = TypeVar("Column_T", bound=ColumnProtocol)
'ConnectionManager_T', bound=ConnectionManagerProtocol Compiler_T = TypeVar("Compiler_T", bound=CompilerProtocol)
)
Relation_T = TypeVar(
'Relation_T', bound=RelationProtocol
)
Column_T = TypeVar(
'Column_T', bound=ColumnProtocol
)
Compiler_T = TypeVar('Compiler_T', bound=CompilerProtocol)
class AdapterProtocol( # TODO CT-211
class AdapterProtocol( # type: ignore[misc]
Protocol, Protocol,
Generic[ Generic[
AdapterConfig_T, AdapterConfig_T,
@@ -87,7 +86,7 @@ class AdapterProtocol(
Relation_T, Relation_T,
Column_T, Column_T,
Compiler_T, Compiler_T,
] ],
): ):
AdapterSpecificConfigs: ClassVar[Type[AdapterConfig_T]] AdapterSpecificConfigs: ClassVar[Type[AdapterConfig_T]]
Column: ClassVar[Type[Column_T]] Column: ClassVar[Type[Column_T]]

View File

@@ -0,0 +1,24 @@
# this module exists to resolve circular imports with the events module
from collections import namedtuple
from typing import Optional
_ReferenceKey = namedtuple("_ReferenceKey", "database schema identifier")
def lowercase(value: Optional[str]) -> Optional[str]:
if value is None:
return None
else:
return value.lower()
def _make_key(relation) -> _ReferenceKey:
"""Make _ReferenceKeys with lowercase values for the cache so we don't have
to keep track of quoting
"""
# databases and schemas can both be None
return _ReferenceKey(
lowercase(relation.database), lowercase(relation.schema), lowercase(relation.identifier)
)

View File

@@ -7,10 +7,9 @@ import agate
import dbt.clients.agate_helper import dbt.clients.agate_helper
import dbt.exceptions import dbt.exceptions
from dbt.adapters.base import BaseConnectionManager from dbt.adapters.base import BaseConnectionManager
from dbt.contracts.connection import ( from dbt.contracts.connection import Connection, ConnectionState, AdapterResponse
Connection, ConnectionState, AdapterResponse from dbt.events.functions import fire_event
) from dbt.events.types import ConnectionUsed, SQLQuery, SQLCommit, SQLQueryStatus
from dbt.logger import GLOBAL_LOGGER as logger
class SQLConnectionManager(BaseConnectionManager): class SQLConnectionManager(BaseConnectionManager):
@@ -22,11 +21,12 @@ class SQLConnectionManager(BaseConnectionManager):
- get_response - get_response
- open - open
""" """
@abc.abstractmethod @abc.abstractmethod
def cancel(self, connection: Connection): def cancel(self, connection: Connection):
"""Cancel the given connection.""" """Cancel the given connection."""
raise dbt.exceptions.NotImplementedException( raise dbt.exceptions.NotImplementedException(
'`cancel` is not implemented for this adapter!' "`cancel` is not implemented for this adapter!"
) )
def cancel_open(self) -> List[str]: def cancel_open(self) -> List[str]:
@@ -39,10 +39,7 @@ class SQLConnectionManager(BaseConnectionManager):
# if the connection failed, the handle will be None so we have # if the connection failed, the handle will be None so we have
# nothing to cancel. # nothing to cancel.
if ( if connection.handle is not None and connection.state == ConnectionState.OPEN:
connection.handle is not None and
connection.state == ConnectionState.OPEN
):
self.cancel(connection) self.cancel(connection)
if connection.name is not None: if connection.name is not None:
names.append(connection.name) names.append(connection.name)
@@ -53,34 +50,29 @@ class SQLConnectionManager(BaseConnectionManager):
sql: str, sql: str,
auto_begin: bool = True, auto_begin: bool = True,
bindings: Optional[Any] = None, bindings: Optional[Any] = None,
abridge_sql_log: bool = False abridge_sql_log: bool = False,
) -> Tuple[Connection, Any]: ) -> Tuple[Connection, Any]:
connection = self.get_thread_connection() connection = self.get_thread_connection()
if auto_begin and connection.transaction_open is False: if auto_begin and connection.transaction_open is False:
self.begin() self.begin()
fire_event(ConnectionUsed(conn_type=self.TYPE, conn_name=connection.name))
logger.debug('Using {} connection "{}".'
.format(self.TYPE, connection.name))
with self.exception_handler(sql): with self.exception_handler(sql):
if abridge_sql_log: if abridge_sql_log:
log_sql = '{}...'.format(sql[:512]) log_sql = "{}...".format(sql[:512])
else: else:
log_sql = sql log_sql = sql
logger.debug( fire_event(SQLQuery(conn_name=connection.name, sql=log_sql))
'On {connection_name}: {sql}',
connection_name=connection.name,
sql=log_sql,
)
pre = time.time() pre = time.time()
cursor = connection.handle.cursor() cursor = connection.handle.cursor()
cursor.execute(sql, bindings) cursor.execute(sql, bindings)
logger.debug(
"SQL status: {status} in {elapsed:0.2f} seconds", fire_event(
status=self.get_response(cursor), SQLQueryStatus(
elapsed=(time.time() - pre) status=str(self.get_response(cursor)), elapsed=round((time.time() - pre), 2)
)
) )
return connection, cursor return connection, cursor
@@ -89,23 +81,26 @@ class SQLConnectionManager(BaseConnectionManager):
def get_response(cls, cursor: Any) -> Union[AdapterResponse, str]: def get_response(cls, cursor: Any) -> Union[AdapterResponse, str]:
"""Get the status of the cursor.""" """Get the status of the cursor."""
raise dbt.exceptions.NotImplementedException( raise dbt.exceptions.NotImplementedException(
'`get_response` is not implemented for this adapter!' "`get_response` is not implemented for this adapter!"
) )
@classmethod @classmethod
def process_results( def process_results(
cls, cls, column_names: Iterable[str], rows: Iterable[Any]
column_names: Iterable[str],
rows: Iterable[Any]
) -> List[Dict[str, Any]]: ) -> List[Dict[str, Any]]:
unique_col_names = dict() # TODO CT-211
for idx in range(len(column_names)): unique_col_names = dict() # type: ignore[var-annotated]
col_name = column_names[idx] # TODO CT-211
for idx in range(len(column_names)): # type: ignore[arg-type]
# TODO CT-211
col_name = column_names[idx] # type: ignore[index]
if col_name in unique_col_names: if col_name in unique_col_names:
unique_col_names[col_name] += 1 unique_col_names[col_name] += 1
column_names[idx] = f'{col_name}_{unique_col_names[col_name]}' # TODO CT-211
column_names[idx] = f"{col_name}_{unique_col_names[col_name]}" # type: ignore[index] # noqa
else: else:
unique_col_names[column_names[idx]] = 1 # TODO CT-211
unique_col_names[column_names[idx]] = 1 # type: ignore[index]
return [dict(zip(column_names, row)) for row in rows] return [dict(zip(column_names, row)) for row in rows]
@classmethod @classmethod
@@ -118,10 +113,7 @@ class SQLConnectionManager(BaseConnectionManager):
rows = cursor.fetchall() rows = cursor.fetchall()
data = cls.process_results(column_names, rows) data = cls.process_results(column_names, rows)
return dbt.clients.agate_helper.table_from_data_flat( return dbt.clients.agate_helper.table_from_data_flat(data, column_names)
data,
column_names
)
def execute( def execute(
self, sql: str, auto_begin: bool = False, fetch: bool = False self, sql: str, auto_begin: bool = False, fetch: bool = False
@@ -136,17 +128,18 @@ class SQLConnectionManager(BaseConnectionManager):
return response, table return response, table
def add_begin_query(self): def add_begin_query(self):
return self.add_query('BEGIN', auto_begin=False) return self.add_query("BEGIN", auto_begin=False)
def add_commit_query(self): def add_commit_query(self):
return self.add_query('COMMIT', auto_begin=False) return self.add_query("COMMIT", auto_begin=False)
def begin(self): def begin(self):
connection = self.get_thread_connection() connection = self.get_thread_connection()
if connection.transaction_open is True: if connection.transaction_open is True:
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
'Tried to begin a new transaction on connection "{}", but ' 'Tried to begin a new transaction on connection "{}", but '
'it already had one open!'.format(connection.name)) "it already had one open!".format(connection.name)
)
self.add_begin_query() self.add_begin_query()
@@ -158,9 +151,10 @@ class SQLConnectionManager(BaseConnectionManager):
if connection.transaction_open is False: if connection.transaction_open is False:
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
'Tried to commit transaction on connection "{}", but ' 'Tried to commit transaction on connection "{}", but '
'it does not have one open!'.format(connection.name)) "it does not have one open!".format(connection.name)
)
logger.debug('On {}: COMMIT'.format(connection.name)) fire_event(SQLCommit(conn_name=connection.name))
self.add_commit_query() self.add_commit_query()
connection.transaction_open = False connection.transaction_open = False

View File

@@ -5,26 +5,29 @@ import dbt.clients.agate_helper
from dbt.contracts.connection import Connection from dbt.contracts.connection import Connection
import dbt.exceptions import dbt.exceptions
from dbt.adapters.base import BaseAdapter, available from dbt.adapters.base import BaseAdapter, available
from dbt.adapters.cache import _make_key
from dbt.adapters.sql import SQLConnectionManager from dbt.adapters.sql import SQLConnectionManager
from dbt.logger import GLOBAL_LOGGER as logger from dbt.events.functions import fire_event
from dbt.events.types import ColTypeChange, SchemaCreation, SchemaDrop
from dbt.adapters.base.relation import BaseRelation from dbt.adapters.base.relation import BaseRelation
LIST_RELATIONS_MACRO_NAME = 'list_relations_without_caching' LIST_RELATIONS_MACRO_NAME = "list_relations_without_caching"
GET_COLUMNS_IN_RELATION_MACRO_NAME = 'get_columns_in_relation' GET_COLUMNS_IN_RELATION_MACRO_NAME = "get_columns_in_relation"
LIST_SCHEMAS_MACRO_NAME = 'list_schemas' LIST_SCHEMAS_MACRO_NAME = "list_schemas"
CHECK_SCHEMA_EXISTS_MACRO_NAME = 'check_schema_exists' CHECK_SCHEMA_EXISTS_MACRO_NAME = "check_schema_exists"
CREATE_SCHEMA_MACRO_NAME = 'create_schema' CREATE_SCHEMA_MACRO_NAME = "create_schema"
DROP_SCHEMA_MACRO_NAME = 'drop_schema' DROP_SCHEMA_MACRO_NAME = "drop_schema"
RENAME_RELATION_MACRO_NAME = 'rename_relation' RENAME_RELATION_MACRO_NAME = "rename_relation"
TRUNCATE_RELATION_MACRO_NAME = 'truncate_relation' TRUNCATE_RELATION_MACRO_NAME = "truncate_relation"
DROP_RELATION_MACRO_NAME = 'drop_relation' DROP_RELATION_MACRO_NAME = "drop_relation"
ALTER_COLUMN_TYPE_MACRO_NAME = 'alter_column_type' ALTER_COLUMN_TYPE_MACRO_NAME = "alter_column_type"
class SQLAdapter(BaseAdapter): class SQLAdapter(BaseAdapter):
"""The default adapter with the common agate conversions and some SQL """The default adapter with the common agate conversions and some SQL
methods implemented. This adapter has a different much shorter list of methods was implemented. This adapter has a different much shorter list of
methods to implement, but some more macros that must be implemented. methods to implement, but some more macros that must be implemented.
To implement a macro, implement "${adapter_type}__${macro_name}". in the To implement a macro, implement "${adapter_type}__${macro_name}". in the
@@ -60,30 +63,24 @@ class SQLAdapter(BaseAdapter):
:param abridge_sql_log: If set, limit the raw sql logged to 512 :param abridge_sql_log: If set, limit the raw sql logged to 512
characters characters
""" """
return self.connections.add_query(sql, auto_begin, bindings, return self.connections.add_query(sql, auto_begin, bindings, abridge_sql_log)
abridge_sql_log)
@classmethod @classmethod
def convert_text_type(cls, agate_table: agate.Table, col_idx: int) -> str: def convert_text_type(cls, agate_table: agate.Table, col_idx: int) -> str:
return "text" return "text"
@classmethod @classmethod
def convert_number_type( def convert_number_type(cls, agate_table: agate.Table, col_idx: int) -> str:
cls, agate_table: agate.Table, col_idx: int # TODO CT-211
) -> str: decimals = agate_table.aggregate(agate.MaxPrecision(col_idx)) # type: ignore[attr-defined]
decimals = agate_table.aggregate(agate.MaxPrecision(col_idx))
return "float8" if decimals else "integer" return "float8" if decimals else "integer"
@classmethod @classmethod
def convert_boolean_type( def convert_boolean_type(cls, agate_table: agate.Table, col_idx: int) -> str:
cls, agate_table: agate.Table, col_idx: int
) -> str:
return "boolean" return "boolean"
@classmethod @classmethod
def convert_datetime_type( def convert_datetime_type(cls, agate_table: agate.Table, col_idx: int) -> str:
cls, agate_table: agate.Table, col_idx: int
) -> str:
return "timestamp without time zone" return "timestamp without time zone"
@classmethod @classmethod
@@ -99,31 +96,27 @@ class SQLAdapter(BaseAdapter):
return True return True
def expand_column_types(self, goal, current): def expand_column_types(self, goal, current):
reference_columns = { reference_columns = {c.name: c for c in self.get_columns_in_relation(goal)}
c.name: c for c in
self.get_columns_in_relation(goal)
}
target_columns = { target_columns = {c.name: c for c in self.get_columns_in_relation(current)}
c.name: c for c
in self.get_columns_in_relation(current)
}
for column_name, reference_column in reference_columns.items(): for column_name, reference_column in reference_columns.items():
target_column = target_columns.get(column_name) target_column = target_columns.get(column_name)
if target_column is not None and \ if target_column is not None and target_column.can_expand_to(reference_column):
target_column.can_expand_to(reference_column):
col_string_size = reference_column.string_size() col_string_size = reference_column.string_size()
new_type = self.Column.string_type(col_string_size) new_type = self.Column.string_type(col_string_size)
logger.debug("Changing col type from {} to {} in table {}", fire_event(
target_column.data_type, new_type, current) ColTypeChange(
orig_type=target_column.data_type,
new_type=new_type,
table=_make_key(current),
)
)
self.alter_column_type(current, column_name, new_type) self.alter_column_type(current, column_name, new_type)
def alter_column_type( def alter_column_type(self, relation, column_name, new_column_type) -> None:
self, relation, column_name, new_column_type
) -> None:
""" """
1. Create a new column (w/ temp name and correct type) 1. Create a new column (w/ temp name and correct type)
2. Copy data over to it 2. Copy data over to it
@@ -131,53 +124,40 @@ class SQLAdapter(BaseAdapter):
4. Rename the new column to existing column 4. Rename the new column to existing column
""" """
kwargs = { kwargs = {
'relation': relation, "relation": relation,
'column_name': column_name, "column_name": column_name,
'new_column_type': new_column_type, "new_column_type": new_column_type,
} }
self.execute_macro( self.execute_macro(ALTER_COLUMN_TYPE_MACRO_NAME, kwargs=kwargs)
ALTER_COLUMN_TYPE_MACRO_NAME,
kwargs=kwargs
)
def drop_relation(self, relation): def drop_relation(self, relation):
if relation.type is None: if relation.type is None:
dbt.exceptions.raise_compiler_error( dbt.exceptions.raise_compiler_error(
'Tried to drop relation {}, but its type is null.' "Tried to drop relation {}, but its type is null.".format(relation)
.format(relation)) )
self.cache_dropped(relation) self.cache_dropped(relation)
self.execute_macro( self.execute_macro(DROP_RELATION_MACRO_NAME, kwargs={"relation": relation})
DROP_RELATION_MACRO_NAME,
kwargs={'relation': relation}
)
def truncate_relation(self, relation): def truncate_relation(self, relation):
self.execute_macro( self.execute_macro(TRUNCATE_RELATION_MACRO_NAME, kwargs={"relation": relation})
TRUNCATE_RELATION_MACRO_NAME,
kwargs={'relation': relation}
)
def rename_relation(self, from_relation, to_relation): def rename_relation(self, from_relation, to_relation):
self.cache_renamed(from_relation, to_relation) self.cache_renamed(from_relation, to_relation)
kwargs = {'from_relation': from_relation, 'to_relation': to_relation} kwargs = {"from_relation": from_relation, "to_relation": to_relation}
self.execute_macro( self.execute_macro(RENAME_RELATION_MACRO_NAME, kwargs=kwargs)
RENAME_RELATION_MACRO_NAME,
kwargs=kwargs
)
def get_columns_in_relation(self, relation): def get_columns_in_relation(self, relation):
return self.execute_macro( return self.execute_macro(
GET_COLUMNS_IN_RELATION_MACRO_NAME, GET_COLUMNS_IN_RELATION_MACRO_NAME, kwargs={"relation": relation}
kwargs={'relation': relation}
) )
def create_schema(self, relation: BaseRelation) -> None: def create_schema(self, relation: BaseRelation) -> None:
relation = relation.without_identifier() relation = relation.without_identifier()
logger.debug('Creating schema "{}"', relation) fire_event(SchemaCreation(relation=_make_key(relation)))
kwargs = { kwargs = {
'relation': relation, "relation": relation,
} }
self.execute_macro(CREATE_SCHEMA_MACRO_NAME, kwargs=kwargs) self.execute_macro(CREATE_SCHEMA_MACRO_NAME, kwargs=kwargs)
self.commit_if_has_connection() self.commit_if_has_connection()
@@ -186,51 +166,44 @@ class SQLAdapter(BaseAdapter):
def drop_schema(self, relation: BaseRelation) -> None: def drop_schema(self, relation: BaseRelation) -> None:
relation = relation.without_identifier() relation = relation.without_identifier()
logger.debug('Dropping schema "{}".', relation) fire_event(SchemaDrop(relation=_make_key(relation)))
kwargs = { kwargs = {
'relation': relation, "relation": relation,
} }
self.execute_macro(DROP_SCHEMA_MACRO_NAME, kwargs=kwargs) self.execute_macro(DROP_SCHEMA_MACRO_NAME, kwargs=kwargs)
# we can update the cache here # we can update the cache here
self.cache.drop_schema(relation.database, relation.schema) self.cache.drop_schema(relation.database, relation.schema)
def list_relations_without_caching( def list_relations_without_caching(
self, schema_relation: BaseRelation, self,
schema_relation: BaseRelation,
) -> List[BaseRelation]: ) -> List[BaseRelation]:
kwargs = {'schema_relation': schema_relation} kwargs = {"schema_relation": schema_relation}
results = self.execute_macro( results = self.execute_macro(LIST_RELATIONS_MACRO_NAME, kwargs=kwargs)
LIST_RELATIONS_MACRO_NAME,
kwargs=kwargs
)
relations = [] relations = []
quote_policy = { quote_policy = {"database": True, "schema": True, "identifier": True}
'database': True,
'schema': True,
'identifier': True
}
for _database, name, _schema, _type in results: for _database, name, _schema, _type in results:
try: try:
_type = self.Relation.get_relation_type(_type) _type = self.Relation.get_relation_type(_type)
except ValueError: except ValueError:
_type = self.Relation.External _type = self.Relation.External
relations.append(self.Relation.create( relations.append(
self.Relation.create(
database=_database, database=_database,
schema=_schema, schema=_schema,
identifier=name, identifier=name,
quote_policy=quote_policy, quote_policy=quote_policy,
type=_type type=_type,
)) )
)
return relations return relations
def quote(self, identifier): def quote(self, identifier):
return '"{}"'.format(identifier) return '"{}"'.format(identifier)
def list_schemas(self, database: str) -> List[str]: def list_schemas(self, database: str) -> List[str]:
results = self.execute_macro( results = self.execute_macro(LIST_SCHEMAS_MACRO_NAME, kwargs={"database": database})
LIST_SCHEMAS_MACRO_NAME,
kwargs={'database': database}
)
return [row[0] for row in results] return [row[0] for row in results]
@@ -238,13 +211,10 @@ class SQLAdapter(BaseAdapter):
information_schema = self.Relation.create( information_schema = self.Relation.create(
database=database, database=database,
schema=schema, schema=schema,
identifier='INFORMATION_SCHEMA', identifier="INFORMATION_SCHEMA",
quote_policy=self.config.quoting quote_policy=self.config.quoting,
).information_schema() ).information_schema()
kwargs = {'information_schema': information_schema, 'schema': schema} kwargs = {"information_schema": information_schema, "schema": schema}
results = self.execute_macro( results = self.execute_macro(CHECK_SCHEMA_EXISTS_MACRO_NAME, kwargs=kwargs)
CHECK_SCHEMA_EXISTS_MACRO_NAME,
kwargs=kwargs
)
return results[0][0] > 0 return results[0][0] > 0

View File

@@ -0,0 +1 @@
# Clients README

View File

@@ -10,79 +10,83 @@ def regex(pat):
class BlockData: class BlockData:
"""raw plaintext data from the top level of the file.""" """raw plaintext data from the top level of the file."""
def __init__(self, contents): def __init__(self, contents):
self.block_type_name = '__dbt__data' self.block_type_name = "__dbt__data"
self.contents = contents self.contents = contents
self.full_block = contents self.full_block = contents
class BlockTag: class BlockTag:
def __init__(self, block_type_name, block_name, contents=None, def __init__(self, block_type_name, block_name, contents=None, full_block=None, **kw):
full_block=None, **kw):
self.block_type_name = block_type_name self.block_type_name = block_type_name
self.block_name = block_name self.block_name = block_name
self.contents = contents self.contents = contents
self.full_block = full_block self.full_block = full_block
def __str__(self): def __str__(self):
return 'BlockTag({!r}, {!r})'.format(self.block_type_name, return "BlockTag({!r}, {!r})".format(self.block_type_name, self.block_name)
self.block_name)
def __repr__(self): def __repr__(self):
return str(self) return str(self)
@property @property
def end_block_type_name(self): def end_block_type_name(self):
return 'end{}'.format(self.block_type_name) return "end{}".format(self.block_type_name)
def end_pat(self): def end_pat(self):
# we don't want to use string formatting here because jinja uses most # we don't want to use string formatting here because jinja uses most
# of the string formatting operators in its syntax... # of the string formatting operators in its syntax...
pattern = ''.join(( pattern = "".join(
r'(?P<endblock>((?:\s*\{\%\-|\{\%)\s*', (
r"(?P<endblock>((?:\s*\{\%\-|\{\%)\s*",
self.end_block_type_name, self.end_block_type_name,
r'\s*(?:\-\%\}\s*|\%\})))', r"\s*(?:\-\%\}\s*|\%\})))",
)) )
)
return regex(pattern) return regex(pattern)
Tag = namedtuple('Tag', 'block_type_name block_name start end') Tag = namedtuple("Tag", "block_type_name block_name start end")
_NAME_PATTERN = r'[A-Za-z_][A-Za-z_0-9]*' _NAME_PATTERN = r"[A-Za-z_][A-Za-z_0-9]*"
COMMENT_START_PATTERN = regex(r'(?:(?P<comment_start>(\s*\{\#)))') COMMENT_START_PATTERN = regex(r"(?:(?P<comment_start>(\s*\{\#)))")
COMMENT_END_PATTERN = regex(r'(.*?)(\s*\#\})') COMMENT_END_PATTERN = regex(r"(.*?)(\s*\#\})")
RAW_START_PATTERN = regex( RAW_START_PATTERN = regex(r"(?:\s*\{\%\-|\{\%)\s*(?P<raw_start>(raw))\s*(?:\-\%\}\s*|\%\})")
r'(?:\s*\{\%\-|\{\%)\s*(?P<raw_start>(raw))\s*(?:\-\%\}\s*|\%\})' EXPR_START_PATTERN = regex(r"(?P<expr_start>(\{\{\s*))")
) EXPR_END_PATTERN = regex(r"(?P<expr_end>(\s*\}\}))")
EXPR_START_PATTERN = regex(r'(?P<expr_start>(\{\{\s*))')
EXPR_END_PATTERN = regex(r'(?P<expr_end>(\s*\}\}))')
BLOCK_START_PATTERN = regex(''.join(( BLOCK_START_PATTERN = regex(
r'(?:\s*\{\%\-|\{\%)\s*', "".join(
r'(?P<block_type_name>({}))'.format(_NAME_PATTERN), (
r"(?:\s*\{\%\-|\{\%)\s*",
r"(?P<block_type_name>({}))".format(_NAME_PATTERN),
# some blocks have a 'block name'. # some blocks have a 'block name'.
r'(?:\s+(?P<block_name>({})))?'.format(_NAME_PATTERN), r"(?:\s+(?P<block_name>({})))?".format(_NAME_PATTERN),
))) )
)
)
RAW_BLOCK_PATTERN = regex(''.join(( RAW_BLOCK_PATTERN = regex(
r'(?:\s*\{\%\-|\{\%)\s*raw\s*(?:\-\%\}\s*|\%\})', "".join(
r'(?:.*?)', (
r'(?:\s*\{\%\-|\{\%)\s*endraw\s*(?:\-\%\}\s*|\%\})', r"(?:\s*\{\%\-|\{\%)\s*raw\s*(?:\-\%\}\s*|\%\})",
))) r"(?:.*?)",
r"(?:\s*\{\%\-|\{\%)\s*endraw\s*(?:\-\%\}\s*|\%\})",
)
)
)
TAG_CLOSE_PATTERN = regex(r'(?:(?P<tag_close>(\-\%\}\s*|\%\})))') TAG_CLOSE_PATTERN = regex(r"(?:(?P<tag_close>(\-\%\}\s*|\%\})))")
# stolen from jinja's lexer. Note that we've consumed all prefix whitespace by # stolen from jinja's lexer. Note that we've consumed all prefix whitespace by
# the time we want to use this. # the time we want to use this.
STRING_PATTERN = regex( STRING_PATTERN = regex(r"(?P<string>('([^'\\]*(?:\\.[^'\\]*)*)'|" r'"([^"\\]*(?:\\.[^"\\]*)*)"))')
r"(?P<string>('([^'\\]*(?:\\.[^'\\]*)*)'|"
r'"([^"\\]*(?:\\.[^"\\]*)*)"))'
)
QUOTE_START_PATTERN = regex(r'''(?P<quote>(['"]))''') QUOTE_START_PATTERN = regex(r"""(?P<quote>(['"]))""")
class TagIterator: class TagIterator:
@@ -99,10 +103,10 @@ class TagIterator:
end_val: int = self.pos if end is None else end end_val: int = self.pos if end is None else end
data = self.data[:end_val] data = self.data[:end_val]
# if not found, rfind returns -1, and -1+1=0, which is perfect! # if not found, rfind returns -1, and -1+1=0, which is perfect!
last_line_start = data.rfind('\n') + 1 last_line_start = data.rfind("\n") + 1
# it's easy to forget this, but line numbers are 1-indexed # it's easy to forget this, but line numbers are 1-indexed
line_number = data.count('\n') + 1 line_number = data.count("\n") + 1
return f'{line_number}:{end_val - last_line_start}' return f"{line_number}:{end_val - last_line_start}"
def advance(self, new_position): def advance(self, new_position):
self.pos = new_position self.pos = new_position
@@ -120,7 +124,7 @@ class TagIterator:
matches = [] matches = []
for pattern in patterns: for pattern in patterns:
# default to 'search', but sometimes we want to 'match'. # default to 'search', but sometimes we want to 'match'.
if kwargs.get('method', 'search') == 'search': if kwargs.get("method", "search") == "search":
match = self._search(pattern) match = self._search(pattern)
else: else:
match = self._match(pattern) match = self._match(pattern)
@@ -136,7 +140,7 @@ class TagIterator:
match = self._first_match(*patterns, **kwargs) match = self._first_match(*patterns, **kwargs)
if match is None: if match is None:
msg = 'unexpected EOF, expected {}, got "{}"'.format( msg = 'unexpected EOF, expected {}, got "{}"'.format(
expected_name, self.data[self.pos:] expected_name, self.data[self.pos :]
) )
dbt.exceptions.raise_compiler_error(msg) dbt.exceptions.raise_compiler_error(msg)
return match return match
@@ -156,22 +160,20 @@ class TagIterator:
""" """
self.advance(match.end()) self.advance(match.end())
while True: while True:
match = self._expect_match('}}', match = self._expect_match("}}", EXPR_END_PATTERN, QUOTE_START_PATTERN)
EXPR_END_PATTERN, if match.groupdict().get("expr_end") is not None:
QUOTE_START_PATTERN)
if match.groupdict().get('expr_end') is not None:
break break
else: else:
# it's a quote. we haven't advanced for this match yet, so # it's a quote. we haven't advanced for this match yet, so
# just slurp up the whole string, no need to rewind. # just slurp up the whole string, no need to rewind.
match = self._expect_match('string', STRING_PATTERN) match = self._expect_match("string", STRING_PATTERN)
self.advance(match.end()) self.advance(match.end())
self.advance(match.end()) self.advance(match.end())
def handle_comment(self, match): def handle_comment(self, match):
self.advance(match.end()) self.advance(match.end())
match = self._expect_match('#}', COMMENT_END_PATTERN) match = self._expect_match("#}", COMMENT_END_PATTERN)
self.advance(match.end()) self.advance(match.end())
def _expect_block_close(self): def _expect_block_close(self):
@@ -188,22 +190,19 @@ class TagIterator:
""" """
while True: while True:
end_match = self._expect_match( end_match = self._expect_match(
'tag close ("%}")', 'tag close ("%}")', QUOTE_START_PATTERN, TAG_CLOSE_PATTERN
QUOTE_START_PATTERN,
TAG_CLOSE_PATTERN
) )
self.advance(end_match.end()) self.advance(end_match.end())
if end_match.groupdict().get('tag_close') is not None: if end_match.groupdict().get("tag_close") is not None:
return return
# must be a string. Rewind to its start and advance past it. # must be a string. Rewind to its start and advance past it.
self.rewind() self.rewind()
string_match = self._expect_match('string', STRING_PATTERN) string_match = self._expect_match("string", STRING_PATTERN)
self.advance(string_match.end()) self.advance(string_match.end())
def handle_raw(self): def handle_raw(self):
# raw blocks are super special, they are a single complete regex # raw blocks are super special, they are a single complete regex
match = self._expect_match('{% raw %}...{% endraw %}', match = self._expect_match("{% raw %}...{% endraw %}", RAW_BLOCK_PATTERN)
RAW_BLOCK_PATTERN)
self.advance(match.end()) self.advance(match.end())
return match.end() return match.end()
@@ -220,30 +219,24 @@ class TagIterator:
""" """
groups = match.groupdict() groups = match.groupdict()
# always a value # always a value
block_type_name = groups['block_type_name'] block_type_name = groups["block_type_name"]
# might be None # might be None
block_name = groups.get('block_name') block_name = groups.get("block_name")
start_pos = self.pos start_pos = self.pos
if block_type_name == 'raw': if block_type_name == "raw":
match = self._expect_match('{% raw %}...{% endraw %}', match = self._expect_match("{% raw %}...{% endraw %}", RAW_BLOCK_PATTERN)
RAW_BLOCK_PATTERN)
self.advance(match.end()) self.advance(match.end())
else: else:
self.advance(match.end()) self.advance(match.end())
self._expect_block_close() self._expect_block_close()
return Tag( return Tag(
block_type_name=block_type_name, block_type_name=block_type_name, block_name=block_name, start=start_pos, end=self.pos
block_name=block_name,
start=start_pos,
end=self.pos
) )
def find_tags(self): def find_tags(self):
while True: while True:
match = self._first_match( match = self._first_match(
BLOCK_START_PATTERN, BLOCK_START_PATTERN, COMMENT_START_PATTERN, EXPR_START_PATTERN
COMMENT_START_PATTERN,
EXPR_START_PATTERN
) )
if match is None: if match is None:
break break
@@ -252,9 +245,9 @@ class TagIterator:
# start = self.pos # start = self.pos
groups = match.groupdict() groups = match.groupdict()
comment_start = groups.get('comment_start') comment_start = groups.get("comment_start")
expr_start = groups.get('expr_start') expr_start = groups.get("expr_start")
block_type_name = groups.get('block_type_name') block_type_name = groups.get("block_type_name")
if comment_start is not None: if comment_start is not None:
self.handle_comment(match) self.handle_comment(match)
@@ -264,8 +257,8 @@ class TagIterator:
yield self.handle_tag(match) yield self.handle_tag(match)
else: else:
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
'Invalid regex match in next_block, expected block start, ' "Invalid regex match in next_block, expected block start, "
'expr start, or comment start' "expr start, or comment start"
) )
def __iter__(self): def __iter__(self):
@@ -273,21 +266,18 @@ class TagIterator:
duplicate_tags = ( duplicate_tags = (
'Got nested tags: {outer.block_type_name} (started at {outer.start}) did ' "Got nested tags: {outer.block_type_name} (started at {outer.start}) did "
'not have a matching {{% end{outer.block_type_name} %}} before a ' "not have a matching {{% end{outer.block_type_name} %}} before a "
'subsequent {inner.block_type_name} was found (started at {inner.start})' "subsequent {inner.block_type_name} was found (started at {inner.start})"
) )
_CONTROL_FLOW_TAGS = { _CONTROL_FLOW_TAGS = {
'if': 'endif', "if": "endif",
'for': 'endfor', "for": "endfor",
} }
_CONTROL_FLOW_END_TAGS = { _CONTROL_FLOW_END_TAGS = {v: k for k, v in _CONTROL_FLOW_TAGS.items()}
v: k
for k, v in _CONTROL_FLOW_TAGS.items()
}
class BlockIterator: class BlockIterator:
@@ -310,15 +300,15 @@ class BlockIterator:
def is_current_end(self, tag): def is_current_end(self, tag):
return ( return (
tag.block_type_name.startswith('end') and tag.block_type_name.startswith("end")
self.current is not None and and self.current is not None
tag.block_type_name[3:] == self.current.block_type_name and tag.block_type_name[3:] == self.current.block_type_name
) )
def find_blocks(self, allowed_blocks=None, collect_raw_data=True): def find_blocks(self, allowed_blocks=None, collect_raw_data=True):
"""Find all top-level blocks in the data.""" """Find all top-level blocks in the data."""
if allowed_blocks is None: if allowed_blocks is None:
allowed_blocks = {'snapshot', 'macro', 'materialization', 'docs'} allowed_blocks = {"snapshot", "macro", "materialization", "docs"}
for tag in self.tag_parser.find_tags(): for tag in self.tag_parser.find_tags():
if tag.block_type_name in _CONTROL_FLOW_TAGS: if tag.block_type_name in _CONTROL_FLOW_TAGS:
@@ -329,37 +319,35 @@ class BlockIterator:
found = self.stack.pop() found = self.stack.pop()
else: else:
expected = _CONTROL_FLOW_END_TAGS[tag.block_type_name] expected = _CONTROL_FLOW_END_TAGS[tag.block_type_name]
dbt.exceptions.raise_compiler_error(( dbt.exceptions.raise_compiler_error(
'Got an unexpected control flow end tag, got {} but ' (
'never saw a preceeding {} (@ {})' "Got an unexpected control flow end tag, got {} but "
).format( "never saw a preceeding {} (@ {})"
tag.block_type_name, ).format(tag.block_type_name, expected, self.tag_parser.linepos(tag.start))
expected, )
self.tag_parser.linepos(tag.start)
))
expected = _CONTROL_FLOW_TAGS[found] expected = _CONTROL_FLOW_TAGS[found]
if expected != tag.block_type_name: if expected != tag.block_type_name:
dbt.exceptions.raise_compiler_error(( dbt.exceptions.raise_compiler_error(
'Got an unexpected control flow end tag, got {} but ' (
'expected {} next (@ {})' "Got an unexpected control flow end tag, got {} but "
).format( "expected {} next (@ {})"
tag.block_type_name, ).format(tag.block_type_name, expected, self.tag_parser.linepos(tag.start))
expected, )
self.tag_parser.linepos(tag.start)
))
if tag.block_type_name in allowed_blocks: if tag.block_type_name in allowed_blocks:
if self.stack: if self.stack:
dbt.exceptions.raise_compiler_error(( dbt.exceptions.raise_compiler_error(
'Got a block definition inside control flow at {}. ' (
'All dbt block definitions must be at the top level' "Got a block definition inside control flow at {}. "
).format(self.tag_parser.linepos(tag.start))) "All dbt block definitions must be at the top level"
).format(self.tag_parser.linepos(tag.start))
)
if self.current is not None: if self.current is not None:
dbt.exceptions.raise_compiler_error( dbt.exceptions.raise_compiler_error(
duplicate_tags.format(outer=self.current, inner=tag) duplicate_tags.format(outer=self.current, inner=tag)
) )
if collect_raw_data: if collect_raw_data:
raw_data = self.data[self.last_position:tag.start] raw_data = self.data[self.last_position : tag.start]
self.last_position = tag.start self.last_position = tag.start
if raw_data: if raw_data:
yield BlockData(raw_data) yield BlockData(raw_data)
@@ -371,23 +359,25 @@ class BlockIterator:
yield BlockTag( yield BlockTag(
block_type_name=self.current.block_type_name, block_type_name=self.current.block_type_name,
block_name=self.current.block_name, block_name=self.current.block_name,
contents=self.data[self.current.end:tag.start], contents=self.data[self.current.end : tag.start],
full_block=self.data[self.current.start:tag.end] full_block=self.data[self.current.start : tag.end],
) )
self.current = None self.current = None
if self.current: if self.current:
linecount = self.data[:self.current.end].count('\n') + 1 linecount = self.data[: self.current.end].count("\n") + 1
dbt.exceptions.raise_compiler_error(( dbt.exceptions.raise_compiler_error(
'Reached EOF without finding a close tag for ' (
'{} (searched from line {})' "Reached EOF without finding a close tag for " "{} (searched from line {})"
).format(self.current.block_type_name, linecount)) ).format(self.current.block_type_name, linecount)
)
if collect_raw_data: if collect_raw_data:
raw_data = self.data[self.last_position:] raw_data = self.data[self.last_position :]
if raw_data: if raw_data:
yield BlockData(raw_data) yield BlockData(raw_data)
def lex_for_blocks(self, allowed_blocks=None, collect_raw_data=True): def lex_for_blocks(self, allowed_blocks=None, collect_raw_data=True):
return list(self.find_blocks(allowed_blocks=allowed_blocks, return list(
collect_raw_data=collect_raw_data)) self.find_blocks(allowed_blocks=allowed_blocks, collect_raw_data=collect_raw_data)
)

View File

@@ -10,7 +10,17 @@ from typing import Iterable, List, Dict, Union, Optional, Any
from dbt.exceptions import RuntimeException from dbt.exceptions import RuntimeException
BOM = BOM_UTF8.decode('utf-8') # '\ufeff' BOM = BOM_UTF8.decode("utf-8") # '\ufeff'
class Number(agate.data_types.Number):
# undo the change in https://github.com/wireservice/agate/pull/733
# i.e. do not cast True and False to numeric 1 and 0
def cast(self, d):
if type(d) == bool:
raise agate.exceptions.CastError("Do not cast True to 1 or False to 0.")
else:
return super().cast(d)
class ISODateTime(agate.data_types.DateTime): class ISODateTime(agate.data_types.DateTime):
@@ -30,32 +40,24 @@ class ISODateTime(agate.data_types.DateTime):
except: # noqa except: # noqa
pass pass
raise agate.exceptions.CastError( raise agate.exceptions.CastError('Can not parse value "%s" as datetime.' % d)
'Can not parse value "%s" as datetime.' % d
)
def build_type_tester( def build_type_tester(
text_columns: Iterable[str], text_columns: Iterable[str], string_null_values: Optional[Iterable[str]] = ("null", "")
string_null_values: Optional[Iterable[str]] = ('null', '')
) -> agate.TypeTester: ) -> agate.TypeTester:
types = [ types = [
agate.data_types.Number(null_values=('null', '')), Number(null_values=("null", "")),
agate.data_types.Date(null_values=('null', ''), agate.data_types.Date(null_values=("null", ""), date_format="%Y-%m-%d"),
date_format='%Y-%m-%d'), agate.data_types.DateTime(null_values=("null", ""), datetime_format="%Y-%m-%d %H:%M:%S"),
agate.data_types.DateTime(null_values=('null', ''), ISODateTime(null_values=("null", "")),
datetime_format='%Y-%m-%d %H:%M:%S'), agate.data_types.Boolean(
ISODateTime(null_values=('null', '')), true_values=("true",), false_values=("false",), null_values=("null", "")
agate.data_types.Boolean(true_values=('true',), ),
false_values=('false',), agate.data_types.Text(null_values=string_null_values),
null_values=('null', '')),
agate.data_types.Text(null_values=string_null_values)
] ]
force = { force = {k: agate.data_types.Text(null_values=string_null_values) for k in text_columns}
k: agate.data_types.Text(null_values=string_null_values)
for k in text_columns
}
return agate.TypeTester(force=force, types=types) return agate.TypeTester(force=force, types=types)
@@ -72,16 +74,13 @@ def table_from_rows(
else: else:
# If text_only_columns are present, prevent coercing empty string or # If text_only_columns are present, prevent coercing empty string or
# literal 'null' strings to a None representation. # literal 'null' strings to a None representation.
column_types = build_type_tester( column_types = build_type_tester(text_only_columns, string_null_values=())
text_only_columns,
string_null_values=()
)
return agate.Table(rows, column_names, column_types=column_types) return agate.Table(rows, column_names, column_types=column_types)
def table_from_data(data, column_names: Iterable[str]) -> agate.Table: def table_from_data(data, column_names: Iterable[str]) -> agate.Table:
"Convert list of dictionaries into an Agate table" "Convert a list of dictionaries into an Agate table"
# The agate table is generated from a list of dicts, so the column order # The agate table is generated from a list of dicts, so the column order
# from `data` is not preserved. We can use `select` to reorder the columns # from `data` is not preserved. We can use `select` to reorder the columns
@@ -120,9 +119,7 @@ def table_from_data_flat(data, column_names: Iterable[str]) -> agate.Table:
rows.append(row) rows.append(row)
return table_from_rows( return table_from_rows(
rows=rows, rows=rows, column_names=column_names, text_only_columns=text_only_columns
column_names=column_names,
text_only_columns=text_only_columns
) )
@@ -140,7 +137,7 @@ def as_matrix(table):
def from_csv(abspath, text_columns): def from_csv(abspath, text_columns):
type_tester = build_type_tester(text_columns=text_columns) type_tester = build_type_tester(text_columns=text_columns)
with open(abspath, encoding='utf-8') as fp: with open(abspath, encoding="utf-8") as fp:
if fp.read(1) != BOM: if fp.read(1) != BOM:
fp.seek(0) fp.seek(0)
return agate.Table.from_csv(fp, column_types=type_tester) return agate.Table.from_csv(fp, column_types=type_tester)
@@ -172,8 +169,8 @@ class ColumnTypeBuilder(Dict[str, NullableAgateType]):
elif not isinstance(value, type(existing_type)): elif not isinstance(value, type(existing_type)):
# actual type mismatch! # actual type mismatch!
raise RuntimeException( raise RuntimeException(
f'Tables contain columns with the same names ({key}), ' f"Tables contain columns with the same names ({key}), "
f'but different types ({value} vs {existing_type})' f"but different types ({value} vs {existing_type})"
) )
def finalize(self) -> Dict[str, agate.data_types.DataType]: def finalize(self) -> Dict[str, agate.data_types.DataType]:
@@ -187,9 +184,7 @@ class ColumnTypeBuilder(Dict[str, NullableAgateType]):
return result return result
def _merged_column_types( def _merged_column_types(tables: List[agate.Table]) -> Dict[str, agate.data_types.DataType]:
tables: List[agate.Table]
) -> Dict[str, agate.data_types.DataType]:
# this is a lot like agate.Table.merge, but with handling for all-null # this is a lot like agate.Table.merge, but with handling for all-null
# rows being "any type". # rows being "any type".
new_columns: ColumnTypeBuilder = ColumnTypeBuilder() new_columns: ColumnTypeBuilder = ColumnTypeBuilder()
@@ -215,10 +210,7 @@ def merge_tables(tables: List[agate.Table]) -> agate.Table:
rows: List[agate.Row] = [] rows: List[agate.Row] = []
for table in tables: for table in tables:
if ( if table.column_names == column_names and table.column_types == column_types:
table.column_names == column_names and
table.column_types == column_types
):
rows.extend(table.rows) rows.extend(table.rows)
else: else:
for row in table.rows: for row in table.rows:

View File

@@ -2,8 +2,23 @@ import re
import os.path import os.path
from dbt.clients.system import run_cmd, rmdir from dbt.clients.system import run_cmd, rmdir
from dbt.logger import GLOBAL_LOGGER as logger from dbt.events.functions import fire_event
import dbt.exceptions from dbt.events.types import (
GitSparseCheckoutSubdirectory,
GitProgressCheckoutRevision,
GitProgressUpdatingExistingDependency,
GitProgressPullingNewDependency,
GitNothingToDo,
GitProgressUpdatedCheckoutRange,
GitProgressCheckedOutAt,
)
from dbt.exceptions import (
CommandResultError,
RuntimeException,
bad_package_spec,
raise_git_cloning_error,
raise_git_cloning_problem,
)
from packaging import version from packaging import version
@@ -12,14 +27,24 @@ def _is_commit(revision: str) -> bool:
return bool(re.match(r"\b[0-9a-f]{40}\b", revision)) return bool(re.match(r"\b[0-9a-f]{40}\b", revision))
def _raise_git_cloning_error(repo, revision, error):
stderr = error.stderr.decode("utf-8").strip()
if "usage: git" in stderr:
stderr = stderr.split("\nusage: git")[0]
if re.match("fatal: destination path '(.+)' already exists", stderr):
raise_git_cloning_error(error)
bad_package_spec(repo, revision, stderr)
def clone(repo, cwd, dirname=None, remove_git_dir=False, revision=None, subdirectory=None): def clone(repo, cwd, dirname=None, remove_git_dir=False, revision=None, subdirectory=None):
has_revision = revision is not None has_revision = revision is not None
is_commit = _is_commit(revision or "") is_commit = _is_commit(revision or "")
clone_cmd = ['git', 'clone', '--depth', '1'] clone_cmd = ["git", "clone", "--depth", "1"]
if subdirectory: if subdirectory:
logger.debug(' Subdirectory specified: {}, using sparse checkout.'.format(subdirectory)) fire_event(GitSparseCheckoutSubdirectory(subdir=subdirectory))
out, _ = run_cmd(cwd, ['git', '--version'], env={'LC_ALL': 'C'}) out, _ = run_cmd(cwd, ["git", "--version"], env={"LC_ALL": "C"})
git_version = version.parse(re.search(r"\d+\.\d+\.\d+", out.decode("utf-8")).group(0)) git_version = version.parse(re.search(r"\d+\.\d+\.\d+", out.decode("utf-8")).group(0))
if not git_version >= version.parse("2.25.0"): if not git_version >= version.parse("2.25.0"):
# 2.25.0 introduces --sparse # 2.25.0 introduces --sparse
@@ -27,78 +52,86 @@ def clone(repo, cwd, dirname=None, remove_git_dir=False, revision=None, subdirec
"Please update your git version to pull a dbt package " "Please update your git version to pull a dbt package "
"from a subdirectory: your version is {}, >= 2.25.0 needed".format(git_version) "from a subdirectory: your version is {}, >= 2.25.0 needed".format(git_version)
) )
clone_cmd.extend(['--filter=blob:none', '--sparse']) clone_cmd.extend(["--filter=blob:none", "--sparse"])
if has_revision and not is_commit: if has_revision and not is_commit:
clone_cmd.extend(['--branch', revision]) clone_cmd.extend(["--branch", revision])
clone_cmd.append(repo) clone_cmd.append(repo)
if dirname is not None: if dirname is not None:
clone_cmd.append(dirname) clone_cmd.append(dirname)
result = run_cmd(cwd, clone_cmd, env={'LC_ALL': 'C'}) try:
result = run_cmd(cwd, clone_cmd, env={"LC_ALL": "C"})
except CommandResultError as exc:
_raise_git_cloning_error(repo, revision, exc)
if subdirectory: if subdirectory:
run_cmd(os.path.join(cwd, dirname or ''), ['git', 'sparse-checkout', 'set', subdirectory]) cwd_subdir = os.path.join(cwd, dirname or "")
clone_cmd_subdir = ["git", "sparse-checkout", "set", subdirectory]
try:
run_cmd(cwd_subdir, clone_cmd_subdir)
except CommandResultError as exc:
_raise_git_cloning_error(repo, revision, exc)
if remove_git_dir: if remove_git_dir:
rmdir(os.path.join(dirname, '.git')) rmdir(os.path.join(dirname, ".git"))
return result return result
def list_tags(cwd): def list_tags(cwd):
out, err = run_cmd(cwd, ['git', 'tag', '--list'], env={'LC_ALL': 'C'}) out, err = run_cmd(cwd, ["git", "tag", "--list"], env={"LC_ALL": "C"})
tags = out.decode('utf-8').strip().split("\n") tags = out.decode("utf-8").strip().split("\n")
return tags return tags
def _checkout(cwd, repo, revision): def _checkout(cwd, repo, revision):
logger.debug(' Checking out revision {}.'.format(revision)) fire_event(GitProgressCheckoutRevision(revision=revision))
fetch_cmd = ["git", "fetch", "origin", "--depth", "1"] fetch_cmd = ["git", "fetch", "origin", "--depth", "1"]
if _is_commit(revision): if _is_commit(revision):
run_cmd(cwd, fetch_cmd + [revision]) run_cmd(cwd, fetch_cmd + [revision])
else: else:
run_cmd(cwd, ['git', 'remote', 'set-branches', 'origin', revision]) run_cmd(cwd, ["git", "remote", "set-branches", "origin", revision])
run_cmd(cwd, fetch_cmd + ["--tags", revision]) run_cmd(cwd, fetch_cmd + ["--tags", revision])
if _is_commit(revision): if _is_commit(revision):
spec = revision spec = revision
# Prefer tags to branches if one exists # Prefer tags to branches if one exists
elif revision in list_tags(cwd): elif revision in list_tags(cwd):
spec = 'tags/{}'.format(revision) spec = "tags/{}".format(revision)
else: else:
spec = 'origin/{}'.format(revision) spec = "origin/{}".format(revision)
out, err = run_cmd(cwd, ['git', 'reset', '--hard', spec], out, err = run_cmd(cwd, ["git", "reset", "--hard", spec], env={"LC_ALL": "C"})
env={'LC_ALL': 'C'})
return out, err return out, err
def checkout(cwd, repo, revision=None): def checkout(cwd, repo, revision=None):
if revision is None: if revision is None:
revision = 'HEAD' revision = "HEAD"
try: try:
return _checkout(cwd, repo, revision) return _checkout(cwd, repo, revision)
except dbt.exceptions.CommandResultError as exc: except CommandResultError as exc:
stderr = exc.stderr.decode('utf-8').strip() stderr = exc.stderr.decode("utf-8").strip()
dbt.exceptions.bad_package_spec(repo, revision, stderr) bad_package_spec(repo, revision, stderr)
def get_current_sha(cwd): def get_current_sha(cwd):
out, err = run_cmd(cwd, ['git', 'rev-parse', 'HEAD'], env={'LC_ALL': 'C'}) out, err = run_cmd(cwd, ["git", "rev-parse", "HEAD"], env={"LC_ALL": "C"})
return out.decode('utf-8') return out.decode("utf-8")
def remove_remote(cwd): def remove_remote(cwd):
return run_cmd(cwd, ['git', 'remote', 'rm', 'origin'], env={'LC_ALL': 'C'}) return run_cmd(cwd, ["git", "remote", "rm", "origin"], env={"LC_ALL": "C"})
def clone_and_checkout(repo, cwd, dirname=None, remove_git_dir=False, def clone_and_checkout(
revision=None, subdirectory=None): repo, cwd, dirname=None, remove_git_dir=False, revision=None, subdirectory=None
):
exists = None exists = None
try: try:
_, err = clone( _, err = clone(
@@ -108,35 +141,34 @@ def clone_and_checkout(repo, cwd, dirname=None, remove_git_dir=False,
remove_git_dir=remove_git_dir, remove_git_dir=remove_git_dir,
subdirectory=subdirectory, subdirectory=subdirectory,
) )
except dbt.exceptions.CommandResultError as exc: except CommandResultError as exc:
err = exc.stderr.decode('utf-8') err = exc.stderr.decode("utf-8")
exists = re.match("fatal: destination path '(.+)' already exists", err) exists = re.match("fatal: destination path '(.+)' already exists", err)
if not exists: # something else is wrong, raise it if not exists:
raise raise_git_cloning_problem(repo)
directory = None directory = None
start_sha = None start_sha = None
if exists: if exists:
directory = exists.group(1) directory = exists.group(1)
logger.debug('Updating existing dependency {}.', directory) fire_event(GitProgressUpdatingExistingDependency(dir=directory))
else: else:
matches = re.match("Cloning into '(.+)'", err.decode('utf-8')) matches = re.match("Cloning into '(.+)'", err.decode("utf-8"))
if matches is None: if matches is None:
raise dbt.exceptions.RuntimeException( raise RuntimeException(f'Error cloning {repo} - never saw "Cloning into ..." from git')
f'Error cloning {repo} - never saw "Cloning into ..." from git'
)
directory = matches.group(1) directory = matches.group(1)
logger.debug('Pulling new dependency {}.', directory) fire_event(GitProgressPullingNewDependency(dir=directory))
full_path = os.path.join(cwd, directory) full_path = os.path.join(cwd, directory)
start_sha = get_current_sha(full_path) start_sha = get_current_sha(full_path)
checkout(full_path, repo, revision) checkout(full_path, repo, revision)
end_sha = get_current_sha(full_path) end_sha = get_current_sha(full_path)
if exists: if exists:
if start_sha == end_sha: if start_sha == end_sha:
logger.debug(' Already at {}, nothing to do.', start_sha[:7]) fire_event(GitNothingToDo(sha=start_sha[:7]))
else: else:
logger.debug(' Updated checkout from {} to {}.', fire_event(
start_sha[:7], end_sha[:7]) GitProgressUpdatedCheckoutRange(start_sha=start_sha[:7], end_sha=end_sha[:7])
)
else: else:
logger.debug(' Checked out at {}.', end_sha[:7]) fire_event(GitProgressCheckedOutAt(end_sha=end_sha[:7]))
return os.path.join(directory, subdirectory or '') return os.path.join(directory, subdirectory or "")

View File

@@ -7,10 +7,7 @@ import threading
from ast import literal_eval from ast import literal_eval
from contextlib import contextmanager from contextlib import contextmanager
from itertools import chain, islice from itertools import chain, islice
from typing import ( from typing import List, Union, Set, Optional, Dict, Any, Iterator, Type, NoReturn, Tuple, Callable
List, Union, Set, Optional, Dict, Any, Iterator, Type, NoReturn, Tuple,
Callable
)
import jinja2 import jinja2
import jinja2.ext import jinja2.ext
@@ -20,20 +17,26 @@ import jinja2.parser
import jinja2.sandbox import jinja2.sandbox
from dbt.utils import ( from dbt.utils import (
get_dbt_macro_name, get_docs_macro_name, get_materialization_macro_name, get_dbt_macro_name,
get_test_macro_name, deep_map get_docs_macro_name,
get_materialization_macro_name,
get_test_macro_name,
deep_map_render,
) )
from dbt.clients._jinja_blocks import BlockIterator, BlockData, BlockTag from dbt.clients._jinja_blocks import BlockIterator, BlockData, BlockTag
from dbt.contracts.graph.compiled import CompiledGenericTestNode from dbt.contracts.graph.compiled import CompiledGenericTestNode
from dbt.contracts.graph.parsed import ParsedGenericTestNode from dbt.contracts.graph.parsed import ParsedGenericTestNode
from dbt.exceptions import ( from dbt.exceptions import (
InternalException, raise_compiler_error, CompilationException, InternalException,
invalid_materialization_argument, MacroReturn, JinjaRenderingException, raise_compiler_error,
UndefinedMacroException CompilationException,
invalid_materialization_argument,
MacroReturn,
JinjaRenderingException,
UndefinedMacroException,
) )
from dbt import flags from dbt import flags
from dbt.logger import GLOBAL_LOGGER as logger # noqa
def _linecache_inject(source, write): def _linecache_inject(source, write):
@@ -41,27 +44,22 @@ def _linecache_inject(source, write):
# this is the only reliable way to accomplish this. Obviously, it's # this is the only reliable way to accomplish this. Obviously, it's
# really darn noisy and will fill your temporary directory # really darn noisy and will fill your temporary directory
tmp_file = tempfile.NamedTemporaryFile( tmp_file = tempfile.NamedTemporaryFile(
prefix='dbt-macro-compiled-', prefix="dbt-macro-compiled-",
suffix='.py', suffix=".py",
delete=False, delete=False,
mode='w+', mode="w+",
encoding='utf-8', encoding="utf-8",
) )
tmp_file.write(source) tmp_file.write(source)
filename = tmp_file.name filename = tmp_file.name
else: else:
# `codecs.encode` actually takes a `bytes` as the first argument if # `codecs.encode` actually takes a `bytes` as the first argument if
# the second argument is 'hex' - mypy does not know this. # the second argument is 'hex' - mypy does not know this.
rnd = codecs.encode(os.urandom(12), 'hex') # type: ignore rnd = codecs.encode(os.urandom(12), "hex") # type: ignore
filename = rnd.decode('ascii') filename = rnd.decode("ascii")
# put ourselves in the cache # put ourselves in the cache
cache_entry = ( cache_entry = (len(source), None, [line + "\n" for line in source.splitlines()], filename)
len(source),
None,
[line + '\n' for line in source.splitlines()],
filename
)
# linecache does in fact have an attribute `cache`, thanks # linecache does in fact have an attribute `cache`, thanks
linecache.cache[filename] = cache_entry # type: ignore linecache.cache[filename] = cache_entry # type: ignore
return filename return filename
@@ -74,12 +72,10 @@ class MacroFuzzParser(jinja2.parser.Parser):
# modified to fuzz macros defined in the same file. this way # modified to fuzz macros defined in the same file. this way
# dbt can understand the stack of macros being called. # dbt can understand the stack of macros being called.
# - @cmcarthur # - @cmcarthur
node.name = get_dbt_macro_name( node.name = get_dbt_macro_name(self.parse_assign_target(name_only=True).name)
self.parse_assign_target(name_only=True).name)
self.parse_signature(node) self.parse_signature(node)
node.body = self.parse_statements(('name:endmacro',), node.body = self.parse_statements(("name:endmacro",), drop_needle=True)
drop_needle=True)
return node return node
@@ -95,8 +91,8 @@ class MacroFuzzEnvironment(jinja2.sandbox.SandboxedEnvironment):
If the value is 'write', also write the files to disk. If the value is 'write', also write the files to disk.
WARNING: This can write a ton of data if you aren't careful. WARNING: This can write a ton of data if you aren't careful.
""" """
if filename == '<template>' and flags.MACRO_DEBUGGING: if filename == "<template>" and flags.MACRO_DEBUGGING:
write = flags.MACRO_DEBUGGING == 'write' write = flags.MACRO_DEBUGGING == "write"
filename = _linecache_inject(source, write) filename = _linecache_inject(source, write)
return super()._compile(source, filename) # type: ignore return super()._compile(source, filename) # type: ignore
@@ -107,7 +103,7 @@ class NativeSandboxEnvironment(MacroFuzzEnvironment):
class TextMarker(str): class TextMarker(str):
"""A special native-env marker that indicates that a value is text and is """A special native-env marker that indicates a value is text and is
not to be evaluated. Use this to prevent your numbery-strings from becoming not to be evaluated. Use this to prevent your numbery-strings from becoming
numbers! numbers!
""" """
@@ -139,7 +135,7 @@ def quoted_native_concat(nodes):
head = list(islice(nodes, 2)) head = list(islice(nodes, 2))
if not head: if not head:
return '' return ""
if len(head) == 1: if len(head) == 1:
raw = head[0] raw = head[0]
@@ -157,13 +153,9 @@ def quoted_native_concat(nodes):
except (ValueError, SyntaxError, MemoryError): except (ValueError, SyntaxError, MemoryError):
result = raw result = raw
if isinstance(raw, BoolMarker) and not isinstance(result, bool): if isinstance(raw, BoolMarker) and not isinstance(result, bool):
raise JinjaRenderingException( raise JinjaRenderingException(f"Could not convert value '{raw!s}' into type 'bool'")
f"Could not convert value '{raw!s}' into type 'bool'"
)
if isinstance(raw, NumberMarker) and not _is_number(result): if isinstance(raw, NumberMarker) and not _is_number(result):
raise JinjaRenderingException( raise JinjaRenderingException(f"Could not convert value '{raw!s}' into type 'number'")
f"Could not convert value '{raw!s}' into type 'number'"
)
return result return result
@@ -181,9 +173,7 @@ class NativeSandboxTemplate(jinja2.nativetypes.NativeTemplate): # mypy: ignore
vars = dict(*args, **kwargs) vars = dict(*args, **kwargs)
try: try:
return quoted_native_concat( return quoted_native_concat(self.root_render_func(self.new_context(vars)))
self.root_render_func(self.new_context(vars))
)
except Exception: except Exception:
return self.environment.handle_exception() return self.environment.handle_exception()
@@ -222,10 +212,10 @@ class BaseMacroGenerator:
self.context: Optional[Dict[str, Any]] = context self.context: Optional[Dict[str, Any]] = context
def get_template(self): def get_template(self):
raise NotImplementedError('get_template not implemented!') raise NotImplementedError("get_template not implemented!")
def get_name(self) -> str: def get_name(self) -> str:
raise NotImplementedError('get_name not implemented!') raise NotImplementedError("get_name not implemented!")
def get_macro(self): def get_macro(self):
name = self.get_name() name = self.get_name()
@@ -248,9 +238,7 @@ class BaseMacroGenerator:
def call_macro(self, *args, **kwargs): def call_macro(self, *args, **kwargs):
# called from __call__ methods # called from __call__ methods
if self.context is None: if self.context is None:
raise InternalException( raise InternalException("Context is still None in call_macro!")
'Context is still None in call_macro!'
)
assert self.context is not None assert self.context is not None
macro = self.get_macro() macro = self.get_macro()
@@ -277,7 +265,7 @@ class MacroStack(threading.local):
def pop(self, name): def pop(self, name):
got = self.call_stack.pop() got = self.call_stack.pop()
if got != name: if got != name:
raise InternalException(f'popped {got}, expected {name}') raise InternalException(f"popped {got}, expected {name}")
class MacroGenerator(BaseMacroGenerator): class MacroGenerator(BaseMacroGenerator):
@@ -286,7 +274,7 @@ class MacroGenerator(BaseMacroGenerator):
macro, macro,
context: Optional[Dict[str, Any]] = None, context: Optional[Dict[str, Any]] = None,
node: Optional[Any] = None, node: Optional[Any] = None,
stack: Optional[MacroStack] = None stack: Optional[MacroStack] = None,
) -> None: ) -> None:
super().__init__(context) super().__init__(context)
self.macro = macro self.macro = macro
@@ -334,9 +322,7 @@ class MacroGenerator(BaseMacroGenerator):
class QueryStringGenerator(BaseMacroGenerator): class QueryStringGenerator(BaseMacroGenerator):
def __init__( def __init__(self, template_str: str, context: Dict[str, Any]) -> None:
self, template_str: str, context: Dict[str, Any]
) -> None:
super().__init__(context) super().__init__(context)
self.template_str: str = template_str self.template_str: str = template_str
env = get_environment() env = get_environment()
@@ -346,7 +332,7 @@ class QueryStringGenerator(BaseMacroGenerator):
) )
def get_name(self) -> str: def get_name(self) -> str:
return 'query_comment_macro' return "query_comment_macro"
def get_template(self): def get_template(self):
"""Don't use the template cache, we don't have a node""" """Don't use the template cache, we don't have a node"""
@@ -357,45 +343,39 @@ class QueryStringGenerator(BaseMacroGenerator):
class MaterializationExtension(jinja2.ext.Extension): class MaterializationExtension(jinja2.ext.Extension):
tags = ['materialization'] tags = ["materialization"]
def parse(self, parser): def parse(self, parser):
node = jinja2.nodes.Macro(lineno=next(parser.stream).lineno) node = jinja2.nodes.Macro(lineno=next(parser.stream).lineno)
materialization_name = \ materialization_name = parser.parse_assign_target(name_only=True).name
parser.parse_assign_target(name_only=True).name
adapter_name = 'default' adapter_name = "default"
node.args = [] node.args = []
node.defaults = [] node.defaults = []
while parser.stream.skip_if('comma'): while parser.stream.skip_if("comma"):
target = parser.parse_assign_target(name_only=True) target = parser.parse_assign_target(name_only=True)
if target.name == 'default': if target.name == "default":
pass pass
elif target.name == 'adapter': elif target.name == "adapter":
parser.stream.expect('assign') parser.stream.expect("assign")
value = parser.parse_expression() value = parser.parse_expression()
adapter_name = value.value adapter_name = value.value
else: else:
invalid_materialization_argument( invalid_materialization_argument(materialization_name, target.name)
materialization_name, target.name
)
node.name = get_materialization_macro_name( node.name = get_materialization_macro_name(materialization_name, adapter_name)
materialization_name, adapter_name
)
node.body = parser.parse_statements(('name:endmaterialization',), node.body = parser.parse_statements(("name:endmaterialization",), drop_needle=True)
drop_needle=True)
return node return node
class DocumentationExtension(jinja2.ext.Extension): class DocumentationExtension(jinja2.ext.Extension):
tags = ['docs'] tags = ["docs"]
def parse(self, parser): def parse(self, parser):
node = jinja2.nodes.Macro(lineno=next(parser.stream).lineno) node = jinja2.nodes.Macro(lineno=next(parser.stream).lineno)
@@ -404,13 +384,12 @@ class DocumentationExtension(jinja2.ext.Extension):
node.args = [] node.args = []
node.defaults = [] node.defaults = []
node.name = get_docs_macro_name(docs_name) node.name = get_docs_macro_name(docs_name)
node.body = parser.parse_statements(('name:enddocs',), node.body = parser.parse_statements(("name:enddocs",), drop_needle=True)
drop_needle=True)
return node return node
class TestExtension(jinja2.ext.Extension): class TestExtension(jinja2.ext.Extension):
tags = ['test'] tags = ["test"]
def parse(self, parser): def parse(self, parser):
node = jinja2.nodes.Macro(lineno=next(parser.stream).lineno) node = jinja2.nodes.Macro(lineno=next(parser.stream).lineno)
@@ -418,13 +397,12 @@ class TestExtension(jinja2.ext.Extension):
parser.parse_signature(node) parser.parse_signature(node)
node.name = get_test_macro_name(test_name) node.name = get_test_macro_name(test_name)
node.body = parser.parse_statements(('name:endtest',), node.body = parser.parse_statements(("name:endtest",), drop_needle=True)
drop_needle=True)
return node return node
def _is_dunder_name(name): def _is_dunder_name(name):
return name.startswith('__') and name.endswith('__') return name.startswith("__") and name.endswith("__")
def create_undefined(node=None): def create_undefined(node=None):
@@ -445,10 +423,9 @@ def create_undefined(node=None):
return self return self
def __getattr__(self, name): def __getattr__(self, name):
if name == 'name' or _is_dunder_name(name): if name == "name" or _is_dunder_name(name):
raise AttributeError( raise AttributeError(
"'{}' object has no attribute '{}'" "'{}' object has no attribute '{}'".format(type(self).__name__, name)
.format(type(self).__name__, name)
) )
self.name = name self.name = name
@@ -459,24 +436,24 @@ def create_undefined(node=None):
return self return self
def __reduce__(self): def __reduce__(self):
raise_compiler_error(f'{self.name} is undefined', node=node) raise_compiler_error(f"{self.name} is undefined", node=node)
return Undefined return Undefined
NATIVE_FILTERS: Dict[str, Callable[[Any], Any]] = { NATIVE_FILTERS: Dict[str, Callable[[Any], Any]] = {
'as_text': TextMarker, "as_text": TextMarker,
'as_bool': BoolMarker, "as_bool": BoolMarker,
'as_native': NativeMarker, "as_native": NativeMarker,
'as_number': NumberMarker, "as_number": NumberMarker,
} }
TEXT_FILTERS: Dict[str, Callable[[Any], Any]] = { TEXT_FILTERS: Dict[str, Callable[[Any], Any]] = {
'as_text': lambda x: x, "as_text": lambda x: x,
'as_bool': lambda x: x, "as_bool": lambda x: x,
'as_native': lambda x: x, "as_native": lambda x: x,
'as_number': lambda x: x, "as_number": lambda x: x,
} }
@@ -486,15 +463,15 @@ def get_environment(
native: bool = False, native: bool = False,
) -> jinja2.Environment: ) -> jinja2.Environment:
args: Dict[str, List[Union[str, Type[jinja2.ext.Extension]]]] = { args: Dict[str, List[Union[str, Type[jinja2.ext.Extension]]]] = {
'extensions': ['jinja2.ext.do'] "extensions": ["jinja2.ext.do"]
} }
if capture_macros: if capture_macros:
args['undefined'] = create_undefined(node) args["undefined"] = create_undefined(node)
args['extensions'].append(MaterializationExtension) args["extensions"].append(MaterializationExtension)
args['extensions'].append(DocumentationExtension) args["extensions"].append(DocumentationExtension)
args['extensions'].append(TestExtension) args["extensions"].append(TestExtension)
env_cls: Type[jinja2.Environment] env_cls: Type[jinja2.Environment]
text_filter: Type text_filter: Type
@@ -557,8 +534,8 @@ def _requote_result(raw_value: str, rendered: str) -> str:
elif single_quoted: elif single_quoted:
quote_char = "'" quote_char = "'"
else: else:
quote_char = '' quote_char = ""
return f'{quote_char}{rendered}{quote_char}' return f"{quote_char}{rendered}{quote_char}"
# performance note: Local benmcharking (so take it with a big grain of salt!) # performance note: Local benmcharking (so take it with a big grain of salt!)
@@ -566,7 +543,7 @@ def _requote_result(raw_value: str, rendered: str) -> str:
# checking two separate patterns, but the standard deviation is smaller with # checking two separate patterns, but the standard deviation is smaller with
# one pattern. The time difference between the two was ~2 std deviations, which # one pattern. The time difference between the two was ~2 std deviations, which
# is small enough that I've just chosen the more readable option. # is small enough that I've just chosen the more readable option.
_HAS_RENDER_CHARS_PAT = re.compile(r'({[{%#]|[#}%]})') _HAS_RENDER_CHARS_PAT = re.compile(r"({[{%#]|[#}%]})")
def get_rendered( def get_rendered(
@@ -582,11 +559,7 @@ def get_rendered(
# If this is desirable in the native env as well, we could handle the # If this is desirable in the native env as well, we could handle the
# native=True case by passing the input string to ast.literal_eval, like # native=True case by passing the input string to ast.literal_eval, like
# the native renderer does. # the native renderer does.
if ( if not native and isinstance(string, str) and _HAS_RENDER_CHARS_PAT.search(string) is None:
not native and
isinstance(string, str) and
_HAS_RENDER_CHARS_PAT.search(string) is None
):
return string return string
template = get_template( template = get_template(
string, string,
@@ -607,7 +580,7 @@ def extract_toplevel_blocks(
allowed_blocks: Optional[Set[str]] = None, allowed_blocks: Optional[Set[str]] = None,
collect_raw_data: bool = True, collect_raw_data: bool = True,
) -> List[Union[BlockData, BlockTag]]: ) -> List[Union[BlockData, BlockTag]]:
"""Extract the top level blocks with matching block types from a jinja """Extract the top-level blocks with matching block types from a jinja
file, with some special handling for block nesting. file, with some special handling for block nesting.
:param data: The data to extract blocks from. :param data: The data to extract blocks from.
@@ -622,12 +595,11 @@ def extract_toplevel_blocks(
`collect_raw_data` is `True`) `BlockData` objects. `collect_raw_data` is `True`) `BlockData` objects.
""" """
return BlockIterator(data).lex_for_blocks( return BlockIterator(data).lex_for_blocks(
allowed_blocks=allowed_blocks, allowed_blocks=allowed_blocks, collect_raw_data=collect_raw_data
collect_raw_data=collect_raw_data
) )
GENERIC_TEST_KWARGS_NAME = '_dbt_generic_test_kwargs' GENERIC_TEST_KWARGS_NAME = "_dbt_generic_test_kwargs"
def add_rendered_test_kwargs( def add_rendered_test_kwargs(
@@ -639,27 +611,24 @@ def add_rendered_test_kwargs(
renderer, then insert that value into the given context as the special test renderer, then insert that value into the given context as the special test
keyword arguments member. keyword arguments member.
""" """
looks_like_func = r'^\s*(env_var|ref|var|source|doc)\s*\(.+\)\s*$' looks_like_func = r"^\s*(env_var|ref|var|source|doc)\s*\(.+\)\s*$"
def _convert_function( def _convert_function(value: Any, keypath: Tuple[Union[str, int], ...]) -> Any:
value: Any, keypath: Tuple[Union[str, int], ...]
) -> Any:
if isinstance(value, str): if isinstance(value, str):
if keypath == ('column_name',): if keypath == ("column_name",):
# special case: Don't render column names as native, make them # special case: Don't render column names as native, make them
# be strings # be strings
return value return value
if re.match(looks_like_func, value) is not None: if re.match(looks_like_func, value) is not None:
# curly braces to make rendering happy # curly braces to make rendering happy
value = f'{{{{ {value} }}}}' value = f"{{{{ {value} }}}}"
value = get_rendered( value = get_rendered(value, context, node, capture_macros=capture_macros, native=True)
value, context, node, capture_macros=capture_macros,
native=True
)
return value return value
kwargs = deep_map(_convert_function, node.test_metadata.kwargs) # The test_metadata.kwargs come from the test builder, and were set
# when the test node was created in _parse_generic_test.
kwargs = deep_map_render(_convert_function, node.test_metadata.kwargs)
context[GENERIC_TEST_KWARGS_NAME] = kwargs context[GENERIC_TEST_KWARGS_NAME] = kwargs

View File

@@ -8,11 +8,11 @@ def statically_extract_macro_calls(string, ctx, db_wrapper=None):
env = get_environment(None, capture_macros=True) env = get_environment(None, capture_macros=True)
parsed = env.parse(string) parsed = env.parse(string)
standard_calls = ['source', 'ref', 'config'] standard_calls = ["source", "ref", "config"]
possible_macro_calls = [] possible_macro_calls = []
for func_call in parsed.find_all(jinja2.nodes.Call): for func_call in parsed.find_all(jinja2.nodes.Call):
func_name = None func_name = None
if hasattr(func_call, 'node') and hasattr(func_call.node, 'name'): if hasattr(func_call, "node") and hasattr(func_call.node, "name"):
func_name = func_call.node.name func_name = func_call.node.name
else: else:
# func_call for dbt_utils.current_timestamp macro # func_call for dbt_utils.current_timestamp macro
@@ -30,22 +30,25 @@ def statically_extract_macro_calls(string, ctx, db_wrapper=None):
# dyn_args=None, # dyn_args=None,
# dyn_kwargs=None # dyn_kwargs=None
# ) # )
if (hasattr(func_call, 'node') and if (
hasattr(func_call.node, 'node') and hasattr(func_call, "node")
type(func_call.node.node).__name__ == 'Name' and and hasattr(func_call.node, "node")
hasattr(func_call.node, 'attr')): and type(func_call.node.node).__name__ == "Name"
and hasattr(func_call.node, "attr")
):
package_name = func_call.node.node.name package_name = func_call.node.node.name
macro_name = func_call.node.attr macro_name = func_call.node.attr
if package_name == 'adapter': if package_name == "adapter":
if macro_name == 'dispatch': if macro_name == "dispatch":
ad_macro_calls = statically_parse_adapter_dispatch( ad_macro_calls = statically_parse_adapter_dispatch(
func_call, ctx, db_wrapper) func_call, ctx, db_wrapper
)
possible_macro_calls.extend(ad_macro_calls) possible_macro_calls.extend(ad_macro_calls)
else: else:
# This skips calls such as adapter.parse_index # This skips calls such as adapter.parse_index
continue continue
else: else:
func_name = f'{package_name}.{macro_name}' func_name = f"{package_name}.{macro_name}"
else: else:
continue continue
if not func_name: if not func_name:
@@ -108,40 +111,41 @@ def statically_parse_adapter_dispatch(func_call, ctx, db_wrapper):
# keyword arguments # keyword arguments
if func_call.kwargs: if func_call.kwargs:
for kwarg in func_call.kwargs: for kwarg in func_call.kwargs:
if kwarg.key == 'macro_name': if kwarg.key == "macro_name":
# This will remain to enable static resolution # This will remain to enable static resolution
if type(kwarg.value).__name__ == 'Const': if type(kwarg.value).__name__ == "Const":
func_name = kwarg.value.value func_name = kwarg.value.value
possible_macro_calls.append(func_name) possible_macro_calls.append(func_name)
else: else:
raise_compiler_error(f"The macro_name parameter ({kwarg.value.value}) " raise_compiler_error(
"to adapter.dispatch was not a string") f"The macro_name parameter ({kwarg.value.value}) "
elif kwarg.key == 'macro_namespace': "to adapter.dispatch was not a string"
)
elif kwarg.key == "macro_namespace":
# This will remain to enable static resolution # This will remain to enable static resolution
kwarg_type = type(kwarg.value).__name__ kwarg_type = type(kwarg.value).__name__
if kwarg_type == 'Const': if kwarg_type == "Const":
macro_namespace = kwarg.value.value macro_namespace = kwarg.value.value
else: else:
raise_compiler_error("The macro_namespace parameter to adapter.dispatch " raise_compiler_error(
f"is a {kwarg_type}, not a string") "The macro_namespace parameter to adapter.dispatch "
f"is a {kwarg_type}, not a string"
)
# positional arguments # positional arguments
if packages_arg: if packages_arg:
if packages_arg_type == 'List': if packages_arg_type == "List":
# This will remain to enable static resolution # This will remain to enable static resolution
packages = [] packages = []
for item in packages_arg.items: for item in packages_arg.items:
packages.append(item.value) packages.append(item.value)
elif packages_arg_type == 'Const': elif packages_arg_type == "Const":
# This will remain to enable static resolution # This will remain to enable static resolution
macro_namespace = packages_arg.value macro_namespace = packages_arg.value
if db_wrapper: if db_wrapper:
macro = db_wrapper.dispatch( macro = db_wrapper.dispatch(func_name, macro_namespace=macro_namespace).macro
func_name, func_name = f"{macro.package_name}.{macro.name}"
macro_namespace=macro_namespace
).macro
func_name = f'{macro.package_name}.{macro.name}'
possible_macro_calls.append(func_name) possible_macro_calls.append(func_name)
else: # this is only for test/unit/test_macro_calls.py else: # this is only for test/unit/test_macro_calls.py
if macro_namespace: if macro_namespace:
@@ -149,6 +153,6 @@ def statically_parse_adapter_dispatch(func_call, ctx, db_wrapper):
else: else:
packages = [] packages = []
for package_name in packages: for package_name in packages:
possible_macro_calls.append(f'{package_name}.{func_name}') possible_macro_calls.append(f"{package_name}.{func_name}")
return possible_macro_calls return possible_macro_calls

View File

@@ -1,21 +1,22 @@
import functools import functools
import requests import requests
from dbt.events.functions import fire_event
from dbt.events.types import RegistryProgressMakingGETRequest, RegistryProgressGETResponse
from dbt.utils import memoized, _connection_exception_retry as connection_exception_retry from dbt.utils import memoized, _connection_exception_retry as connection_exception_retry
from dbt.logger import GLOBAL_LOGGER as logger
from dbt import deprecations from dbt import deprecations
import os import os
if os.getenv('DBT_PACKAGE_HUB_URL'): if os.getenv("DBT_PACKAGE_HUB_URL"):
DEFAULT_REGISTRY_BASE_URL = os.getenv('DBT_PACKAGE_HUB_URL') DEFAULT_REGISTRY_BASE_URL = os.getenv("DBT_PACKAGE_HUB_URL")
else: else:
DEFAULT_REGISTRY_BASE_URL = 'https://hub.getdbt.com/' DEFAULT_REGISTRY_BASE_URL = "https://hub.getdbt.com/"
def _get_url(url, registry_base_url=None): def _get_url(url, registry_base_url=None):
if registry_base_url is None: if registry_base_url is None:
registry_base_url = DEFAULT_REGISTRY_BASE_URL registry_base_url = DEFAULT_REGISTRY_BASE_URL
return '{}{}'.format(registry_base_url, url) return "{}{}".format(registry_base_url, url)
def _get_with_retries(path, registry_base_url=None): def _get_with_retries(path, registry_base_url=None):
@@ -25,55 +26,63 @@ def _get_with_retries(path, registry_base_url=None):
def _get(path, registry_base_url=None): def _get(path, registry_base_url=None):
url = _get_url(path, registry_base_url) url = _get_url(path, registry_base_url)
logger.debug('Making package registry request: GET {}'.format(url)) fire_event(RegistryProgressMakingGETRequest(url=url))
resp = requests.get(url, timeout=30) resp = requests.get(url, timeout=30)
logger.debug('Response from registry: GET {} {}'.format(url, fire_event(RegistryProgressGETResponse(url=url, resp_code=resp.status_code))
resp.status_code))
resp.raise_for_status() resp.raise_for_status()
# It is unexpected for the content of the response to be None so if it is, raising this error
# will cause this function to retry (if called within _get_with_retries) and hopefully get
# a response. This seems to happen when there's an issue with the Hub.
# See https://github.com/dbt-labs/dbt-core/issues/4577
if resp.json() is None:
raise requests.exceptions.ContentDecodingError(
"Request error: The response is None", response=resp
)
return resp.json() return resp.json()
def index(registry_base_url=None): def index(registry_base_url=None):
return _get_with_retries('api/v1/index.json', registry_base_url) return _get_with_retries("api/v1/index.json", registry_base_url)
index_cached = memoized(index) index_cached = memoized(index)
def packages(registry_base_url=None): def packages(registry_base_url=None):
return _get_with_retries('api/v1/packages.json', registry_base_url) return _get_with_retries("api/v1/packages.json", registry_base_url)
def package(name, registry_base_url=None): def package(name, registry_base_url=None):
response = _get_with_retries('api/v1/{}.json'.format(name), registry_base_url) response = _get_with_retries("api/v1/{}.json".format(name), registry_base_url)
# Either redirectnamespace or redirectname in the JSON response indicate a redirect # Either redirectnamespace or redirectname in the JSON response indicate a redirect
# redirectnamespace redirects based on package ownership # redirectnamespace redirects based on package ownership
# redirectname redirects based on package name # redirectname redirects based on package name
# Both can be present at the same time, or neither. Fails gracefully to old name # Both can be present at the same time, or neither. Fails gracefully to old name
if ('redirectnamespace' in response) or ('redirectname' in response): if ("redirectnamespace" in response) or ("redirectname" in response):
if ('redirectnamespace' in response) and response['redirectnamespace'] is not None: if ("redirectnamespace" in response) and response["redirectnamespace"] is not None:
use_namespace = response['redirectnamespace'] use_namespace = response["redirectnamespace"]
else: else:
use_namespace = response['namespace'] use_namespace = response["namespace"]
if ('redirectname' in response) and response['redirectname'] is not None: if ("redirectname" in response) and response["redirectname"] is not None:
use_name = response['redirectname'] use_name = response["redirectname"]
else: else:
use_name = response['name'] use_name = response["name"]
new_nwo = use_namespace + "/" + use_name new_nwo = use_namespace + "/" + use_name
deprecations.warn('package-redirect', old_name=name, new_name=new_nwo) deprecations.warn("package-redirect", old_name=name, new_name=new_nwo)
return response return response
def package_version(name, version, registry_base_url=None): def package_version(name, version, registry_base_url=None):
return _get_with_retries('api/v1/{}/{}.json'.format(name, version), registry_base_url) return _get_with_retries("api/v1/{}/{}.json".format(name, version), registry_base_url)
def get_available_versions(name): def get_available_versions(name):
response = package(name) response = package(name)
return list(response['versions']) return list(response["versions"])

View File

@@ -11,15 +11,21 @@ import sys
import tarfile import tarfile
import requests import requests
import stat import stat
from typing import ( from typing import Type, NoReturn, List, Optional, Dict, Any, Tuple, Callable, Union
Type, NoReturn, List, Optional, Dict, Any, Tuple, Callable, Union
)
from dbt.events.functions import fire_event
from dbt.events.types import (
SystemErrorRetrievingModTime,
SystemCouldNotWrite,
SystemExecutingCmd,
SystemStdOutMsg,
SystemStdErrMsg,
SystemReportReturnCode,
)
import dbt.exceptions import dbt.exceptions
from dbt.logger import GLOBAL_LOGGER as logger
from dbt.utils import _connection_exception_retry as connection_exception_retry from dbt.utils import _connection_exception_retry as connection_exception_retry
if sys.platform == 'win32': if sys.platform == "win32":
from ctypes import WinDLL, c_bool from ctypes import WinDLL, c_bool
else: else:
WinDLL = None WinDLL = None
@@ -51,38 +57,35 @@ def find_matching(
reobj = re.compile(regex, re.IGNORECASE) reobj = re.compile(regex, re.IGNORECASE)
for relative_path_to_search in relative_paths_to_search: for relative_path_to_search in relative_paths_to_search:
absolute_path_to_search = os.path.join( absolute_path_to_search = os.path.join(root_path, relative_path_to_search)
root_path, relative_path_to_search)
walk_results = os.walk(absolute_path_to_search) walk_results = os.walk(absolute_path_to_search)
for current_path, subdirectories, local_files in walk_results: for current_path, subdirectories, local_files in walk_results:
for local_file in local_files: for local_file in local_files:
absolute_path = os.path.join(current_path, local_file) absolute_path = os.path.join(current_path, local_file)
relative_path = os.path.relpath( relative_path = os.path.relpath(absolute_path, absolute_path_to_search)
absolute_path, absolute_path_to_search
)
modification_time = 0.0 modification_time = 0.0
try: try:
modification_time = os.path.getmtime(absolute_path) modification_time = os.path.getmtime(absolute_path)
except OSError: except OSError:
logger.exception( fire_event(SystemErrorRetrievingModTime(path=absolute_path))
f"Error retrieving modification time for file {absolute_path}"
)
if reobj.match(local_file): if reobj.match(local_file):
matching.append({ matching.append(
'searched_path': relative_path_to_search, {
'absolute_path': absolute_path, "searched_path": relative_path_to_search,
'relative_path': relative_path, "absolute_path": absolute_path,
'modification_time': modification_time, "relative_path": relative_path,
}) "modification_time": modification_time,
}
)
return matching return matching
def load_file_contents(path: str, strip: bool = True) -> str: def load_file_contents(path: str, strip: bool = True) -> str:
path = convert_path(path) path = convert_path(path)
with open(path, 'rb') as handle: with open(path, "rb") as handle:
to_return = handle.read().decode('utf-8') to_return = handle.read().decode("utf-8")
if strip: if strip:
to_return = to_return.strip() to_return = to_return.strip()
@@ -109,14 +112,14 @@ def make_directory(path: str) -> None:
raise e raise e
def make_file(path: str, contents: str = '', overwrite: bool = False) -> bool: def make_file(path: str, contents: str = "", overwrite: bool = False) -> bool:
""" """
Make a file at `path` assuming that the directory it resides in already Make a file at `path` assuming that the directory it resides in already
exists. The file is saved with contents `contents` exists. The file is saved with contents `contents`
""" """
if overwrite or not os.path.exists(path): if overwrite or not os.path.exists(path):
path = convert_path(path) path = convert_path(path)
with open(path, 'w') as fh: with open(path, "w") as fh:
fh.write(contents) fh.write(contents)
return True return True
@@ -128,7 +131,7 @@ def make_symlink(source: str, link_path: str) -> None:
Create a symlink at `link_path` referring to `source`. Create a symlink at `link_path` referring to `source`.
""" """
if not supports_symlinks(): if not supports_symlinks():
dbt.exceptions.system_error('create a symbolic link') dbt.exceptions.system_error("create a symbolic link")
os.symlink(source, link_path) os.symlink(source, link_path)
@@ -137,11 +140,11 @@ def supports_symlinks() -> bool:
return getattr(os, "symlink", None) is not None return getattr(os, "symlink", None) is not None
def write_file(path: str, contents: str = '') -> bool: def write_file(path: str, contents: str = "") -> bool:
path = convert_path(path) path = convert_path(path)
try: try:
make_directory(os.path.dirname(path)) make_directory(os.path.dirname(path))
with open(path, 'w', encoding='utf-8') as f: with open(path, "w", encoding="utf-8") as f:
f.write(str(contents)) f.write(str(contents))
except Exception as exc: except Exception as exc:
# note that you can't just catch FileNotFound, because sometimes # note that you can't just catch FileNotFound, because sometimes
@@ -150,21 +153,18 @@ def write_file(path: str, contents: str = '') -> bool:
# sometimes windows fails to write paths that are less than the length # sometimes windows fails to write paths that are less than the length
# limit. So on windows, suppress all errors that happen from writing # limit. So on windows, suppress all errors that happen from writing
# to disk. # to disk.
if os.name == 'nt': if os.name == "nt":
# sometimes we get a winerror of 3 which means the path was # sometimes we get a winerror of 3 which means the path was
# definitely too long, but other times we don't and it means the # definitely too long, but other times we don't and it means the
# path was just probably too long. This is probably based on the # path was just probably too long. This is probably based on the
# windows/python version. # windows/python version.
if getattr(exc, 'winerror', 0) == 3: if getattr(exc, "winerror", 0) == 3:
reason = 'Path was too long' reason = "Path was too long"
else: else:
reason = 'Path was possibly too long' reason = "Path was possibly too long"
# all our hard work and the path was still too long. Log and # all our hard work and the path was still too long. Log and
# continue. # continue.
logger.debug( fire_event(SystemCouldNotWrite(path=path, reason=reason, exc=exc))
f'Could not write to path {path}({len(path)} characters): '
f'{reason}\nexception: {exc}'
)
else: else:
raise raise
return True return True
@@ -178,9 +178,7 @@ def write_json(path: str, data: Dict[str, Any]) -> bool:
return write_file(path, json.dumps(data, cls=dbt.utils.JSONEncoder)) return write_file(path, json.dumps(data, cls=dbt.utils.JSONEncoder))
def _windows_rmdir_readonly( def _windows_rmdir_readonly(func: Callable[[str], Any], path: str, exc: Tuple[Any, OSError, Any]):
func: Callable[[str], Any], path: str, exc: Tuple[Any, OSError, Any]
):
exception_val = exc[1] exception_val = exc[1]
if exception_val.errno == errno.EACCES: if exception_val.errno == errno.EACCES:
os.chmod(path, stat.S_IWUSR) os.chmod(path, stat.S_IWUSR)
@@ -197,10 +195,7 @@ def resolve_path_from_base(path_to_resolve: str, base_path: str) -> str:
If path_to_resolve is an absolute path or a user path (~), just If path_to_resolve is an absolute path or a user path (~), just
resolve it to an absolute path and return. resolve it to an absolute path and return.
""" """
return os.path.abspath( return os.path.abspath(os.path.join(base_path, os.path.expanduser(path_to_resolve)))
os.path.join(
base_path,
os.path.expanduser(path_to_resolve)))
def rmdir(path: str) -> None: def rmdir(path: str) -> None:
@@ -210,7 +205,7 @@ def rmdir(path: str) -> None:
cloned via git) can cause rmtree to throw a PermissionError exception cloned via git) can cause rmtree to throw a PermissionError exception
""" """
path = convert_path(path) path = convert_path(path)
if sys.platform == 'win32': if sys.platform == "win32":
onerror = _windows_rmdir_readonly onerror = _windows_rmdir_readonly
else: else:
onerror = None onerror = None
@@ -229,7 +224,7 @@ def _win_prepare_path(path: str) -> str:
# letter back in. # letter back in.
# Unless it starts with '\\'. In that case, the path is a UNC mount point # Unless it starts with '\\'. In that case, the path is a UNC mount point
# and splitdrive will be fine. # and splitdrive will be fine.
if not path.startswith('\\\\') and path.startswith('\\'): if not path.startswith("\\\\") and path.startswith("\\"):
curdrive = os.path.splitdrive(os.getcwd())[0] curdrive = os.path.splitdrive(os.getcwd())[0]
path = curdrive + path path = curdrive + path
@@ -244,7 +239,7 @@ def _win_prepare_path(path: str) -> str:
def _supports_long_paths() -> bool: def _supports_long_paths() -> bool:
if sys.platform != 'win32': if sys.platform != "win32":
return True return True
# Eryk Sun says to use `WinDLL('ntdll')` instead of `windll.ntdll` because # Eryk Sun says to use `WinDLL('ntdll')` instead of `windll.ntdll` because
# of pointer caching in a comment here: # of pointer caching in a comment here:
@@ -252,11 +247,11 @@ def _supports_long_paths() -> bool:
# I don't know exaclty what he means, but I am inclined to believe him as # I don't know exaclty what he means, but I am inclined to believe him as
# he's pretty active on Python windows bugs! # he's pretty active on Python windows bugs!
try: try:
dll = WinDLL('ntdll') dll = WinDLL("ntdll")
except OSError: # I don't think this happens? you need ntdll to run python except OSError: # I don't think this happens? you need ntdll to run python
return False return False
# not all windows versions have it at all # not all windows versions have it at all
if not hasattr(dll, 'RtlAreLongPathsEnabled'): if not hasattr(dll, "RtlAreLongPathsEnabled"):
return False return False
# tell windows we want to get back a single unsigned byte (a bool). # tell windows we want to get back a single unsigned byte (a bool).
dll.RtlAreLongPathsEnabled.restype = c_bool dll.RtlAreLongPathsEnabled.restype = c_bool
@@ -276,7 +271,7 @@ def convert_path(path: str) -> str:
if _supports_long_paths(): if _supports_long_paths():
return path return path
prefix = '\\\\?\\' prefix = "\\\\?\\"
# Nothing to do # Nothing to do
if path.startswith(prefix): if path.startswith(prefix):
return path return path
@@ -307,44 +302,40 @@ def path_is_symlink(path: str) -> bool:
def open_dir_cmd() -> str: def open_dir_cmd() -> str:
# https://docs.python.org/2/library/sys.html#sys.platform # https://docs.python.org/2/library/sys.html#sys.platform
if sys.platform == 'win32': if sys.platform == "win32":
return 'start' return "start"
elif sys.platform == 'darwin': elif sys.platform == "darwin":
return 'open' return "open"
else: else:
return 'xdg-open' return "xdg-open"
def _handle_posix_cwd_error( def _handle_posix_cwd_error(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn:
exc: OSError, cwd: str, cmd: List[str]
) -> NoReturn:
if exc.errno == errno.ENOENT: if exc.errno == errno.ENOENT:
message = 'Directory does not exist' message = "Directory does not exist"
elif exc.errno == errno.EACCES: elif exc.errno == errno.EACCES:
message = 'Current user cannot access directory, check permissions' message = "Current user cannot access directory, check permissions"
elif exc.errno == errno.ENOTDIR: elif exc.errno == errno.ENOTDIR:
message = 'Not a directory' message = "Not a directory"
else: else:
message = 'Unknown OSError: {} - cwd'.format(str(exc)) message = "Unknown OSError: {} - cwd".format(str(exc))
raise dbt.exceptions.WorkingDirectoryError(cwd, cmd, message) raise dbt.exceptions.WorkingDirectoryError(cwd, cmd, message)
def _handle_posix_cmd_error( def _handle_posix_cmd_error(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn:
exc: OSError, cwd: str, cmd: List[str]
) -> NoReturn:
if exc.errno == errno.ENOENT: if exc.errno == errno.ENOENT:
message = "Could not find command, ensure it is in the user's PATH" message = "Could not find command, ensure it is in the user's PATH"
elif exc.errno == errno.EACCES: elif exc.errno == errno.EACCES:
message = 'User does not have permissions for this command' message = "User does not have permissions for this command"
else: else:
message = 'Unknown OSError: {} - cmd'.format(str(exc)) message = "Unknown OSError: {} - cmd".format(str(exc))
raise dbt.exceptions.ExecutableError(cwd, cmd, message) raise dbt.exceptions.ExecutableError(cwd, cmd, message)
def _handle_posix_error(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn: def _handle_posix_error(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn:
"""OSError handling for posix systems. """OSError handling for POSIX systems.
Some things that could happen to trigger an OSError: Some things that could happen to trigger an OSError:
- cwd could not exist - cwd could not exist
@@ -364,7 +355,7 @@ def _handle_posix_error(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn:
- exc.errno == EACCES - exc.errno == EACCES
- exc.filename == None(?) - exc.filename == None(?)
""" """
if getattr(exc, 'filename', None) == cwd: if getattr(exc, "filename", None) == cwd:
_handle_posix_cwd_error(exc, cwd, cmd) _handle_posix_cwd_error(exc, cwd, cmd)
else: else:
_handle_posix_cmd_error(exc, cwd, cmd) _handle_posix_cmd_error(exc, cwd, cmd)
@@ -373,46 +364,46 @@ def _handle_posix_error(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn:
def _handle_windows_error(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn: def _handle_windows_error(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn:
cls: Type[dbt.exceptions.Exception] = dbt.exceptions.CommandError cls: Type[dbt.exceptions.Exception] = dbt.exceptions.CommandError
if exc.errno == errno.ENOENT: if exc.errno == errno.ENOENT:
message = ("Could not find command, ensure it is in the user's PATH " message = (
"and that the user has permissions to run it") "Could not find command, ensure it is in the user's PATH "
"and that the user has permissions to run it"
)
cls = dbt.exceptions.ExecutableError cls = dbt.exceptions.ExecutableError
elif exc.errno == errno.ENOEXEC: elif exc.errno == errno.ENOEXEC:
message = ('Command was not executable, ensure it is valid') message = "Command was not executable, ensure it is valid"
cls = dbt.exceptions.ExecutableError cls = dbt.exceptions.ExecutableError
elif exc.errno == errno.ENOTDIR: elif exc.errno == errno.ENOTDIR:
message = ('Unable to cd: path does not exist, user does not have' message = (
' permissions, or not a directory') "Unable to cd: path does not exist, user does not have"
" permissions, or not a directory"
)
cls = dbt.exceptions.WorkingDirectoryError cls = dbt.exceptions.WorkingDirectoryError
else: else:
message = 'Unknown error: {} (errno={}: "{}")'.format( message = 'Unknown error: {} (errno={}: "{}")'.format(
str(exc), exc.errno, errno.errorcode.get(exc.errno, '<Unknown!>') str(exc), exc.errno, errno.errorcode.get(exc.errno, "<Unknown!>")
) )
raise cls(cwd, cmd, message) raise cls(cwd, cmd, message)
def _interpret_oserror(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn: def _interpret_oserror(exc: OSError, cwd: str, cmd: List[str]) -> NoReturn:
"""Interpret an OSError exc and raise the appropriate dbt exception. """Interpret an OSError exception and raise the appropriate dbt exception."""
"""
if len(cmd) == 0: if len(cmd) == 0:
raise dbt.exceptions.CommandError(cwd, cmd) raise dbt.exceptions.CommandError(cwd, cmd)
# all of these functions raise unconditionally # all of these functions raise unconditionally
if os.name == 'nt': if os.name == "nt":
_handle_windows_error(exc, cwd, cmd) _handle_windows_error(exc, cwd, cmd)
else: else:
_handle_posix_error(exc, cwd, cmd) _handle_posix_error(exc, cwd, cmd)
# this should not be reachable, raise _something_ at least! # this should not be reachable, raise _something_ at least!
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
'Unhandled exception in _interpret_oserror: {}'.format(exc) "Unhandled exception in _interpret_oserror: {}".format(exc)
) )
def run_cmd( def run_cmd(cwd: str, cmd: List[str], env: Optional[Dict[str, Any]] = None) -> Tuple[bytes, bytes]:
cwd: str, cmd: List[str], env: Optional[Dict[str, Any]] = None fire_event(SystemExecutingCmd(cmd=cmd))
) -> Tuple[bytes, bytes]:
logger.debug('Executing "{}"'.format(' '.join(cmd)))
if len(cmd) == 0: if len(cmd) == 0:
raise dbt.exceptions.CommandError(cwd, cmd) raise dbt.exceptions.CommandError(cwd, cmd)
@@ -428,23 +419,19 @@ def run_cmd(
if exe_pth: if exe_pth:
cmd = [os.path.abspath(exe_pth)] + list(cmd[1:]) cmd = [os.path.abspath(exe_pth)] + list(cmd[1:])
proc = subprocess.Popen( proc = subprocess.Popen(
cmd, cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=full_env
cwd=cwd, )
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=full_env)
out, err = proc.communicate() out, err = proc.communicate()
except OSError as exc: except OSError as exc:
_interpret_oserror(exc, cwd, cmd) _interpret_oserror(exc, cwd, cmd)
logger.debug('STDOUT: "{!s}"'.format(out)) fire_event(SystemStdOutMsg(bmsg=out))
logger.debug('STDERR: "{!s}"'.format(err)) fire_event(SystemStdErrMsg(bmsg=err))
if proc.returncode != 0: if proc.returncode != 0:
logger.debug('command return code={}'.format(proc.returncode)) fire_event(SystemReportReturnCode(returncode=proc.returncode))
raise dbt.exceptions.CommandResultError(cwd, cmd, proc.returncode, raise dbt.exceptions.CommandResultError(cwd, cmd, proc.returncode, out, err)
out, err)
return out, err return out, err
@@ -456,13 +443,11 @@ def download_with_retries(
connection_exception_retry(download_fn, 5) connection_exception_retry(download_fn, 5)
def download( def download(url: str, path: str, timeout: Optional[Union[float, tuple]] = None) -> None:
url: str, path: str, timeout: Optional[Union[float, tuple]] = None
) -> None:
path = convert_path(path) path = convert_path(path)
connection_timeout = timeout or float(os.getenv('DBT_HTTP_TIMEOUT', 10)) connection_timeout = timeout or float(os.getenv("DBT_HTTP_TIMEOUT", 10))
response = requests.get(url, timeout=connection_timeout) response = requests.get(url, timeout=connection_timeout)
with open(path, 'wb') as handle: with open(path, "wb") as handle:
for block in response.iter_content(1024 * 64): for block in response.iter_content(1024 * 64):
handle.write(block) handle.write(block)
@@ -481,12 +466,10 @@ def rename(from_path: str, to_path: str, force: bool = False) -> None:
shutil.move(from_path, to_path) shutil.move(from_path, to_path)
def untar_package( def untar_package(tar_path: str, dest_dir: str, rename_to: Optional[str] = None) -> None:
tar_path: str, dest_dir: str, rename_to: Optional[str] = None
) -> None:
tar_path = convert_path(tar_path) tar_path = convert_path(tar_path)
tar_dir_name = None tar_dir_name = None
with tarfile.open(tar_path, 'r') as tarball: with tarfile.open(tar_path, "r:gz") as tarball:
tarball.extractall(dest_dir) tarball.extractall(dest_dir)
tar_dir_name = os.path.commonprefix(tarball.getnames()) tar_dir_name = os.path.commonprefix(tarball.getnames())
if rename_to: if rename_to:
@@ -502,7 +485,7 @@ def chmod_and_retry(func, path, exc_info):
We want to retry most operations here, but listdir is one that we know will We want to retry most operations here, but listdir is one that we know will
be useless. be useless.
""" """
if func is os.listdir or os.name != 'nt': if func is os.listdir or os.name != "nt":
raise raise
os.chmod(path, stat.S_IREAD | stat.S_IWRITE) os.chmod(path, stat.S_IREAD | stat.S_IWRITE)
# on error,this will raise. # on error,this will raise.
@@ -518,12 +501,12 @@ def move(src, dst):
directory on windows when it has read-only files in it and the move is directory on windows when it has read-only files in it and the move is
between two drives. between two drives.
This is almost identical to the real shutil.move, except it uses our rmtree This is almost identical to the real shutil.move, except it, uses our rmtree
and skips handling non-windows OSes since the existing one works ok there. and skips handling non-windows OSes since the existing one works ok there.
""" """
src = convert_path(src) src = convert_path(src)
dst = convert_path(dst) dst = convert_path(dst)
if os.name != 'nt': if os.name != "nt":
return shutil.move(src, dst) return shutil.move(src, dst)
if os.path.isdir(dst): if os.path.isdir(dst):
@@ -531,7 +514,7 @@ def move(src, dst):
os.rename(src, dst) os.rename(src, dst)
return return
dst = os.path.join(dst, os.path.basename(src.rstrip('/\\'))) dst = os.path.join(dst, os.path.basename(src.rstrip("/\\")))
if os.path.exists(dst): if os.path.exists(dst):
raise EnvironmentError("Path '{}' already exists".format(dst)) raise EnvironmentError("Path '{}' already exists".format(dst))
@@ -540,11 +523,10 @@ def move(src, dst):
except OSError: except OSError:
# probably different drives # probably different drives
if os.path.isdir(src): if os.path.isdir(src):
if _absnorm(dst + '\\').startswith(_absnorm(src + '\\')): if _absnorm(dst + "\\").startswith(_absnorm(src + "\\")):
# dst is inside src # dst is inside src
raise EnvironmentError( raise EnvironmentError(
"Cannot move a directory '{}' into itself '{}'" "Cannot move a directory '{}' into itself '{}'".format(src, dst)
.format(src, dst)
) )
shutil.copytree(src, dst, symlinks=True) shutil.copytree(src, dst, symlinks=True)
rmtree(src) rmtree(src)
@@ -554,7 +536,7 @@ def move(src, dst):
def rmtree(path): def rmtree(path):
"""Recursively remove path. On permissions errors on windows, try to remove """Recursively remove the path. On permissions errors on windows, try to remove
the read-only flag and try again. the read-only flag and try again.
""" """
path = convert_path(path) path = convert_path(path)

View File

@@ -4,15 +4,9 @@ import yaml
# the C version is faster, but it doesn't always exist # the C version is faster, but it doesn't always exist
try: try:
from yaml import ( from yaml import CLoader as Loader, CSafeLoader as SafeLoader, CDumper as Dumper
CLoader as Loader,
CSafeLoader as SafeLoader,
CDumper as Dumper
)
except ImportError: except ImportError:
from yaml import ( # type: ignore # noqa: F401 from yaml import Loader, SafeLoader, Dumper # type: ignore # noqa: F401
Loader, SafeLoader, Dumper
)
YAML_ERROR_MESSAGE = """ YAML_ERROR_MESSAGE = """
@@ -32,14 +26,12 @@ def line_no(i, line, width=3):
def prefix_with_line_numbers(string, no_start, no_end): def prefix_with_line_numbers(string, no_start, no_end):
line_list = string.split('\n') line_list = string.split("\n")
numbers = range(no_start, no_end) numbers = range(no_start, no_end)
relevant_lines = line_list[no_start:no_end] relevant_lines = line_list[no_start:no_end]
return "\n".join([ return "\n".join([line_no(i + 1, line) for (i, line) in zip(numbers, relevant_lines)])
line_no(i + 1, line) for (i, line) in zip(numbers, relevant_lines)
])
def contextualized_yaml_error(raw_contents, error): def contextualized_yaml_error(raw_contents, error):
@@ -50,9 +42,9 @@ def contextualized_yaml_error(raw_contents, error):
nice_error = prefix_with_line_numbers(raw_contents, min_line, max_line) nice_error = prefix_with_line_numbers(raw_contents, min_line, max_line)
return YAML_ERROR_MESSAGE.format(line_number=mark.line + 1, return YAML_ERROR_MESSAGE.format(
nice_error=nice_error, line_number=mark.line + 1, nice_error=nice_error, raw_error=error
raw_error=error) )
def safe_load(contents) -> Optional[Dict[str, Any]]: def safe_load(contents) -> Optional[Dict[str, Any]]:
@@ -63,7 +55,7 @@ def load_yaml_text(contents):
try: try:
return safe_load(contents) return safe_load(contents)
except (yaml.scanner.ScannerError, yaml.YAMLError) as e: except (yaml.scanner.ScannerError, yaml.YAMLError) as e:
if hasattr(e, 'problem_mark'): if hasattr(e, "problem_mark"):
error = contextualized_yaml_error(contents, e) error = contextualized_yaml_error(contents, e)
else: else:
error = str(e) error = str(e)

View File

@@ -3,13 +3,14 @@ from collections import defaultdict
from typing import List, Dict, Any, Tuple, cast, Optional from typing import List, Dict, Any, Tuple, cast, Optional
import networkx as nx # type: ignore import networkx as nx # type: ignore
import pickle
import sqlparse import sqlparse
from dbt import flags from dbt import flags
from dbt.adapters.factory import get_adapter from dbt.adapters.factory import get_adapter
from dbt.clients import jinja from dbt.clients import jinja
from dbt.clients.system import make_directory from dbt.clients.system import make_directory
from dbt.context.providers import generate_runtime_model from dbt.context.providers import generate_runtime_model_context, generate_runtime_sql_operation_context
from dbt.contracts.graph.manifest import Manifest, UniqueID from dbt.contracts.graph.manifest import Manifest, UniqueID
from dbt.contracts.graph.compiled import ( from dbt.contracts.graph.compiled import (
COMPILED_TYPES, COMPILED_TYPES,
@@ -18,6 +19,8 @@ from dbt.contracts.graph.compiled import (
InjectedCTE, InjectedCTE,
ManifestNode, ManifestNode,
NonSourceCompiledNode, NonSourceCompiledNode,
CompiledSqlNode,
CompiledRPCNode,
) )
from dbt.contracts.graph.parsed import ParsedNode from dbt.contracts.graph.parsed import ParsedNode
from dbt.exceptions import ( from dbt.exceptions import (
@@ -26,33 +29,35 @@ from dbt.exceptions import (
RuntimeException, RuntimeException,
) )
from dbt.graph import Graph from dbt.graph import Graph
from dbt.logger import GLOBAL_LOGGER as logger from dbt.events.functions import fire_event
from dbt.events.types import FoundStats, CompilingNode, WritingInjectedSQLForNode
from dbt.node_types import NodeType from dbt.node_types import NodeType
from dbt.utils import pluralize from dbt.events.format import pluralize
import dbt.tracking import dbt.tracking
graph_file_name = 'graph.gpickle' graph_file_name = "graph.gpickle"
def _compiled_type_for(model: ParsedNode): def _compiled_type_for(model: ParsedNode):
if type(model) not in COMPILED_TYPES: if type(model) not in COMPILED_TYPES:
raise InternalException( raise InternalException(
f'Asked to compile {type(model)} node, but it has no compiled form' f"Asked to compile {type(model)} node, but it has no compiled form"
) )
return COMPILED_TYPES[type(model)] return COMPILED_TYPES[type(model)]
def print_compile_stats(stats): def print_compile_stats(stats):
names = { names = {
NodeType.Model: 'model', NodeType.Model: "model",
NodeType.Test: 'test', NodeType.Test: "test",
NodeType.Snapshot: 'snapshot', NodeType.Snapshot: "snapshot",
NodeType.Analysis: 'analysis', NodeType.Analysis: "analysis",
NodeType.Macro: 'macro', NodeType.Macro: "macro",
NodeType.Operation: 'operation', NodeType.Operation: "operation",
NodeType.Seed: 'seed file', NodeType.Seed: "seed file",
NodeType.Source: 'source', NodeType.Source: "source",
NodeType.Exposure: 'exposure', NodeType.Exposure: "exposure",
NodeType.Metric: "metric",
} }
results = {k: 0 for k in names.keys()} results = {k: 0 for k in names.keys()}
@@ -63,12 +68,9 @@ def print_compile_stats(stats):
resource_counts = {k.pluralize(): v for k, v in results.items()} resource_counts = {k.pluralize(): v for k, v in results.items()}
dbt.tracking.track_resource_counts(resource_counts) dbt.tracking.track_resource_counts(resource_counts)
stat_line = ", ".join([ stat_line = ", ".join([pluralize(ct, names.get(t)) for t, ct in results.items() if t in names])
pluralize(ct, names.get(t)) for t, ct in results.items()
if t in names
])
logger.info("Found {}".format(stat_line)) fire_event(FoundStats(stat_line=stat_line))
def _node_enabled(node: ManifestNode): def _node_enabled(node: ManifestNode):
@@ -89,6 +91,8 @@ def _generate_stats(manifest: Manifest):
stats[source.resource_type] += 1 stats[source.resource_type] += 1
for exposure in manifest.exposures.values(): for exposure in manifest.exposures.values():
stats[exposure.resource_type] += 1 stats[exposure.resource_type] += 1
for metric in manifest.metrics.values():
stats[metric.resource_type] += 1
for macro in manifest.macros.values(): for macro in manifest.macros.values():
stats[macro.resource_type] += 1 stats[macro.resource_type] += 1
return stats return stats
@@ -108,13 +112,13 @@ def _extend_prepended_ctes(prepended_ctes, new_prepended_ctes):
def _get_tests_for_node(manifest: Manifest, unique_id: UniqueID) -> List[UniqueID]: def _get_tests_for_node(manifest: Manifest, unique_id: UniqueID) -> List[UniqueID]:
""" Get a list of tests that depend on the node with the """Get a list of tests that depend on the node with the
provided unique id """ provided unique id"""
tests = [] tests = []
if unique_id in manifest.child_map: if unique_id in manifest.child_map:
for child_unique_id in manifest.child_map[unique_id]: for child_unique_id in manifest.child_map[unique_id]:
if child_unique_id.startswith('test.'): if child_unique_id.startswith("test."):
tests.append(child_unique_id) tests.append(child_unique_id)
return tests return tests
@@ -158,7 +162,8 @@ class Linker:
for node_id in self.graph: for node_id in self.graph:
data = manifest.expect(node_id).to_dict(omit_none=True) data = manifest.expect(node_id).to_dict(omit_none=True)
out_graph.add_node(node_id, **data) out_graph.add_node(node_id, **data)
nx.write_gpickle(out_graph, outfile) with open(outfile, "wb") as outfh:
pickle.dump(out_graph, outfh, protocol=pickle.HIGHEST_PROTOCOL)
class Compiler: class Compiler:
@@ -178,9 +183,11 @@ class Compiler:
extra_context: Dict[str, Any], extra_context: Dict[str, Any],
) -> Dict[str, Any]: ) -> Dict[str, Any]:
context = generate_runtime_model( if isinstance(node, CompiledSqlNode) or isinstance(node, CompiledRPCNode):
node, self.config, manifest # or node.resource_type in ('SqlOperation', 'RPCCall'):
) context = generate_runtime_sql_operation_context(node, self.config, manifest)
else:
context = generate_runtime_model_context(node, self.config, manifest)
context.update(extra_context) context.update(extra_context)
if isinstance(node, CompiledGenericTestNode): if isinstance(node, CompiledGenericTestNode):
# for test nodes, add a special keyword args value to the context # for test nodes, add a special keyword args value to the context
@@ -238,26 +245,21 @@ class Compiler:
with_stmt = None with_stmt = None
for token in parsed.tokens: for token in parsed.tokens:
if token.is_keyword and token.normalized == 'WITH': if token.is_keyword and token.normalized == "WITH":
with_stmt = token with_stmt = token
break break
if with_stmt is None: if with_stmt is None:
# no with stmt, add one, and inject CTEs right at the beginning # no with stmt, add one, and inject CTEs right at the beginning
first_token = parsed.token_first() first_token = parsed.token_first()
with_stmt = sqlparse.sql.Token(sqlparse.tokens.Keyword, 'with') with_stmt = sqlparse.sql.Token(sqlparse.tokens.Keyword, "with")
parsed.insert_before(first_token, with_stmt) parsed.insert_before(first_token, with_stmt)
else: else:
# stmt exists, add a comma (which will come after injected CTEs) # stmt exists, add a comma (which will come after injected CTEs)
trailing_comma = sqlparse.sql.Token( trailing_comma = sqlparse.sql.Token(sqlparse.tokens.Punctuation, ",")
sqlparse.tokens.Punctuation, ','
)
parsed.insert_after(with_stmt, trailing_comma) parsed.insert_after(with_stmt, trailing_comma)
token = sqlparse.sql.Token( token = sqlparse.sql.Token(sqlparse.tokens.Keyword, ", ".join(c.sql for c in ctes))
sqlparse.tokens.Keyword,
", ".join(c.sql for c in ctes)
)
parsed.insert_after(with_stmt, token) parsed.insert_after(with_stmt, token)
return str(parsed) return str(parsed)
@@ -276,9 +278,7 @@ class Compiler:
inserting CTEs into the SQL. inserting CTEs into the SQL.
""" """
if model.compiled_sql is None: if model.compiled_sql is None:
raise RuntimeException( raise RuntimeException("Cannot inject ctes into an unparsed node", model)
'Cannot inject ctes into an unparsed node', model
)
if model.extra_ctes_injected: if model.extra_ctes_injected:
return (model, model.extra_ctes) return (model, model.extra_ctes)
@@ -299,17 +299,17 @@ class Compiler:
for cte in model.extra_ctes: for cte in model.extra_ctes:
if cte.id not in manifest.nodes: if cte.id not in manifest.nodes:
raise InternalException( raise InternalException(
f'During compilation, found a cte reference that ' f"During compilation, found a cte reference that "
f'could not be resolved: {cte.id}' f"could not be resolved: {cte.id}"
) )
cte_model = manifest.nodes[cte.id] cte_model = manifest.nodes[cte.id]
if not cte_model.is_ephemeral_model: if not cte_model.is_ephemeral_model:
raise InternalException(f'{cte.id} is not ephemeral') raise InternalException(f"{cte.id} is not ephemeral")
# This model has already been compiled, so it's been # This model has already been compiled, so it's been
# through here before # through here before
if getattr(cte_model, 'compiled', False): if getattr(cte_model, "compiled", False):
assert isinstance(cte_model, tuple(COMPILED_TYPES.values())) assert isinstance(cte_model, tuple(COMPILED_TYPES.values()))
cte_model = cast(NonSourceCompiledNode, cte_model) cte_model = cast(NonSourceCompiledNode, cte_model)
new_prepended_ctes = cte_model.extra_ctes new_prepended_ctes = cte_model.extra_ctes
@@ -318,11 +318,9 @@ class Compiler:
else: else:
# This is an ephemeral parsed model that we can compile. # This is an ephemeral parsed model that we can compile.
# Compile and update the node # Compile and update the node
cte_model = self._compile_node( cte_model = self._compile_node(cte_model, manifest, extra_context)
cte_model, manifest, extra_context)
# recursively call this method # recursively call this method
cte_model, new_prepended_ctes = \ cte_model, new_prepended_ctes = self._recursively_prepend_ctes(
self._recursively_prepend_ctes(
cte_model, manifest, extra_context cte_model, manifest, extra_context
) )
# Save compiled SQL file and sync manifest # Save compiled SQL file and sync manifest
@@ -332,10 +330,8 @@ class Compiler:
_extend_prepended_ctes(prepended_ctes, new_prepended_ctes) _extend_prepended_ctes(prepended_ctes, new_prepended_ctes)
new_cte_name = self.add_ephemeral_prefix(cte_model.name) new_cte_name = self.add_ephemeral_prefix(cte_model.name)
rendered_sql = ( rendered_sql = cte_model._pre_injected_sql or cte_model.compiled_sql
cte_model._pre_injected_sql or cte_model.compiled_sql sql = f" {new_cte_name} as (\n{rendered_sql}\n)"
)
sql = f' {new_cte_name} as (\n{rendered_sql}\n)'
_add_prepended_cte(prepended_ctes, InjectedCTE(id=cte.id, sql=sql)) _add_prepended_cte(prepended_ctes, InjectedCTE(id=cte.id, sql=sql))
@@ -366,20 +362,20 @@ class Compiler:
if extra_context is None: if extra_context is None:
extra_context = {} extra_context = {}
logger.debug("Compiling {}".format(node.unique_id)) fire_event(CompilingNode(unique_id=node.unique_id))
data = node.to_dict(omit_none=True) data = node.to_dict(omit_none=True)
data.update({ data.update(
'compiled': False, {
'compiled_sql': None, "compiled": False,
'extra_ctes_injected': False, "compiled_sql": None,
'extra_ctes': [], "extra_ctes_injected": False,
}) "extra_ctes": [],
}
)
compiled_node = _compiled_type_for(node).from_dict(data) compiled_node = _compiled_type_for(node).from_dict(data)
context = self._create_node_context( context = self._create_node_context(compiled_node, manifest, extra_context)
compiled_node, manifest, extra_context
)
compiled_node.compiled_sql = jinja.get_rendered( compiled_node.compiled_sql = jinja.get_rendered(
node.raw_sql, node.raw_sql,
@@ -399,47 +395,41 @@ class Compiler:
if flags.WRITE_JSON: if flags.WRITE_JSON:
linker.write_graph(graph_path, manifest) linker.write_graph(graph_path, manifest)
def link_node( def link_node(self, linker: Linker, node: GraphMemberNode, manifest: Manifest):
self, linker: Linker, node: GraphMemberNode, manifest: Manifest
):
linker.add_node(node.unique_id) linker.add_node(node.unique_id)
for dependency in node.depends_on_nodes: for dependency in node.depends_on_nodes:
if dependency in manifest.nodes: if dependency in manifest.nodes:
linker.dependency( linker.dependency(node.unique_id, (manifest.nodes[dependency].unique_id))
node.unique_id,
(manifest.nodes[dependency].unique_id)
)
elif dependency in manifest.sources: elif dependency in manifest.sources:
linker.dependency( linker.dependency(node.unique_id, (manifest.sources[dependency].unique_id))
node.unique_id,
(manifest.sources[dependency].unique_id)
)
else: else:
dependency_not_found(node, dependency) dependency_not_found(node, dependency)
def link_graph(self, linker: Linker, manifest: Manifest): def link_graph(self, linker: Linker, manifest: Manifest, add_test_edges: bool = False):
for source in manifest.sources.values(): for source in manifest.sources.values():
linker.add_node(source.unique_id) linker.add_node(source.unique_id)
for node in manifest.nodes.values(): for node in manifest.nodes.values():
self.link_node(linker, node, manifest) self.link_node(linker, node, manifest)
for exposure in manifest.exposures.values(): for exposure in manifest.exposures.values():
self.link_node(linker, exposure, manifest) self.link_node(linker, exposure, manifest)
for metric in manifest.metrics.values():
self.link_node(linker, metric, manifest)
cycle = linker.find_cycles() cycle = linker.find_cycles()
if cycle: if cycle:
raise RuntimeError("Found a cycle: {}".format(cycle)) raise RuntimeError("Found a cycle: {}".format(cycle))
if add_test_edges:
manifest.build_parent_and_child_maps() manifest.build_parent_and_child_maps()
self.add_test_edges(linker, manifest)
self.resolve_graph(linker, manifest) def add_test_edges(self, linker: Linker, manifest: Manifest) -> None:
"""This method adds additional edges to the DAG. For a given non-test
def resolve_graph(self, linker: Linker, manifest: Manifest) -> None:
""" This method adds additional edges to the DAG. For a given non-test
executable node, add an edge from an upstream test to the given node if executable node, add an edge from an upstream test to the given node if
the set of nodes the test depends on is a proper/strict subset of the the set of nodes the test depends on is a subset of the upstream nodes
upstream nodes for the given node. """ for the given node."""
# Given a graph: # Given a graph:
# model1 --> model2 --> model3 # model1 --> model2 --> model3
@@ -450,34 +440,27 @@ class Compiler:
# #
# Produce the following graph: # Produce the following graph:
# model1 --> model2 --> model3 # model1 --> model2 --> model3
# | | /\ /\ # | /\ | /\ /\
# | \/ | | # | | \/ | |
# \/ test2 ------- | # \/ | test2 ----| |
# test1 ------------------- # test1 ----|---------------|
for node_id in linker.graph: for node_id in linker.graph:
# If node is executable (in manifest.nodes) and does _not_ # If node is executable (in manifest.nodes) and does _not_
# represent a test, continue. # represent a test, continue.
if ( if (
node_id in manifest.nodes and node_id in manifest.nodes
manifest.nodes[node_id].resource_type != NodeType.Test and manifest.nodes[node_id].resource_type != NodeType.Test
): ):
# Get *everything* upstream of the node # Get *everything* upstream of the node
all_upstream_nodes = nx.traversal.bfs_tree( all_upstream_nodes = nx.traversal.bfs_tree(linker.graph, node_id, reverse=True)
linker.graph, node_id, reverse=True
)
# Get the set of upstream nodes not including the current node. # Get the set of upstream nodes not including the current node.
upstream_nodes = set([ upstream_nodes = set([n for n in all_upstream_nodes if n != node_id])
n for n in all_upstream_nodes if n != node_id
])
# Get all tests that depend on any upstream nodes. # Get all tests that depend on any upstream nodes.
upstream_tests = [] upstream_tests = []
for upstream_node in upstream_nodes: for upstream_node in upstream_nodes:
upstream_tests += _get_tests_for_node( upstream_tests += _get_tests_for_node(manifest, upstream_node)
manifest,
upstream_node
)
for upstream_test in upstream_tests: for upstream_test in upstream_tests:
# Get the set of all nodes that the test depends on # Get the set of all nodes that the test depends on
@@ -486,26 +469,19 @@ class Compiler:
# relationship tests). Test nodes do not distinguish # relationship tests). Test nodes do not distinguish
# between what node the test is "testing" and what # between what node the test is "testing" and what
# node(s) it depends on. # node(s) it depends on.
test_depends_on = set( test_depends_on = set(manifest.nodes[upstream_test].depends_on_nodes)
manifest.nodes[upstream_test].depends_on_nodes
)
# If the set of nodes that an upstream test depends on # If the set of nodes that an upstream test depends on
# is a proper (or strict) subset of all upstream nodes of # is a subset of all upstream nodes of the current node,
# the current node, add an edge from the upstream test # add an edge from the upstream test to the current node.
# to the current node. Must be a proper/strict subset to if test_depends_on.issubset(upstream_nodes):
# avoid adding a circular dependency to the graph. linker.graph.add_edge(upstream_test, node_id)
if (test_depends_on < upstream_nodes):
linker.graph.add_edge(
upstream_test,
node_id
)
def compile(self, manifest: Manifest, write=True) -> Graph: def compile(self, manifest: Manifest, write=True, add_test_edges=False) -> Graph:
self.initialize() self.initialize()
linker = Linker() linker = Linker()
self.link_graph(linker, manifest) self.link_graph(linker, manifest, add_test_edges)
stats = _generate_stats(manifest) stats = _generate_stats(manifest)
@@ -517,16 +493,13 @@ class Compiler:
# writes the "compiled_sql" into the target/compiled directory # writes the "compiled_sql" into the target/compiled directory
def _write_node(self, node: NonSourceCompiledNode) -> ManifestNode: def _write_node(self, node: NonSourceCompiledNode) -> ManifestNode:
if (not node.extra_ctes_injected or if not node.extra_ctes_injected or node.resource_type == NodeType.Snapshot:
node.resource_type == NodeType.Snapshot):
return node return node
logger.debug(f'Writing injected SQL for node "{node.unique_id}"') fire_event(WritingInjectedSQLForNode(unique_id=node.unique_id))
if node.compiled_sql: if node.compiled_sql:
node.compiled_path = node.write_node( node.compiled_path = node.write_node(
self.config.target_path, self.config.target_path, "compiled", node.compiled_sql
'compiled',
node.compiled_sql
) )
return node return node
@@ -545,9 +518,7 @@ class Compiler:
""" """
node = self._compile_node(node, manifest, extra_context) node = self._compile_node(node, manifest, extra_context)
node, _ = self._recursively_prepend_ctes( node, _ = self._recursively_prepend_ctes(node, manifest, extra_context)
node, manifest, extra_context
)
if write: if write:
self._write_node(node) self._write_node(node)
return node return node

View File

@@ -0,0 +1 @@
# Config README

View File

@@ -15,14 +15,15 @@ from dbt.exceptions import DbtProjectError
from dbt.exceptions import ValidationException from dbt.exceptions import ValidationException
from dbt.exceptions import RuntimeException from dbt.exceptions import RuntimeException
from dbt.exceptions import validator_error_message from dbt.exceptions import validator_error_message
from dbt.logger import GLOBAL_LOGGER as logger from dbt.events.types import MissingProfileTarget
from dbt.events.functions import fire_event
from dbt.utils import coerce_dict_str from dbt.utils import coerce_dict_str
from .renderer import ProfileRenderer from .renderer import ProfileRenderer
DEFAULT_THREADS = 1 DEFAULT_THREADS = 1
DEFAULT_PROFILES_DIR = os.path.join(os.path.expanduser('~'), '.dbt') DEFAULT_PROFILES_DIR = os.path.join(os.path.expanduser("~"), ".dbt")
INVALID_PROFILE_MESSAGE = """ INVALID_PROFILE_MESSAGE = """
dbt encountered an error while trying to read your profiles.yml file. dbt encountered an error while trying to read your profiles.yml file.
@@ -42,11 +43,13 @@ Here, [profile name] should be replaced with a profile name
defined in your profiles.yml file. You can find profiles.yml here: defined in your profiles.yml file. You can find profiles.yml here:
{profiles_file}/profiles.yml {profiles_file}/profiles.yml
""".format(profiles_file=DEFAULT_PROFILES_DIR) """.format(
profiles_file=DEFAULT_PROFILES_DIR
)
def read_profile(profiles_dir: str) -> Dict[str, Any]: def read_profile(profiles_dir: str) -> Dict[str, Any]:
path = os.path.join(profiles_dir, 'profiles.yml') path = os.path.join(profiles_dir, "profiles.yml")
contents = None contents = None
if os.path.isfile(path): if os.path.isfile(path):
@@ -54,12 +57,8 @@ def read_profile(profiles_dir: str) -> Dict[str, Any]:
contents = load_file_contents(path, strip=False) contents = load_file_contents(path, strip=False)
yaml_content = load_yaml_text(contents) yaml_content = load_yaml_text(contents)
if not yaml_content: if not yaml_content:
msg = f'The profiles.yml file at {path} is empty' msg = f"The profiles.yml file at {path} is empty"
raise DbtProfileError( raise DbtProfileError(INVALID_PROFILE_MESSAGE.format(error_string=msg))
INVALID_PROFILE_MESSAGE.format(
error_string=msg
)
)
return yaml_content return yaml_content
except ValidationException as e: except ValidationException as e:
msg = INVALID_PROFILE_MESSAGE.format(error_string=e) msg = INVALID_PROFILE_MESSAGE.format(error_string=e)
@@ -72,7 +71,7 @@ def read_user_config(directory: str) -> UserConfig:
try: try:
profile = read_profile(directory) profile = read_profile(directory)
if profile: if profile:
user_config = coerce_dict_str(profile.get('config', {})) user_config = coerce_dict_str(profile.get("config", {}))
if user_config is not None: if user_config is not None:
UserConfig.validate(user_config) UserConfig.validate(user_config)
return UserConfig.from_dict(user_config) return UserConfig.from_dict(user_config)
@@ -91,6 +90,7 @@ class Profile(HasCredentials):
user_config: UserConfig user_config: UserConfig
threads: int threads: int
credentials: Credentials credentials: Credentials
profile_env_vars: Dict[str, Any]
def __init__( def __init__(
self, self,
@@ -98,7 +98,7 @@ class Profile(HasCredentials):
target_name: str, target_name: str,
user_config: UserConfig, user_config: UserConfig,
threads: int, threads: int,
credentials: Credentials credentials: Credentials,
): ):
"""Explicitly defining `__init__` to work around bug in Python 3.9.7 """Explicitly defining `__init__` to work around bug in Python 3.9.7
https://bugs.python.org/issue45081 https://bugs.python.org/issue45081
@@ -108,10 +108,9 @@ class Profile(HasCredentials):
self.user_config = user_config self.user_config = user_config
self.threads = threads self.threads = threads
self.credentials = credentials self.credentials = credentials
self.profile_env_vars = {} # never available on init
def to_profile_info( def to_profile_info(self, serialize_credentials: bool = False) -> Dict[str, Any]:
self, serialize_credentials: bool = False
) -> Dict[str, Any]:
"""Unlike to_project_config, this dict is not a mirror of any existing """Unlike to_project_config, this dict is not a mirror of any existing
on-disk data structure. It's used when creating a new profile from an on-disk data structure. It's used when creating a new profile from an
existing one. existing one.
@@ -121,34 +120,33 @@ class Profile(HasCredentials):
:returns dict: The serialized profile. :returns dict: The serialized profile.
""" """
result = { result = {
'profile_name': self.profile_name, "profile_name": self.profile_name,
'target_name': self.target_name, "target_name": self.target_name,
'user_config': self.user_config, "user_config": self.user_config,
'threads': self.threads, "threads": self.threads,
'credentials': self.credentials, "credentials": self.credentials,
} }
if serialize_credentials: if serialize_credentials:
result['user_config'] = self.user_config.to_dict(omit_none=True) result["user_config"] = self.user_config.to_dict(omit_none=True)
result['credentials'] = self.credentials.to_dict(omit_none=True) result["credentials"] = self.credentials.to_dict(omit_none=True)
return result return result
def to_target_dict(self) -> Dict[str, Any]: def to_target_dict(self) -> Dict[str, Any]:
target = dict( target = dict(self.credentials.connection_info(with_aliases=True))
self.credentials.connection_info(with_aliases=True) target.update(
{
"type": self.credentials.type,
"threads": self.threads,
"name": self.target_name,
"target_name": self.target_name,
"profile_name": self.profile_name,
"config": self.user_config.to_dict(omit_none=True),
}
) )
target.update({
'type': self.credentials.type,
'threads': self.threads,
'name': self.target_name,
'target_name': self.target_name,
'profile_name': self.profile_name,
'config': self.user_config.to_dict(omit_none=True),
})
return target return target
def __eq__(self, other: object) -> bool: def __eq__(self, other: object) -> bool:
if not (isinstance(other, self.__class__) and if not (isinstance(other, self.__class__) and isinstance(self, other.__class__)):
isinstance(self, other.__class__)):
return NotImplemented return NotImplemented
return self.to_profile_info() == other.to_profile_info() return self.to_profile_info() == other.to_profile_info()
@@ -168,14 +166,17 @@ class Profile(HasCredentials):
) -> Credentials: ) -> Credentials:
# avoid an import cycle # avoid an import cycle
from dbt.adapters.factory import load_plugin from dbt.adapters.factory import load_plugin
# credentials carry their 'type' in their actual type, not their # credentials carry their 'type' in their actual type, not their
# attributes. We do want this in order to pick our Credentials class. # attributes. We do want this in order to pick our Credentials class.
if 'type' not in profile: if "type" not in profile:
raise DbtProfileError( raise DbtProfileError(
'required field "type" not found in profile {} and target {}' 'required field "type" not found in profile {} and target {}'.format(
.format(profile_name, target_name)) profile_name, target_name
)
)
typename = profile.pop('type') typename = profile.pop("type")
try: try:
cls = load_plugin(typename) cls = load_plugin(typename)
data = cls.translate_aliases(profile) data = cls.translate_aliases(profile)
@@ -184,8 +185,9 @@ class Profile(HasCredentials):
except (RuntimeException, ValidationError) as e: except (RuntimeException, ValidationError) as e:
msg = str(e) if isinstance(e, RuntimeException) else e.message msg = str(e) if isinstance(e, RuntimeException) else e.message
raise DbtProfileError( raise DbtProfileError(
'Credentials in profile "{}", target "{}" invalid: {}' 'Credentials in profile "{}", target "{}" invalid: {}'.format(
.format(profile_name, target_name, msg) profile_name, target_name, msg
)
) from e ) from e
return credentials return credentials
@@ -206,19 +208,19 @@ class Profile(HasCredentials):
def _get_profile_data( def _get_profile_data(
profile: Dict[str, Any], profile_name: str, target_name: str profile: Dict[str, Any], profile_name: str, target_name: str
) -> Dict[str, Any]: ) -> Dict[str, Any]:
if 'outputs' not in profile: if "outputs" not in profile:
raise DbtProfileError( raise DbtProfileError("outputs not specified in profile '{}'".format(profile_name))
"outputs not specified in profile '{}'".format(profile_name) outputs = profile["outputs"]
)
outputs = profile['outputs']
if target_name not in outputs: if target_name not in outputs:
outputs = '\n'.join(' - {}'.format(output) outputs = "\n".join(" - {}".format(output) for output in outputs)
for output in outputs) msg = (
msg = ("The profile '{}' does not have a target named '{}'. The " "The profile '{}' does not have a target named '{}'. The "
"valid target names for this profile are:\n{}" "valid target names for this profile are:\n{}".format(
.format(profile_name, target_name, outputs)) profile_name, target_name, outputs
raise DbtProfileError(msg, result_type='invalid_target') )
)
raise DbtProfileError(msg, result_type="invalid_target")
profile_data = outputs[target_name] profile_data = outputs[target_name]
if not isinstance(profile_data, dict): if not isinstance(profile_data, dict):
@@ -226,7 +228,7 @@ class Profile(HasCredentials):
f"output '{target_name}' of profile '{profile_name}' is " f"output '{target_name}' of profile '{profile_name}' is "
f"misconfigured in profiles.yml" f"misconfigured in profiles.yml"
) )
raise DbtProfileError(msg, result_type='invalid_target') raise DbtProfileError(msg, result_type="invalid_target")
return profile_data return profile_data
@@ -237,8 +239,8 @@ class Profile(HasCredentials):
threads: int, threads: int,
profile_name: str, profile_name: str,
target_name: str, target_name: str,
user_config: Optional[Dict[str, Any]] = None user_config: Optional[Dict[str, Any]] = None,
) -> 'Profile': ) -> "Profile":
"""Create a profile from an existing set of Credentials and the """Create a profile from an existing set of Credentials and the
remaining information. remaining information.
@@ -261,7 +263,7 @@ class Profile(HasCredentials):
target_name=target_name, target_name=target_name,
user_config=user_config_obj, user_config=user_config_obj,
threads=threads, threads=threads,
credentials=credentials credentials=credentials,
) )
profile.validate() profile.validate()
return profile return profile
@@ -286,19 +288,14 @@ class Profile(HasCredentials):
# name to extract a profile that we can render. # name to extract a profile that we can render.
if target_override is not None: if target_override is not None:
target_name = target_override target_name = target_override
elif 'target' in raw_profile: elif "target" in raw_profile:
# render the target if it was parsed from yaml # render the target if it was parsed from yaml
target_name = renderer.render_value(raw_profile['target']) target_name = renderer.render_value(raw_profile["target"])
else: else:
target_name = 'default' target_name = "default"
logger.debug( fire_event(MissingProfileTarget(profile_name=profile_name, target_name=target_name))
"target not specified in profile '{}', using '{}'"
.format(profile_name, target_name)
)
raw_profile_data = cls._get_profile_data( raw_profile_data = cls._get_profile_data(raw_profile, profile_name, target_name)
raw_profile, profile_name, target_name
)
try: try:
profile_data = renderer.render_data(raw_profile_data) profile_data = renderer.render_data(raw_profile_data)
@@ -315,7 +312,7 @@ class Profile(HasCredentials):
user_config: Optional[Dict[str, Any]] = None, user_config: Optional[Dict[str, Any]] = None,
target_override: Optional[str] = None, target_override: Optional[str] = None,
threads_override: Optional[int] = None, threads_override: Optional[int] = None,
) -> 'Profile': ) -> "Profile":
"""Create a profile from its raw profile information. """Create a profile from its raw profile information.
(this is an intermediate step, mostly useful for unit testing) (this is an intermediate step, mostly useful for unit testing)
@@ -336,7 +333,7 @@ class Profile(HasCredentials):
""" """
# user_config is not rendered. # user_config is not rendered.
if user_config is None: if user_config is None:
user_config = raw_profile.get('config') user_config = raw_profile.get("config")
# TODO: should it be, and the values coerced to bool? # TODO: should it be, and the values coerced to bool?
target_name, profile_data = cls.render_profile( target_name, profile_data = cls.render_profile(
raw_profile, profile_name, target_override, renderer raw_profile, profile_name, target_override, renderer
@@ -344,7 +341,7 @@ class Profile(HasCredentials):
# valid connections never include the number of threads, but it's # valid connections never include the number of threads, but it's
# stored on a per-connection level in the raw configs # stored on a per-connection level in the raw configs
threads = profile_data.pop('threads', DEFAULT_THREADS) threads = profile_data.pop("threads", DEFAULT_THREADS)
if threads_override is not None: if threads_override is not None:
threads = threads_override threads = threads_override
@@ -357,7 +354,7 @@ class Profile(HasCredentials):
profile_name=profile_name, profile_name=profile_name,
target_name=target_name, target_name=target_name,
threads=threads, threads=threads,
user_config=user_config user_config=user_config,
) )
@classmethod @classmethod
@@ -368,7 +365,7 @@ class Profile(HasCredentials):
renderer: ProfileRenderer, renderer: ProfileRenderer,
target_override: Optional[str] = None, target_override: Optional[str] = None,
threads_override: Optional[int] = None, threads_override: Optional[int] = None,
) -> 'Profile': ) -> "Profile":
""" """
:param raw_profiles: The profile data, from disk as yaml. :param raw_profiles: The profile data, from disk as yaml.
:param profile_name: The profile name to use. :param profile_name: The profile name to use.
@@ -384,23 +381,15 @@ class Profile(HasCredentials):
:returns: The new Profile object. :returns: The new Profile object.
""" """
if profile_name not in raw_profiles: if profile_name not in raw_profiles:
raise DbtProjectError( raise DbtProjectError("Could not find profile named '{}'".format(profile_name))
"Could not find profile named '{}'".format(profile_name)
)
# First, we've already got our final decision on profile name, and we # First, we've already got our final decision on profile name, and we
# don't render keys, so we can pluck that out # don't render keys, so we can pluck that out
raw_profile = raw_profiles[profile_name] raw_profile = raw_profiles[profile_name]
if not raw_profile: if not raw_profile:
msg = ( msg = f"Profile {profile_name} in profiles.yml is empty"
f'Profile {profile_name} in profiles.yml is empty' raise DbtProfileError(INVALID_PROFILE_MESSAGE.format(error_string=msg))
) user_config = raw_profiles.get("config")
raise DbtProfileError(
INVALID_PROFILE_MESSAGE.format(
error_string=msg
)
)
user_config = raw_profiles.get('config')
return cls.from_raw_profile_info( return cls.from_raw_profile_info(
raw_profile=raw_profile, raw_profile=raw_profile,
@@ -417,7 +406,7 @@ class Profile(HasCredentials):
args: Any, args: Any,
renderer: ProfileRenderer, renderer: ProfileRenderer,
project_profile_name: Optional[str], project_profile_name: Optional[str],
) -> 'Profile': ) -> "Profile":
"""Given the raw profiles as read from disk and the name of the desired """Given the raw profiles as read from disk and the name of the desired
profile if specified, return the profile component of the runtime profile if specified, return the profile component of the runtime
config. config.
@@ -432,15 +421,14 @@ class Profile(HasCredentials):
target could not be found. target could not be found.
:returns Profile: The new Profile object. :returns Profile: The new Profile object.
""" """
threads_override = getattr(args, 'threads', None) threads_override = getattr(args, "threads", None)
target_override = getattr(args, 'target', None) target_override = getattr(args, "target", None)
raw_profiles = read_profile(flags.PROFILES_DIR) raw_profiles = read_profile(flags.PROFILES_DIR)
profile_name = cls.pick_profile_name(getattr(args, 'profile', None), profile_name = cls.pick_profile_name(getattr(args, "profile", None), project_profile_name)
project_profile_name)
return cls.from_raw_profiles( return cls.from_raw_profiles(
raw_profiles=raw_profiles, raw_profiles=raw_profiles,
profile_name=profile_name, profile_name=profile_name,
renderer=renderer, renderer=renderer,
target_override=target_override, target_override=target_override,
threads_override=threads_override threads_override=threads_override,
) )

View File

@@ -2,7 +2,13 @@ from copy import deepcopy
from dataclasses import dataclass, field from dataclasses import dataclass, field
from itertools import chain from itertools import chain
from typing import ( from typing import (
List, Dict, Any, Optional, TypeVar, Union, Mapping, List,
Dict,
Any,
Optional,
TypeVar,
Union,
Mapping,
) )
from typing_extensions import Protocol, runtime_checkable from typing_extensions import Protocol, runtime_checkable
@@ -45,7 +51,7 @@ INVALID_VERSION_ERROR = """\
This version of dbt is not supported with the '{package}' package. This version of dbt is not supported with the '{package}' package.
Installed version of dbt: {installed} Installed version of dbt: {installed}
Required version of dbt for '{package}': {version_spec} Required version of dbt for '{package}': {version_spec}
Check the requirements for the '{package}' package, or run dbt again with \ Check for a different version of the '{package}' package, or run dbt again with \
--no-version-check --no-version-check
""" """
@@ -54,7 +60,7 @@ IMPOSSIBLE_VERSION_ERROR = """\
The package version requirement can never be satisfied for the '{package} The package version requirement can never be satisfied for the '{package}
package. package.
Required versions of dbt for '{package}': {version_spec} Required versions of dbt for '{package}': {version_spec}
Check the requirements for the '{package}' package, or run dbt again with \ Check for a different version of the '{package}' package, or run dbt again with \
--no-version-check --no-version-check
""" """
@@ -83,9 +89,7 @@ def _load_yaml(path):
def package_data_from_root(project_root): def package_data_from_root(project_root):
package_filepath = resolve_path_from_base( package_filepath = resolve_path_from_base("packages.yml", project_root)
'packages.yml', project_root
)
if path_exists(package_filepath): if path_exists(package_filepath):
packages_dict = _load_yaml(package_filepath) packages_dict = _load_yaml(package_filepath)
@@ -96,15 +100,13 @@ def package_data_from_root(project_root):
def package_config_from_data(packages_data: Dict[str, Any]): def package_config_from_data(packages_data: Dict[str, Any]):
if not packages_data: if not packages_data:
packages_data = {'packages': []} packages_data = {"packages": []}
try: try:
PackageConfig.validate(packages_data) PackageConfig.validate(packages_data)
packages = PackageConfig.from_dict(packages_data) packages = PackageConfig.from_dict(packages_data)
except ValidationError as e: except ValidationError as e:
raise DbtProjectError( raise DbtProjectError(MALFORMED_PACKAGE_ERROR.format(error=str(e.message))) from e
MALFORMED_PACKAGE_ERROR.format(error=str(e.message))
) from e
return packages return packages
@@ -119,7 +121,7 @@ def _parse_versions(versions: Union[List[str], str]) -> List[VersionSpecifier]:
Regardless, this will return a list of VersionSpecifiers Regardless, this will return a list of VersionSpecifiers
""" """
if isinstance(versions, str): if isinstance(versions, str):
versions = versions.split(',') versions = versions.split(",")
return [VersionSpecifier.from_version_string(v) for v in versions] return [VersionSpecifier.from_version_string(v) for v in versions]
@@ -130,11 +132,10 @@ def _all_source_paths(
analysis_paths: List[str], analysis_paths: List[str],
macro_paths: List[str], macro_paths: List[str],
) -> List[str]: ) -> List[str]:
return list(chain(model_paths, seed_paths, snapshot_paths, analysis_paths, return list(chain(model_paths, seed_paths, snapshot_paths, analysis_paths, macro_paths))
macro_paths))
T = TypeVar('T') T = TypeVar("T")
def value_or(value: Optional[T], default: T) -> T: def value_or(value: Optional[T], default: T) -> T:
@@ -147,21 +148,18 @@ def value_or(value: Optional[T], default: T) -> T:
def _raw_project_from(project_root: str) -> Dict[str, Any]: def _raw_project_from(project_root: str) -> Dict[str, Any]:
project_root = os.path.normpath(project_root) project_root = os.path.normpath(project_root)
project_yaml_filepath = os.path.join(project_root, 'dbt_project.yml') project_yaml_filepath = os.path.join(project_root, "dbt_project.yml")
# get the project.yml contents # get the project.yml contents
if not path_exists(project_yaml_filepath): if not path_exists(project_yaml_filepath):
raise DbtProjectError( raise DbtProjectError(
'no dbt_project.yml found at expected path {}' "no dbt_project.yml found at expected path {}".format(project_yaml_filepath)
.format(project_yaml_filepath)
) )
project_dict = _load_yaml(project_yaml_filepath) project_dict = _load_yaml(project_yaml_filepath)
if not isinstance(project_dict, dict): if not isinstance(project_dict, dict):
raise DbtProjectError( raise DbtProjectError("dbt_project.yml does not parse to a dictionary")
'dbt_project.yml does not parse to a dictionary'
)
return project_dict return project_dict
@@ -170,7 +168,7 @@ def _query_comment_from_cfg(
cfg_query_comment: Union[QueryComment, NoValue, str, None] cfg_query_comment: Union[QueryComment, NoValue, str, None]
) -> QueryComment: ) -> QueryComment:
if not cfg_query_comment: if not cfg_query_comment:
return QueryComment(comment='') return QueryComment(comment="")
if isinstance(cfg_query_comment, str): if isinstance(cfg_query_comment, str):
return QueryComment(comment=cfg_query_comment) return QueryComment(comment=cfg_query_comment)
@@ -186,10 +184,7 @@ def validate_version(dbt_version: List[VersionSpecifier], project_name: str):
installed = get_installed_version() installed = get_installed_version()
if not versions_compatible(*dbt_version): if not versions_compatible(*dbt_version):
msg = IMPOSSIBLE_VERSION_ERROR.format( msg = IMPOSSIBLE_VERSION_ERROR.format(
package=project_name, package=project_name, version_spec=[x.to_version_string() for x in dbt_version]
version_spec=[
x.to_version_string() for x in dbt_version
]
) )
raise DbtProjectError(msg) raise DbtProjectError(msg)
@@ -197,9 +192,7 @@ def validate_version(dbt_version: List[VersionSpecifier], project_name: str):
msg = INVALID_VERSION_ERROR.format( msg = INVALID_VERSION_ERROR.format(
package=project_name, package=project_name,
installed=installed.to_version_string(), installed=installed.to_version_string(),
version_spec=[ version_spec=[x.to_version_string() for x in dbt_version],
x.to_version_string() for x in dbt_version
]
) )
raise DbtProjectError(msg) raise DbtProjectError(msg)
@@ -208,8 +201,8 @@ def _get_required_version(
project_dict: Dict[str, Any], project_dict: Dict[str, Any],
verify_version: bool, verify_version: bool,
) -> List[VersionSpecifier]: ) -> List[VersionSpecifier]:
dbt_raw_version: Union[List[str], str] = '>=0.0.0' dbt_raw_version: Union[List[str], str] = ">=0.0.0"
required = project_dict.get('require-dbt-version') required = project_dict.get("require-dbt-version")
if required is not None: if required is not None:
dbt_raw_version = required dbt_raw_version = required
@@ -220,46 +213,39 @@ def _get_required_version(
if verify_version: if verify_version:
# no name is also an error that we want to raise # no name is also an error that we want to raise
if 'name' not in project_dict: if "name" not in project_dict:
raise DbtProjectError( raise DbtProjectError(
'Required "name" field not present in project', 'Required "name" field not present in project',
) )
validate_version(dbt_version, project_dict['name']) validate_version(dbt_version, project_dict["name"])
return dbt_version return dbt_version
@dataclass @dataclass
class RenderComponents: class RenderComponents:
project_dict: Dict[str, Any] = field( project_dict: Dict[str, Any] = field(metadata=dict(description="The project dictionary"))
metadata=dict(description='The project dictionary') packages_dict: Dict[str, Any] = field(metadata=dict(description="The packages dictionary"))
) selectors_dict: Dict[str, Any] = field(metadata=dict(description="The selectors dictionary"))
packages_dict: Dict[str, Any] = field(
metadata=dict(description='The packages dictionary')
)
selectors_dict: Dict[str, Any] = field(
metadata=dict(description='The selectors dictionary')
)
@dataclass @dataclass
class PartialProject(RenderComponents): class PartialProject(RenderComponents):
profile_name: Optional[str] = field(metadata=dict( profile_name: Optional[str] = field(
description='The unrendered profile name in the project, if set' metadata=dict(description="The unrendered profile name in the project, if set")
)) )
project_name: Optional[str] = field(metadata=dict( project_name: Optional[str] = field(
description=( metadata=dict(
'The name of the project. This should always be set and will not ' description=(
'be rendered' "The name of the project. This should always be set and will not " "be rendered"
)
)
) )
))
project_root: str = field( project_root: str = field(
metadata=dict(description='The root directory of the project'), metadata=dict(description="The root directory of the project"),
) )
verify_version: bool = field( verify_version: bool = field(
metadata=dict(description=( metadata=dict(description=("If True, verify the dbt version matches the required version"))
'If True, verify the dbt version matches the required version'
))
) )
def render_profile_name(self, renderer) -> Optional[str]: def render_profile_name(self, renderer) -> Optional[str]:
@@ -272,9 +258,7 @@ class PartialProject(RenderComponents):
renderer: DbtProjectYamlRenderer, renderer: DbtProjectYamlRenderer,
) -> RenderComponents: ) -> RenderComponents:
rendered_project = renderer.render_project( rendered_project = renderer.render_project(self.project_dict, self.project_root)
self.project_dict, self.project_root
)
rendered_packages = renderer.render_packages(self.packages_dict) rendered_packages = renderer.render_packages(self.packages_dict)
rendered_selectors = renderer.render_selectors(self.selectors_dict) rendered_selectors = renderer.render_selectors(self.selectors_dict)
@@ -284,31 +268,35 @@ class PartialProject(RenderComponents):
selectors_dict=rendered_selectors, selectors_dict=rendered_selectors,
) )
def render(self, renderer: DbtProjectYamlRenderer) -> 'Project': # Called by 'collect_parts' in RuntimeConfig
def render(self, renderer: DbtProjectYamlRenderer) -> "Project":
try: try:
rendered = self.get_rendered(renderer) rendered = self.get_rendered(renderer)
return self.create_project(rendered) return self.create_project(rendered)
except DbtProjectError as exc: except DbtProjectError as exc:
if exc.path is None: if exc.path is None:
exc.path = os.path.join(self.project_root, 'dbt_project.yml') exc.path = os.path.join(self.project_root, "dbt_project.yml")
raise raise
def check_config_path(self, project_dict, deprecated_path, exp_path): def check_config_path(self, project_dict, deprecated_path, exp_path):
if deprecated_path in project_dict: if deprecated_path in project_dict:
if exp_path in project_dict: if exp_path in project_dict:
msg = ( msg = (
'{deprecated_path} and {exp_path} cannot both be defined. The ' "{deprecated_path} and {exp_path} cannot both be defined. The "
'`{deprecated_path}` config has been deprecated in favor of `{exp_path}`. ' "`{deprecated_path}` config has been deprecated in favor of `{exp_path}`. "
'Please update your `dbt_project.yml` configuration to reflect this ' "Please update your `dbt_project.yml` configuration to reflect this "
'change.' "change."
) )
raise DbtProjectError(msg.format(deprecated_path=deprecated_path, raise DbtProjectError(
exp_path=exp_path)) msg.format(deprecated_path=deprecated_path, exp_path=exp_path)
deprecations.warn('project_config_path', )
deprecations.warn(
f"project-config-{deprecated_path}",
deprecated_path=deprecated_path, deprecated_path=deprecated_path,
exp_path=exp_path) exp_path=exp_path,
)
def create_project(self, rendered: RenderComponents) -> 'Project': def create_project(self, rendered: RenderComponents) -> "Project":
unrendered = RenderComponents( unrendered = RenderComponents(
project_dict=self.project_dict, project_dict=self.project_dict,
packages_dict=self.packages_dict, packages_dict=self.packages_dict,
@@ -319,14 +307,12 @@ class PartialProject(RenderComponents):
verify_version=self.verify_version, verify_version=self.verify_version,
) )
self.check_config_path(rendered.project_dict, 'source-paths', 'model-paths') self.check_config_path(rendered.project_dict, "source-paths", "model-paths")
self.check_config_path(rendered.project_dict, 'data-paths', 'seed-paths') self.check_config_path(rendered.project_dict, "data-paths", "seed-paths")
try: try:
ProjectContract.validate(rendered.project_dict) ProjectContract.validate(rendered.project_dict)
cfg = ProjectContract.from_dict( cfg = ProjectContract.from_dict(rendered.project_dict)
rendered.project_dict
)
except ValidationError as e: except ValidationError as e:
raise DbtProjectError(validator_error_message(e)) from e raise DbtProjectError(validator_error_message(e)) from e
# name/version are required in the Project definition, so we can assume # name/version are required in the Project definition, so we can assume
@@ -336,7 +322,7 @@ class PartialProject(RenderComponents):
# this is added at project_dict parse time and should always be here # this is added at project_dict parse time and should always be here
# once we see it. # once we see it.
if cfg.project_root is None: if cfg.project_root is None:
raise DbtProjectError('cfg must have a project root!') raise DbtProjectError("cfg must have a project root!")
else: else:
project_root = cfg.project_root project_root = cfg.project_root
# this is only optional in the sense that if it's not present, it needs # this is only optional in the sense that if it's not present, it needs
@@ -346,30 +332,30 @@ class PartialProject(RenderComponents):
# `source_paths` is deprecated but still allowed. Copy it into # `source_paths` is deprecated but still allowed. Copy it into
# `model_paths` to simlify logic throughout the rest of the system. # `model_paths` to simlify logic throughout the rest of the system.
model_paths: List[str] = value_or(cfg.model_paths model_paths: List[str] = value_or(
if 'model-paths' in rendered.project_dict cfg.model_paths if "model-paths" in rendered.project_dict else cfg.source_paths,
else cfg.source_paths, ['models']) ["models"],
macro_paths: List[str] = value_or(cfg.macro_paths, ['macros']) )
macro_paths: List[str] = value_or(cfg.macro_paths, ["macros"])
# `data_paths` is deprecated but still allowed. Copy it into # `data_paths` is deprecated but still allowed. Copy it into
# `seed_paths` to simlify logic throughout the rest of the system. # `seed_paths` to simlify logic throughout the rest of the system.
seed_paths: List[str] = value_or(cfg.seed_paths seed_paths: List[str] = value_or(
if 'seed-paths' in rendered.project_dict cfg.seed_paths if "seed-paths" in rendered.project_dict else cfg.data_paths, ["seeds"]
else cfg.data_paths, ['seeds']) )
test_paths: List[str] = value_or(cfg.test_paths, ['tests']) test_paths: List[str] = value_or(cfg.test_paths, ["tests"])
analysis_paths: List[str] = value_or(cfg.analysis_paths, ['analyses']) analysis_paths: List[str] = value_or(cfg.analysis_paths, ["analyses"])
snapshot_paths: List[str] = value_or(cfg.snapshot_paths, ['snapshots']) snapshot_paths: List[str] = value_or(cfg.snapshot_paths, ["snapshots"])
all_source_paths: List[str] = _all_source_paths( all_source_paths: List[str] = _all_source_paths(
model_paths, seed_paths, snapshot_paths, analysis_paths, model_paths, seed_paths, snapshot_paths, analysis_paths, macro_paths
macro_paths
) )
docs_paths: List[str] = value_or(cfg.docs_paths, all_source_paths) docs_paths: List[str] = value_or(cfg.docs_paths, all_source_paths)
asset_paths: List[str] = value_or(cfg.asset_paths, []) asset_paths: List[str] = value_or(cfg.asset_paths, [])
target_path: str = value_or(cfg.target_path, 'target') target_path: str = value_or(cfg.target_path, "target")
clean_targets: List[str] = value_or(cfg.clean_targets, [target_path]) clean_targets: List[str] = value_or(cfg.clean_targets, [target_path])
log_path: str = value_or(cfg.log_path, 'logs') log_path: str = value_or(cfg.log_path, "logs")
packages_install_path: str = value_or(cfg.packages_install_path, 'dbt_packages') packages_install_path: str = value_or(cfg.packages_install_path, "dbt_packages")
# in the default case we'll populate this once we know the adapter type # in the default case we'll populate this once we know the adapter type
# It would be nice to just pass along a Quoting here, but that would # It would be nice to just pass along a Quoting here, but that would
# break many things # break many things
@@ -397,6 +383,8 @@ class PartialProject(RenderComponents):
vars_dict = cfg.vars vars_dict = cfg.vars
vars_value = VarProvider(vars_dict) vars_value = VarProvider(vars_dict)
# There will never be any project_env_vars when it's first created
project_env_vars: Dict[str, Any] = {}
on_run_start: List[str] = value_or(cfg.on_run_start, []) on_run_start: List[str] = value_or(cfg.on_run_start, [])
on_run_end: List[str] = value_or(cfg.on_run_end, []) on_run_end: List[str] = value_or(cfg.on_run_end, [])
@@ -405,11 +393,12 @@ class PartialProject(RenderComponents):
packages = package_config_from_data(rendered.packages_dict) packages = package_config_from_data(rendered.packages_dict)
selectors = selector_config_from_data(rendered.selectors_dict) selectors = selector_config_from_data(rendered.selectors_dict)
manifest_selectors: Dict[str, Any] = {} manifest_selectors: Dict[str, Any] = {}
if rendered.selectors_dict and rendered.selectors_dict['selectors']: if rendered.selectors_dict and rendered.selectors_dict["selectors"]:
# this is a dict with a single key 'selectors' pointing to a list # this is a dict with a single key 'selectors' pointing to a list
# of dicts. # of dicts.
manifest_selectors = SelectorDict.parse_from_selectors_list( manifest_selectors = SelectorDict.parse_from_selectors_list(
rendered.selectors_dict['selectors']) rendered.selectors_dict["selectors"]
)
project = Project( project = Project(
project_name=name, project_name=name,
version=version, version=version,
@@ -444,6 +433,7 @@ class PartialProject(RenderComponents):
vars=vars_value, vars=vars_value,
config_version=cfg.config_version, config_version=cfg.config_version,
unrendered=unrendered, unrendered=unrendered,
project_env_vars=project_env_vars,
) )
# sanity check - this means an internal issue # sanity check - this means an internal issue
project.validate() project.validate()
@@ -459,10 +449,9 @@ class PartialProject(RenderComponents):
*, *,
verify_version: bool = False, verify_version: bool = False,
): ):
"""Construct a partial project from its constituent dicts. """Construct a partial project from its constituent dicts."""
""" project_name = project_dict.get("name")
project_name = project_dict.get('name') profile_name = project_dict.get("profile")
profile_name = project_dict.get('profile')
return cls( return cls(
profile_name=profile_name, profile_name=profile_name,
@@ -477,14 +466,14 @@ class PartialProject(RenderComponents):
@classmethod @classmethod
def from_project_root( def from_project_root(
cls, project_root: str, *, verify_version: bool = False cls, project_root: str, *, verify_version: bool = False
) -> 'PartialProject': ) -> "PartialProject":
project_root = os.path.normpath(project_root) project_root = os.path.normpath(project_root)
project_dict = _raw_project_from(project_root) project_dict = _raw_project_from(project_root)
config_version = project_dict.get('config-version', 1) config_version = project_dict.get("config-version", 1)
if config_version != 2: if config_version != 2:
raise DbtProjectError( raise DbtProjectError(
f'Invalid config version: {config_version}, expected 2', f"Invalid config version: {config_version}, expected 2",
path=os.path.join(project_root, 'dbt_project.yml') path=os.path.join(project_root, "dbt_project.yml"),
) )
packages_dict = package_data_from_root(project_root) packages_dict = package_data_from_root(project_root)
@@ -501,15 +490,10 @@ class PartialProject(RenderComponents):
class VarProvider: class VarProvider:
"""Var providers are tied to a particular Project.""" """Var providers are tied to a particular Project."""
def __init__( def __init__(self, vars: Dict[str, Dict[str, Any]]) -> None:
self,
vars: Dict[str, Dict[str, Any]]
) -> None:
self.vars = vars self.vars = vars
def vars_for( def vars_for(self, node: IsFQNResource, adapter_type: str) -> Mapping[str, Any]:
self, node: IsFQNResource, adapter_type: str
) -> Mapping[str, Any]:
# in v2, vars are only either project or globally scoped # in v2, vars are only either project or globally scoped
merged = MultiDict([self.vars]) merged = MultiDict([self.vars])
merged.add(self.vars.get(node.package_name, {})) merged.add(self.vars.get(node.package_name, {}))
@@ -556,24 +540,35 @@ class Project:
query_comment: QueryComment query_comment: QueryComment
config_version: int config_version: int
unrendered: RenderComponents unrendered: RenderComponents
project_env_vars: Dict[str, Any]
@property @property
def all_source_paths(self) -> List[str]: def all_source_paths(self) -> List[str]:
return _all_source_paths( return _all_source_paths(
self.model_paths, self.seed_paths, self.snapshot_paths, self.model_paths,
self.analysis_paths, self.macro_paths self.seed_paths,
self.snapshot_paths,
self.analysis_paths,
self.macro_paths,
) )
@property
def generic_test_paths(self):
generic_test_paths = []
for test_path in self.test_paths:
generic_test_paths.append(os.path.join(test_path, "generic"))
return generic_test_paths
def __str__(self): def __str__(self):
cfg = self.to_project_config(with_packages=True) cfg = self.to_project_config(with_packages=True)
return str(cfg) return str(cfg)
def __eq__(self, other): def __eq__(self, other):
if not (isinstance(other, self.__class__) and if not (isinstance(other, self.__class__) and isinstance(self, other.__class__)):
isinstance(self, other.__class__)):
return False return False
return self.to_project_config(with_packages=True) == \ return self.to_project_config(with_packages=True) == other.to_project_config(
other.to_project_config(with_packages=True) with_packages=True
)
def to_project_config(self, with_packages=False): def to_project_config(self, with_packages=False):
"""Return a dict representation of the config that could be written to """Return a dict representation of the config that could be written to
@@ -583,40 +578,39 @@ class Project:
file in the root. file in the root.
:returns dict: The serialized profile. :returns dict: The serialized profile.
""" """
result = deepcopy({ result = deepcopy(
'name': self.project_name, {
'version': self.version, "name": self.project_name,
'project-root': self.project_root, "version": self.version,
'profile': self.profile_name, "project-root": self.project_root,
'model-paths': self.model_paths, "profile": self.profile_name,
'macro-paths': self.macro_paths, "model-paths": self.model_paths,
'seed-paths': self.seed_paths, "macro-paths": self.macro_paths,
'test-paths': self.test_paths, "seed-paths": self.seed_paths,
'analysis-paths': self.analysis_paths, "test-paths": self.test_paths,
'docs-paths': self.docs_paths, "analysis-paths": self.analysis_paths,
'asset-paths': self.asset_paths, "docs-paths": self.docs_paths,
'target-path': self.target_path, "asset-paths": self.asset_paths,
'snapshot-paths': self.snapshot_paths, "target-path": self.target_path,
'clean-targets': self.clean_targets, "snapshot-paths": self.snapshot_paths,
'log-path': self.log_path, "clean-targets": self.clean_targets,
'quoting': self.quoting, "log-path": self.log_path,
'models': self.models, "quoting": self.quoting,
'on-run-start': self.on_run_start, "models": self.models,
'on-run-end': self.on_run_end, "on-run-start": self.on_run_start,
'dispatch': self.dispatch, "on-run-end": self.on_run_end,
'seeds': self.seeds, "dispatch": self.dispatch,
'snapshots': self.snapshots, "seeds": self.seeds,
'sources': self.sources, "snapshots": self.snapshots,
'tests': self.tests, "sources": self.sources,
'vars': self.vars.to_dict(), "tests": self.tests,
'require-dbt-version': [ "vars": self.vars.to_dict(),
v.to_version_string() for v in self.dbt_version "require-dbt-version": [v.to_version_string() for v in self.dbt_version],
], "config-version": self.config_version,
'config-version': self.config_version, }
}) )
if self.query_comment: if self.query_comment:
result['query-comment'] = \ result["query-comment"] = self.query_comment.to_dict(omit_none=True)
self.query_comment.to_dict(omit_none=True)
if with_packages: if with_packages:
result.update(self.packages.to_dict(omit_none=True)) result.update(self.packages.to_dict(omit_none=True))
@@ -630,34 +624,12 @@ class Project:
raise DbtProjectError(validator_error_message(e)) from e raise DbtProjectError(validator_error_message(e)) from e
@classmethod @classmethod
def partial_load( def partial_load(cls, project_root: str, *, verify_version: bool = False) -> PartialProject:
cls, project_root: str, *, verify_version: bool = False
) -> PartialProject:
return PartialProject.from_project_root( return PartialProject.from_project_root(
project_root, project_root,
verify_version=verify_version, verify_version=verify_version,
) )
@classmethod
def render_from_dict(
cls,
project_root: str,
project_dict: Dict[str, Any],
packages_dict: Dict[str, Any],
selectors_dict: Dict[str, Any],
renderer: DbtProjectYamlRenderer,
*,
verify_version: bool = False
) -> 'Project':
partial = PartialProject.from_dicts(
project_root=project_root,
project_dict=project_dict,
packages_dict=packages_dict,
selectors_dict=selectors_dict,
verify_version=verify_version,
)
return partial.render(renderer)
@classmethod @classmethod
def from_project_root( def from_project_root(
cls, cls,
@@ -665,18 +637,17 @@ class Project:
renderer: DbtProjectYamlRenderer, renderer: DbtProjectYamlRenderer,
*, *,
verify_version: bool = False, verify_version: bool = False,
) -> 'Project': ) -> "Project":
partial = cls.partial_load(project_root, verify_version=verify_version) partial = cls.partial_load(project_root, verify_version=verify_version)
return partial.render(renderer) return partial.render(renderer)
def hashed_name(self): def hashed_name(self):
return hashlib.md5(self.project_name.encode('utf-8')).hexdigest() return hashlib.md5(self.project_name.encode("utf-8")).hexdigest()
def get_selector(self, name: str) -> Union[SelectionSpec, bool]: def get_selector(self, name: str) -> Union[SelectionSpec, bool]:
if name not in self.selectors: if name not in self.selectors:
raise RuntimeException( raise RuntimeException(
f'Could not find selector named {name}, expected one of ' f"Could not find selector named {name}, expected one of " f"{list(self.selectors)}"
f'{list(self.selectors)}'
) )
return self.selectors[name]["definition"] return self.selectors[name]["definition"]
@@ -693,6 +664,6 @@ class Project:
def get_macro_search_order(self, macro_namespace: str): def get_macro_search_order(self, macro_namespace: str):
for dispatch_entry in self.dispatch: for dispatch_entry in self.dispatch:
if dispatch_entry['macro_namespace'] == macro_namespace: if dispatch_entry["macro_namespace"] == macro_namespace:
return dispatch_entry['search_order'] return dispatch_entry["search_order"]
return None return None

View File

@@ -1,12 +1,12 @@
from typing import Dict, Any, Tuple, Optional, Union, Callable from typing import Dict, Any, Tuple, Optional, Union, Callable
from dbt.clients.jinja import get_rendered, catch_jinja from dbt.clients.jinja import get_rendered, catch_jinja
from dbt.context.target import TargetContext
from dbt.exceptions import ( from dbt.context.secret import SecretContext
DbtProjectError, CompilationException, RecursionException from dbt.context.base import BaseContext
) from dbt.contracts.connection import HasCredentials
from dbt.node_types import NodeType from dbt.exceptions import DbtProjectError, CompilationException, RecursionException
from dbt.utils import deep_map from dbt.utils import deep_map_render
Keypath = Tuple[Union[str, int], ...] Keypath = Tuple[Union[str, int], ...]
@@ -18,7 +18,7 @@ class BaseRenderer:
@property @property
def name(self): def name(self):
return 'Rendering' return "Rendering"
def should_render_keypath(self, keypath: Keypath) -> bool: def should_render_keypath(self, keypath: Keypath) -> bool:
return True return True
@@ -29,9 +29,7 @@ class BaseRenderer:
return self.render_value(value, keypath) return self.render_value(value, keypath)
def render_value( def render_value(self, value: Any, keypath: Optional[Keypath] = None) -> Any:
self, value: Any, keypath: Optional[Keypath] = None
) -> Any:
# keypath is ignored. # keypath is ignored.
# if it wasn't read as a string, ignore it # if it wasn't read as a string, ignore it
if not isinstance(value, str): if not isinstance(value, str):
@@ -40,18 +38,15 @@ class BaseRenderer:
with catch_jinja(): with catch_jinja():
return get_rendered(value, self.context, native=True) return get_rendered(value, self.context, native=True)
except CompilationException as exc: except CompilationException as exc:
msg = f'Could not render {value}: {exc.msg}' msg = f"Could not render {value}: {exc.msg}"
raise CompilationException(msg) from exc raise CompilationException(msg) from exc
def render_data( def render_data(self, data: Dict[str, Any]) -> Dict[str, Any]:
self, data: Dict[str, Any]
) -> Dict[str, Any]:
try: try:
return deep_map(self.render_entry, data) return deep_map_render(self.render_entry, data)
except RecursionException: except RecursionException:
raise DbtProjectError( raise DbtProjectError(
f'Cycle detected: {self.name} input has a reference to itself', f"Cycle detected: {self.name} input has a reference to itself", project=data
project=data
) )
@@ -78,15 +73,15 @@ class ProjectPostprocessor(Dict[Keypath, Callable[[Any], Any]]):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self[('on-run-start',)] = _list_if_none_or_string self[("on-run-start",)] = _list_if_none_or_string
self[('on-run-end',)] = _list_if_none_or_string self[("on-run-end",)] = _list_if_none_or_string
for k in ('models', 'seeds', 'snapshots'): for k in ("models", "seeds", "snapshots"):
self[(k,)] = _dict_if_none self[(k,)] = _dict_if_none
self[(k, 'vars')] = _dict_if_none self[(k, "vars")] = _dict_if_none
self[(k, 'pre-hook')] = _list_if_none_or_string self[(k, "pre-hook")] = _list_if_none_or_string
self[(k, 'post-hook')] = _list_if_none_or_string self[(k, "post-hook")] = _list_if_none_or_string
self[('seeds', 'column_types')] = _dict_if_none self[("seeds", "column_types")] = _dict_if_none
def postprocess(self, value: Any, key: Keypath) -> Any: def postprocess(self, value: Any, key: Keypath) -> Any:
if key in self: if key in self:
@@ -99,9 +94,25 @@ class ProjectPostprocessor(Dict[Keypath, Callable[[Any], Any]]):
class DbtProjectYamlRenderer(BaseRenderer): class DbtProjectYamlRenderer(BaseRenderer):
_KEYPATH_HANDLERS = ProjectPostprocessor() _KEYPATH_HANDLERS = ProjectPostprocessor()
def __init__(
self, profile: Optional[HasCredentials] = None, cli_vars: Optional[Dict[str, Any]] = None
) -> None:
# Generate contexts here because we want to save the context
# object in order to retrieve the env_vars. This is almost always
# a TargetContext, but in the debug task we want a project
# even when we don't have a profile.
if cli_vars is None:
cli_vars = {}
if profile:
self.ctx_obj = TargetContext(profile, cli_vars)
else:
self.ctx_obj = BaseContext(cli_vars) # type:ignore
context = self.ctx_obj.to_dict()
super().__init__(context)
@property @property
def name(self): def name(self):
'Project config' "Project config"
def get_package_renderer(self) -> BaseRenderer: def get_package_renderer(self) -> BaseRenderer:
return PackageRenderer(self.context) return PackageRenderer(self.context)
@@ -116,7 +127,7 @@ class DbtProjectYamlRenderer(BaseRenderer):
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Render the project and insert the project root after rendering.""" """Render the project and insert the project root after rendering."""
rendered_project = self.render_data(project) rendered_project = self.render_data(project)
rendered_project['project-root'] = project_root rendered_project["project-root"] = project_root
return rendered_project return rendered_project
def render_packages(self, packages: Dict[str, Any]): def render_packages(self, packages: Dict[str, Any]):
@@ -138,101 +149,50 @@ class DbtProjectYamlRenderer(BaseRenderer):
first = keypath[0] first = keypath[0]
# run hooks are not rendered # run hooks are not rendered
if first in {'on-run-start', 'on-run-end', 'query-comment'}: if first in {"on-run-start", "on-run-end", "query-comment"}:
return False return False
# don't render vars blocks until runtime # don't render vars blocks until runtime
if first == 'vars': if first == "vars":
return False return False
if first in {'seeds', 'models', 'snapshots', 'tests'}: if first in {"seeds", "models", "snapshots", "tests"}:
keypath_parts = { keypath_parts = {(k.lstrip("+ ") if isinstance(k, str) else k) for k in keypath}
(k.lstrip('+ ') if isinstance(k, str) else k)
for k in keypath
}
# model-level hooks # model-level hooks
if 'pre-hook' in keypath_parts or 'post-hook' in keypath_parts: if "pre-hook" in keypath_parts or "post-hook" in keypath_parts:
return False return False
return True return True
class ProfileRenderer(BaseRenderer):
@property
def name(self):
'Profile'
class SchemaYamlRenderer(BaseRenderer):
DOCUMENTABLE_NODES = frozenset(
n.pluralize() for n in NodeType.documentable()
)
@property
def name(self):
return 'Rendering yaml'
def _is_norender_key(self, keypath: Keypath) -> bool:
"""
models:
- name: blah
- description: blah
tests: ...
- columns:
- name:
- description: blah
tests: ...
Return True if it's tests or description - those aren't rendered
"""
if len(keypath) >= 2 and keypath[1] in ('tests', 'description'):
return True
if (
len(keypath) >= 4 and
keypath[1] == 'columns' and
keypath[3] in ('tests', 'description')
):
return True
return False
# don't render descriptions or test keyword arguments
def should_render_keypath(self, keypath: Keypath) -> bool:
if len(keypath) < 2:
return True
if keypath[0] not in self.DOCUMENTABLE_NODES:
return True
if len(keypath) < 3:
return True
if keypath[0] == NodeType.Source.pluralize():
if keypath[2] == 'description':
return False
if keypath[2] == 'tables':
if self._is_norender_key(keypath[3:]):
return False
elif keypath[0] == NodeType.Macro.pluralize():
if keypath[2] == 'arguments':
if self._is_norender_key(keypath[3:]):
return False
elif self._is_norender_key(keypath[1:]):
return False
else: # keypath[0] in self.DOCUMENTABLE_NODES:
if self._is_norender_key(keypath[1:]):
return False
return True
class PackageRenderer(BaseRenderer):
@property
def name(self):
return 'Packages config'
class SelectorRenderer(BaseRenderer): class SelectorRenderer(BaseRenderer):
@property @property
def name(self): def name(self):
return 'Selector config' return "Selector config"
class SecretRenderer(BaseRenderer):
def __init__(self, cli_vars: Optional[Dict[str, Any]] = None) -> None:
# Generate contexts here because we want to save the context
# object in order to retrieve the env_vars.
if cli_vars is None:
cli_vars = {}
self.ctx_obj = SecretContext(cli_vars)
context = self.ctx_obj.to_dict()
super().__init__(context)
@property
def name(self):
return "Secret"
class ProfileRenderer(SecretRenderer):
@property
def name(self):
return "Profile"
class PackageRenderer(SecretRenderer):
@property
def name(self):
return "Packages config"

View File

@@ -1,45 +1,36 @@
import itertools import itertools
import os import os
from copy import deepcopy from copy import deepcopy
from dataclasses import dataclass, fields from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import ( from typing import Dict, Any, Optional, Mapping, Iterator, Iterable, Tuple, List, MutableSet, Type
Dict, Any, Optional, Mapping, Iterator, Iterable, Tuple, List, MutableSet,
Type
)
from .profile import Profile from .profile import Profile
from .project import Project from .project import Project
from .renderer import DbtProjectYamlRenderer, ProfileRenderer from .renderer import DbtProjectYamlRenderer, ProfileRenderer
from .utils import parse_cli_vars from .utils import parse_cli_vars
from dbt import flags from dbt import flags
from dbt import tracking
from dbt.adapters.factory import get_relation_class_by_name, get_include_paths from dbt.adapters.factory import get_relation_class_by_name, get_include_paths
from dbt.helper_types import FQNPath, PathSet from dbt.helper_types import FQNPath, PathSet, DictDefaultEmptyStr
from dbt.context.base import generate_base_context from dbt.config.profile import read_user_config
from dbt.context.target import generate_target_context
from dbt.contracts.connection import AdapterRequiredConfig, Credentials from dbt.contracts.connection import AdapterRequiredConfig, Credentials
from dbt.contracts.graph.manifest import ManifestMetadata from dbt.contracts.graph.manifest import ManifestMetadata
from dbt.contracts.relation import ComponentName from dbt.contracts.relation import ComponentName
from dbt.logger import GLOBAL_LOGGER as logger
from dbt.ui import warning_tag from dbt.ui import warning_tag
from dbt.contracts.project import Configuration, UserConfig from dbt.contracts.project import Configuration, UserConfig
from dbt.exceptions import ( from dbt.exceptions import (
RuntimeException, RuntimeException,
DbtProfileError,
DbtProjectError, DbtProjectError,
validator_error_message, validator_error_message,
warn_or_error, warn_or_error,
raise_compiler_error raise_compiler_error,
) )
from dbt.dataclass_schema import ValidationError from dbt.dataclass_schema import ValidationError
def _project_quoting_dict( def _project_quoting_dict(proj: Project, profile: Profile) -> Dict[ComponentName, bool]:
proj: Project, profile: Profile
) -> Dict[ComponentName, bool]:
src: Dict[str, Any] = profile.credentials.translate_aliases(proj.quoting) src: Dict[str, Any] = profile.credentials.translate_aliases(proj.quoting)
result: Dict[ComponentName, bool] = {} result: Dict[ComponentName, bool] = {}
for key in ComponentName: for key in ComponentName:
@@ -55,19 +46,20 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
args: Any args: Any
profile_name: str profile_name: str
cli_vars: Dict[str, Any] cli_vars: Dict[str, Any]
dependencies: Optional[Mapping[str, 'RuntimeConfig']] = None dependencies: Optional[Mapping[str, "RuntimeConfig"]] = None
def __post_init__(self): def __post_init__(self):
self.validate() self.validate()
# Called by 'new_project' and 'from_args'
@classmethod @classmethod
def from_parts( def from_parts(
cls, cls,
project: Project, project: Project,
profile: Profile, profile: Profile,
args: Any, args: Any,
dependencies: Optional[Mapping[str, 'RuntimeConfig']] = None, dependencies: Optional[Mapping[str, "RuntimeConfig"]] = None,
) -> 'RuntimeConfig': ) -> "RuntimeConfig":
"""Instantiate a RuntimeConfig from its components. """Instantiate a RuntimeConfig from its components.
:param profile: A parsed dbt Profile. :param profile: A parsed dbt Profile.
@@ -81,7 +73,7 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
.replace_dict(_project_quoting_dict(project, profile)) .replace_dict(_project_quoting_dict(project, profile))
).to_dict(omit_none=True) ).to_dict(omit_none=True)
cli_vars: Dict[str, Any] = parse_cli_vars(getattr(args, 'vars', '{}')) cli_vars: Dict[str, Any] = parse_cli_vars(getattr(args, "vars", "{}"))
return cls( return cls(
project_name=project.project_name, project_name=project.project_name,
@@ -116,6 +108,8 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
vars=project.vars, vars=project.vars,
config_version=project.config_version, config_version=project.config_version,
unrendered=project.unrendered, unrendered=project.unrendered,
project_env_vars=project.project_env_vars,
profile_env_vars=profile.profile_env_vars,
profile_name=profile.profile_name, profile_name=profile.profile_name,
target_name=profile.target_name, target_name=profile.target_name,
user_config=profile.user_config, user_config=profile.user_config,
@@ -126,7 +120,8 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
dependencies=dependencies, dependencies=dependencies,
) )
def new_project(self, project_root: str) -> 'RuntimeConfig': # Called by 'load_projects' in this class
def new_project(self, project_root: str) -> "RuntimeConfig":
"""Given a new project root, read in its project dictionary, supply the """Given a new project root, read in its project dictionary, supply the
existing project's profile info, and create a new project file. existing project's profile info, and create a new project file.
@@ -140,7 +135,7 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
profile.validate() profile.validate()
# load the new project and its packages. Don't pass cli variables. # load the new project and its packages. Don't pass cli variables.
renderer = DbtProjectYamlRenderer(generate_target_context(profile, {})) renderer = DbtProjectYamlRenderer(profile)
project = Project.from_project_root( project = Project.from_project_root(
project_root, project_root,
@@ -148,14 +143,14 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
verify_version=bool(flags.VERSION_CHECK), verify_version=bool(flags.VERSION_CHECK),
) )
cfg = self.from_parts( runtime_config = self.from_parts(
project=project, project=project,
profile=profile, profile=profile,
args=deepcopy(self.args), args=deepcopy(self.args),
) )
# force our quoting back onto the new project. # force our quoting back onto the new project.
cfg.quoting = deepcopy(self.quoting) runtime_config.quoting = deepcopy(self.quoting)
return cfg return runtime_config
def serialize(self) -> Dict[str, Any]: def serialize(self) -> Dict[str, Any]:
"""Serialize the full configuration to a single dictionary. For any """Serialize the full configuration to a single dictionary. For any
@@ -168,7 +163,7 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
""" """
result = self.to_project_config(with_packages=True) result = self.to_project_config(with_packages=True)
result.update(self.to_profile_info(serialize_credentials=True)) result.update(self.to_profile_info(serialize_credentials=True))
result['cli_vars'] = deepcopy(self.cli_vars) result["cli_vars"] = deepcopy(self.cli_vars)
return result return result
def validate(self): def validate(self):
@@ -188,40 +183,37 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
profile_renderer: ProfileRenderer, profile_renderer: ProfileRenderer,
profile_name: Optional[str], profile_name: Optional[str],
) -> Profile: ) -> Profile:
return Profile.render_from_args(
args, profile_renderer, profile_name return Profile.render_from_args(args, profile_renderer, profile_name)
)
@classmethod @classmethod
def collect_parts( def collect_parts(cls: Type["RuntimeConfig"], args: Any) -> Tuple[Project, Profile]:
cls: Type['RuntimeConfig'], args: Any
) -> Tuple[Project, Profile]:
# profile_name from the project # profile_name from the project
project_root = args.project_dir if args.project_dir else os.getcwd() project_root = args.project_dir if args.project_dir else os.getcwd()
version_check = bool(flags.VERSION_CHECK) version_check = bool(flags.VERSION_CHECK)
partial = Project.partial_load( partial = Project.partial_load(project_root, verify_version=version_check)
project_root,
verify_version=version_check
)
# build the profile using the base renderer and the one fact we know # build the profile using the base renderer and the one fact we know
cli_vars: Dict[str, Any] = parse_cli_vars(getattr(args, 'vars', '{}')) # Note: only the named profile section is rendered. The rest of the
profile_renderer = ProfileRenderer(generate_base_context(cli_vars)) # profile is ignored.
cli_vars: Dict[str, Any] = parse_cli_vars(getattr(args, "vars", "{}"))
profile_renderer = ProfileRenderer(cli_vars)
profile_name = partial.render_profile_name(profile_renderer) profile_name = partial.render_profile_name(profile_renderer)
profile = cls._get_rendered_profile(args, profile_renderer, profile_name)
profile = cls._get_rendered_profile( # Save env_vars encountered in rendering for partial parsing
args, profile_renderer, profile_name profile.profile_env_vars = profile_renderer.ctx_obj.env_vars
)
# get a new renderer using our target information and render the # get a new renderer using our target information and render the
# project # project
ctx = generate_target_context(profile, cli_vars) project_renderer = DbtProjectYamlRenderer(profile, cli_vars)
project_renderer = DbtProjectYamlRenderer(ctx)
project = partial.render(project_renderer) project = partial.render(project_renderer)
# Save env_vars encountered in rendering for partial parsing
project.project_env_vars = project_renderer.ctx_obj.env_vars
return (project, profile) return (project, profile)
# Called in main.py, lib.py, task/base.py
@classmethod @classmethod
def from_args(cls, args: Any) -> 'RuntimeConfig': def from_args(cls, args: Any) -> "RuntimeConfig":
"""Given arguments, read in dbt_project.yml from the current directory, """Given arguments, read in dbt_project.yml from the current directory,
read in packages.yml if it exists, and use them to find the profile to read in packages.yml if it exists, and use them to find the profile to
load. load.
@@ -240,10 +232,7 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
) )
def get_metadata(self) -> ManifestMetadata: def get_metadata(self) -> ManifestMetadata:
return ManifestMetadata( return ManifestMetadata(project_id=self.hashed_name(), adapter_type=self.credentials.type)
project_id=self.hashed_name(),
adapter_type=self.credentials.type
)
def _get_v2_config_paths( def _get_v2_config_paths(
self, self,
@@ -252,8 +241,8 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
paths: MutableSet[FQNPath], paths: MutableSet[FQNPath],
) -> PathSet: ) -> PathSet:
for key, value in config.items(): for key, value in config.items():
if isinstance(value, dict) and not key.startswith('+'): if isinstance(value, dict) and not key.startswith("+"):
self._get_v2_config_paths(value, path + (key,), paths) self._get_config_paths(value, path + (key,), paths)
else: else:
paths.add(path) paths.add(path)
return frozenset(paths) return frozenset(paths)
@@ -268,7 +257,7 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
paths = set() paths = set()
for key, value in config.items(): for key, value in config.items():
if isinstance(value, dict) and not key.startswith('+'): if isinstance(value, dict) and not key.startswith("+"):
self._get_v2_config_paths(value, path + (key,), paths) self._get_v2_config_paths(value, path + (key,), paths)
else: else:
paths.add(path) paths.add(path)
@@ -280,11 +269,11 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
a configured path in the resource. a configured path in the resource.
""" """
return { return {
'models': self._get_config_paths(self.models), "models": self._get_config_paths(self.models),
'seeds': self._get_config_paths(self.seeds), "seeds": self._get_config_paths(self.seeds),
'snapshots': self._get_config_paths(self.snapshots), "snapshots": self._get_config_paths(self.snapshots),
'sources': self._get_config_paths(self.sources), "sources": self._get_config_paths(self.sources),
'tests': self._get_config_paths(self.tests), "tests": self._get_config_paths(self.tests),
} }
def get_unused_resource_config_paths( def get_unused_resource_config_paths(
@@ -305,9 +294,7 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
for config_path in config_paths: for config_path in config_paths:
if not _is_config_used(config_path, fqns): if not _is_config_used(config_path, fqns):
unused_resource_config_paths.append( unused_resource_config_paths.append((resource_type,) + config_path)
(resource_type,) + config_path
)
return unused_resource_config_paths return unused_resource_config_paths
def warn_for_unused_resource_config_paths( def warn_for_unused_resource_config_paths(
@@ -320,13 +307,12 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
return return
msg = UNUSED_RESOURCE_CONFIGURATION_PATH_MESSAGE.format( msg = UNUSED_RESOURCE_CONFIGURATION_PATH_MESSAGE.format(
len(unused), len(unused), "\n".join("- {}".format(".".join(u)) for u in unused)
'\n'.join('- {}'.format('.'.join(u)) for u in unused)
) )
warn_or_error(msg, log_fmt=warning_tag('{}')) warn_or_error(msg, log_fmt=warning_tag("{}"))
def load_dependencies(self) -> Mapping[str, 'RuntimeConfig']: def load_dependencies(self) -> Mapping[str, "RuntimeConfig"]:
if self.dependencies is None: if self.dependencies is None:
all_projects = {self.project_name: self} all_projects = {self.project_name: self}
internal_packages = get_include_paths(self.credentials.type) internal_packages = get_include_paths(self.credentials.type)
@@ -335,23 +321,20 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
count_packages_installed = len(tuple(self._get_project_directories())) count_packages_installed = len(tuple(self._get_project_directories()))
if count_packages_specified > count_packages_installed: if count_packages_specified > count_packages_installed:
raise_compiler_error( raise_compiler_error(
f'dbt found {count_packages_specified} package(s) ' f"dbt found {count_packages_specified} package(s) "
f'specified in packages.yml, but only ' f"specified in packages.yml, but only "
f'{count_packages_installed} package(s) installed ' f"{count_packages_installed} package(s) installed "
f'in {self.packages_install_path}. Run "dbt deps" to ' f'in {self.packages_install_path}. Run "dbt deps" to '
f'install package dependencies.' f"install package dependencies."
)
project_paths = itertools.chain(
internal_packages,
self._get_project_directories()
) )
project_paths = itertools.chain(internal_packages, self._get_project_directories())
for project_name, project in self.load_projects(project_paths): for project_name, project in self.load_projects(project_paths):
if project_name in all_projects: if project_name in all_projects:
raise_compiler_error( raise_compiler_error(
f'dbt found more than one package with the name ' f"dbt found more than one package with the name "
f'"{project_name}" included in this project. Package ' f'"{project_name}" included in this project. Package '
f'names must be unique in a project. Please rename ' f"names must be unique in a project. Please rename "
f'one of these packages.' f"one of these packages."
) )
all_projects[project_name] = project all_projects[project_name] = project
self.dependencies = all_projects self.dependencies = all_projects
@@ -360,16 +343,15 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
def clear_dependencies(self): def clear_dependencies(self):
self.dependencies = None self.dependencies = None
def load_projects( # Called by 'load_dependencies' in this class
self, paths: Iterable[Path] def load_projects(self, paths: Iterable[Path]) -> Iterator[Tuple[str, "RuntimeConfig"]]:
) -> Iterator[Tuple[str, 'RuntimeConfig']]:
for path in paths: for path in paths:
try: try:
project = self.new_project(str(path)) project = self.new_project(str(path))
except DbtProjectError as e: except DbtProjectError as e:
raise DbtProjectError( raise DbtProjectError(
f'Failed to read package: {e}', f"Failed to read package: {e}",
result_type='invalid_project', result_type="invalid_project",
path=path, path=path,
) from e ) from e
else: else:
@@ -380,13 +362,13 @@ class RuntimeConfig(Project, Profile, AdapterRequiredConfig):
if root.exists(): if root.exists():
for path in root.iterdir(): for path in root.iterdir():
if path.is_dir() and not path.name.startswith('__'): if path.is_dir() and not path.name.startswith("__"):
yield path yield path
class UnsetCredentials(Credentials): class UnsetCredentials(Credentials):
def __init__(self): def __init__(self):
super().__init__('', '') super().__init__("", "")
@property @property
def type(self): def type(self):
@@ -403,37 +385,28 @@ class UnsetCredentials(Credentials):
return () return ()
class UnsetConfig(UserConfig): # This is used by UnsetProfileConfig, for commands which do
def __getattribute__(self, name): # not require a profile, i.e. dbt deps and clean
if name in {f.name for f in fields(UserConfig)}:
raise AttributeError(
f"'UnsetConfig' object has no attribute {name}"
)
def __post_serialize__(self, dct):
return {}
class UnsetProfile(Profile): class UnsetProfile(Profile):
def __init__(self): def __init__(self):
self.credentials = UnsetCredentials() self.credentials = UnsetCredentials()
self.user_config = UnsetConfig() self.user_config = UserConfig() # This will be read in _get_rendered_profile
self.profile_name = '' self.profile_name = ""
self.target_name = '' self.target_name = ""
self.threads = -1 self.threads = -1
def to_target_dict(self): def to_target_dict(self):
return {} return DictDefaultEmptyStr({})
def __getattribute__(self, name): def __getattribute__(self, name):
if name in {'profile_name', 'target_name', 'threads'}: if name in {"profile_name", "target_name", "threads"}:
raise RuntimeException( raise RuntimeException(f'Error: disallowed attribute "{name}" - no profile!')
f'Error: disallowed attribute "{name}" - no profile!'
)
return Profile.__getattribute__(self, name) return Profile.__getattribute__(self, name)
# This class is used by the dbt deps and clean commands, because they don't
# require a functioning profile.
@dataclass @dataclass
class UnsetProfileConfig(RuntimeConfig): class UnsetProfileConfig(RuntimeConfig):
"""This class acts a lot _like_ a RuntimeConfig, except if your profile is """This class acts a lot _like_ a RuntimeConfig, except if your profile is
@@ -450,17 +423,15 @@ class UnsetProfileConfig(RuntimeConfig):
def __getattribute__(self, name): def __getattribute__(self, name):
# Override __getattribute__ to check that the attribute isn't 'banned'. # Override __getattribute__ to check that the attribute isn't 'banned'.
if name in {'profile_name', 'target_name'}: if name in {"profile_name", "target_name"}:
raise RuntimeException( raise RuntimeException(f'Error: disallowed attribute "{name}" - no profile!')
f'Error: disallowed attribute "{name}" - no profile!'
)
# avoid every attribute access triggering infinite recursion # avoid every attribute access triggering infinite recursion
return RuntimeConfig.__getattribute__(self, name) return RuntimeConfig.__getattribute__(self, name)
def to_target_dict(self): def to_target_dict(self):
# re-override the poisoned profile behavior # re-override the poisoned profile behavior
return {} return DictDefaultEmptyStr({})
@classmethod @classmethod
def from_parts( def from_parts(
@@ -468,8 +439,8 @@ class UnsetProfileConfig(RuntimeConfig):
project: Project, project: Project,
profile: Profile, profile: Profile,
args: Any, args: Any,
dependencies: Optional[Mapping[str, 'RuntimeConfig']] = None, dependencies: Optional[Mapping[str, "RuntimeConfig"]] = None,
) -> 'RuntimeConfig': ) -> "RuntimeConfig":
"""Instantiate a RuntimeConfig from its components. """Instantiate a RuntimeConfig from its components.
:param profile: Ignored. :param profile: Ignored.
@@ -477,7 +448,7 @@ class UnsetProfileConfig(RuntimeConfig):
:param args: The parsed command-line arguments. :param args: The parsed command-line arguments.
:returns RuntimeConfig: The new configuration. :returns RuntimeConfig: The new configuration.
""" """
cli_vars: Dict[str, Any] = parse_cli_vars(getattr(args, 'vars', '{}')) cli_vars: Dict[str, Any] = parse_cli_vars(getattr(args, "vars", "{}"))
return cls( return cls(
project_name=project.project_name, project_name=project.project_name,
@@ -512,10 +483,12 @@ class UnsetProfileConfig(RuntimeConfig):
vars=project.vars, vars=project.vars,
config_version=project.config_version, config_version=project.config_version,
unrendered=project.unrendered, unrendered=project.unrendered,
profile_name='', project_env_vars=project.project_env_vars,
target_name='', profile_env_vars=profile.profile_env_vars,
user_config=UnsetConfig(), profile_name="",
threads=getattr(args, 'threads', 1), target_name="",
user_config=UserConfig(),
threads=getattr(args, "threads", 1),
credentials=UnsetCredentials(), credentials=UnsetCredentials(),
args=args, args=args,
cli_vars=cli_vars, cli_vars=cli_vars,
@@ -529,26 +502,16 @@ class UnsetProfileConfig(RuntimeConfig):
profile_renderer: ProfileRenderer, profile_renderer: ProfileRenderer,
profile_name: Optional[str], profile_name: Optional[str],
) -> Profile: ) -> Profile:
try:
profile = Profile.render_from_args(
args, profile_renderer, profile_name
)
except (DbtProjectError, DbtProfileError) as exc:
logger.debug(
'Profile not loaded due to error: {}', exc, exc_info=True
)
logger.info(
'No profile "{}" found, continuing with no target',
profile_name
)
# return the poisoned form
profile = UnsetProfile() profile = UnsetProfile()
# disable anonymous usage statistics # The profile (for warehouse connection) is not needed, but we want
tracking.disable_tracking() # to get the UserConfig, which is also in profiles.yml
user_config = read_user_config(flags.PROFILES_DIR)
profile.user_config = user_config
return profile return profile
@classmethod @classmethod
def from_args(cls: Type[RuntimeConfig], args: Any) -> 'RuntimeConfig': def from_args(cls: Type[RuntimeConfig], args: Any) -> "RuntimeConfig":
"""Given arguments, read in dbt_project.yml from the current directory, """Given arguments, read in dbt_project.yml from the current directory,
read in packages.yml if it exists, and use them to find the profile to read in packages.yml if it exists, and use them to find the profile to
load. load.
@@ -559,15 +522,8 @@ class UnsetProfileConfig(RuntimeConfig):
:raises ValidationException: If the cli variables are invalid. :raises ValidationException: If the cli variables are invalid.
""" """
project, profile = cls.collect_parts(args) project, profile = cls.collect_parts(args)
if not isinstance(profile, UnsetProfile):
# if it's a real profile, return a real config
cls = RuntimeConfig
return cls.from_parts( return cls.from_parts(project=project, profile=profile, args=args)
project=project,
profile=profile,
args=args
)
UNUSED_RESOURCE_CONFIGURATION_PATH_MESSAGE = """\ UNUSED_RESOURCE_CONFIGURATION_PATH_MESSAGE = """\
@@ -581,6 +537,6 @@ There are {} unused configuration paths:
def _is_config_used(path, fqns): def _is_config_used(path, fqns):
if fqns: if fqns:
for fqn in fqns: for fqn in fqns:
if len(path) <= len(fqn) and fqn[:len(path)] == path: if len(path) <= len(fqn) and fqn[: len(path)] == path:
return True return True
return False return False

View File

@@ -1,8 +1,6 @@
from pathlib import Path from pathlib import Path
from typing import Dict, Any, Union from typing import Dict, Any, Union
from dbt.clients.yaml_helper import ( # noqa: F401 from dbt.clients.yaml_helper import yaml, Loader, Dumper, load_yaml_text # noqa: F401
yaml, Loader, Dumper, load_yaml_text
)
from dbt.dataclass_schema import ValidationError from dbt.dataclass_schema import ValidationError
from .renderer import SelectorRenderer from .renderer import SelectorRenderer
@@ -30,9 +28,8 @@ Validator Error:
class SelectorConfig(Dict[str, Dict[str, Union[SelectionSpec, bool]]]): class SelectorConfig(Dict[str, Dict[str, Union[SelectionSpec, bool]]]):
@classmethod @classmethod
def selectors_from_dict(cls, data: Dict[str, Any]) -> 'SelectorConfig': def selectors_from_dict(cls, data: Dict[str, Any]) -> "SelectorConfig":
try: try:
SelectorFile.validate(data) SelectorFile.validate(data)
selector_file = SelectorFile.from_dict(data) selector_file = SelectorFile.from_dict(data)
@@ -46,12 +43,12 @@ class SelectorConfig(Dict[str, Dict[str, Union[SelectionSpec, bool]]]):
f"union, intersection, string, dictionary. No lists. " f"union, intersection, string, dictionary. No lists. "
f"\nhttps://docs.getdbt.com/reference/node-selection/" f"\nhttps://docs.getdbt.com/reference/node-selection/"
f"yaml-selectors", f"yaml-selectors",
result_type='invalid_selector' result_type="invalid_selector",
) from exc ) from exc
except RuntimeException as exc: except RuntimeException as exc:
raise DbtSelectorsError( raise DbtSelectorsError(
f'Could not read selector file data: {exc}', f"Could not read selector file data: {exc}",
result_type='invalid_selector', result_type="invalid_selector",
) from exc ) from exc
return cls(selectors) return cls(selectors)
@@ -61,26 +58,28 @@ class SelectorConfig(Dict[str, Dict[str, Union[SelectionSpec, bool]]]):
cls, cls,
data: Dict[str, Any], data: Dict[str, Any],
renderer: SelectorRenderer, renderer: SelectorRenderer,
) -> 'SelectorConfig': ) -> "SelectorConfig":
try: try:
rendered = renderer.render_data(data) rendered = renderer.render_data(data)
except (ValidationError, RuntimeException) as exc: except (ValidationError, RuntimeException) as exc:
raise DbtSelectorsError( raise DbtSelectorsError(
f'Could not render selector data: {exc}', f"Could not render selector data: {exc}",
result_type='invalid_selector', result_type="invalid_selector",
) from exc ) from exc
return cls.selectors_from_dict(rendered) return cls.selectors_from_dict(rendered)
@classmethod @classmethod
def from_path( def from_path(
cls, path: Path, renderer: SelectorRenderer, cls,
) -> 'SelectorConfig': path: Path,
renderer: SelectorRenderer,
) -> "SelectorConfig":
try: try:
data = load_yaml_text(load_file_contents(str(path))) data = load_yaml_text(load_file_contents(str(path)))
except (ValidationError, RuntimeException) as exc: except (ValidationError, RuntimeException) as exc:
raise DbtSelectorsError( raise DbtSelectorsError(
f'Could not read selector file: {exc}', f"Could not read selector file: {exc}",
result_type='invalid_selector', result_type="invalid_selector",
path=path, path=path,
) from exc ) from exc
@@ -92,9 +91,7 @@ class SelectorConfig(Dict[str, Dict[str, Union[SelectionSpec, bool]]]):
def selector_data_from_root(project_root: str) -> Dict[str, Any]: def selector_data_from_root(project_root: str) -> Dict[str, Any]:
selector_filepath = resolve_path_from_base( selector_filepath = resolve_path_from_base("selectors.yml", project_root)
'selectors.yml', project_root
)
if path_exists(selector_filepath): if path_exists(selector_filepath):
selectors_dict = load_yaml_text(load_file_contents(selector_filepath)) selectors_dict = load_yaml_text(load_file_contents(selector_filepath))
@@ -103,18 +100,16 @@ def selector_data_from_root(project_root: str) -> Dict[str, Any]:
return selectors_dict return selectors_dict
def selector_config_from_data( def selector_config_from_data(selectors_data: Dict[str, Any]) -> SelectorConfig:
selectors_data: Dict[str, Any]
) -> SelectorConfig:
if not selectors_data: if not selectors_data:
selectors_data = {'selectors': []} selectors_data = {"selectors": []}
try: try:
selectors = SelectorConfig.selectors_from_dict(selectors_data) selectors = SelectorConfig.selectors_from_dict(selectors_data)
except ValidationError as e: except ValidationError as e:
raise DbtSelectorsError( raise DbtSelectorsError(
MALFORMED_SELECTOR_ERROR.format(error=str(e.message)), MALFORMED_SELECTOR_ERROR.format(error=str(e.message)),
result_type='invalid_selector', result_type="invalid_selector",
) from e ) from e
return selectors return selectors
@@ -144,7 +139,6 @@ def validate_selector_default(selector_file: SelectorFile) -> None:
# be necessary to make changes here. Ideally it would be # be necessary to make changes here. Ideally it would be
# good to combine the two flows into one at some point. # good to combine the two flows into one at some point.
class SelectorDict: class SelectorDict:
@classmethod @classmethod
def parse_dict_definition(cls, definition): def parse_dict_definition(cls, definition):
key = list(definition)[0] key = list(definition)[0]
@@ -155,10 +149,10 @@ class SelectorDict:
new_value = cls.parse_from_definition(sel_def) new_value = cls.parse_from_definition(sel_def)
new_values.append(new_value) new_values.append(new_value)
value = new_values value = new_values
if key == 'exclude': if key == "exclude":
definition = {key: value} definition = {key: value}
elif len(definition) == 1: elif len(definition) == 1:
definition = {'method': key, 'value': value} definition = {"method": key, "value": value}
return definition return definition
@classmethod @classmethod
@@ -180,10 +174,10 @@ class SelectorDict:
def parse_from_definition(cls, definition): def parse_from_definition(cls, definition):
if isinstance(definition, str): if isinstance(definition, str):
definition = SelectionCriteria.dict_from_single_spec(definition) definition = SelectionCriteria.dict_from_single_spec(definition)
elif 'union' in definition: elif "union" in definition:
definition = cls.parse_a_definition('union', definition) definition = cls.parse_a_definition("union", definition)
elif 'intersection' in definition: elif "intersection" in definition:
definition = cls.parse_a_definition('intersection', definition) definition = cls.parse_a_definition("intersection", definition)
elif isinstance(definition, dict): elif isinstance(definition, dict):
definition = cls.parse_dict_definition(definition) definition = cls.parse_dict_definition(definition)
return definition return definition
@@ -194,8 +188,8 @@ class SelectorDict:
def parse_from_selectors_list(cls, selectors): def parse_from_selectors_list(cls, selectors):
selector_dict = {} selector_dict = {}
for selector in selectors: for selector in selectors:
sel_name = selector['name'] sel_name = selector["name"]
selector_dict[sel_name] = selector selector_dict[sel_name] = selector
definition = cls.parse_from_definition(selector['definition']) definition = cls.parse_from_definition(selector["definition"])
selector_dict[sel_name]['definition'] = definition selector_dict[sel_name]["definition"] = definition
return selector_dict return selector_dict

View File

@@ -1,8 +1,9 @@
from typing import Dict, Any from typing import Dict, Any
from dbt.clients import yaml_helper from dbt.clients import yaml_helper
from dbt.events.functions import fire_event
from dbt.exceptions import raise_compiler_error, ValidationException from dbt.exceptions import raise_compiler_error, ValidationException
from dbt.logger import GLOBAL_LOGGER as logger from dbt.events.types import InvalidVarsYAML
def parse_cli_vars(var_string: str) -> Dict[str, Any]: def parse_cli_vars(var_string: str) -> Dict[str, Any]:
@@ -15,9 +16,8 @@ def parse_cli_vars(var_string: str) -> Dict[str, Any]:
type_name = var_type.__name__ type_name = var_type.__name__
raise_compiler_error( raise_compiler_error(
"The --vars argument must be a YAML dictionary, but was " "The --vars argument must be a YAML dictionary, but was "
"of type '{}'".format(type_name)) "of type '{}'".format(type_name)
except ValidationException:
logger.error(
"The YAML provided in the --vars argument is not valid.\n"
) )
except ValidationException:
fire_event(InvalidVarsYAML())
raise raise

View File

@@ -0,0 +1 @@
# Contexts and Jinja rendering

View File

@@ -1,18 +1,20 @@
import json import json
import os import os
from typing import ( from typing import Any, Dict, NoReturn, Optional, Mapping
Any, Dict, NoReturn, Optional, Mapping
)
from dbt import flags from dbt import flags
from dbt import tracking from dbt import tracking
from dbt.clients.jinja import undefined_error, get_rendered from dbt.clients.jinja import get_rendered
from dbt.clients.yaml_helper import ( # noqa: F401 from dbt.clients.yaml_helper import yaml, safe_load, SafeLoader, Loader, Dumper # noqa: F401
yaml, safe_load, SafeLoader, Loader, Dumper
)
from dbt.contracts.graph.compiled import CompiledResource from dbt.contracts.graph.compiled import CompiledResource
from dbt.exceptions import raise_compiler_error, MacroReturn from dbt.exceptions import (
from dbt.events.functions import fire_event raise_compiler_error,
MacroReturn,
raise_parsing_error,
disallow_secret_env_var,
)
from dbt.logger import SECRET_ENV_PREFIX
from dbt.events.functions import fire_event, get_invocation_id
from dbt.events.types import MacroEventInfo, MacroEventDebug from dbt.events.types import MacroEventInfo, MacroEventDebug
from dbt.version import __version__ as dbt_version from dbt.version import __version__ as dbt_version
@@ -22,42 +24,64 @@ import pytz
import datetime import datetime
import re import re
# Contexts in dbt Core
# Contexts are used for Jinja rendering. They include context methods,
# executable macros, and various settings that are available in Jinja.
#
# Different contexts are used in different places because we allow access
# to different methods and data in different places. Executable SQL, for
# example, includes the available macros and the model, while Jinja in
# yaml files is more limited.
#
# The context that is passed to Jinja is always in a dictionary format,
# not an actual class, so a 'to_dict()' is executed on a context class
# before it is used for rendering.
#
# Each context has a generate_<name>_context function to create the context.
# ProviderContext subclasses have different generate functions for
# parsing and for execution.
#
# Context class hierarchy
#
# BaseContext -- core/dbt/context/base.py
# SecretContext -- core/dbt/context/secret.py
# TargetContext -- core/dbt/context/target.py
# ConfiguredContext -- core/dbt/context/configured.py
# SchemaYamlContext -- core/dbt/context/configured.py
# DocsRuntimeContext -- core/dbt/context/configured.py
# MacroResolvingContext -- core/dbt/context/configured.py
# ManifestContext -- core/dbt/context/manifest.py
# QueryHeaderContext -- core/dbt/context/manifest.py
# ProviderContext -- core/dbt/context/provider.py
# MacroContext -- core/dbt/context/provider.py
# ModelContext -- core/dbt/context/provider.py
# TestContext -- core/dbt/context/provider.py
def get_pytz_module_context() -> Dict[str, Any]: def get_pytz_module_context() -> Dict[str, Any]:
context_exports = pytz.__all__ # type: ignore context_exports = pytz.__all__ # type: ignore
return { return {name: getattr(pytz, name) for name in context_exports}
name: getattr(pytz, name) for name in context_exports
}
def get_datetime_module_context() -> Dict[str, Any]: def get_datetime_module_context() -> Dict[str, Any]:
context_exports = [ context_exports = ["date", "datetime", "time", "timedelta", "tzinfo"]
'date',
'datetime',
'time',
'timedelta',
'tzinfo'
]
return { return {name: getattr(datetime, name) for name in context_exports}
name: getattr(datetime, name) for name in context_exports
}
def get_re_module_context() -> Dict[str, Any]: def get_re_module_context() -> Dict[str, Any]:
context_exports = re.__all__ # TODO CT-211
context_exports = re.__all__ # type: ignore[attr-defined]
return { return {name: getattr(re, name) for name in context_exports}
name: getattr(re, name) for name in context_exports
}
def get_context_modules() -> Dict[str, Dict[str, Any]]: def get_context_modules() -> Dict[str, Dict[str, Any]]:
return { return {
'pytz': get_pytz_module_context(), "pytz": get_pytz_module_context(),
'datetime': get_datetime_module_context(), "datetime": get_datetime_module_context(),
're': get_re_module_context(), "re": get_re_module_context(),
} }
@@ -91,8 +115,8 @@ class ContextMeta(type):
new_dct = {} new_dct = {}
for base in bases: for base in bases:
context_members.update(getattr(base, '_context_members_', {})) context_members.update(getattr(base, "_context_members_", {}))
context_attrs.update(getattr(base, '_context_attrs_', {})) context_attrs.update(getattr(base, "_context_attrs_", {}))
for key, value in dct.items(): for key, value in dct.items():
if isinstance(value, ContextMember): if isinstance(value, ContextMember):
@@ -101,21 +125,20 @@ class ContextMeta(type):
context_attrs[context_key] = key context_attrs[context_key] = key
value = value.inner value = value.inner
new_dct[key] = value new_dct[key] = value
new_dct['_context_members_'] = context_members new_dct["_context_members_"] = context_members
new_dct['_context_attrs_'] = context_attrs new_dct["_context_attrs_"] = context_attrs
return type.__new__(mcls, name, bases, new_dct) return type.__new__(mcls, name, bases, new_dct)
class Var: class Var:
UndefinedVarError = "Required var '{}' not found in config:\nVars "\ UndefinedVarError = "Required var '{}' not found in config:\nVars " "supplied to {} = {}"
"supplied to {} = {}"
_VAR_NOTSET = object() _VAR_NOTSET = object()
def __init__( def __init__(
self, self,
context: Mapping[str, Any], context: Mapping[str, Any],
cli_vars: Mapping[str, Any], cli_vars: Mapping[str, Any],
node: Optional[CompiledResource] = None node: Optional[CompiledResource] = None,
) -> None: ) -> None:
self._context: Mapping[str, Any] = context self._context: Mapping[str, Any] = context
self._cli_vars: Mapping[str, Any] = cli_vars self._cli_vars: Mapping[str, Any] = cli_vars
@@ -130,14 +153,12 @@ class Var:
if self._node is not None: if self._node is not None:
return self._node.name return self._node.name
else: else:
return '<Configuration>' return "<Configuration>"
def get_missing_var(self, var_name): def get_missing_var(self, var_name):
dct = {k: self._merged[k] for k in self._merged} dct = {k: self._merged[k] for k in self._merged}
pretty_vars = json.dumps(dct, sort_keys=True, indent=4) pretty_vars = json.dumps(dct, sort_keys=True, indent=4)
msg = self.UndefinedVarError.format( msg = self.UndefinedVarError.format(var_name, self.node_name, pretty_vars)
var_name, self.node_name, pretty_vars
)
raise_compiler_error(msg, self._node) raise_compiler_error(msg, self._node)
def has_var(self, var_name: str): def has_var(self, var_name: str):
@@ -161,14 +182,16 @@ class Var:
class BaseContext(metaclass=ContextMeta): class BaseContext(metaclass=ContextMeta):
# subclass is TargetContext
def __init__(self, cli_vars): def __init__(self, cli_vars):
self._ctx = {} self._ctx = {}
self.cli_vars = cli_vars self.cli_vars = cli_vars
self.env_vars = {}
def generate_builtins(self): def generate_builtins(self):
builtins: Dict[str, Any] = {} builtins: Dict[str, Any] = {}
for key, value in self._context_members_.items(): for key, value in self._context_members_.items():
if hasattr(value, '__get__'): if hasattr(value, "__get__"):
# handle properties, bound methods, etc # handle properties, bound methods, etc
value = value.__get__(self) value = value.__get__(self)
builtins[key] = value builtins[key] = value
@@ -176,9 +199,9 @@ class BaseContext(metaclass=ContextMeta):
# no dbtClassMixin so this is not an actual override # no dbtClassMixin so this is not an actual override
def to_dict(self): def to_dict(self):
self._ctx['context'] = self._ctx self._ctx["context"] = self._ctx
builtins = self.generate_builtins() builtins = self.generate_builtins()
self._ctx['builtins'] = builtins self._ctx["builtins"] = builtins
self._ctx.update(builtins) self._ctx.update(builtins)
return self._ctx return self._ctx
@@ -272,33 +295,41 @@ class BaseContext(metaclass=ContextMeta):
return Var(self._ctx, self.cli_vars) return Var(self._ctx, self.cli_vars)
@contextmember @contextmember
@staticmethod def env_var(self, var: str, default: Optional[str] = None) -> str:
def env_var(var: str, default: Optional[str] = None) -> str:
"""The env_var() function. Return the environment variable named 'var'. """The env_var() function. Return the environment variable named 'var'.
If there is no such environment variable set, return the default. If there is no such environment variable set, return the default.
If the default is None, raise an exception for an undefined variable. If the default is None, raise an exception for an undefined variable.
""" """
return_value = None
if var.startswith(SECRET_ENV_PREFIX):
disallow_secret_env_var(var)
if var in os.environ: if var in os.environ:
return os.environ[var] return_value = os.environ[var]
elif default is not None: elif default is not None:
return default return_value = default
if return_value is not None:
self.env_vars[var] = return_value
return return_value
else: else:
msg = f"Env var required but not provided: '{var}'" msg = f"Env var required but not provided: '{var}'"
undefined_error(msg) raise_parsing_error(msg)
if os.environ.get("DBT_MACRO_DEBUGGING"):
if os.environ.get('DBT_MACRO_DEBUGGING'):
@contextmember @contextmember
@staticmethod @staticmethod
def debug(): def debug():
"""Enter a debugger at this line in the compiled jinja code.""" """Enter a debugger at this line in the compiled jinja code."""
import sys import sys
import ipdb # type: ignore import ipdb # type: ignore
frame = sys._getframe(3) frame = sys._getframe(3)
ipdb.set_trace(frame) ipdb.set_trace(frame)
return '' return ""
@contextmember('return') @contextmember("return")
@staticmethod @staticmethod
def _return(data: Any) -> NoReturn: def _return(data: Any) -> NoReturn:
"""The `return` function can be used in macros to return data to the """The `return` function can be used in macros to return data to the
@@ -349,9 +380,7 @@ class BaseContext(metaclass=ContextMeta):
@contextmember @contextmember
@staticmethod @staticmethod
def tojson( def tojson(value: Any, default: Any = None, sort_keys: bool = False) -> Any:
value: Any, default: Any = None, sort_keys: bool = False
) -> Any:
"""The `tojson` context method can be used to serialize a Python """The `tojson` context method can be used to serialize a Python
object primitive, eg. a `dict` or `list` to a json string. object primitive, eg. a `dict` or `list` to a json string.
@@ -444,10 +473,10 @@ class BaseContext(metaclass=ContextMeta):
{% endmacro %}" {% endmacro %}"
""" """
if info: if info:
fire_event(MacroEventInfo(msg)) fire_event(MacroEventInfo(msg=msg))
else: else:
fire_event(MacroEventDebug(msg)) fire_event(MacroEventDebug(msg=msg))
return '' return ""
@contextproperty @contextproperty
def run_started_at(self) -> Optional[datetime.datetime]: def run_started_at(self) -> Optional[datetime.datetime]:
@@ -482,10 +511,7 @@ class BaseContext(metaclass=ContextMeta):
"""invocation_id outputs a UUID generated for this dbt run (useful for """invocation_id outputs a UUID generated for this dbt run (useful for
auditing) auditing)
""" """
if tracking.active_user is not None: return get_invocation_id()
return tracking.active_user.invocation_id
else:
return None
@contextproperty @contextproperty
def modules(self) -> Dict[str, Any]: def modules(self) -> Dict[str, Any]:
@@ -530,6 +556,22 @@ class BaseContext(metaclass=ContextMeta):
""" """
return flags return flags
@contextmember
@staticmethod
def print(msg: str) -> str:
"""Prints a line to stdout.
:param msg: The message to print
> macros/my_log_macro.sql
{% macro some_macro(arg1, arg2) %}
{{ print("Running some_macro: " ~ arg1 ~ ", " ~ arg2) }}
{% endmacro %}"
"""
print(msg)
return ""
def generate_base_context(cli_vars: Dict[str, Any]) -> Dict[str, Any]: def generate_base_context(cli_vars: Dict[str, Any]) -> Dict[str, Any]:
ctx = BaseContext(cli_vars) ctx = BaseContext(cli_vars)

View File

@@ -1,19 +1,21 @@
from typing import Any, Dict import os
from typing import Any, Dict, Optional
from dbt.contracts.connection import AdapterRequiredConfig from dbt.contracts.connection import AdapterRequiredConfig
from dbt.logger import SECRET_ENV_PREFIX
from dbt.node_types import NodeType from dbt.node_types import NodeType
from dbt.utils import MultiDict from dbt.utils import MultiDict
from dbt.context.base import contextproperty, Var from dbt.context.base import contextproperty, contextmember, Var
from dbt.context.target import TargetContext from dbt.context.target import TargetContext
from dbt.exceptions import raise_parsing_error, disallow_secret_env_var
class ConfiguredContext(TargetContext): class ConfiguredContext(TargetContext):
# subclasses are SchemaYamlContext, MacroResolvingContext, ManifestContext
config: AdapterRequiredConfig config: AdapterRequiredConfig
def __init__( def __init__(self, config: AdapterRequiredConfig) -> None:
self, config: AdapterRequiredConfig
) -> None:
super().__init__(config, config.cli_vars) super().__init__(config, config.cli_vars)
@contextproperty @contextproperty
@@ -63,16 +65,40 @@ class ConfiguredVar(Var):
return self.get_missing_var(var_name) return self.get_missing_var(var_name)
class SchemaYamlVars:
def __init__(self):
self.env_vars = {}
self.vars = {}
class SchemaYamlContext(ConfiguredContext): class SchemaYamlContext(ConfiguredContext):
def __init__(self, config, project_name: str): # subclass is DocsRuntimeContext
def __init__(self, config, project_name: str, schema_yaml_vars: Optional[SchemaYamlVars]):
super().__init__(config) super().__init__(config)
self._project_name = project_name self._project_name = project_name
self.schema_yaml_vars = schema_yaml_vars
@contextproperty @contextproperty
def var(self) -> ConfiguredVar: def var(self) -> ConfiguredVar:
return ConfiguredVar( return ConfiguredVar(self._ctx, self.config, self._project_name)
self._ctx, self.config, self._project_name
) @contextmember
def env_var(self, var: str, default: Optional[str] = None) -> str:
return_value = None
if var.startswith(SECRET_ENV_PREFIX):
disallow_secret_env_var(var)
if var in os.environ:
return_value = os.environ[var]
elif default is not None:
return_value = default
if return_value is not None:
if self.schema_yaml_vars:
self.schema_yaml_vars.env_vars[var] = return_value
return return_value
else:
msg = f"Env var required but not provided: '{var}'"
raise_parsing_error(msg)
class MacroResolvingContext(ConfiguredContext): class MacroResolvingContext(ConfiguredContext):
@@ -81,15 +107,13 @@ class MacroResolvingContext(ConfiguredContext):
@contextproperty @contextproperty
def var(self) -> ConfiguredVar: def var(self) -> ConfiguredVar:
return ConfiguredVar( return ConfiguredVar(self._ctx, self.config, self.config.project_name)
self._ctx, self.config, self.config.project_name
)
def generate_schema_yml( def generate_schema_yml_context(
config: AdapterRequiredConfig, project_name: str config: AdapterRequiredConfig, project_name: str, schema_yaml_vars: SchemaYamlVars = None
) -> Dict[str, Any]: ) -> Dict[str, Any]:
ctx = SchemaYamlContext(config, project_name) ctx = SchemaYamlContext(config, project_name, schema_yaml_vars)
return ctx.to_dict() return ctx.to_dict()

View File

@@ -17,8 +17,8 @@ class ModelParts(IsFQNResource):
package_name: str package_name: str
T = TypeVar('T') # any old type T = TypeVar("T") # any old type
C = TypeVar('C', bound=BaseConfig) C = TypeVar("C", bound=BaseConfig)
class ConfigSource: class ConfigSource:
@@ -36,15 +36,15 @@ class UnrenderedConfig(ConfigSource):
def get_config_dict(self, resource_type: NodeType) -> Dict[str, Any]: def get_config_dict(self, resource_type: NodeType) -> Dict[str, Any]:
unrendered = self.project.unrendered.project_dict unrendered = self.project.unrendered.project_dict
if resource_type == NodeType.Seed: if resource_type == NodeType.Seed:
model_configs = unrendered.get('seeds') model_configs = unrendered.get("seeds")
elif resource_type == NodeType.Snapshot: elif resource_type == NodeType.Snapshot:
model_configs = unrendered.get('snapshots') model_configs = unrendered.get("snapshots")
elif resource_type == NodeType.Source: elif resource_type == NodeType.Source:
model_configs = unrendered.get('sources') model_configs = unrendered.get("sources")
elif resource_type == NodeType.Test: elif resource_type == NodeType.Test:
model_configs = unrendered.get('tests') model_configs = unrendered.get("tests")
else: else:
model_configs = unrendered.get('models') model_configs = unrendered.get("models")
if model_configs is None: if model_configs is None:
return {} return {}
@@ -83,8 +83,8 @@ class BaseContextConfigGenerator(Generic[T]):
dependencies = self._active_project.load_dependencies() dependencies = self._active_project.load_dependencies()
if project_name not in dependencies: if project_name not in dependencies:
raise InternalException( raise InternalException(
f'Project name {project_name} not found in dependencies ' f"Project name {project_name} not found in dependencies "
f'(found {list(dependencies)})' f"(found {list(dependencies)})"
) )
return dependencies[project_name] return dependencies[project_name]
@@ -96,7 +96,7 @@ class BaseContextConfigGenerator(Generic[T]):
for level_config in fqn_search(model_configs, fqn): for level_config in fqn_search(model_configs, fqn):
result = {} result = {}
for key, value in level_config.items(): for key, value in level_config.items():
if key.startswith('+'): if key.startswith("+"):
result[key[1:].strip()] = deepcopy(value) result[key[1:].strip()] = deepcopy(value)
elif not isinstance(value, dict): elif not isinstance(value, dict):
result[key] = deepcopy(value) result[key] = deepcopy(value)
@@ -109,9 +109,7 @@ class BaseContextConfigGenerator(Generic[T]):
return self._project_configs(self._active_project, fqn, resource_type) return self._project_configs(self._active_project, fqn, resource_type)
@abstractmethod @abstractmethod
def _update_from_config( def _update_from_config(self, result: T, partial: Dict[str, Any], validate: bool = False) -> T:
self, result: T, partial: Dict[str, Any], validate: bool = False
) -> T:
... ...
@abstractmethod @abstractmethod
@@ -125,7 +123,7 @@ class BaseContextConfigGenerator(Generic[T]):
resource_type: NodeType, resource_type: NodeType,
project_name: str, project_name: str,
base: bool, base: bool,
patch_config_dict: Dict[str, Any] = None patch_config_dict: Dict[str, Any] = None,
) -> BaseConfig: ) -> BaseConfig:
own_config = self.get_node_project(project_name) own_config = self.get_node_project(project_name)
@@ -150,7 +148,8 @@ class BaseContextConfigGenerator(Generic[T]):
result = self._update_from_config(result, fqn_config) result = self._update_from_config(result, fqn_config)
# this is mostly impactful in the snapshot config case # this is mostly impactful in the snapshot config case
return result # TODO CT-211
return result # type: ignore[return-value]
@abstractmethod @abstractmethod
def calculate_node_config_dict( def calculate_node_config_dict(
@@ -181,16 +180,10 @@ class ContextConfigGenerator(BaseContextConfigGenerator[C]):
result = config_cls.from_dict({}) result = config_cls.from_dict({})
return result return result
def _update_from_config( def _update_from_config(self, result: C, partial: Dict[str, Any], validate: bool = False) -> C:
self, result: C, partial: Dict[str, Any], validate: bool = False translated = self._active_project.credentials.translate_aliases(partial)
) -> C:
translated = self._active_project.credentials.translate_aliases(
partial
)
return result.update_from( return result.update_from(
translated, translated, self._active_project.credentials.type, validate=validate
self._active_project.credentials.type,
validate=validate
) )
def calculate_node_config_dict( def calculate_node_config_dict(
@@ -200,7 +193,7 @@ class ContextConfigGenerator(BaseContextConfigGenerator[C]):
resource_type: NodeType, resource_type: NodeType,
project_name: str, project_name: str,
base: bool, base: bool,
patch_config_dict: dict = None patch_config_dict: dict = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
config = self.calculate_node_config( config = self.calculate_node_config(
config_call_dict=config_call_dict, config_call_dict=config_call_dict,
@@ -208,7 +201,7 @@ class ContextConfigGenerator(BaseContextConfigGenerator[C]):
resource_type=resource_type, resource_type=resource_type,
project_name=project_name, project_name=project_name,
base=base, base=base,
patch_config_dict=patch_config_dict patch_config_dict=patch_config_dict,
) )
finalized = config.finalize_and_validate() finalized = config.finalize_and_validate()
return finalized.to_dict(omit_none=True) return finalized.to_dict(omit_none=True)
@@ -225,22 +218,19 @@ class UnrenderedConfigGenerator(BaseContextConfigGenerator[Dict[str, Any]]):
resource_type: NodeType, resource_type: NodeType,
project_name: str, project_name: str,
base: bool, base: bool,
patch_config_dict: dict = None patch_config_dict: dict = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
# TODO CT-211
return self.calculate_node_config( return self.calculate_node_config(
config_call_dict=config_call_dict, config_call_dict=config_call_dict,
fqn=fqn, fqn=fqn,
resource_type=resource_type, resource_type=resource_type,
project_name=project_name, project_name=project_name,
base=base, base=base,
patch_config_dict=patch_config_dict patch_config_dict=patch_config_dict,
) ) # type: ignore[return-value]
def initial_result( def initial_result(self, resource_type: NodeType, base: bool) -> Dict[str, Any]:
self,
resource_type: NodeType,
base: bool
) -> Dict[str, Any]:
return {} return {}
def _update_from_config( def _update_from_config(
@@ -249,9 +239,7 @@ class UnrenderedConfigGenerator(BaseContextConfigGenerator[Dict[str, Any]]):
partial: Dict[str, Any], partial: Dict[str, Any],
validate: bool = False, validate: bool = False,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
translated = self._active_project.credentials.translate_aliases( translated = self._active_project.credentials.translate_aliases(partial)
partial
)
result.update(translated) result.update(translated)
return result return result
@@ -279,11 +267,11 @@ class ContextConfig:
for k, v in opts.items(): for k, v in opts.items():
# MergeBehavior for post-hook and pre-hook is to collect all # MergeBehavior for post-hook and pre-hook is to collect all
# values, instead of overwriting # values, instead of overwriting
if k in BaseConfig.mergebehavior['append']: if k in BaseConfig.mergebehavior["append"]:
if not isinstance(v, list): if not isinstance(v, list):
v = [v] v = [v]
if k in BaseConfig.mergebehavior['update'] and not isinstance(v, dict): if k in BaseConfig.mergebehavior["update"] and not isinstance(v, dict):
raise InternalException(f'expected dict, got {v}') raise InternalException(f"expected dict, got {v}")
if k in config_call_dict and isinstance(config_call_dict[k], list): if k in config_call_dict and isinstance(config_call_dict[k], list):
config_call_dict[k].extend(v) config_call_dict[k].extend(v)
elif k in config_call_dict and isinstance(config_call_dict[k], dict): elif k in config_call_dict and isinstance(config_call_dict[k], dict):
@@ -292,16 +280,14 @@ class ContextConfig:
config_call_dict[k] = v config_call_dict[k] = v
def build_config_dict( def build_config_dict(
self, self, base: bool = False, *, rendered: bool = True, patch_config_dict: dict = None
base: bool = False,
*,
rendered: bool = True,
patch_config_dict: dict = None
) -> Dict[str, Any]: ) -> Dict[str, Any]:
if rendered: if rendered:
src = ContextConfigGenerator(self._active_project) # TODO CT-211
src = ContextConfigGenerator(self._active_project) # type: ignore[var-annotated]
else: else:
src = UnrenderedConfigGenerator(self._active_project) # TODO CT-211
src = UnrenderedConfigGenerator(self._active_project) # type: ignore[assignment]
return src.calculate_node_config_dict( return src.calculate_node_config_dict(
config_call_dict=self._config_call_dict, config_call_dict=self._config_call_dict,
@@ -309,5 +295,5 @@ class ContextConfig:
resource_type=self._resource_type, resource_type=self._resource_type,
project_name=self._project_name, project_name=self._project_name,
base=base, base=base,
patch_config_dict=patch_config_dict patch_config_dict=patch_config_dict,
) )

View File

@@ -1,6 +1,4 @@
from typing import ( from typing import Any, Dict, Union
Any, Dict, Union
)
from dbt.exceptions import ( from dbt.exceptions import (
doc_invalid_args, doc_invalid_args,
@@ -23,7 +21,7 @@ class DocsRuntimeContext(SchemaYamlContext):
manifest: Manifest, manifest: Manifest,
current_project: str, current_project: str,
) -> None: ) -> None:
super().__init__(config, current_project) super().__init__(config, current_project, None)
self.node = node self.node = node
self.manifest = manifest self.manifest = manifest
@@ -68,14 +66,15 @@ class DocsRuntimeContext(SchemaYamlContext):
file_id = target_doc.file_id file_id = target_doc.file_id
if file_id in self.manifest.files: if file_id in self.manifest.files:
source_file = self.manifest.files[file_id] source_file = self.manifest.files[file_id]
source_file.add_node(self.node.unique_id) # TODO CT-211
source_file.add_node(self.node.unique_id) # type: ignore[union-attr]
else: else:
doc_target_not_found(self.node, doc_name, doc_package_name) doc_target_not_found(self.node, doc_name, doc_package_name)
return target_doc.block_contents return target_doc.block_contents
def generate_runtime_docs( def generate_runtime_docs_context(
config: RuntimeConfig, config: RuntimeConfig,
target: Any, target: Any,
manifest: Manifest, manifest: Manifest,

View File

@@ -1,6 +1,4 @@
from typing import ( from typing import Dict, MutableMapping, Optional
Dict, MutableMapping, Optional
)
from dbt.contracts.graph.parsed import ParsedMacro from dbt.contracts.graph.parsed import ParsedMacro
from dbt.exceptions import raise_duplicate_macro_name, raise_compiler_error from dbt.exceptions import raise_duplicate_macro_name, raise_compiler_error
from dbt.include.global_project import PROJECT_NAME as GLOBAL_PROJECT_NAME from dbt.include.global_project import PROJECT_NAME as GLOBAL_PROJECT_NAME
@@ -49,8 +47,7 @@ class MacroResolver:
for pkg in reversed(self.internal_package_names): for pkg in reversed(self.internal_package_names):
if pkg in self.internal_packages: if pkg in self.internal_packages:
# Turn the internal packages into a flat namespace # Turn the internal packages into a flat namespace
self.internal_packages_namespace.update( self.internal_packages_namespace.update(self.internal_packages[pkg])
self.internal_packages[pkg])
# search order: # search order:
# local_namespace (package of particular node), not including # local_namespace (package of particular node), not including
@@ -89,9 +86,7 @@ class MacroResolver:
package_namespaces[macro.package_name] = namespace package_namespaces[macro.package_name] = namespace
if macro.name in namespace: if macro.name in namespace:
raise_duplicate_macro_name( raise_duplicate_macro_name(macro, macro, macro.package_name)
macro, macro, macro.package_name
)
package_namespaces[macro.package_name][macro.name] = macro package_namespaces[macro.package_name][macro.name] = macro
def add_macro(self, macro: ParsedMacro): def add_macro(self, macro: ParsedMacro):
@@ -114,8 +109,7 @@ class MacroResolver:
def get_macro(self, local_package, macro_name): def get_macro(self, local_package, macro_name):
local_package_macros = {} local_package_macros = {}
if (local_package not in self.internal_package_names and if local_package not in self.internal_package_names and local_package in self.packages:
local_package in self.packages):
local_package_macros = self.packages[local_package] local_package_macros = self.packages[local_package]
# First: search the local packages for this macro # First: search the local packages for this macro
if macro_name in local_package_macros: if macro_name in local_package_macros:
@@ -140,9 +134,7 @@ class MacroResolver:
# is that you can limit the number of macros provided to the # is that you can limit the number of macros provided to the
# context dictionary in the 'to_dict' manifest method. # context dictionary in the 'to_dict' manifest method.
class TestMacroNamespace: class TestMacroNamespace:
def __init__( def __init__(self, macro_resolver, ctx, node, thread_ctx, depends_on_macros):
self, macro_resolver, ctx, node, thread_ctx, depends_on_macros
):
self.macro_resolver = macro_resolver self.macro_resolver = macro_resolver
self.ctx = ctx self.ctx = ctx
self.node = node # can be none self.node = node # can be none
@@ -155,11 +147,14 @@ class TestMacroNamespace:
for macro_unique_id in dep_macros: for macro_unique_id in dep_macros:
if macro_unique_id in self.macro_resolver.macros: if macro_unique_id in self.macro_resolver.macros:
# Split up the macro unique_id to get the project_name # Split up the macro unique_id to get the project_name
(_, project_name, macro_name) = macro_unique_id.split('.') (_, project_name, macro_name) = macro_unique_id.split(".")
# Save the plain macro_name in the local_namespace # Save the plain macro_name in the local_namespace
macro = self.macro_resolver.macros[macro_unique_id] macro = self.macro_resolver.macros[macro_unique_id]
macro_gen = MacroGenerator( macro_gen = MacroGenerator(
macro, self.ctx, self.node, self.thread_ctx, macro,
self.ctx,
self.node,
self.thread_ctx,
) )
self.local_namespace[macro_name] = macro_gen self.local_namespace[macro_name] = macro_gen
# We also need the two part macro name # We also need the two part macro name
@@ -177,9 +172,7 @@ class TestMacroNamespace:
if macro.depends_on.macros: if macro.depends_on.macros:
self.recursively_get_depends_on_macros(macro.depends_on.macros, dep_macros) self.recursively_get_depends_on_macros(macro.depends_on.macros, dep_macros)
def get_from_package( def get_from_package(self, package_name: Optional[str], name: str) -> Optional[MacroGenerator]:
self, package_name: Optional[str], name: str
) -> Optional[MacroGenerator]:
macro = None macro = None
if package_name is None: if package_name is None:
macro = self.macro_resolver.macros_by_name.get(name) macro = self.macro_resolver.macros_by_name.get(name)
@@ -188,12 +181,8 @@ class TestMacroNamespace:
elif package_name in self.macro_resolver.packages: elif package_name in self.macro_resolver.packages:
macro = self.macro_resolver.packages[package_name].get(name) macro = self.macro_resolver.packages[package_name].get(name)
else: else:
raise_compiler_error( raise_compiler_error(f"Could not find package '{package_name}'")
f"Could not find package '{package_name}'"
)
if not macro: if not macro:
return None return None
macro_func = MacroGenerator( macro_func = MacroGenerator(macro, self.ctx, self.node, self.thread_ctx)
macro, self.ctx, self.node, self.thread_ctx
)
return macro_func return macro_func

View File

@@ -1,13 +1,9 @@
from typing import ( from typing import Any, Dict, Iterable, Union, Optional, List, Iterator, Mapping, Set
Any, Dict, Iterable, Union, Optional, List, Iterator, Mapping, Set
)
from dbt.clients.jinja import MacroGenerator, MacroStack from dbt.clients.jinja import MacroGenerator, MacroStack
from dbt.contracts.graph.parsed import ParsedMacro from dbt.contracts.graph.parsed import ParsedMacro
from dbt.include.global_project import PROJECT_NAME as GLOBAL_PROJECT_NAME from dbt.include.global_project import PROJECT_NAME as GLOBAL_PROJECT_NAME
from dbt.exceptions import ( from dbt.exceptions import raise_duplicate_macro_name, raise_compiler_error
raise_duplicate_macro_name, raise_compiler_error
)
FlatNamespace = Dict[str, MacroGenerator] FlatNamespace = Dict[str, MacroGenerator]
@@ -39,9 +35,11 @@ class MacroNamespace(Mapping):
def _search_order(self) -> Iterable[Union[FullNamespace, FlatNamespace]]: def _search_order(self) -> Iterable[Union[FullNamespace, FlatNamespace]]:
yield self.local_namespace # local package yield self.local_namespace # local package
yield self.global_namespace # root package yield self.global_namespace # root package
yield self.packages # non-internal packages # TODO CT-211
yield self.packages # type: ignore[misc] # non-internal packages
yield { yield {
GLOBAL_PROJECT_NAME: self.global_project_namespace, # dbt # TODO CT-211
GLOBAL_PROJECT_NAME: self.global_project_namespace, # type: ignore[misc] # dbt
} }
yield self.global_project_namespace # other internal project besides dbt yield self.global_project_namespace # other internal project besides dbt
@@ -68,9 +66,7 @@ class MacroNamespace(Mapping):
return dct[key] return dct[key]
raise KeyError(key) raise KeyError(key)
def get_from_package( def get_from_package(self, package_name: Optional[str], name: str) -> Optional[MacroGenerator]:
self, package_name: Optional[str], name: str
) -> Optional[MacroGenerator]:
pkg: FlatNamespace pkg: FlatNamespace
if package_name is None: if package_name is None:
return self.get(name) return self.get(name)
@@ -79,9 +75,7 @@ class MacroNamespace(Mapping):
elif package_name in self.packages: elif package_name in self.packages:
return self.packages[package_name].get(name) return self.packages[package_name].get(name)
else: else:
raise_compiler_error( raise_compiler_error(f"Could not find package '{package_name}'")
f"Could not find package '{package_name}'"
)
# This class builds the MacroNamespace by adding macros to # This class builds the MacroNamespace by adding macros to
@@ -128,9 +122,7 @@ class MacroNamespaceBuilder:
hierarchy[macro.package_name] = namespace hierarchy[macro.package_name] = namespace
if macro.name in namespace: if macro.name in namespace:
raise_duplicate_macro_name( raise_duplicate_macro_name(macro_func.macro, macro, macro.package_name)
macro_func.macro, macro, macro.package_name
)
hierarchy[macro.package_name][macro.name] = macro_func hierarchy[macro.package_name][macro.name] = macro_func
def add_macro(self, macro: ParsedMacro, ctx: Dict[str, Any]): def add_macro(self, macro: ParsedMacro, ctx: Dict[str, Any]):
@@ -139,9 +131,7 @@ class MacroNamespaceBuilder:
# MacroGenerator is in clients/jinja.py # MacroGenerator is in clients/jinja.py
# a MacroGenerator object is a callable object that will # a MacroGenerator object is a callable object that will
# execute the MacroGenerator.__call__ function # execute the MacroGenerator.__call__ function
macro_func: MacroGenerator = MacroGenerator( macro_func: MacroGenerator = MacroGenerator(macro, ctx, self.node, self.thread_ctx)
macro, ctx, self.node, self.thread_ctx
)
# internal macros (from plugins) will be processed separately from # internal macros (from plugins) will be processed separately from
# project macros, so store them in a different place # project macros, so store them in a different place

View File

@@ -17,6 +17,8 @@ class ManifestContext(ConfiguredContext):
The given macros can override any previous context values, which will be The given macros can override any previous context values, which will be
available as if they were accessed relative to the package name. available as if they were accessed relative to the package name.
""" """
# subclasses are QueryHeaderContext and ProviderContext
def __init__( def __init__(
self, self,
config: AdapterRequiredConfig, config: AdapterRequiredConfig,
@@ -37,16 +39,13 @@ class ManifestContext(ConfiguredContext):
# this takes all the macros in the manifest and adds them # this takes all the macros in the manifest and adds them
# to the MacroNamespaceBuilder stored in self.namespace # to the MacroNamespaceBuilder stored in self.namespace
builder = self._get_namespace_builder() builder = self._get_namespace_builder()
return builder.build_namespace( return builder.build_namespace(self.manifest.macros.values(), self._ctx)
self.manifest.macros.values(), self._ctx
)
def _get_namespace_builder(self) -> MacroNamespaceBuilder: def _get_namespace_builder(self) -> MacroNamespaceBuilder:
# avoid an import loop # avoid an import loop
from dbt.adapters.factory import get_adapter_package_names from dbt.adapters.factory import get_adapter_package_names
internal_packages: List[str] = get_adapter_package_names(
self.config.credentials.type internal_packages: List[str] = get_adapter_package_names(self.config.credentials.type)
)
return MacroNamespaceBuilder( return MacroNamespaceBuilder(
self.config.project_name, self.config.project_name,
self.search_package, self.search_package,
@@ -69,14 +68,10 @@ class ManifestContext(ConfiguredContext):
class QueryHeaderContext(ManifestContext): class QueryHeaderContext(ManifestContext):
def __init__( def __init__(self, config: AdapterRequiredConfig, manifest: Manifest) -> None:
self, config: AdapterRequiredConfig, manifest: Manifest
) -> None:
super().__init__(config, manifest, config.project_name) super().__init__(config, manifest, config.project_name)
def generate_query_header_context( def generate_query_header_context(config: AdapterRequiredConfig, manifest: Manifest):
config: AdapterRequiredConfig, manifest: Manifest
):
ctx = QueryHeaderContext(config, manifest) ctx = QueryHeaderContext(config, manifest)
return ctx.to_dict() return ctx.to_dict()

View File

@@ -1,41 +1,50 @@
import abc import abc
import os import os
from typing import ( from typing import (
Callable, Any, Dict, Optional, Union, List, TypeVar, Type, Iterable, Callable,
Any,
Dict,
Optional,
Union,
List,
TypeVar,
Type,
Iterable,
Mapping, Mapping,
) )
from typing_extensions import Protocol from typing_extensions import Protocol
from dbt.adapters.base.column import Column from dbt.adapters.base.column import Column
from dbt.adapters.factory import ( from dbt.adapters.factory import get_adapter, get_adapter_package_names, get_adapter_type_names
get_adapter, get_adapter_package_names, get_adapter_type_names
)
from dbt.clients import agate_helper from dbt.clients import agate_helper
from dbt.clients.jinja import get_rendered, MacroGenerator, MacroStack from dbt.clients.jinja import get_rendered, MacroGenerator, MacroStack
from dbt.config import RuntimeConfig, Project from dbt.config import RuntimeConfig, Project
from .base import contextmember, contextproperty, Var from .base import contextmember, contextproperty, Var
from .configured import FQNLookup from .configured import FQNLookup
from .context_config import ContextConfig from .context_config import ContextConfig
from dbt.logger import SECRET_ENV_PREFIX
from dbt.context.macro_resolver import MacroResolver, TestMacroNamespace from dbt.context.macro_resolver import MacroResolver, TestMacroNamespace
from .macros import MacroNamespaceBuilder, MacroNamespace from .macros import MacroNamespaceBuilder, MacroNamespace
from .manifest import ManifestContext from .manifest import ManifestContext
from dbt.contracts.connection import AdapterResponse from dbt.contracts.connection import AdapterResponse
from dbt.contracts.graph.manifest import ( from dbt.contracts.graph.manifest import Manifest, Disabled
Manifest, Disabled
)
from dbt.contracts.graph.compiled import ( from dbt.contracts.graph.compiled import (
CompiledResource, CompiledResource,
CompiledSeedNode, CompiledSeedNode,
ManifestNode, ManifestNode,
CompiledSqlNode,
CompiledRPCNode,
) )
from dbt.contracts.graph.parsed import ( from dbt.contracts.graph.parsed import (
ParsedMacro, ParsedMacro,
ParsedExposure, ParsedExposure,
ParsedMetric,
ParsedSeedNode, ParsedSeedNode,
ParsedSourceDefinition, ParsedSourceDefinition,
) )
from dbt.exceptions import ( from dbt.exceptions import (
CompilationException, CompilationException,
ParsingException,
InternalException, InternalException,
ValidationException, ValidationException,
RuntimeException, RuntimeException,
@@ -47,13 +56,13 @@ from dbt.exceptions import (
ref_bad_context, ref_bad_context,
source_target_not_found, source_target_not_found,
wrapped_exports, wrapped_exports,
raise_parsing_error,
disallow_secret_env_var,
) )
from dbt.config import IsFQNResource from dbt.config import IsFQNResource
from dbt.node_types import NodeType from dbt.node_types import NodeType
from dbt.utils import ( from dbt.utils import merge, AttrDict, MultiDict
merge, AttrDict, MultiDict
)
import agate import agate
@@ -76,10 +85,7 @@ class RelationProxy:
return self._relation_type.create_from_source(*args, **kwargs) return self._relation_type.create_from_source(*args, **kwargs)
def create(self, *args, **kwargs): def create(self, *args, **kwargs):
kwargs['quote_policy'] = merge( kwargs["quote_policy"] = merge(self._quoting_config, kwargs.pop("quote_policy", {}))
self._quoting_config,
kwargs.pop('quote_policy', {})
)
return self._relation_type.create(*args, **kwargs) return self._relation_type.create(*args, **kwargs)
@@ -95,7 +101,7 @@ class BaseDatabaseWrapper:
self._namespace = namespace self._namespace = namespace
def __getattr__(self, name): def __getattr__(self, name):
raise NotImplementedError('subclasses need to implement this') raise NotImplementedError("subclasses need to implement this")
@property @property
def config(self): def config(self):
@@ -112,7 +118,7 @@ class BaseDatabaseWrapper:
# 1. current adapter # 1. current adapter
# 2. any parent adapters (dependencies) # 2. any parent adapters (dependencies)
# 3. 'default' # 3. 'default'
search_prefixes = get_adapter_type_names(self._adapter.type()) + ['default'] search_prefixes = get_adapter_type_names(self._adapter.type()) + ["default"]
return search_prefixes return search_prefixes
def dispatch( def dispatch(
@@ -123,8 +129,8 @@ class BaseDatabaseWrapper:
) -> MacroGenerator: ) -> MacroGenerator:
search_packages: List[Optional[str]] search_packages: List[Optional[str]]
if '.' in macro_name: if "." in macro_name:
suggest_macro_namespace, suggest_macro_name = macro_name.split('.', 1) suggest_macro_namespace, suggest_macro_name = macro_name.split(".", 1)
msg = ( msg = (
f'In adapter.dispatch, got a macro name of "{macro_name}", ' f'In adapter.dispatch, got a macro name of "{macro_name}", '
f'but "." is not a valid macro name component. Did you mean ' f'but "." is not a valid macro name component. Did you mean '
@@ -147,7 +153,7 @@ class BaseDatabaseWrapper:
else: else:
# Not a string and not None so must be a list # Not a string and not None so must be a list
raise CompilationException( raise CompilationException(
f'In adapter.dispatch, got a list macro_namespace argument ' f"In adapter.dispatch, got a list macro_namespace argument "
f'("{macro_namespace}"), but macro_namespace should be None or a string.' f'("{macro_namespace}"), but macro_namespace should be None or a string.'
) )
@@ -155,12 +161,10 @@ class BaseDatabaseWrapper:
for package_name in search_packages: for package_name in search_packages:
for prefix in self._get_adapter_macro_prefixes(): for prefix in self._get_adapter_macro_prefixes():
search_name = f'{prefix}__{macro_name}' search_name = f"{prefix}__{macro_name}"
try: try:
# this uses the namespace from the context # this uses the namespace from the context
macro = self._namespace.get_from_package( macro = self._namespace.get_from_package(package_name, search_name)
package_name, search_name
)
except CompilationException: except CompilationException:
# Only raise CompilationException if macro is not found in # Only raise CompilationException if macro is not found in
# any package # any package
@@ -169,16 +173,13 @@ class BaseDatabaseWrapper:
if package_name is None: if package_name is None:
attempts.append(search_name) attempts.append(search_name)
else: else:
attempts.append(f'{package_name}.{search_name}') attempts.append(f"{package_name}.{search_name}")
if macro is not None: if macro is not None:
return macro return macro
searched = ', '.join(repr(a) for a in attempts) searched = ", ".join(repr(a) for a in attempts)
msg = ( msg = f"In dispatch: No macro named '{macro_name}' found\n" f" Searched for: {searched}"
f"In dispatch: No macro named '{macro_name}' found\n"
f" Searched for: {searched}"
)
raise CompilationException(msg) raise CompilationException(msg)
@@ -204,14 +205,10 @@ class BaseResolver(metaclass=abc.ABCMeta):
class BaseRefResolver(BaseResolver): class BaseRefResolver(BaseResolver):
@abc.abstractmethod @abc.abstractmethod
def resolve( def resolve(self, name: str, package: Optional[str] = None) -> RelationProxy:
self, name: str, package: Optional[str] = None
) -> RelationProxy:
... ...
def _repack_args( def _repack_args(self, name: str, package: Optional[str]) -> List[str]:
self, name: str, package: Optional[str]
) -> List[str]:
if package is None: if package is None:
return [name] return [name]
else: else:
@@ -220,14 +217,12 @@ class BaseRefResolver(BaseResolver):
def validate_args(self, name: str, package: Optional[str]): def validate_args(self, name: str, package: Optional[str]):
if not isinstance(name, str): if not isinstance(name, str):
raise CompilationException( raise CompilationException(
f'The name argument to ref() must be a string, got ' f"The name argument to ref() must be a string, got " f"{type(name)}"
f'{type(name)}'
) )
if package is not None and not isinstance(package, str): if package is not None and not isinstance(package, str):
raise CompilationException( raise CompilationException(
f'The package argument to ref() must be a string or None, got ' f"The package argument to ref() must be a string or None, got " f"{type(package)}"
f'{type(package)}'
) )
def __call__(self, *args: str) -> RelationProxy: def __call__(self, *args: str) -> RelationProxy:
@@ -252,20 +247,19 @@ class BaseSourceResolver(BaseResolver):
def validate_args(self, source_name: str, table_name: str): def validate_args(self, source_name: str, table_name: str):
if not isinstance(source_name, str): if not isinstance(source_name, str):
raise CompilationException( raise CompilationException(
f'The source name (first) argument to source() must be a ' f"The source name (first) argument to source() must be a "
f'string, got {type(source_name)}' f"string, got {type(source_name)}"
) )
if not isinstance(table_name, str): if not isinstance(table_name, str):
raise CompilationException( raise CompilationException(
f'The table name (second) argument to source() must be a ' f"The table name (second) argument to source() must be a "
f'string, got {type(table_name)}' f"string, got {type(table_name)}"
) )
def __call__(self, *args: str) -> RelationProxy: def __call__(self, *args: str) -> RelationProxy:
if len(args) != 2: if len(args) != 2:
raise_compiler_error( raise_compiler_error(
f"source() takes exactly two arguments ({len(args)} given)", f"source() takes exactly two arguments ({len(args)} given)", self.model
self.model
) )
self.validate_args(args[0], args[1]) self.validate_args(args[0], args[1])
return self.resolve(args[0], args[1]) return self.resolve(args[0], args[1])
@@ -283,14 +277,15 @@ class ParseConfigObject(Config):
self.context_config = context_config self.context_config = context_config
def _transform_config(self, config): def _transform_config(self, config):
for oldkey in ('pre_hook', 'post_hook'): for oldkey in ("pre_hook", "post_hook"):
if oldkey in config: if oldkey in config:
newkey = oldkey.replace('_', '-') newkey = oldkey.replace("_", "-")
if newkey in config: if newkey in config:
raise_compiler_error( raise_compiler_error(
'Invalid config, has conflicting keys "{}" and "{}"' 'Invalid config, has conflicting keys "{}" and "{}"'.format(
.format(oldkey, newkey), oldkey, newkey
self.model ),
self.model,
) )
config[newkey] = config.pop(oldkey) config[newkey] = config.pop(oldkey)
return config return config
@@ -301,29 +296,25 @@ class ParseConfigObject(Config):
elif len(args) == 0 and len(kwargs) > 0: elif len(args) == 0 and len(kwargs) > 0:
opts = kwargs opts = kwargs
else: else:
raise_compiler_error( raise_compiler_error("Invalid inline model config", self.model)
"Invalid inline model config",
self.model)
opts = self._transform_config(opts) opts = self._transform_config(opts)
# it's ok to have a parse context with no context config, but you must # it's ok to have a parse context with no context config, but you must
# not call it! # not call it!
if self.context_config is None: if self.context_config is None:
raise RuntimeException( raise RuntimeException("At parse time, did not receive a context config")
'At parse time, did not receive a context config'
)
self.context_config.add_config_call(opts) self.context_config.add_config_call(opts)
return '' return ""
def set(self, name, value): def set(self, name, value):
return self.__call__({name: value}) return self.__call__({name: value})
def require(self, name, validator=None): def require(self, name, validator=None):
return '' return ""
def get(self, name, validator=None, default=None): def get(self, name, default=None, validator=None):
return '' return ""
def persist_relation_docs(self) -> bool: def persist_relation_docs(self) -> bool:
return False return False
@@ -333,14 +324,12 @@ class ParseConfigObject(Config):
class RuntimeConfigObject(Config): class RuntimeConfigObject(Config):
def __init__( def __init__(self, model, context_config: Optional[ContextConfig] = None):
self, model, context_config: Optional[ContextConfig] = None
):
self.model = model self.model = model
# we never use or get a config, only the parser cares # we never use or get a config, only the parser cares
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
return '' return ""
def set(self, name, value): def set(self, name, value):
return self.__call__({name: value}) return self.__call__({name: value})
@@ -350,7 +339,7 @@ class RuntimeConfigObject(Config):
def _lookup(self, name, default=_MISSING): def _lookup(self, name, default=_MISSING):
# if this is a macro, there might be no `model.config`. # if this is a macro, there might be no `model.config`.
if not hasattr(self.model, 'config'): if not hasattr(self.model, "config"):
result = default result = default
else: else:
result = self.model.config.get(name, default) result = self.model.config.get(name, default)
@@ -366,7 +355,7 @@ class RuntimeConfigObject(Config):
return to_return return to_return
def get(self, name, validator=None, default=None): def get(self, name, default=None, validator=None):
to_return = self._lookup(name, default) to_return = self._lookup(name, default)
if validator is not None and default is not None: if validator is not None and default is not None:
@@ -375,22 +364,24 @@ class RuntimeConfigObject(Config):
return to_return return to_return
def persist_relation_docs(self) -> bool: def persist_relation_docs(self) -> bool:
persist_docs = self.get('persist_docs', default={}) persist_docs = self.get("persist_docs", default={})
if not isinstance(persist_docs, dict): if not isinstance(persist_docs, dict):
raise_compiler_error( raise_compiler_error(
f"Invalid value provided for 'persist_docs'. Expected dict " f"Invalid value provided for 'persist_docs'. Expected dict "
f"but received {type(persist_docs)}") f"but received {type(persist_docs)}"
)
return persist_docs.get('relation', False) return persist_docs.get("relation", False)
def persist_column_docs(self) -> bool: def persist_column_docs(self) -> bool:
persist_docs = self.get('persist_docs', default={}) persist_docs = self.get("persist_docs", default={})
if not isinstance(persist_docs, dict): if not isinstance(persist_docs, dict):
raise_compiler_error( raise_compiler_error(
f"Invalid value provided for 'persist_docs'. Expected dict " f"Invalid value provided for 'persist_docs'. Expected dict "
f"but received {type(persist_docs)}") f"but received {type(persist_docs)}"
)
return persist_docs.get('columns', False) return persist_docs.get("columns", False)
# `adapter` implementations # `adapter` implementations
@@ -400,8 +391,7 @@ class ParseDatabaseWrapper(BaseDatabaseWrapper):
""" """
def __getattr__(self, name): def __getattr__(self, name):
override = (name in self._adapter._available_ and override = name in self._adapter._available_ and name in self._adapter._parse_replacements_
name in self._adapter._parse_replacements_)
if override: if override:
return self._adapter._parse_replacements_[name] return self._adapter._parse_replacements_[name]
@@ -409,9 +399,7 @@ class ParseDatabaseWrapper(BaseDatabaseWrapper):
return getattr(self._adapter, name) return getattr(self._adapter, name)
else: else:
raise AttributeError( raise AttributeError(
"'{}' object has no attribute '{}'".format( "'{}' object has no attribute '{}'".format(self.__class__.__name__, name)
self.__class__.__name__, name
)
) )
@@ -425,17 +413,13 @@ class RuntimeDatabaseWrapper(BaseDatabaseWrapper):
return getattr(self._adapter, name) return getattr(self._adapter, name)
else: else:
raise AttributeError( raise AttributeError(
"'{}' object has no attribute '{}'".format( "'{}' object has no attribute '{}'".format(self.__class__.__name__, name)
self.__class__.__name__, name
)
) )
# `ref` implementations # `ref` implementations
class ParseRefResolver(BaseRefResolver): class ParseRefResolver(BaseRefResolver):
def resolve( def resolve(self, name: str, package: Optional[str] = None) -> RelationProxy:
self, name: str, package: Optional[str] = None
) -> RelationProxy:
self.model.refs.append(self._repack_args(name, package)) self.model.refs.append(self._repack_args(name, package))
return self.Relation.create_from(self.config, self.model) return self.Relation.create_from(self.config, self.model)
@@ -445,9 +429,7 @@ ResolveRef = Union[Disabled, ManifestNode]
class RuntimeRefResolver(BaseRefResolver): class RuntimeRefResolver(BaseRefResolver):
def resolve( def resolve(self, target_name: str, target_package: Optional[str] = None) -> RelationProxy:
self, target_name: str, target_package: Optional[str] = None
) -> RelationProxy:
target_model = self.manifest.resolve_ref( target_model = self.manifest.resolve_ref(
target_name, target_name,
target_package, target_package,
@@ -465,22 +447,15 @@ class RuntimeRefResolver(BaseRefResolver):
self.validate(target_model, target_name, target_package) self.validate(target_model, target_name, target_package)
return self.create_relation(target_model, target_name) return self.create_relation(target_model, target_name)
def create_relation( def create_relation(self, target_model: ManifestNode, name: str) -> RelationProxy:
self, target_model: ManifestNode, name: str
) -> RelationProxy:
if target_model.is_ephemeral_model: if target_model.is_ephemeral_model:
self.model.set_cte(target_model.unique_id, None) self.model.set_cte(target_model.unique_id, None)
return self.Relation.create_ephemeral_from_node( return self.Relation.create_ephemeral_from_node(self.config, target_model)
self.config, target_model
)
else: else:
return self.Relation.create_from(self.config, target_model) return self.Relation.create_from(self.config, target_model)
def validate( def validate(
self, self, resolved: ManifestNode, target_name: str, target_package: Optional[str]
resolved: ManifestNode,
target_name: str,
target_package: Optional[str]
) -> None: ) -> None:
if resolved.unique_id not in self.model.depends_on.nodes: if resolved.unique_id not in self.model.depends_on.nodes:
args = self._repack_args(target_name, target_package) args = self._repack_args(target_name, target_package)
@@ -496,16 +471,15 @@ class OperationRefResolver(RuntimeRefResolver):
) -> None: ) -> None:
pass pass
def create_relation( def create_relation(self, target_model: ManifestNode, name: str) -> RelationProxy:
self, target_model: ManifestNode, name: str if not hasattr(self.model, "set_cte") and target_model.is_ephemeral_model:
) -> RelationProxy:
if target_model.is_ephemeral_model:
# In operations, we can't ref() ephemeral nodes, because # In operations, we can't ref() ephemeral nodes, because
# ParsedMacros do not support set_cte # ParsedMacros do not support set_cte
raise_compiler_error( raise_compiler_error(
'Operations can not ref() ephemeral nodes, but {} is ephemeral' "Macros run as operations cannot ref() ephemeral nodes, but {} is ephemeral".format(
.format(target_model.name), target_model.name
self.model ),
self.model,
) )
else: else:
return super().create_relation(target_model, name) return super().create_relation(target_model, name)
@@ -556,10 +530,7 @@ class ModelConfiguredVar(Var):
if package_name != self._config.project_name: if package_name != self._config.project_name:
if package_name not in dependencies: if package_name not in dependencies:
# I don't think this is actually reachable # I don't think this is actually reachable
raise_compiler_error( raise_compiler_error(f"Node package named {package_name} not found!", self._node)
f'Node package named {package_name} not found!',
self._node
)
yield dependencies[package_name] yield dependencies[package_name]
yield self._config yield self._config
@@ -630,11 +601,12 @@ class OperationProvider(RuntimeProvider):
ref = OperationRefResolver ref = OperationRefResolver
T = TypeVar('T') T = TypeVar("T")
# Base context collection, used for parsing configs. # Base context collection, used for parsing configs.
class ProviderContext(ManifestContext): class ProviderContext(ManifestContext):
# subclasses are MacroContext, ModelContext, TestContext
def __init__( def __init__(
self, self,
model, model,
@@ -644,9 +616,7 @@ class ProviderContext(ManifestContext):
context_config: Optional[ContextConfig], context_config: Optional[ContextConfig],
) -> None: ) -> None:
if provider is None: if provider is None:
raise InternalException( raise InternalException(f"Invalid provider given to context: {provider}")
f"Invalid provider given to context: {provider}"
)
# mypy appeasement - we know it'll be a RuntimeConfig # mypy appeasement - we know it'll be a RuntimeConfig
self.config: RuntimeConfig self.config: RuntimeConfig
self.model: Union[ParsedMacro, ManifestNode] = model self.model: Union[ParsedMacro, ManifestNode] = model
@@ -656,16 +626,12 @@ class ProviderContext(ManifestContext):
self.provider: Provider = provider self.provider: Provider = provider
self.adapter = get_adapter(self.config) self.adapter = get_adapter(self.config)
# The macro namespace is used in creating the DatabaseWrapper # The macro namespace is used in creating the DatabaseWrapper
self.db_wrapper = self.provider.DatabaseWrapper( self.db_wrapper = self.provider.DatabaseWrapper(self.adapter, self.namespace)
self.adapter, self.namespace
)
# This overrides the method in ManifestContext, and provides # This overrides the method in ManifestContext, and provides
# a model, which the ManifestContext builder does not # a model, which the ManifestContext builder does not
def _get_namespace_builder(self): def _get_namespace_builder(self):
internal_packages = get_adapter_package_names( internal_packages = get_adapter_package_names(self.config.credentials.type)
self.config.credentials.type
)
return MacroNamespaceBuilder( return MacroNamespaceBuilder(
self.config.project_name, self.config.project_name,
self.search_package, self.search_package,
@@ -684,19 +650,19 @@ class ProviderContext(ManifestContext):
@contextmember @contextmember
def store_result( def store_result(
self, name: str, self, name: str, response: Any, agate_table: Optional[agate.Table] = None
response: Any,
agate_table: Optional[agate.Table] = None
) -> str: ) -> str:
if agate_table is None: if agate_table is None:
agate_table = agate_helper.empty_table() agate_table = agate_helper.empty_table()
self.sql_results[name] = AttrDict({ self.sql_results[name] = AttrDict(
'response': response, {
'data': agate_helper.as_matrix(agate_table), "response": response,
'table': agate_table "data": agate_helper.as_matrix(agate_table),
}) "table": agate_table,
return '' }
)
return ""
@contextmember @contextmember
def store_raw_result( def store_raw_result(
@@ -705,10 +671,9 @@ class ProviderContext(ManifestContext):
message=Optional[str], message=Optional[str],
code=Optional[str], code=Optional[str],
rows_affected=Optional[str], rows_affected=Optional[str],
agate_table: Optional[agate.Table] = None agate_table: Optional[agate.Table] = None,
) -> str: ) -> str:
response = AdapterResponse( response = AdapterResponse(_message=message, code=code, rows_affected=rows_affected)
_message=message, code=code, rows_affected=rows_affected)
return self.store_result(name, response, agate_table) return self.store_result(name, response, agate_table)
@contextproperty @contextproperty
@@ -721,25 +686,24 @@ class ProviderContext(ManifestContext):
elif value == arg: elif value == arg:
return return
raise ValidationException( raise ValidationException(
'Expected value "{}" to be one of {}' 'Expected value "{}" to be one of {}'.format(value, ",".join(map(str, args)))
.format(value, ','.join(map(str, args)))) )
return inner return inner
return AttrDict({ return AttrDict(
'any': validate_any, {
}) "any": validate_any,
}
)
@contextmember @contextmember
def write(self, payload: str) -> str: def write(self, payload: str) -> str:
# macros/source defs aren't 'writeable'. # macros/source defs aren't 'writeable'.
if isinstance(self.model, (ParsedMacro, ParsedSourceDefinition)): if isinstance(self.model, (ParsedMacro, ParsedSourceDefinition)):
raise_compiler_error( raise_compiler_error('cannot "write" macros or sources')
'cannot "write" macros or sources' self.model.build_path = self.model.write_node(self.config.target_path, "run", payload)
) return ""
self.model.build_path = self.model.write_node(
self.config.target_path, 'run', payload
)
return ''
@contextmember @contextmember
def render(self, string: str) -> str: def render(self, string: str) -> str:
@@ -752,20 +716,15 @@ class ProviderContext(ManifestContext):
try: try:
return func(*args, **kwargs) return func(*args, **kwargs)
except Exception: except Exception:
raise_compiler_error( raise_compiler_error(message_if_exception, self.model)
message_if_exception, self.model
)
@contextmember @contextmember
def load_agate_table(self) -> agate.Table: def load_agate_table(self) -> agate.Table:
if not isinstance(self.model, (ParsedSeedNode, CompiledSeedNode)): if not isinstance(self.model, (ParsedSeedNode, CompiledSeedNode)):
raise_compiler_error( raise_compiler_error(
'can only load_agate_table for seeds (got a {})' "can only load_agate_table for seeds (got a {})".format(self.model.resource_type)
.format(self.model.resource_type)
)
path = os.path.join(
self.model.root_path, self.model.original_file_path
) )
path = os.path.join(self.model.root_path, self.model.original_file_path)
column_types = self.model.config.column_types column_types = self.model.config.column_types
try: try:
table = agate_helper.from_csv(path, text_columns=column_types) table = agate_helper.from_csv(path, text_columns=column_types)
@@ -813,17 +772,13 @@ class ProviderContext(ManifestContext):
select * from {{ ref('package_name', 'model_name') }}" select * from {{ ref('package_name', 'model_name') }}"
""" """
return self.provider.ref( return self.provider.ref(self.db_wrapper, self.model, self.config, self.manifest)
self.db_wrapper, self.model, self.config, self.manifest
)
@contextproperty @contextproperty
def source(self) -> Callable: def source(self) -> Callable:
return self.provider.source( return self.provider.source(self.db_wrapper, self.model, self.config, self.manifest)
self.db_wrapper, self.model, self.config, self.manifest
)
@contextproperty('config') @contextproperty("config")
def ctx_config(self) -> Config: def ctx_config(self) -> Config:
"""The `config` variable exists to handle end-user configuration for """The `config` variable exists to handle end-user configuration for
custom materializations. Configs like `unique_key` can be implemented custom materializations. Configs like `unique_key` can be implemented
@@ -995,7 +950,7 @@ class ProviderContext(ManifestContext):
node=self.model, node=self.model,
) )
@contextproperty('adapter') @contextproperty("adapter")
def ctx_adapter(self) -> BaseDatabaseWrapper: def ctx_adapter(self) -> BaseDatabaseWrapper:
"""`adapter` is a wrapper around the internal database adapter used by """`adapter` is a wrapper around the internal database adapter used by
dbt. It allows users to make calls to the database in their dbt models. dbt. It allows users to make calls to the database in their dbt models.
@@ -1007,8 +962,8 @@ class ProviderContext(ManifestContext):
@contextproperty @contextproperty
def api(self) -> Dict[str, Any]: def api(self) -> Dict[str, Any]:
return { return {
'Relation': self.db_wrapper.Relation, "Relation": self.db_wrapper.Relation,
'Column': self.adapter.Column, "Column": self.adapter.Column,
} }
@contextproperty @contextproperty
@@ -1126,7 +1081,7 @@ class ProviderContext(ManifestContext):
""" # noqa """ # noqa
return self.manifest.flat_graph return self.manifest.flat_graph
@contextproperty('model') @contextproperty("model")
def ctx_model(self) -> Dict[str, Any]: def ctx_model(self) -> Dict[str, Any]:
return self.model.to_dict(omit_none=True) return self.model.to_dict(omit_none=True)
@@ -1148,23 +1103,53 @@ class ProviderContext(ManifestContext):
@contextmember @contextmember
def adapter_macro(self, name: str, *args, **kwargs): def adapter_macro(self, name: str, *args, **kwargs):
"""This was deprecated in v0.18 in favor of adapter.dispatch """This was deprecated in v0.18 in favor of adapter.dispatch"""
"""
msg = ( msg = (
'The "adapter_macro" macro has been deprecated. Instead, use ' 'The "adapter_macro" macro has been deprecated. Instead, use '
'the `adapter.dispatch` method to find a macro and call the ' "the `adapter.dispatch` method to find a macro and call the "
'result. For more information, see: ' "result. For more information, see: "
'https://docs.getdbt.com/reference/dbt-jinja-functions/dispatch)' "https://docs.getdbt.com/reference/dbt-jinja-functions/dispatch)"
' adapter_macro was called for: {macro_name}' " adapter_macro was called for: {macro_name}".format(macro_name=name)
.format(macro_name=name)
) )
raise CompilationException(msg) raise CompilationException(msg)
@contextmember
def env_var(self, var: str, default: Optional[str] = None) -> str:
"""The env_var() function. Return the environment variable named 'var'.
If there is no such environment variable set, return the default.
If the default is None, raise an exception for an undefined variable.
"""
return_value = None
if var.startswith(SECRET_ENV_PREFIX):
disallow_secret_env_var(var)
if var in os.environ:
return_value = os.environ[var]
elif default is not None:
return_value = default
if return_value is not None:
# Save the env_var value in the manifest and the var name in the source_file.
# If this is compiling, do not save because it's irrelevant to parsing.
if self.model and not hasattr(self.model, "compiled"):
self.manifest.env_vars[var] = return_value
# hooks come from dbt_project.yml which doesn't have a real file_id
if self.model.file_id in self.manifest.files:
source_file = self.manifest.files[self.model.file_id]
# Schema files should never get here
if source_file.parse_file_type != "schema":
# TODO CT-211
source_file.env_vars.append(var) # type: ignore[union-attr]
return return_value
else:
msg = f"Env var required but not provided: '{var}'"
raise_parsing_error(msg)
class MacroContext(ProviderContext): class MacroContext(ProviderContext):
"""Internally, macros can be executed like nodes, with some restrictions: """Internally, macros can be executed like nodes, with some restrictions:
- they don't have have all values available that nodes do: - they don't have all values available that nodes do:
- 'this', 'pre_hooks', 'post_hooks', and 'sql' are missing - 'this', 'pre_hooks', 'post_hooks', and 'sql' are missing
- 'schema' does not use any 'model' information - 'schema' does not use any 'model' information
- they can't be configured with config() directives - they can't be configured with config() directives
@@ -1194,35 +1179,34 @@ class ModelContext(ProviderContext):
def pre_hooks(self) -> List[Dict[str, Any]]: def pre_hooks(self) -> List[Dict[str, Any]]:
if self.model.resource_type in [NodeType.Source, NodeType.Test]: if self.model.resource_type in [NodeType.Source, NodeType.Test]:
return [] return []
# TODO CT-211
return [ return [
h.to_dict(omit_none=True) for h in self.model.config.pre_hook h.to_dict(omit_none=True) for h in self.model.config.pre_hook # type: ignore[union-attr] # noqa
] ]
@contextproperty @contextproperty
def post_hooks(self) -> List[Dict[str, Any]]: def post_hooks(self) -> List[Dict[str, Any]]:
if self.model.resource_type in [NodeType.Source, NodeType.Test]: if self.model.resource_type in [NodeType.Source, NodeType.Test]:
return [] return []
# TODO CT-211
return [ return [
h.to_dict(omit_none=True) for h in self.model.config.post_hook h.to_dict(omit_none=True) for h in self.model.config.post_hook # type: ignore[union-attr] # noqa
] ]
@contextproperty @contextproperty
def sql(self) -> Optional[str]: def sql(self) -> Optional[str]:
if getattr(self.model, 'extra_ctes_injected', None): if getattr(self.model, "extra_ctes_injected", None):
return self.model.compiled_sql # TODO CT-211
return self.model.compiled_sql # type: ignore[union-attr]
return None return None
@contextproperty @contextproperty
def database(self) -> str: def database(self) -> str:
return getattr( return getattr(self.model, "database", self.config.credentials.database)
self.model, 'database', self.config.credentials.database
)
@contextproperty @contextproperty
def schema(self) -> str: def schema(self) -> str:
return getattr( return getattr(self.model, "schema", self.config.credentials.schema)
self.model, 'schema', self.config.credentials.schema
)
@contextproperty @contextproperty
def this(self) -> Optional[RelationProxy]: def this(self) -> Optional[RelationProxy]:
@@ -1261,7 +1245,7 @@ class ModelContext(ProviderContext):
# This is called by '_context_for', used in 'render_with_context' # This is called by '_context_for', used in 'render_with_context'
def generate_parser_model( def generate_parser_model_context(
model: ManifestNode, model: ManifestNode,
config: RuntimeConfig, config: RuntimeConfig,
manifest: Manifest, manifest: Manifest,
@@ -1270,45 +1254,46 @@ def generate_parser_model(
# The __init__ method of ModelContext also initializes # The __init__ method of ModelContext also initializes
# a ManifestContext object which creates a MacroNamespaceBuilder # a ManifestContext object which creates a MacroNamespaceBuilder
# which adds every macro in the Manifest. # which adds every macro in the Manifest.
ctx = ModelContext( ctx = ModelContext(model, config, manifest, ParseProvider(), context_config)
model, config, manifest, ParseProvider(), context_config
)
# The 'to_dict' method in ManifestContext moves all of the macro names # The 'to_dict' method in ManifestContext moves all of the macro names
# in the macro 'namespace' up to top level keys # in the macro 'namespace' up to top level keys
return ctx.to_dict() return ctx.to_dict()
def generate_generate_component_name_macro( def generate_generate_name_macro_context(
macro: ParsedMacro, macro: ParsedMacro,
config: RuntimeConfig, config: RuntimeConfig,
manifest: Manifest, manifest: Manifest,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
ctx = MacroContext( ctx = MacroContext(macro, config, manifest, GenerateNameProvider(), None)
macro, config, manifest, GenerateNameProvider(), None
)
return ctx.to_dict() return ctx.to_dict()
def generate_runtime_model( def generate_runtime_model_context(
model: ManifestNode, model: ManifestNode,
config: RuntimeConfig, config: RuntimeConfig,
manifest: Manifest, manifest: Manifest,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
ctx = ModelContext( ctx = ModelContext(model, config, manifest, RuntimeProvider(), None)
model, config, manifest, RuntimeProvider(), None
)
return ctx.to_dict() return ctx.to_dict()
def generate_runtime_macro( def generate_runtime_macro_context(
macro: ParsedMacro, macro: ParsedMacro,
config: RuntimeConfig, config: RuntimeConfig,
manifest: Manifest, manifest: Manifest,
package_name: Optional[str], package_name: Optional[str],
) -> Dict[str, Any]: ) -> Dict[str, Any]:
ctx = MacroContext( ctx = MacroContext(macro, config, manifest, OperationProvider(), package_name)
macro, config, manifest, OperationProvider(), package_name return ctx.to_dict()
)
def generate_runtime_sql_operation_context(
model: Union[CompiledSqlNode, CompiledRPCNode],
config: RuntimeConfig,
manifest: Manifest,
) -> Dict[str, Any]:
ctx = ModelContext(model, config, manifest, OperationProvider(), None)
return ctx.to_dict() return ctx.to_dict()
@@ -1317,18 +1302,17 @@ class ExposureRefResolver(BaseResolver):
if len(args) not in (1, 2): if len(args) not in (1, 2):
ref_invalid_args(self.model, args) ref_invalid_args(self.model, args)
self.model.refs.append(list(args)) self.model.refs.append(list(args))
return '' return ""
class ExposureSourceResolver(BaseResolver): class ExposureSourceResolver(BaseResolver):
def __call__(self, *args) -> str: def __call__(self, *args) -> str:
if len(args) != 2: if len(args) != 2:
raise_compiler_error( raise_compiler_error(
f"source() takes exactly two arguments ({len(args)} given)", f"source() takes exactly two arguments ({len(args)} given)", self.model
self.model
) )
self.model.sources.append(list(args)) self.model.sources.append(list(args))
return '' return ""
def generate_parse_exposure( def generate_parse_exposure(
@@ -1339,18 +1323,56 @@ def generate_parse_exposure(
) -> Dict[str, Any]: ) -> Dict[str, Any]:
project = config.load_dependencies()[package_name] project = config.load_dependencies()[package_name]
return { return {
'ref': ExposureRefResolver( "ref": ExposureRefResolver(
None, None,
exposure, exposure,
project, project,
manifest, manifest,
), ),
'source': ExposureSourceResolver( "source": ExposureSourceResolver(
None, None,
exposure, exposure,
project, project,
manifest, manifest,
),
}
class MetricRefResolver(BaseResolver):
def __call__(self, *args) -> str:
package = None
if len(args) == 1:
name = args[0]
elif len(args) == 2:
package, name = args
else:
ref_invalid_args(self.model, args)
self.validate_args(name, package)
self.model.refs.append(list(args))
return ""
def validate_args(self, name, package):
if not isinstance(name, str):
raise ParsingException(
f"In a metrics section in {self.model.original_file_path} "
f"the name argument to ref() must be a string"
) )
def generate_parse_metrics(
metric: ParsedMetric,
config: RuntimeConfig,
manifest: Manifest,
package_name: str,
) -> Dict[str, Any]:
project = config.load_dependencies()[package_name]
return {
"ref": MetricRefResolver(
None,
metric,
project,
manifest,
),
} }
@@ -1375,9 +1397,7 @@ class TestContext(ProviderContext):
self._build_test_namespace() self._build_test_namespace()
# We need to rebuild this because it's already been built by # We need to rebuild this because it's already been built by
# the ProviderContext with the wrong namespace. # the ProviderContext with the wrong namespace.
self.db_wrapper = self.provider.DatabaseWrapper( self.db_wrapper = self.provider.DatabaseWrapper(self.adapter, self.namespace)
self.adapter, self.namespace
)
def _build_namespace(self): def _build_namespace(self):
return {} return {}
@@ -1388,8 +1408,13 @@ class TestContext(ProviderContext):
# 'depends_on.macros' by using the TestMacroNamespace # 'depends_on.macros' by using the TestMacroNamespace
def _build_test_namespace(self): def _build_test_namespace(self):
depends_on_macros = [] depends_on_macros = []
# all generic tests use a macro named 'get_where_subquery' to wrap 'model' arg
# see generic_test_builders.build_model_str
get_where_subquery = self.macro_resolver.macros_by_name.get("get_where_subquery")
if get_where_subquery:
depends_on_macros.append(get_where_subquery.unique_id)
if self.model.depends_on and self.model.depends_on.macros: if self.model.depends_on and self.model.depends_on.macros:
depends_on_macros = self.model.depends_on.macros depends_on_macros.extend(self.model.depends_on.macros)
lookup_macros = depends_on_macros.copy() lookup_macros = depends_on_macros.copy()
for macro_unique_id in lookup_macros: for macro_unique_id in lookup_macros:
lookup_macro = self.macro_resolver.macros.get(macro_unique_id) lookup_macro = self.macro_resolver.macros.get(macro_unique_id)
@@ -1397,23 +1422,46 @@ class TestContext(ProviderContext):
depends_on_macros.extend(lookup_macro.depends_on.macros) depends_on_macros.extend(lookup_macro.depends_on.macros)
macro_namespace = TestMacroNamespace( macro_namespace = TestMacroNamespace(
self.macro_resolver, self._ctx, self.model, self.thread_ctx, self.macro_resolver, self._ctx, self.model, self.thread_ctx, depends_on_macros
depends_on_macros
) )
self.namespace = macro_namespace self.namespace = macro_namespace
@contextmember
def env_var(self, var: str, default: Optional[str] = None) -> str:
return_value = None
if var.startswith(SECRET_ENV_PREFIX):
disallow_secret_env_var(var)
if var in os.environ:
return_value = os.environ[var]
elif default is not None:
return_value = default
if return_value is not None:
# Save the env_var value in the manifest and the var name in the source_file
if self.model:
self.manifest.env_vars[var] = return_value
# the "model" should only be test nodes, but just in case, check
# TODO CT-211
if self.model.resource_type == NodeType.Test and self.model.file_key_name: # type: ignore[union-attr] # noqa
source_file = self.manifest.files[self.model.file_id]
# TODO CT-211
(yaml_key, name) = self.model.file_key_name.split(".") # type: ignore[union-attr] # noqa
# TODO CT-211
source_file.add_env_var(var, yaml_key, name) # type: ignore[union-attr]
return return_value
else:
msg = f"Env var required but not provided: '{var}'"
raise_parsing_error(msg)
def generate_test_context( def generate_test_context(
model: ManifestNode, model: ManifestNode,
config: RuntimeConfig, config: RuntimeConfig,
manifest: Manifest, manifest: Manifest,
context_config: ContextConfig, context_config: ContextConfig,
macro_resolver: MacroResolver macro_resolver: MacroResolver,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
ctx = TestContext( ctx = TestContext(model, config, manifest, ParseProvider(), context_config, macro_resolver)
model, config, manifest, ParseProvider(), context_config,
macro_resolver
)
# The 'to_dict' method in ManifestContext moves all of the macro names # The 'to_dict' method in ManifestContext moves all of the macro names
# in the macro 'namespace' up to top level keys # in the macro 'namespace' up to top level keys
return ctx.to_dict() return ctx.to_dict()

View File

@@ -0,0 +1,45 @@
import os
from typing import Any, Dict, Optional
from .base import BaseContext, contextmember
from dbt.exceptions import raise_parsing_error
from dbt.logger import SECRET_ENV_PREFIX
class SecretContext(BaseContext):
"""This context is used in profiles.yml + packages.yml. It can render secret
env vars that aren't usable elsewhere"""
@contextmember
def env_var(self, var: str, default: Optional[str] = None) -> str:
"""The env_var() function. Return the environment variable named 'var'.
If there is no such environment variable set, return the default.
If the default is None, raise an exception for an undefined variable.
In this context *only*, env_var will return the actual values of
env vars prefixed with DBT_ENV_SECRET_
"""
return_value = None
if var in os.environ:
return_value = os.environ[var]
elif default is not None:
return_value = default
if return_value is not None:
# do not save secret environment variables
if not var.startswith(SECRET_ENV_PREFIX):
self.env_vars[var] = return_value
# return the value even if its a secret
return return_value
else:
msg = f"Env var required but not provided: '{var}'"
raise_parsing_error(msg)
def generate_secret_context(cli_vars: Dict[str, Any]) -> Dict[str, Any]:
ctx = SecretContext(cli_vars)
# This is not a Mashumaro to_dict call
return ctx.to_dict()

View File

@@ -2,12 +2,11 @@ from typing import Any, Dict
from dbt.contracts.connection import HasCredentials from dbt.contracts.connection import HasCredentials
from dbt.context.base import ( from dbt.context.base import BaseContext, contextproperty
BaseContext, contextproperty
)
class TargetContext(BaseContext): class TargetContext(BaseContext):
# subclass is ConfiguredContext
def __init__(self, config: HasCredentials, cli_vars: Dict[str, Any]): def __init__(self, config: HasCredentials, cli_vars: Dict[str, Any]):
super().__init__(cli_vars=cli_vars) super().__init__(cli_vars=cli_vars)
self.config = config self.config = config
@@ -77,8 +76,6 @@ class TargetContext(BaseContext):
return self.config.to_target_dict() return self.config.to_target_dict()
def generate_target_context( def generate_target_context(config: HasCredentials, cli_vars: Dict[str, Any]) -> Dict[str, Any]:
config: HasCredentials, cli_vars: Dict[str, Any]
) -> Dict[str, Any]:
ctx = TargetContext(config, cli_vars) ctx = TargetContext(config, cli_vars)
return ctx.to_dict() return ctx.to_dict()

View File

@@ -0,0 +1 @@
# Contracts README

View File

@@ -3,25 +3,37 @@ import itertools
import hashlib import hashlib
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import ( from typing import (
Any, ClassVar, Dict, Tuple, Iterable, Optional, List, Callable, Any,
ClassVar,
Dict,
Tuple,
Iterable,
Optional,
List,
Callable,
) )
from dbt.exceptions import InternalException from dbt.exceptions import InternalException
from dbt.utils import translate_aliases from dbt.utils import translate_aliases
from dbt.logger import GLOBAL_LOGGER as logger from dbt.events.functions import fire_event
from dbt.events.types import NewConnectionOpening
from typing_extensions import Protocol from typing_extensions import Protocol
from dbt.dataclass_schema import ( from dbt.dataclass_schema import (
dbtClassMixin, StrEnum, ExtensibleDbtClassMixin, HyphenatedDbtClassMixin, dbtClassMixin,
ValidatedStringMixin, register_pattern StrEnum,
ExtensibleDbtClassMixin,
HyphenatedDbtClassMixin,
ValidatedStringMixin,
register_pattern,
) )
from dbt.contracts.util import Replaceable from dbt.contracts.util import Replaceable
class Identifier(ValidatedStringMixin): class Identifier(ValidatedStringMixin):
ValidationRegex = r'^[A-Za-z_][A-Za-z0-9_]+$' ValidationRegex = r"^[A-Za-z_][A-Za-z0-9_]+$"
# we need register_pattern for jsonschema validation # we need register_pattern for jsonschema validation
register_pattern(Identifier, r'^[A-Za-z_][A-Za-z0-9_]+$') register_pattern(Identifier, r"^[A-Za-z_][A-Za-z0-9_]+$")
@dataclass @dataclass
@@ -35,10 +47,10 @@ class AdapterResponse(dbtClassMixin):
class ConnectionState(StrEnum): class ConnectionState(StrEnum):
INIT = 'init' INIT = "init"
OPEN = 'open' OPEN = "open"
CLOSED = 'closed' CLOSED = "closed"
FAIL = 'fail' FAIL = "fail"
@dataclass(init=False) @dataclass(init=False)
@@ -82,8 +94,7 @@ class Connection(ExtensibleDbtClassMixin, Replaceable):
self._handle.resolve(self) self._handle.resolve(self)
except RecursionError as exc: except RecursionError as exc:
raise InternalException( raise InternalException(
"A connection's open() method attempted to read the " "A connection's open() method attempted to read the " "handle value"
"handle value"
) from exc ) from exc
return self._handle return self._handle
@@ -93,7 +104,7 @@ class Connection(ExtensibleDbtClassMixin, Replaceable):
class LazyHandle: class LazyHandle:
"""Opener must be a callable that takes a Connection object and opens the """The opener must be a callable that takes a Connection object and opens the
connection, updating the handle on the Connection. connection, updating the handle on the Connection.
""" """
@@ -101,10 +112,7 @@ class LazyHandle:
self.opener = opener self.opener = opener
def resolve(self, connection: Connection) -> Connection: def resolve(self, connection: Connection) -> Connection:
logger.debug( fire_event(NewConnectionOpening(connection_state=connection.state))
'Opening a new connection, currently in state {}'
.format(connection.state)
)
return self.opener(connection) return self.opener(connection)
@@ -113,20 +121,14 @@ class LazyHandle:
# for why we have type: ignore. Maybe someday dataclasses + abstract classes # for why we have type: ignore. Maybe someday dataclasses + abstract classes
# will work. # will work.
@dataclass # type: ignore @dataclass # type: ignore
class Credentials( class Credentials(ExtensibleDbtClassMixin, Replaceable, metaclass=abc.ABCMeta):
ExtensibleDbtClassMixin,
Replaceable,
metaclass=abc.ABCMeta
):
database: str database: str
schema: str schema: str
_ALIASES: ClassVar[Dict[str, str]] = field(default={}, init=False) _ALIASES: ClassVar[Dict[str, str]] = field(default={}, init=False)
@abc.abstractproperty @abc.abstractproperty
def type(self) -> str: def type(self) -> str:
raise NotImplementedError( raise NotImplementedError("type not implemented for base credentials class")
'type not implemented for base credentials class'
)
@property @property
def unique_field(self) -> str: def unique_field(self) -> str:
@@ -134,25 +136,18 @@ class Credentials(
Return the field from Credentials that can uniquely identify Return the field from Credentials that can uniquely identify
one team/organization using this adapter one team/organization using this adapter
""" """
raise NotImplementedError( raise NotImplementedError("unique_field not implemented for base credentials class")
'unique_field not implemented for base credentials class'
)
def hashed_unique_field(self) -> str: def hashed_unique_field(self) -> str:
return hashlib.md5(self.unique_field.encode('utf-8')).hexdigest() return hashlib.md5(self.unique_field.encode("utf-8")).hexdigest()
def connection_info( def connection_info(self, *, with_aliases: bool = False) -> Iterable[Tuple[str, Any]]:
self, *, with_aliases: bool = False """Return an ordered iterator of key/value pairs for pretty-printing."""
) -> Iterable[Tuple[str, Any]]:
"""Return an ordered iterator of key/value pairs for pretty-printing.
"""
as_dict = self.to_dict(omit_none=False) as_dict = self.to_dict(omit_none=False)
connection_keys = set(self._connection_keys()) connection_keys = set(self._connection_keys())
aliases: List[str] = [] aliases: List[str] = []
if with_aliases: if with_aliases:
aliases = [ aliases = [k for k, v in self._ALIASES.items() if v in connection_keys]
k for k, v in self._ALIASES.items() if v in connection_keys
]
for key in itertools.chain(self._connection_keys(), aliases): for key in itertools.chain(self._connection_keys(), aliases):
if key in as_dict: if key in as_dict:
yield key, as_dict[key] yield key, as_dict[key]
@@ -168,19 +163,19 @@ class Credentials(
return data return data
@classmethod @classmethod
def translate_aliases( def translate_aliases(cls, kwargs: Dict[str, Any], recurse: bool = False) -> Dict[str, Any]:
cls, kwargs: Dict[str, Any], recurse: bool = False
) -> Dict[str, Any]:
return translate_aliases(kwargs, cls._ALIASES, recurse) return translate_aliases(kwargs, cls._ALIASES, recurse)
def __post_serialize__(self, dct): def __post_serialize__(self, dct):
# no super() -- do we need it? # no super() -- do we need it?
if self._ALIASES: if self._ALIASES:
dct.update({ dct.update(
{
new_name: dct[canonical_name] new_name: dct[canonical_name]
for new_name, canonical_name in self._ALIASES.items() for new_name, canonical_name in self._ALIASES.items()
if canonical_name in dct if canonical_name in dct
}) }
)
return dct return dct
@@ -199,10 +194,10 @@ class HasCredentials(Protocol):
threads: int threads: int
def to_target_dict(self): def to_target_dict(self):
raise NotImplementedError('to_target_dict not implemented') raise NotImplementedError("to_target_dict not implemented")
DEFAULT_QUERY_COMMENT = ''' DEFAULT_QUERY_COMMENT = """
{%- set comment_dict = {} -%} {%- set comment_dict = {} -%}
{%- do comment_dict.update( {%- do comment_dict.update(
app='dbt', app='dbt',
@@ -219,7 +214,7 @@ DEFAULT_QUERY_COMMENT = '''
{%- do comment_dict.update(connection_name=connection_name) -%} {%- do comment_dict.update(connection_name=connection_name) -%}
{%- endif -%} {%- endif -%}
{{ return(tojson(comment_dict)) }} {{ return(tojson(comment_dict)) }}
''' """
@dataclass @dataclass

View File

@@ -10,33 +10,33 @@ from .util import SourceKey
MAXIMUM_SEED_SIZE = 1 * 1024 * 1024 MAXIMUM_SEED_SIZE = 1 * 1024 * 1024
MAXIMUM_SEED_SIZE_NAME = '1MB' MAXIMUM_SEED_SIZE_NAME = "1MB"
class ParseFileType(StrEnum): class ParseFileType(StrEnum):
Macro = 'macro' Macro = "macro"
Model = 'model' Model = "model"
Snapshot = 'snapshot' Snapshot = "snapshot"
Analysis = 'analysis' Analysis = "analysis"
SingularTest = 'singular_test' SingularTest = "singular_test"
GenericTest = 'generic_test' GenericTest = "generic_test"
Seed = 'seed' Seed = "seed"
Documentation = 'docs' Documentation = "docs"
Schema = 'schema' Schema = "schema"
Hook = 'hook' # not a real filetype, from dbt_project.yml Hook = "hook" # not a real filetype, from dbt_project.yml
parse_file_type_to_parser = { parse_file_type_to_parser = {
ParseFileType.Macro: 'MacroParser', ParseFileType.Macro: "MacroParser",
ParseFileType.Model: 'ModelParser', ParseFileType.Model: "ModelParser",
ParseFileType.Snapshot: 'SnapshotParser', ParseFileType.Snapshot: "SnapshotParser",
ParseFileType.Analysis: 'AnalysisParser', ParseFileType.Analysis: "AnalysisParser",
ParseFileType.SingularTest: 'SingularTestParser', ParseFileType.SingularTest: "SingularTestParser",
ParseFileType.GenericTest: 'GenericTestParser', ParseFileType.GenericTest: "GenericTestParser",
ParseFileType.Seed: 'SeedParser', ParseFileType.Seed: "SeedParser",
ParseFileType.Documentation: 'DocumentationParser', ParseFileType.Documentation: "DocumentationParser",
ParseFileType.Schema: 'SchemaParser', ParseFileType.Schema: "SchemaParser",
ParseFileType.Hook: 'HookParser', ParseFileType.Hook: "HookParser",
} }
@@ -55,9 +55,7 @@ class FilePath(dbtClassMixin):
@property @property
def full_path(self) -> str: def full_path(self) -> str:
# useful for symlink preservation # useful for symlink preservation
return os.path.join( return os.path.join(self.project_root, self.searched_path, self.relative_path)
self.project_root, self.searched_path, self.relative_path
)
@property @property
def absolute_path(self) -> str: def absolute_path(self) -> str:
@@ -67,13 +65,10 @@ class FilePath(dbtClassMixin):
def original_file_path(self) -> str: def original_file_path(self) -> str:
# this is mostly used for reporting errors. It doesn't show the project # this is mostly used for reporting errors. It doesn't show the project
# name, should it? # name, should it?
return os.path.join( return os.path.join(self.searched_path, self.relative_path)
self.searched_path, self.relative_path
)
def seed_too_large(self) -> bool: def seed_too_large(self) -> bool:
"""Return whether the file this represents is over the seed size limit """Return whether the file this represents is over the seed size limit"""
"""
return os.stat(self.full_path).st_size > MAXIMUM_SEED_SIZE return os.stat(self.full_path).st_size > MAXIMUM_SEED_SIZE
@@ -84,35 +79,35 @@ class FileHash(dbtClassMixin):
@classmethod @classmethod
def empty(cls): def empty(cls):
return FileHash(name='none', checksum='') return FileHash(name="none", checksum="")
@classmethod @classmethod
def path(cls, path: str): def path(cls, path: str):
return FileHash(name='path', checksum=path) return FileHash(name="path", checksum=path)
def __eq__(self, other): def __eq__(self, other):
if not isinstance(other, FileHash): if not isinstance(other, FileHash):
return NotImplemented return NotImplemented
if self.name == 'none' or self.name != other.name: if self.name == "none" or self.name != other.name:
return False return False
return self.checksum == other.checksum return self.checksum == other.checksum
def compare(self, contents: str) -> bool: def compare(self, contents: str) -> bool:
"""Compare the file contents with the given hash""" """Compare the file contents with the given hash"""
if self.name == 'none': if self.name == "none":
return False return False
return self.from_contents(contents, name=self.name) == self.checksum return self.from_contents(contents, name=self.name) == self.checksum
@classmethod @classmethod
def from_contents(cls, contents: str, name='sha256') -> 'FileHash': def from_contents(cls, contents: str, name="sha256") -> "FileHash":
"""Create a file hash from the given file contents. The hash is always """Create a file hash from the given file contents. The hash is always
the utf-8 encoding of the contents given, because dbt only reads files the utf-8 encoding of the contents given, because dbt only reads files
as utf-8. as utf-8.
""" """
data = contents.encode('utf-8') data = contents.encode("utf-8")
checksum = hashlib.new(name, data).hexdigest() checksum = hashlib.new(name, data).hexdigest()
return cls(name=name, checksum=checksum) return cls(name=name, checksum=checksum)
@@ -121,28 +116,29 @@ class FileHash(dbtClassMixin):
class RemoteFile(dbtClassMixin): class RemoteFile(dbtClassMixin):
@property @property
def searched_path(self) -> str: def searched_path(self) -> str:
return 'from remote system' return "from remote system"
@property @property
def relative_path(self) -> str: def relative_path(self) -> str:
return 'from remote system' return "from remote system"
@property @property
def absolute_path(self) -> str: def absolute_path(self) -> str:
return 'from remote system' return "from remote system"
@property @property
def original_file_path(self): def original_file_path(self):
return 'from remote system' return "from remote system"
@property @property
def modification_time(self): def modification_time(self):
return 'from remote system' return "from remote system"
@dataclass @dataclass
class BaseSourceFile(dbtClassMixin, SerializableType): class BaseSourceFile(dbtClassMixin, SerializableType):
"""Define a source file in dbt""" """Define a source file in dbt"""
path: Union[FilePath, RemoteFile] # the path information path: Union[FilePath, RemoteFile] # the path information
checksum: FileHash checksum: FileHash
# Seems like knowing which project the file came from would be useful # Seems like knowing which project the file came from would be useful
@@ -157,7 +153,7 @@ class BaseSourceFile(dbtClassMixin, SerializableType):
def file_id(self): def file_id(self):
if isinstance(self.path, RemoteFile): if isinstance(self.path, RemoteFile):
return None return None
return f'{self.project_name}://{self.path.original_file_path}' return f"{self.project_name}://{self.path.original_file_path}"
def _serialize(self): def _serialize(self):
dct = self.to_dict() dct = self.to_dict()
@@ -165,7 +161,7 @@ class BaseSourceFile(dbtClassMixin, SerializableType):
@classmethod @classmethod
def _deserialize(cls, dct: Dict[str, int]): def _deserialize(cls, dct: Dict[str, int]):
if dct['parse_file_type'] == 'schema': if dct["parse_file_type"] == "schema":
sf = SchemaSourceFile.from_dict(dct) sf = SchemaSourceFile.from_dict(dct)
else: else:
sf = SourceFile.from_dict(dct) sf = SourceFile.from_dict(dct)
@@ -180,8 +176,8 @@ class BaseSourceFile(dbtClassMixin, SerializableType):
del dct[key] del dct[key]
# remove contents. Schema files will still have 'dict_from_yaml' # remove contents. Schema files will still have 'dict_from_yaml'
# from the contents # from the contents
if 'contents' in dct: if "contents" in dct:
del dct['contents'] del dct["contents"]
return dct return dct
@@ -190,12 +186,13 @@ class SourceFile(BaseSourceFile):
nodes: List[str] = field(default_factory=list) nodes: List[str] = field(default_factory=list)
docs: List[str] = field(default_factory=list) docs: List[str] = field(default_factory=list)
macros: List[str] = field(default_factory=list) macros: List[str] = field(default_factory=list)
env_vars: List[str] = field(default_factory=list)
@classmethod @classmethod
def big_seed(cls, path: FilePath) -> 'SourceFile': def big_seed(cls, path: FilePath) -> "SourceFile":
"""Parse seeds over the size limit with just the path""" """Parse seeds over the size limit with just the path"""
self = cls(path=path, checksum=FileHash.path(path.original_file_path)) self = cls(path=path, checksum=FileHash.path(path.original_file_path))
self.contents = '' self.contents = ""
return self return self
def add_node(self, value): def add_node(self, value):
@@ -205,7 +202,7 @@ class SourceFile(BaseSourceFile):
# TODO: do this a different way. This remote file kludge isn't going # TODO: do this a different way. This remote file kludge isn't going
# to work long term # to work long term
@classmethod @classmethod
def remote(cls, contents: str, project_name: str) -> 'SourceFile': def remote(cls, contents: str, project_name: str) -> "SourceFile":
self = cls( self = cls(
path=RemoteFile(), path=RemoteFile(),
checksum=FileHash.from_contents(contents), checksum=FileHash.from_contents(contents),
@@ -222,6 +219,7 @@ class SchemaSourceFile(BaseSourceFile):
tests: Dict[str, Any] = field(default_factory=dict) tests: Dict[str, Any] = field(default_factory=dict)
sources: List[str] = field(default_factory=list) sources: List[str] = field(default_factory=list)
exposures: List[str] = field(default_factory=list) exposures: List[str] = field(default_factory=list)
metrics: List[str] = field(default_factory=list)
# node patches contain models, seeds, snapshots, analyses # node patches contain models, seeds, snapshots, analyses
ndp: List[str] = field(default_factory=list) ndp: List[str] = field(default_factory=list)
# any macro patches in this file by macro unique_id. # any macro patches in this file by macro unique_id.
@@ -230,6 +228,7 @@ class SchemaSourceFile(BaseSourceFile):
# Patches are only against external sources. Sources can be # Patches are only against external sources. Sources can be
# created too, but those are in 'sources' # created too, but those are in 'sources'
sop: List[SourceKey] = field(default_factory=list) sop: List[SourceKey] = field(default_factory=list)
env_vars: Dict[str, Any] = field(default_factory=dict)
pp_dict: Optional[Dict[str, Any]] = None pp_dict: Optional[Dict[str, Any]] = None
pp_test_index: Optional[Dict[str, Any]] = None pp_test_index: Optional[Dict[str, Any]] = None
@@ -252,7 +251,7 @@ class SchemaSourceFile(BaseSourceFile):
def __post_serialize__(self, dct): def __post_serialize__(self, dct):
dct = super().__post_serialize__(dct) dct = super().__post_serialize__(dct)
# Remove partial parsing specific data # Remove partial parsing specific data
for key in ('pp_files', 'pp_test_index', 'pp_dict'): for key in ("pp_test_index", "pp_dict"):
if key in dct: if key in dct:
del dct[key] del dct[key]
return dct return dct
@@ -261,8 +260,8 @@ class SchemaSourceFile(BaseSourceFile):
self.node_patches.append(unique_id) self.node_patches.append(unique_id)
def add_test(self, node_unique_id, test_from): def add_test(self, node_unique_id, test_from):
name = test_from['name'] name = test_from["name"]
key = test_from['key'] key = test_from["key"]
if key not in self.tests: if key not in self.tests:
self.tests[key] = {} self.tests[key] = {}
if name not in self.tests[key]: if name not in self.tests[key]:
@@ -299,5 +298,21 @@ class SchemaSourceFile(BaseSourceFile):
test_ids.extend(self.tests[key][name]) test_ids.extend(self.tests[key][name])
return test_ids return test_ids
def add_env_var(self, var, yaml_key, name):
if yaml_key not in self.env_vars:
self.env_vars[yaml_key] = {}
if name not in self.env_vars[yaml_key]:
self.env_vars[yaml_key][name] = []
if var not in self.env_vars[yaml_key][name]:
self.env_vars[yaml_key][name].append(var)
def delete_from_env_vars(self, yaml_key, name):
# We delete all vars for this yaml_key/name because the
# entry has been scheduled for reparsing.
if yaml_key in self.env_vars and name in self.env_vars[yaml_key]:
del self.env_vars[yaml_key][name]
if not self.env_vars[yaml_key]:
del self.env_vars[yaml_key]
AnySourceFile = Union[SchemaSourceFile, SourceFile] AnySourceFile = Union[SchemaSourceFile, SourceFile]

View File

@@ -6,8 +6,10 @@ from dbt.contracts.graph.parsed import (
ParsedHookNode, ParsedHookNode,
ParsedModelNode, ParsedModelNode,
ParsedExposure, ParsedExposure,
ParsedMetric,
ParsedResource, ParsedResource,
ParsedRPCNode, ParsedRPCNode,
ParsedSqlNode,
ParsedGenericTestNode, ParsedGenericTestNode,
ParsedSeedNode, ParsedSeedNode,
ParsedSnapshotNode, ParsedSnapshotNode,
@@ -58,43 +60,47 @@ class CompiledNode(ParsedNode, CompiledNodeMixin):
def __post_serialize__(self, dct): def __post_serialize__(self, dct):
dct = super().__post_serialize__(dct) dct = super().__post_serialize__(dct)
if '_pre_injected_sql' in dct: if "_pre_injected_sql" in dct:
del dct['_pre_injected_sql'] del dct["_pre_injected_sql"]
return dct return dct
@dataclass @dataclass
class CompiledAnalysisNode(CompiledNode): class CompiledAnalysisNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Analysis]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Analysis]})
@dataclass @dataclass
class CompiledHookNode(CompiledNode): class CompiledHookNode(CompiledNode):
resource_type: NodeType = field( resource_type: NodeType = field(metadata={"restrict": [NodeType.Operation]})
metadata={'restrict': [NodeType.Operation]}
)
index: Optional[int] = None index: Optional[int] = None
@dataclass @dataclass
class CompiledModelNode(CompiledNode): class CompiledModelNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Model]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Model]})
# TODO: rm?
@dataclass
class CompiledRPCNode(CompiledNode):
resource_type: NodeType = field(metadata={"restrict": [NodeType.RPCCall]})
@dataclass @dataclass
class CompiledRPCNode(CompiledNode): class CompiledSqlNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.RPCCall]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.SqlOperation]})
@dataclass @dataclass
class CompiledSeedNode(CompiledNode): class CompiledSeedNode(CompiledNode):
# keep this in sync with ParsedSeedNode! # keep this in sync with ParsedSeedNode!
resource_type: NodeType = field(metadata={'restrict': [NodeType.Seed]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Seed]})
config: SeedConfig = field(default_factory=SeedConfig) config: SeedConfig = field(default_factory=SeedConfig)
@property @property
def empty(self): def empty(self):
""" Seeds are never empty""" """Seeds are never empty"""
return False return False
def same_body(self, other) -> bool: def same_body(self, other) -> bool:
@@ -103,12 +109,12 @@ class CompiledSeedNode(CompiledNode):
@dataclass @dataclass
class CompiledSnapshotNode(CompiledNode): class CompiledSnapshotNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Snapshot]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Snapshot]})
@dataclass @dataclass
class CompiledSingularTestNode(CompiledNode): class CompiledSingularTestNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Test]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Test]})
# Was not able to make mypy happy and keep the code working. We need to # Was not able to make mypy happy and keep the code working. We need to
# refactor the various configs. # refactor the various configs.
config: TestConfig = field(default_factory=TestConfig) # type:ignore config: TestConfig = field(default_factory=TestConfig) # type:ignore
@@ -117,8 +123,9 @@ class CompiledSingularTestNode(CompiledNode):
@dataclass @dataclass
class CompiledGenericTestNode(CompiledNode, HasTestMetadata): class CompiledGenericTestNode(CompiledNode, HasTestMetadata):
# keep this in sync with ParsedGenericTestNode! # keep this in sync with ParsedGenericTestNode!
resource_type: NodeType = field(metadata={'restrict': [NodeType.Test]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Test]})
column_name: Optional[str] = None column_name: Optional[str] = None
file_key_name: Optional[str] = None
# Was not able to make mypy happy and keep the code working. We need to # Was not able to make mypy happy and keep the code working. We need to
# refactor the various configs. # refactor the various configs.
config: TestConfig = field(default_factory=TestConfig) # type:ignore config: TestConfig = field(default_factory=TestConfig) # type:ignore
@@ -127,11 +134,7 @@ class CompiledGenericTestNode(CompiledNode, HasTestMetadata):
if other is None: if other is None:
return False return False
return ( return self.same_config(other) and self.same_fqn(other) and True
self.same_config(other) and
self.same_fqn(other) and
True
)
CompiledTestNode = Union[CompiledSingularTestNode, CompiledGenericTestNode] CompiledTestNode = Union[CompiledSingularTestNode, CompiledGenericTestNode]
@@ -142,6 +145,7 @@ PARSED_TYPES: Dict[Type[CompiledNode], Type[ParsedResource]] = {
CompiledModelNode: ParsedModelNode, CompiledModelNode: ParsedModelNode,
CompiledHookNode: ParsedHookNode, CompiledHookNode: ParsedHookNode,
CompiledRPCNode: ParsedRPCNode, CompiledRPCNode: ParsedRPCNode,
CompiledSqlNode: ParsedSqlNode,
CompiledSeedNode: ParsedSeedNode, CompiledSeedNode: ParsedSeedNode,
CompiledSnapshotNode: ParsedSnapshotNode, CompiledSnapshotNode: ParsedSnapshotNode,
CompiledSingularTestNode: ParsedSingularTestNode, CompiledSingularTestNode: ParsedSingularTestNode,
@@ -154,6 +158,7 @@ COMPILED_TYPES: Dict[Type[ParsedResource], Type[CompiledNode]] = {
ParsedModelNode: CompiledModelNode, ParsedModelNode: CompiledModelNode,
ParsedHookNode: CompiledHookNode, ParsedHookNode: CompiledHookNode,
ParsedRPCNode: CompiledRPCNode, ParsedRPCNode: CompiledRPCNode,
ParsedSqlNode: CompiledSqlNode,
ParsedSeedNode: CompiledSeedNode, ParsedSeedNode: CompiledSeedNode,
ParsedSnapshotNode: CompiledSnapshotNode, ParsedSnapshotNode: CompiledSnapshotNode,
ParsedSingularTestNode: CompiledSingularTestNode, ParsedSingularTestNode: CompiledSingularTestNode,
@@ -177,8 +182,7 @@ def parsed_instance_for(compiled: CompiledNode) -> ParsedResource:
cls = PARSED_TYPES.get(type(compiled)) cls = PARSED_TYPES.get(type(compiled))
if cls is None: if cls is None:
# how??? # how???
raise ValueError('invalid resource_type: {}' raise ValueError("invalid resource_type: {}".format(compiled.resource_type))
.format(compiled.resource_type))
return cls.from_dict(compiled.to_dict(omit_none=True)) return cls.from_dict(compiled.to_dict(omit_none=True))
@@ -189,6 +193,7 @@ NonSourceCompiledNode = Union[
CompiledModelNode, CompiledModelNode,
CompiledHookNode, CompiledHookNode,
CompiledRPCNode, CompiledRPCNode,
CompiledSqlNode,
CompiledGenericTestNode, CompiledGenericTestNode,
CompiledSeedNode, CompiledSeedNode,
CompiledSnapshotNode, CompiledSnapshotNode,
@@ -200,6 +205,7 @@ NonSourceParsedNode = Union[
ParsedHookNode, ParsedHookNode,
ParsedModelNode, ParsedModelNode,
ParsedRPCNode, ParsedRPCNode,
ParsedSqlNode,
ParsedGenericTestNode, ParsedGenericTestNode,
ParsedSeedNode, ParsedSeedNode,
ParsedSnapshotNode, ParsedSnapshotNode,
@@ -220,8 +226,10 @@ CompileResultNode = Union[
ParsedSourceDefinition, ParsedSourceDefinition,
] ]
# anything that participates in the graph: sources, exposures, manifest nodes # anything that participates in the graph: sources, exposures, metrics,
# or manifest nodes
GraphMemberNode = Union[ GraphMemberNode = Union[
CompileResultNode, CompileResultNode,
ParsedExposure, ParsedExposure,
ParsedMetric,
] ]

View File

@@ -4,32 +4,53 @@ from itertools import chain, islice
from mashumaro import DataClassMessagePackMixin from mashumaro import DataClassMessagePackMixin
from multiprocessing.synchronize import Lock from multiprocessing.synchronize import Lock
from typing import ( from typing import (
Dict, List, Optional, Union, Mapping, MutableMapping, Any, Set, Tuple, Dict,
TypeVar, Callable, Generic, cast, AbstractSet, ClassVar List,
Optional,
Union,
Mapping,
MutableMapping,
Any,
Set,
Tuple,
TypeVar,
Callable,
Generic,
cast,
AbstractSet,
ClassVar,
) )
from typing_extensions import Protocol from typing_extensions import Protocol
from uuid import UUID from uuid import UUID
from dbt.contracts.graph.compiled import ( from dbt.contracts.graph.compiled import (
CompileResultNode, ManifestNode, NonSourceCompiledNode, GraphMemberNode CompileResultNode,
ManifestNode,
NonSourceCompiledNode,
GraphMemberNode,
) )
from dbt.contracts.graph.parsed import ( from dbt.contracts.graph.parsed import (
ParsedMacro, ParsedDocumentation, ParsedMacro,
ParsedSourceDefinition, ParsedExposure, HasUniqueID, ParsedDocumentation,
UnpatchedSourceDefinition, ManifestNodes ParsedSourceDefinition,
ParsedExposure,
ParsedMetric,
HasUniqueID,
UnpatchedSourceDefinition,
ManifestNodes,
) )
from dbt.contracts.graph.unparsed import SourcePatch from dbt.contracts.graph.unparsed import SourcePatch
from dbt.contracts.files import SourceFile, SchemaSourceFile, FileHash, AnySourceFile from dbt.contracts.files import SourceFile, SchemaSourceFile, FileHash, AnySourceFile
from dbt.contracts.util import ( from dbt.contracts.util import BaseArtifactMetadata, SourceKey, ArtifactMixin, schema_version
BaseArtifactMetadata, SourceKey, ArtifactMixin, schema_version
)
from dbt.dataclass_schema import dbtClassMixin from dbt.dataclass_schema import dbtClassMixin
from dbt.exceptions import ( from dbt.exceptions import (
CompilationException, CompilationException,
raise_duplicate_resource_name, raise_compiler_error, raise_duplicate_resource_name,
raise_compiler_error,
) )
from dbt.helper_types import PathSet from dbt.helper_types import PathSet
from dbt.logger import GLOBAL_LOGGER as logger from dbt.events.functions import fire_event
from dbt.events.types import MergedFromState
from dbt.node_types import NodeType from dbt.node_types import NodeType
from dbt.ui import line_wrap_message from dbt.ui import line_wrap_message
from dbt import flags from dbt import flags
@@ -61,14 +82,14 @@ def find_unique_id_for_package(storage, key, package: Optional[PackageName]):
class DocLookup(dbtClassMixin): class DocLookup(dbtClassMixin):
def __init__(self, manifest: 'Manifest'): def __init__(self, manifest: "Manifest"):
self.storage: Dict[str, Dict[PackageName, UniqueID]] = {} self.storage: Dict[str, Dict[PackageName, UniqueID]] = {}
self.populate(manifest) self.populate(manifest)
def get_unique_id(self, key, package: Optional[PackageName]): def get_unique_id(self, key, package: Optional[PackageName]):
return find_unique_id_for_package(self.storage, key, package) return find_unique_id_for_package(self.storage, key, package)
def find(self, key, package: Optional[PackageName], manifest: 'Manifest'): def find(self, key, package: Optional[PackageName], manifest: "Manifest"):
unique_id = self.get_unique_id(key, package) unique_id = self.get_unique_id(key, package)
if unique_id is not None: if unique_id is not None:
return self.perform_lookup(unique_id, manifest) return self.perform_lookup(unique_id, manifest)
@@ -83,25 +104,23 @@ class DocLookup(dbtClassMixin):
for doc in manifest.docs.values(): for doc in manifest.docs.values():
self.add_doc(doc) self.add_doc(doc)
def perform_lookup( def perform_lookup(self, unique_id: UniqueID, manifest) -> ParsedDocumentation:
self, unique_id: UniqueID, manifest
) -> ParsedDocumentation:
if unique_id not in manifest.docs: if unique_id not in manifest.docs:
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
f'Doc {unique_id} found in cache but not found in manifest' f"Doc {unique_id} found in cache but not found in manifest"
) )
return manifest.docs[unique_id] return manifest.docs[unique_id]
class SourceLookup(dbtClassMixin): class SourceLookup(dbtClassMixin):
def __init__(self, manifest: 'Manifest'): def __init__(self, manifest: "Manifest"):
self.storage: Dict[str, Dict[PackageName, UniqueID]] = {} self.storage: Dict[str, Dict[PackageName, UniqueID]] = {}
self.populate(manifest) self.populate(manifest)
def get_unique_id(self, search_name, package: Optional[PackageName]): def get_unique_id(self, search_name, package: Optional[PackageName]):
return find_unique_id_for_package(self.storage, search_name, package) return find_unique_id_for_package(self.storage, search_name, package)
def find(self, search_name, package: Optional[PackageName], manifest: 'Manifest'): def find(self, search_name, package: Optional[PackageName], manifest: "Manifest"):
unique_id = self.get_unique_id(search_name, package) unique_id = self.get_unique_id(search_name, package)
if unique_id is not None: if unique_id is not None:
return self.perform_lookup(unique_id, manifest) return self.perform_lookup(unique_id, manifest)
@@ -115,15 +134,13 @@ class SourceLookup(dbtClassMixin):
def populate(self, manifest): def populate(self, manifest):
for source in manifest.sources.values(): for source in manifest.sources.values():
if hasattr(source, 'source_name'): if hasattr(source, "source_name"):
self.add_source(source) self.add_source(source)
def perform_lookup( def perform_lookup(self, unique_id: UniqueID, manifest: "Manifest") -> ParsedSourceDefinition:
self, unique_id: UniqueID, manifest: 'Manifest'
) -> ParsedSourceDefinition:
if unique_id not in manifest.sources: if unique_id not in manifest.sources:
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
f'Source {unique_id} found in cache but not found in manifest' f"Source {unique_id} found in cache but not found in manifest"
) )
return manifest.sources[unique_id] return manifest.sources[unique_id]
@@ -135,14 +152,14 @@ class RefableLookup(dbtClassMixin):
# refables are actually unique, so the Dict[PackageName, UniqueID] will # refables are actually unique, so the Dict[PackageName, UniqueID] will
# only ever have exactly one value, but doing 3 dict lookups instead of 1 # only ever have exactly one value, but doing 3 dict lookups instead of 1
# is not a big deal at all and retains consistency # is not a big deal at all and retains consistency
def __init__(self, manifest: 'Manifest'): def __init__(self, manifest: "Manifest"):
self.storage: Dict[str, Dict[PackageName, UniqueID]] = {} self.storage: Dict[str, Dict[PackageName, UniqueID]] = {}
self.populate(manifest) self.populate(manifest)
def get_unique_id(self, key, package: Optional[PackageName]): def get_unique_id(self, key, package: Optional[PackageName]):
return find_unique_id_for_package(self.storage, key, package) return find_unique_id_for_package(self.storage, key, package)
def find(self, key, package: Optional[PackageName], manifest: 'Manifest'): def find(self, key, package: Optional[PackageName], manifest: "Manifest"):
unique_id = self.get_unique_id(key, package) unique_id = self.get_unique_id(key, package)
if unique_id is not None: if unique_id is not None:
return self.perform_lookup(unique_id, manifest) return self.perform_lookup(unique_id, manifest)
@@ -158,20 +175,17 @@ class RefableLookup(dbtClassMixin):
for node in manifest.nodes.values(): for node in manifest.nodes.values():
self.add_node(node) self.add_node(node)
def perform_lookup( def perform_lookup(self, unique_id: UniqueID, manifest) -> ManifestNode:
self, unique_id: UniqueID, manifest
) -> ManifestNode:
if unique_id not in manifest.nodes: if unique_id not in manifest.nodes:
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
f'Node {unique_id} found in cache but not found in manifest' f"Node {unique_id} found in cache but not found in manifest"
) )
return manifest.nodes[unique_id] return manifest.nodes[unique_id]
# This handles both models/seeds/snapshots and sources # This handles both models/seeds/snapshots and sources
class DisabledLookup(dbtClassMixin): class DisabledLookup(dbtClassMixin):
def __init__(self, manifest: "Manifest"):
def __init__(self, manifest: 'Manifest'):
self.storage: Dict[str, Dict[PackageName, List[Any]]] = {} self.storage: Dict[str, Dict[PackageName, List[Any]]] = {}
self.populate(manifest) self.populate(manifest)
@@ -225,30 +239,31 @@ def _search_packages(
@dataclass @dataclass
class ManifestMetadata(BaseArtifactMetadata): class ManifestMetadata(BaseArtifactMetadata):
"""Metadata for the manifest.""" """Metadata for the manifest."""
dbt_schema_version: str = field( dbt_schema_version: str = field(
default_factory=lambda: str(WritableManifest.dbt_schema_version) default_factory=lambda: str(WritableManifest.dbt_schema_version)
) )
project_id: Optional[str] = field( project_id: Optional[str] = field(
default=None, default=None,
metadata={ metadata={
'description': 'A unique identifier for the project', "description": "A unique identifier for the project",
}, },
) )
user_id: Optional[UUID] = field( user_id: Optional[UUID] = field(
default=None, default=None,
metadata={ metadata={
'description': 'A unique identifier for the user', "description": "A unique identifier for the user",
}, },
) )
send_anonymous_usage_stats: Optional[bool] = field( send_anonymous_usage_stats: Optional[bool] = field(
default=None, default=None,
metadata=dict(description=( metadata=dict(
'Whether dbt is configured to send anonymous usage statistics' description=("Whether dbt is configured to send anonymous usage statistics")
)), ),
) )
adapter_type: Optional[str] = field( adapter_type: Optional[str] = field(
default=None, default=None,
metadata=dict(description='The type name of the adapter'), metadata=dict(description="The type name of the adapter"),
) )
def __post_init__(self): def __post_init__(self):
@@ -294,7 +309,7 @@ def build_node_edges(nodes: List[ManifestNode]):
# Build a map of children of macros and generic tests # Build a map of children of macros and generic tests
def build_macro_edges(nodes: List[Any]): def build_macro_edges(nodes: List[Any]):
forward_edges: Dict[str, List[str]] = { forward_edges: Dict[str, List[str]] = {
n.unique_id: [] for n in nodes if n.unique_id.startswith('macro') or n.depends_on.macros n.unique_id: [] for n in nodes if n.unique_id.startswith("macro") or n.depends_on.macros
} }
for node in nodes: for node in nodes:
for unique_id in node.depends_on.macros: for unique_id in node.depends_on.macros:
@@ -345,7 +360,7 @@ class MaterializationCandidate(MacroCandidate):
@classmethod @classmethod
def from_macro( def from_macro(
cls, candidate: MacroCandidate, specificity: Specificity cls, candidate: MacroCandidate, specificity: Specificity
) -> 'MaterializationCandidate': ) -> "MaterializationCandidate":
return cls( return cls(
locality=candidate.locality, locality=candidate.locality,
macro=candidate.macro, macro=candidate.macro,
@@ -355,16 +370,13 @@ class MaterializationCandidate(MacroCandidate):
def __eq__(self, other: object) -> bool: def __eq__(self, other: object) -> bool:
if not isinstance(other, MaterializationCandidate): if not isinstance(other, MaterializationCandidate):
return NotImplemented return NotImplemented
equal = ( equal = self.specificity == other.specificity and self.locality == other.locality
self.specificity == other.specificity and
self.locality == other.locality
)
if equal: if equal:
raise_compiler_error( raise_compiler_error(
'Found two materializations with the name {} (packages {} and ' "Found two materializations with the name {} (packages {} and "
'{}). dbt cannot resolve this ambiguity' "{}). dbt cannot resolve this ambiguity".format(
.format(self.macro.name, self.macro.package_name, self.macro.name, self.macro.package_name, other.macro.package_name
other.macro.package_name) )
) )
return equal return equal
@@ -383,7 +395,7 @@ class MaterializationCandidate(MacroCandidate):
return False return False
M = TypeVar('M', bound=MacroCandidate) M = TypeVar("M", bound=MacroCandidate)
class CandidateList(List[M]): class CandidateList(List[M]):
@@ -411,10 +423,10 @@ class Searchable(Protocol):
@property @property
def search_name(self) -> str: def search_name(self) -> str:
raise NotImplementedError('search_name not implemented') raise NotImplementedError("search_name not implemented")
D = TypeVar('D') D = TypeVar("D")
@dataclass @dataclass
@@ -425,37 +437,35 @@ class Disabled(Generic[D]):
MaybeDocumentation = Optional[ParsedDocumentation] MaybeDocumentation = Optional[ParsedDocumentation]
MaybeParsedSource = Optional[Union[ MaybeParsedSource = Optional[
Union[
ParsedSourceDefinition, ParsedSourceDefinition,
Disabled[ParsedSourceDefinition], Disabled[ParsedSourceDefinition],
]] ]
]
MaybeNonSource = Optional[Union[ MaybeNonSource = Optional[Union[ManifestNode, Disabled[ManifestNode]]]
ManifestNode,
Disabled[ManifestNode]
]]
T = TypeVar('T', bound=GraphMemberNode) T = TypeVar("T", bound=GraphMemberNode)
def _update_into(dest: MutableMapping[str, T], new_item: T): def _update_into(dest: MutableMapping[str, T], new_item: T):
"""Update dest to overwrite whatever is at dest[new_item.unique_id] with """Update dest to overwrite whatever is at dest[new_item.unique_id] with
new_itme. There must be an existing value to overwrite, and they two nodes new_itme. There must be an existing value to overwrite, and the two nodes
must have the same original file path. must have the same original file path.
""" """
unique_id = new_item.unique_id unique_id = new_item.unique_id
if unique_id not in dest: if unique_id not in dest:
raise dbt.exceptions.RuntimeException( raise dbt.exceptions.RuntimeException(
f'got an update_{new_item.resource_type} call with an ' f"got an update_{new_item.resource_type} call with an "
f'unrecognized {new_item.resource_type}: {new_item.unique_id}' f"unrecognized {new_item.resource_type}: {new_item.unique_id}"
) )
existing = dest[unique_id] existing = dest[unique_id]
if new_item.original_file_path != existing.original_file_path: if new_item.original_file_path != existing.original_file_path:
raise dbt.exceptions.RuntimeException( raise dbt.exceptions.RuntimeException(
f'cannot update a {new_item.resource_type} to have a new file ' f"cannot update a {new_item.resource_type} to have a new file " f"path!"
f'path!'
) )
dest[unique_id] = new_item dest[unique_id] = new_item
@@ -479,6 +489,7 @@ class MacroMethods:
""" """
filter: Optional[Callable[[MacroCandidate], bool]] = None filter: Optional[Callable[[MacroCandidate], bool]] = None
if package is not None: if package is not None:
def filter(candidate: MacroCandidate) -> bool: def filter(candidate: MacroCandidate) -> bool:
return package == candidate.macro.package_name return package == candidate.macro.package_name
@@ -501,11 +512,12 @@ class MacroMethods:
- return the `generate_{component}_name` macro from the 'dbt' - return the `generate_{component}_name` macro from the 'dbt'
internal project internal project
""" """
def filter(candidate: MacroCandidate) -> bool: def filter(candidate: MacroCandidate) -> bool:
return candidate.locality != Locality.Imported return candidate.locality != Locality.Imported
candidates: CandidateList = self._find_macros_by_name( candidates: CandidateList = self._find_macros_by_name(
name=f'generate_{component}_name', name=f"generate_{component}_name",
root_project_name=root_project_name, root_project_name=root_project_name,
# filter out imported packages # filter out imported packages
filter=filter, filter=filter,
@@ -516,12 +528,12 @@ class MacroMethods:
self, self,
name: str, name: str,
root_project_name: str, root_project_name: str,
filter: Optional[Callable[[MacroCandidate], bool]] = None filter: Optional[Callable[[MacroCandidate], bool]] = None,
) -> CandidateList: ) -> CandidateList:
"""Find macros by their name. """Find macros by their name."""
"""
# avoid an import cycle # avoid an import cycle
from dbt.adapters.factory import get_adapter_package_names from dbt.adapters.factory import get_adapter_package_names
candidates: CandidateList = CandidateList() candidates: CandidateList = CandidateList()
packages = set(get_adapter_package_names(self.metadata.adapter_type)) packages = set(get_adapter_package_names(self.metadata.adapter_type))
for unique_id, macro in self.macros.items(): for unique_id, macro in self.macros.items():
@@ -546,14 +558,16 @@ class ParsingInfo:
@dataclass @dataclass
class ManifestStateCheck(dbtClassMixin): class ManifestStateCheck(dbtClassMixin):
vars_hash: FileHash = field(default_factory=FileHash.empty) vars_hash: FileHash = field(default_factory=FileHash.empty)
project_env_vars_hash: FileHash = field(default_factory=FileHash.empty)
profile_env_vars_hash: FileHash = field(default_factory=FileHash.empty)
profile_hash: FileHash = field(default_factory=FileHash.empty) profile_hash: FileHash = field(default_factory=FileHash.empty)
project_hashes: MutableMapping[str, FileHash] = field(default_factory=dict) project_hashes: MutableMapping[str, FileHash] = field(default_factory=dict)
@dataclass @dataclass
class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin): class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
"""The manifest for the full graph, after parsing and during compilation. """The manifest for the full graph, after parsing and during compilation."""
"""
# These attributes are both positional and by keyword. If an attribute # These attributes are both positional and by keyword. If an attribute
# is added it must all be added in the __reduce_ex__ method in the # is added it must all be added in the __reduce_ex__ method in the
# args tuple in the right position. # args tuple in the right position.
@@ -562,6 +576,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
macros: MutableMapping[str, ParsedMacro] = field(default_factory=dict) macros: MutableMapping[str, ParsedMacro] = field(default_factory=dict)
docs: MutableMapping[str, ParsedDocumentation] = field(default_factory=dict) docs: MutableMapping[str, ParsedDocumentation] = field(default_factory=dict)
exposures: MutableMapping[str, ParsedExposure] = field(default_factory=dict) exposures: MutableMapping[str, ParsedExposure] = field(default_factory=dict)
metrics: MutableMapping[str, ParsedMetric] = field(default_factory=dict)
selectors: MutableMapping[str, Any] = field(default_factory=dict) selectors: MutableMapping[str, Any] = field(default_factory=dict)
files: MutableMapping[str, AnySourceFile] = field(default_factory=dict) files: MutableMapping[str, AnySourceFile] = field(default_factory=dict)
metadata: ManifestMetadata = field(default_factory=ManifestMetadata) metadata: ManifestMetadata = field(default_factory=ManifestMetadata)
@@ -569,29 +584,30 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
state_check: ManifestStateCheck = field(default_factory=ManifestStateCheck) state_check: ManifestStateCheck = field(default_factory=ManifestStateCheck)
source_patches: MutableMapping[SourceKey, SourcePatch] = field(default_factory=dict) source_patches: MutableMapping[SourceKey, SourcePatch] = field(default_factory=dict)
disabled: MutableMapping[str, List[CompileResultNode]] = field(default_factory=dict) disabled: MutableMapping[str, List[CompileResultNode]] = field(default_factory=dict)
env_vars: MutableMapping[str, str] = field(default_factory=dict)
_doc_lookup: Optional[DocLookup] = field( _doc_lookup: Optional[DocLookup] = field(
default=None, metadata={'serialize': lambda x: None, 'deserialize': lambda x: None} default=None, metadata={"serialize": lambda x: None, "deserialize": lambda x: None}
) )
_source_lookup: Optional[SourceLookup] = field( _source_lookup: Optional[SourceLookup] = field(
default=None, metadata={'serialize': lambda x: None, 'deserialize': lambda x: None} default=None, metadata={"serialize": lambda x: None, "deserialize": lambda x: None}
) )
_ref_lookup: Optional[RefableLookup] = field( _ref_lookup: Optional[RefableLookup] = field(
default=None, metadata={'serialize': lambda x: None, 'deserialize': lambda x: None} default=None, metadata={"serialize": lambda x: None, "deserialize": lambda x: None}
) )
_disabled_lookup: Optional[DisabledLookup] = field( _disabled_lookup: Optional[DisabledLookup] = field(
default=None, metadata={'serialize': lambda x: None, 'deserialize': lambda x: None} default=None, metadata={"serialize": lambda x: None, "deserialize": lambda x: None}
) )
_analysis_lookup: Optional[AnalysisLookup] = field( _analysis_lookup: Optional[AnalysisLookup] = field(
default=None, metadata={'serialize': lambda x: None, 'deserialize': lambda x: None} default=None, metadata={"serialize": lambda x: None, "deserialize": lambda x: None}
) )
_parsing_info: ParsingInfo = field( _parsing_info: ParsingInfo = field(
default_factory=ParsingInfo, default_factory=ParsingInfo,
metadata={'serialize': lambda x: None, 'deserialize': lambda x: None} metadata={"serialize": lambda x: None, "deserialize": lambda x: None},
) )
_lock: Lock = field( _lock: Lock = field(
default_factory=flags.MP_CONTEXT.Lock, default_factory=flags.MP_CONTEXT.Lock,
metadata={'serialize': lambda x: None, 'deserialize': lambda x: None} metadata={"serialize": lambda x: None, "deserialize": lambda x: None},
) )
def __pre_serialize__(self): def __pre_serialize__(self):
@@ -605,9 +621,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
obj._lock = flags.MP_CONTEXT.Lock() obj._lock = flags.MP_CONTEXT.Lock()
return obj return obj
def sync_update_node( def sync_update_node(self, new_node: NonSourceCompiledNode) -> NonSourceCompiledNode:
self, new_node: NonSourceCompiledNode
) -> NonSourceCompiledNode:
"""update the node with a lock. The only time we should want to lock is """update the node with a lock. The only time we should want to lock is
when compiling an ephemeral ancestor of a node at runtime, because when compiling an ephemeral ancestor of a node at runtime, because
multiple threads could be just-in-time compiling the same ephemeral multiple threads could be just-in-time compiling the same ephemeral
@@ -619,7 +633,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
""" """
with self._lock: with self._lock:
existing = self.nodes[new_node.unique_id] existing = self.nodes[new_node.unique_id]
if getattr(existing, 'compiled', False): if getattr(existing, "compiled", False):
# already compiled -> must be a NonSourceCompiledNode # already compiled -> must be a NonSourceCompiledNode
return cast(NonSourceCompiledNode, existing) return cast(NonSourceCompiledNode, existing)
_update_into(self.nodes, new_node) _update_into(self.nodes, new_node)
@@ -628,6 +642,9 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
def update_exposure(self, new_exposure: ParsedExposure): def update_exposure(self, new_exposure: ParsedExposure):
_update_into(self.exposures, new_exposure) _update_into(self.exposures, new_exposure)
def update_metric(self, new_metric: ParsedMetric):
_update_into(self.metrics, new_metric)
def update_node(self, new_node: ManifestNode): def update_node(self, new_node: ManifestNode):
_update_into(self.nodes, new_node) _update_into(self.nodes, new_node)
@@ -641,18 +658,10 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
manifest! manifest!
""" """
self.flat_graph = { self.flat_graph = {
'exposures': { "exposures": {k: v.to_dict(omit_none=False) for k, v in self.exposures.items()},
k: v.to_dict(omit_none=False) "metrics": {k: v.to_dict(omit_none=False) for k, v in self.metrics.items()},
for k, v in self.exposures.items() "nodes": {k: v.to_dict(omit_none=False) for k, v in self.nodes.items()},
}, "sources": {k: v.to_dict(omit_none=False) for k, v in self.sources.items()},
'nodes': {
k: v.to_dict(omit_none=False)
for k, v in self.nodes.items()
},
'sources': {
k: v.to_dict(omit_none=False)
for k, v in self.sources.items()
}
} }
def build_disabled_by_file_id(self): def build_disabled_by_file_id(self):
@@ -663,7 +672,8 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
return disabled_by_file_id return disabled_by_file_id
def _materialization_candidates_for( def _materialization_candidates_for(
self, project_name: str, self,
project_name: str,
materialization_name: str, materialization_name: str,
adapter_type: Optional[str], adapter_type: Optional[str],
) -> CandidateList: ) -> CandidateList:
@@ -686,18 +696,26 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
def find_materialization_macro_by_name( def find_materialization_macro_by_name(
self, project_name: str, materialization_name: str, adapter_type: str self, project_name: str, materialization_name: str, adapter_type: str
) -> Optional[ParsedMacro]: ) -> Optional[ParsedMacro]:
candidates: CandidateList = CandidateList(chain.from_iterable( candidates: CandidateList = CandidateList(
chain.from_iterable(
self._materialization_candidates_for( self._materialization_candidates_for(
project_name=project_name, project_name=project_name,
materialization_name=materialization_name, materialization_name=materialization_name,
adapter_type=atype, adapter_type=atype,
) for atype in (adapter_type, None) )
)) for atype in (adapter_type, None)
)
)
return candidates.last() return candidates.last()
def get_resource_fqns(self) -> Mapping[str, PathSet]: def get_resource_fqns(self) -> Mapping[str, PathSet]:
resource_fqns: Dict[str, Set[Tuple[str, ...]]] = {} resource_fqns: Dict[str, Set[Tuple[str, ...]]] = {}
all_resources = chain(self.exposures.values(), self.nodes.values(), self.sources.values()) all_resources = chain(
self.exposures.values(),
self.nodes.values(),
self.sources.values(),
self.metrics.values(),
)
for resource in all_resources: for resource in all_resources:
resource_type_plural = resource.resource_type.pluralize() resource_type_plural = resource.resource_type.pluralize()
if resource_type_plural not in resource_fqns: if resource_type_plural not in resource_fqns:
@@ -706,17 +724,16 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
return resource_fqns return resource_fqns
def get_used_schemas(self, resource_types=None): def get_used_schemas(self, resource_types=None):
return frozenset({ return frozenset(
(node.database, node.schema) for node in {
chain(self.nodes.values(), self.sources.values()) (node.database, node.schema)
for node in chain(self.nodes.values(), self.sources.values())
if not resource_types or node.resource_type in resource_types if not resource_types or node.resource_type in resource_types
}) }
)
def get_used_databases(self): def get_used_databases(self):
return frozenset( return frozenset(x.database for x in chain(self.nodes.values(), self.sources.values()))
x.database for x in
chain(self.nodes.values(), self.sources.values())
)
def deepcopy(self): def deepcopy(self):
return Manifest( return Manifest(
@@ -725,6 +742,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
macros={k: _deepcopy(v) for k, v in self.macros.items()}, macros={k: _deepcopy(v) for k, v in self.macros.items()},
docs={k: _deepcopy(v) for k, v in self.docs.items()}, docs={k: _deepcopy(v) for k, v in self.docs.items()},
exposures={k: _deepcopy(v) for k, v in self.exposures.items()}, exposures={k: _deepcopy(v) for k, v in self.exposures.items()},
metrics={k: _deepcopy(v) for k, v in self.metrics.items()},
selectors={k: _deepcopy(v) for k, v in self.selectors.items()}, selectors={k: _deepcopy(v) for k, v in self.selectors.items()},
metadata=self.metadata, metadata=self.metadata,
disabled={k: _deepcopy(v) for k, v in self.disabled.items()}, disabled={k: _deepcopy(v) for k, v in self.disabled.items()},
@@ -733,20 +751,25 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
) )
def build_parent_and_child_maps(self): def build_parent_and_child_maps(self):
edge_members = list(chain( edge_members = list(
chain(
self.nodes.values(), self.nodes.values(),
self.sources.values(), self.sources.values(),
self.exposures.values(), self.exposures.values(),
)) self.metrics.values(),
)
)
forward_edges, backward_edges = build_node_edges(edge_members) forward_edges, backward_edges = build_node_edges(edge_members)
self.child_map = forward_edges self.child_map = forward_edges
self.parent_map = backward_edges self.parent_map = backward_edges
def build_macro_child_map(self): def build_macro_child_map(self):
edge_members = list(chain( edge_members = list(
chain(
self.nodes.values(), self.nodes.values(),
self.macros.values(), self.macros.values(),
)) )
)
forward_edges = build_macro_edges(edge_members) forward_edges = build_macro_edges(edge_members)
return forward_edges return forward_edges
@@ -758,6 +781,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
macros=self.macros, macros=self.macros,
docs=self.docs, docs=self.docs,
exposures=self.exposures, exposures=self.exposures,
metrics=self.metrics,
selectors=self.selectors, selectors=self.selectors,
metadata=self.metadata, metadata=self.metadata,
disabled=self.disabled, disabled=self.disabled,
@@ -777,10 +801,12 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
return self.sources[unique_id] return self.sources[unique_id]
elif unique_id in self.exposures: elif unique_id in self.exposures:
return self.exposures[unique_id] return self.exposures[unique_id]
elif unique_id in self.metrics:
return self.metrics[unique_id]
else: else:
# something terrible has happened # something terrible has happened
raise dbt.exceptions.InternalException( raise dbt.exceptions.InternalException(
'Expected node {} not found in manifest'.format(unique_id) "Expected node {} not found in manifest".format(unique_id)
) )
@property @property
@@ -838,9 +864,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
node: Optional[ManifestNode] = None node: Optional[ManifestNode] = None
disabled: Optional[List[ManifestNode]] = None disabled: Optional[List[ManifestNode]] = None
candidates = _search_packages( candidates = _search_packages(current_project, node_package, target_model_package)
current_project, node_package, target_model_package
)
for pkg in candidates: for pkg in candidates:
node = self.ref_lookup.find(target_model_name, pkg, self) node = self.ref_lookup.find(target_model_name, pkg, self)
@@ -849,9 +873,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
# it's possible that the node is disabled # it's possible that the node is disabled
if disabled is None: if disabled is None:
disabled = self.disabled_lookup.find( disabled = self.disabled_lookup.find(target_model_name, pkg)
target_model_name, pkg
)
if disabled: if disabled:
return Disabled(disabled[0]) return Disabled(disabled[0])
@@ -864,9 +886,9 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
target_source_name: str, target_source_name: str,
target_table_name: str, target_table_name: str,
current_project: str, current_project: str,
node_package: str node_package: str,
) -> MaybeParsedSource: ) -> MaybeParsedSource:
search_name = f'{target_source_name}.{target_table_name}' search_name = f"{target_source_name}.{target_table_name}"
candidates = _search_packages(current_project, node_package) candidates = _search_packages(current_project, node_package)
source: Optional[ParsedSourceDefinition] = None source: Optional[ParsedSourceDefinition] = None
@@ -879,7 +901,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
if disabled is None: if disabled is None:
disabled = self.disabled_lookup.find( disabled = self.disabled_lookup.find(
f'{target_source_name}.{target_table_name}', pkg f"{target_source_name}.{target_table_name}", pkg
) )
if disabled: if disabled:
@@ -898,9 +920,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
resolve_ref except the is_enabled checks are unnecessary as docs are resolve_ref except the is_enabled checks are unnecessary as docs are
always enabled. always enabled.
""" """
candidates = _search_packages( candidates = _search_packages(current_project, node_package, package)
current_project, node_package, package
)
for pkg in candidates: for pkg in candidates:
result = self.doc_lookup.find(name, pkg, self) result = self.doc_lookup.find(name, pkg, self)
@@ -912,7 +932,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
def merge_from_artifact( def merge_from_artifact(
self, self,
adapter, adapter,
other: 'WritableManifest', other: "WritableManifest",
selected: AbstractSet[UniqueID], selected: AbstractSet[UniqueID],
) -> None: ) -> None:
"""Given the selected unique IDs and a writable manifest, update this """Given the selected unique IDs and a writable manifest, update this
@@ -925,21 +945,17 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
for unique_id, node in other.nodes.items(): for unique_id, node in other.nodes.items():
current = self.nodes.get(unique_id) current = self.nodes.get(unique_id)
if current and ( if current and (
node.resource_type in refables and node.resource_type in refables
not node.is_ephemeral and and not node.is_ephemeral
unique_id not in selected and and unique_id not in selected
not adapter.get_relation( and not adapter.get_relation(current.database, current.schema, current.identifier)
current.database, current.schema, current.identifier
)
): ):
merged.add(unique_id) merged.add(unique_id)
self.nodes[unique_id] = node.replace(deferred=True) self.nodes[unique_id] = node.replace(deferred=True)
# log up to 5 items # log up to 5 items
sample = list(islice(merged, 5)) sample = list(islice(merged, 5))
logger.debug( fire_event(MergedFromState(nbr_merged=len(merged), sample=sample))
f'Merged {len(merged)} items from state (sample: {sample})'
)
# Methods that were formerly in ParseResult # Methods that were formerly in ParseResult
@@ -951,7 +967,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
# note that the line wrap eats newlines, so if you want newlines, # note that the line wrap eats newlines, so if you want newlines,
# this is the result :( # this is the result :(
msg = line_wrap_message( msg = line_wrap_message(
f'''\ f"""\
dbt found two macros named "{macro.name}" in the project dbt found two macros named "{macro.name}" in the project
"{macro.package_name}". "{macro.package_name}".
@@ -962,8 +978,8 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
- {macro.original_file_path} - {macro.original_file_path}
- {other_path} - {other_path}
''', """,
subtract=2 subtract=2,
) )
raise_compiler_error(msg) raise_compiler_error(msg)
@@ -979,9 +995,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
my_checksum = self.files[key].checksum my_checksum = self.files[key].checksum
return my_checksum == source_file.checksum return my_checksum == source_file.checksum
def add_source( def add_source(self, source_file: SchemaSourceFile, source: UnpatchedSourceDefinition):
self, source_file: SchemaSourceFile, source: UnpatchedSourceDefinition
):
# sources can't be overwritten! # sources can't be overwritten!
_check_duplicates(source, self.sources) _check_duplicates(source, self.sources)
self.sources[source.unique_id] = source # type: ignore self.sources[source.unique_id] = source # type: ignore
@@ -1005,6 +1019,11 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
self.exposures[exposure.unique_id] = exposure self.exposures[exposure.unique_id] = exposure
source_file.exposures.append(exposure.unique_id) source_file.exposures.append(exposure.unique_id)
def add_metric(self, source_file: SchemaSourceFile, metric: ParsedMetric):
_check_duplicates(metric, self.metrics)
self.metrics[metric.unique_id] = metric
source_file.metrics.append(metric.unique_id)
def add_disabled_nofile(self, node: CompileResultNode): def add_disabled_nofile(self, node: CompileResultNode):
# There can be multiple disabled nodes for the same unique_id # There can be multiple disabled nodes for the same unique_id
if node.unique_id in self.disabled: if node.unique_id in self.disabled:
@@ -1041,6 +1060,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
self.macros, self.macros,
self.docs, self.docs,
self.exposures, self.exposures,
self.metrics,
self.selectors, self.selectors,
self.files, self.files,
self.metadata, self.metadata,
@@ -1048,6 +1068,7 @@ class Manifest(MacroMethods, DataClassMessagePackMixin, dbtClassMixin):
self.state_check, self.state_check,
self.source_patches, self.source_patches,
self.disabled, self.disabled,
self.env_vars,
self._doc_lookup, self._doc_lookup,
self._source_lookup, self._source_lookup,
self._ref_lookup, self._ref_lookup,
@@ -1070,70 +1091,64 @@ AnyManifest = Union[Manifest, MacroManifest]
@dataclass @dataclass
@schema_version('manifest', 3) @schema_version("manifest", 4)
class WritableManifest(ArtifactMixin): class WritableManifest(ArtifactMixin):
nodes: Mapping[UniqueID, ManifestNode] = field( nodes: Mapping[UniqueID, ManifestNode] = field(
metadata=dict(description=( metadata=dict(description=("The nodes defined in the dbt project and its dependencies"))
'The nodes defined in the dbt project and its dependencies'
))
) )
sources: Mapping[UniqueID, ParsedSourceDefinition] = field( sources: Mapping[UniqueID, ParsedSourceDefinition] = field(
metadata=dict(description=( metadata=dict(description=("The sources defined in the dbt project and its dependencies"))
'The sources defined in the dbt project and its dependencies'
))
) )
macros: Mapping[UniqueID, ParsedMacro] = field( macros: Mapping[UniqueID, ParsedMacro] = field(
metadata=dict(description=( metadata=dict(description=("The macros defined in the dbt project and its dependencies"))
'The macros defined in the dbt project and its dependencies'
))
) )
docs: Mapping[UniqueID, ParsedDocumentation] = field( docs: Mapping[UniqueID, ParsedDocumentation] = field(
metadata=dict(description=( metadata=dict(description=("The docs defined in the dbt project and its dependencies"))
'The docs defined in the dbt project and its dependencies'
))
) )
exposures: Mapping[UniqueID, ParsedExposure] = field( exposures: Mapping[UniqueID, ParsedExposure] = field(
metadata=dict(description=( metadata=dict(
'The exposures defined in the dbt project and its dependencies' description=("The exposures defined in the dbt project and its dependencies")
)) )
)
metrics: Mapping[UniqueID, ParsedMetric] = field(
metadata=dict(description=("The metrics defined in the dbt project and its dependencies"))
) )
selectors: Mapping[UniqueID, Any] = field( selectors: Mapping[UniqueID, Any] = field(
metadata=dict(description=( metadata=dict(description=("The selectors defined in selectors.yml"))
'The selectors defined in selectors.yml' )
)) disabled: Optional[Mapping[UniqueID, List[CompileResultNode]]] = field(
metadata=dict(description="A mapping of the disabled nodes in the target")
)
parent_map: Optional[NodeEdgeMap] = field(
metadata=dict(
description="A mapping from child nodes to their dependencies",
)
)
child_map: Optional[NodeEdgeMap] = field(
metadata=dict(
description="A mapping from parent nodes to their dependents",
)
)
metadata: ManifestMetadata = field(
metadata=dict(
description="Metadata about the manifest",
)
) )
disabled: Optional[Mapping[UniqueID, List[CompileResultNode]]] = field(metadata=dict(
description='A mapping of the disabled nodes in the target'
))
parent_map: Optional[NodeEdgeMap] = field(metadata=dict(
description='A mapping from child nodes to their dependencies',
))
child_map: Optional[NodeEdgeMap] = field(metadata=dict(
description='A mapping from parent nodes to their dependents',
))
metadata: ManifestMetadata = field(metadata=dict(
description='Metadata about the manifest',
))
def _check_duplicates( def _check_duplicates(value: HasUniqueID, src: Mapping[str, HasUniqueID]):
value: HasUniqueID, src: Mapping[str, HasUniqueID]
):
if value.unique_id in src: if value.unique_id in src:
raise_duplicate_resource_name(value, src[value.unique_id]) raise_duplicate_resource_name(value, src[value.unique_id])
K_T = TypeVar('K_T') K_T = TypeVar("K_T")
V_T = TypeVar('V_T') V_T = TypeVar("V_T")
def _expect_value( def _expect_value(key: K_T, src: Mapping[K_T, V_T], old_file: SourceFile, name: str) -> V_T:
key: K_T, src: Mapping[K_T, V_T], old_file: SourceFile, name: str
) -> V_T:
if key not in src: if key not in src:
raise CompilationException( raise CompilationException(
'Expected to find "{}" in cached "result.{}" based ' 'Expected to find "{}" in cached "result.{}" based '
'on cached file information: {}!' "on cached file information: {}!".format(key, name, old_file)
.format(key, name, old_file)
) )
return src[key] return src[key]

View File

@@ -1,11 +1,11 @@
from dataclasses import field, Field, dataclass from dataclasses import field, Field, dataclass
from enum import Enum from enum import Enum
from itertools import chain from itertools import chain
from typing import ( from typing import Any, List, Optional, Dict, Union, Type, TypeVar, Callable
Any, List, Optional, Dict, Union, Type, TypeVar, Callable
)
from dbt.dataclass_schema import ( from dbt.dataclass_schema import (
dbtClassMixin, ValidationError, register_pattern, dbtClassMixin,
ValidationError,
register_pattern,
) )
from dbt.contracts.graph.unparsed import AdditionalPropertiesAllowed from dbt.contracts.graph.unparsed import AdditionalPropertiesAllowed
from dbt.exceptions import InternalException, CompilationException from dbt.exceptions import InternalException, CompilationException
@@ -14,7 +14,7 @@ from dbt import hooks
from dbt.node_types import NodeType from dbt.node_types import NodeType
M = TypeVar('M', bound='Metadata') M = TypeVar("M", bound="Metadata")
def _get_meta_value(cls: Type[M], fld: Field, key: str, default: Any) -> M: def _get_meta_value(cls: Type[M], fld: Field, key: str, default: Any) -> M:
@@ -29,14 +29,10 @@ def _get_meta_value(cls: Type[M], fld: Field, key: str, default: Any) -> M:
try: try:
return cls(value) return cls(value)
except ValueError as exc: except ValueError as exc:
raise InternalException( raise InternalException(f"Invalid {cls} value: {value}") from exc
f'Invalid {cls} value: {value}'
) from exc
def _set_meta_value( def _set_meta_value(obj: M, key: str, existing: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
obj: M, key: str, existing: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
if existing is None: if existing is None:
result = {} result = {}
else: else:
@@ -53,19 +49,17 @@ class Metadata(Enum):
return _get_meta_value(cls, fld, key, default) return _get_meta_value(cls, fld, key, default)
def meta( def meta(self, existing: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
self, existing: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
key = self.metadata_key() key = self.metadata_key()
return _set_meta_value(self, key, existing) return _set_meta_value(self, key, existing)
@classmethod @classmethod
def default_field(cls) -> 'Metadata': def default_field(cls) -> "Metadata":
raise NotImplementedError('Not implemented') raise NotImplementedError("Not implemented")
@classmethod @classmethod
def metadata_key(cls) -> str: def metadata_key(cls) -> str:
raise NotImplementedError('Not implemented') raise NotImplementedError("Not implemented")
class MergeBehavior(Metadata): class MergeBehavior(Metadata):
@@ -74,12 +68,12 @@ class MergeBehavior(Metadata):
Clobber = 3 Clobber = 3
@classmethod @classmethod
def default_field(cls) -> 'MergeBehavior': def default_field(cls) -> "MergeBehavior":
return cls.Clobber return cls.Clobber
@classmethod @classmethod
def metadata_key(cls) -> str: def metadata_key(cls) -> str:
return 'merge' return "merge"
class ShowBehavior(Metadata): class ShowBehavior(Metadata):
@@ -87,12 +81,12 @@ class ShowBehavior(Metadata):
Hide = 2 Hide = 2
@classmethod @classmethod
def default_field(cls) -> 'ShowBehavior': def default_field(cls) -> "ShowBehavior":
return cls.Show return cls.Show
@classmethod @classmethod
def metadata_key(cls) -> str: def metadata_key(cls) -> str:
return 'show_hide' return "show_hide"
@classmethod @classmethod
def should_show(cls, fld: Field) -> bool: def should_show(cls, fld: Field) -> bool:
@@ -104,12 +98,12 @@ class CompareBehavior(Metadata):
Exclude = 2 Exclude = 2
@classmethod @classmethod
def default_field(cls) -> 'CompareBehavior': def default_field(cls) -> "CompareBehavior":
return cls.Include return cls.Include
@classmethod @classmethod
def metadata_key(cls) -> str: def metadata_key(cls) -> str:
return 'compare' return "compare"
@classmethod @classmethod
def should_include(cls, fld: Field) -> bool: def should_include(cls, fld: Field) -> bool:
@@ -141,32 +135,28 @@ def _merge_field_value(
return _listify(self_value) + _listify(other_value) return _listify(self_value) + _listify(other_value)
elif merge_behavior == MergeBehavior.Update: elif merge_behavior == MergeBehavior.Update:
if not isinstance(self_value, dict): if not isinstance(self_value, dict):
raise InternalException(f'expected dict, got {self_value}') raise InternalException(f"expected dict, got {self_value}")
if not isinstance(other_value, dict): if not isinstance(other_value, dict):
raise InternalException(f'expected dict, got {other_value}') raise InternalException(f"expected dict, got {other_value}")
value = self_value.copy() value = self_value.copy()
value.update(other_value) value.update(other_value)
return value return value
else: else:
raise InternalException( raise InternalException(f"Got an invalid merge_behavior: {merge_behavior}")
f'Got an invalid merge_behavior: {merge_behavior}'
)
def insensitive_patterns(*patterns: str): def insensitive_patterns(*patterns: str):
lowercased = [] lowercased = []
for pattern in patterns: for pattern in patterns:
lowercased.append( lowercased.append("".join("[{}{}]".format(s.upper(), s.lower()) for s in pattern))
''.join('[{}{}]'.format(s.upper(), s.lower()) for s in pattern) return "^({})$".format("|".join(lowercased))
)
return '^({})$'.format('|'.join(lowercased))
class Severity(str): class Severity(str):
pass pass
register_pattern(Severity, insensitive_patterns('warn', 'error')) register_pattern(Severity, insensitive_patterns("warn", "error"))
@dataclass @dataclass
@@ -176,13 +166,11 @@ class Hook(dbtClassMixin, Replaceable):
index: Optional[int] = None index: Optional[int] = None
T = TypeVar('T', bound='BaseConfig') T = TypeVar("T", bound="BaseConfig")
@dataclass @dataclass
class BaseConfig( class BaseConfig(AdditionalPropertiesAllowed, Replaceable):
AdditionalPropertiesAllowed, Replaceable
):
# enable syntax like: config['key'] # enable syntax like: config['key']
def __getitem__(self, key): def __getitem__(self, key):
@@ -207,8 +195,7 @@ class BaseConfig(
def __delitem__(self, key): def __delitem__(self, key):
if hasattr(self, key): if hasattr(self, key):
msg = ( msg = (
'Error, tried to delete config key "{}": Cannot delete ' 'Error, tried to delete config key "{}": Cannot delete ' "built-in keys"
'built-in keys'
).format(key) ).format(key)
raise CompilationException(msg) raise CompilationException(msg)
else: else:
@@ -248,9 +235,7 @@ class BaseConfig(
return unrendered[key] == other[key] return unrendered[key] == other[key]
@classmethod @classmethod
def same_contents( def same_contents(cls, unrendered: Dict[str, Any], other: Dict[str, Any]) -> bool:
cls, unrendered: Dict[str, Any], other: Dict[str, Any]
) -> bool:
"""This is like __eq__, except it ignores some fields.""" """This is like __eq__, except it ignores some fields."""
seen = set() seen = set()
for fld, target_name in cls._get_fields(): for fld, target_name in cls._get_fields():
@@ -270,14 +255,12 @@ class BaseConfig(
# This is used in 'add_config_call' to created the combined config_call_dict. # This is used in 'add_config_call' to created the combined config_call_dict.
# 'meta' moved here from node # 'meta' moved here from node
mergebehavior = { mergebehavior = {
"append": ['pre-hook', 'pre_hook', 'post-hook', 'post_hook', 'tags'], "append": ["pre-hook", "pre_hook", "post-hook", "post_hook", "tags"],
"update": ['quoting', 'column_types', 'meta'], "update": ["quoting", "column_types", "meta"],
} }
@classmethod @classmethod
def _merge_dicts( def _merge_dicts(cls, src: Dict[str, Any], data: Dict[str, Any]) -> Dict[str, Any]:
cls, src: Dict[str, Any], data: Dict[str, Any]
) -> Dict[str, Any]:
"""Find all the items in data that match a target_field on this class, """Find all the items in data that match a target_field on this class,
and merge them with the data found in `src` for target_field, using the and merge them with the data found in `src` for target_field, using the
field's specified merge behavior. Matching items will be removed from field's specified merge behavior. Matching items will be removed from
@@ -309,14 +292,13 @@ class BaseConfig(
) )
return result return result
def update_from( def update_from(self: T, data: Dict[str, Any], adapter_type: str, validate: bool = True) -> T:
self: T, data: Dict[str, Any], adapter_type: str, validate: bool = True
) -> T:
"""Given a dict of keys, update the current config from them, validate """Given a dict of keys, update the current config from them, validate
it, and return a new config with the updated values it, and return a new config with the updated values
""" """
# sadly, this is a circular import # sadly, this is a circular import
from dbt.adapters.factory import get_config_class_by_name from dbt.adapters.factory import get_config_class_by_name
dct = self.to_dict(omit_none=False) dct = self.to_dict(omit_none=False)
adapter_config_cls = get_config_class_by_name(adapter_type) adapter_config_cls = get_config_class_by_name(adapter_type)
@@ -374,9 +356,7 @@ class NodeAndTestConfig(BaseConfig):
) )
tags: Union[List[str], str] = field( tags: Union[List[str], str] = field(
default_factory=list_str, default_factory=list_str,
metadata=metas(ShowBehavior.Hide, metadata=metas(ShowBehavior.Hide, MergeBehavior.Append, CompareBehavior.Exclude),
MergeBehavior.Append,
CompareBehavior.Exclude),
) )
meta: Dict[str, Any] = field( meta: Dict[str, Any] = field(
default_factory=dict, default_factory=dict,
@@ -388,7 +368,7 @@ class NodeAndTestConfig(BaseConfig):
class NodeConfig(NodeAndTestConfig): class NodeConfig(NodeAndTestConfig):
# Note: if any new fields are added with MergeBehavior, also update the # Note: if any new fields are added with MergeBehavior, also update the
# 'mergebehavior' dictionary # 'mergebehavior' dictionary
materialized: str = 'view' materialized: str = "view"
persist_docs: Dict[str, Any] = field(default_factory=dict) persist_docs: Dict[str, Any] = field(default_factory=dict)
post_hook: List[Hook] = field( post_hook: List[Hook] = field(
default_factory=list, default_factory=list,
@@ -409,12 +389,15 @@ class NodeConfig(NodeAndTestConfig):
metadata=MergeBehavior.Update.meta(), metadata=MergeBehavior.Update.meta(),
) )
full_refresh: Optional[bool] = None full_refresh: Optional[bool] = None
on_schema_change: Optional[str] = 'ignore' # 'unique_key' doesn't use 'Optional' because typing.get_type_hints was
# sometimes getting the Union order wrong, causing serialization failures.
unique_key: Union[str, List[str], None] = None
on_schema_change: Optional[str] = "ignore"
@classmethod @classmethod
def __pre_deserialize__(cls, data): def __pre_deserialize__(cls, data):
data = super().__pre_deserialize__(data) data = super().__pre_deserialize__(data)
field_map = {'post-hook': 'post_hook', 'pre-hook': 'pre_hook'} field_map = {"post-hook": "post_hook", "pre-hook": "pre_hook"}
# create a new dict because otherwise it gets overwritten in # create a new dict because otherwise it gets overwritten in
# tests # tests
new_dict = {} new_dict = {}
@@ -432,7 +415,7 @@ class NodeConfig(NodeAndTestConfig):
def __post_serialize__(self, dct): def __post_serialize__(self, dct):
dct = super().__post_serialize__(dct) dct = super().__post_serialize__(dct)
field_map = {'post_hook': 'post-hook', 'pre_hook': 'pre-hook'} field_map = {"post_hook": "post-hook", "pre_hook": "pre-hook"}
for field_name in field_map: for field_name in field_map:
if field_name in dct: if field_name in dct:
dct[field_map[field_name]] = dct.pop(field_name) dct[field_map[field_name]] = dct.pop(field_name)
@@ -441,12 +424,12 @@ class NodeConfig(NodeAndTestConfig):
# this is still used by jsonschema validation # this is still used by jsonschema validation
@classmethod @classmethod
def field_mapping(cls): def field_mapping(cls):
return {'post_hook': 'post-hook', 'pre_hook': 'pre-hook'} return {"post_hook": "post-hook", "pre_hook": "pre-hook"}
@dataclass @dataclass
class SeedConfig(NodeConfig): class SeedConfig(NodeConfig):
materialized: str = 'seed' materialized: str = "seed"
quote_columns: Optional[bool] = None quote_columns: Optional[bool] = None
@@ -454,31 +437,29 @@ class SeedConfig(NodeConfig):
class TestConfig(NodeAndTestConfig): class TestConfig(NodeAndTestConfig):
# this is repeated because of a different default # this is repeated because of a different default
schema: Optional[str] = field( schema: Optional[str] = field(
default='dbt_test__audit', default="dbt_test__audit",
metadata=CompareBehavior.Exclude.meta(), metadata=CompareBehavior.Exclude.meta(),
) )
materialized: str = 'test' materialized: str = "test"
severity: Severity = Severity('ERROR') severity: Severity = Severity("ERROR")
store_failures: Optional[bool] = None store_failures: Optional[bool] = None
where: Optional[str] = None where: Optional[str] = None
limit: Optional[int] = None limit: Optional[int] = None
fail_calc: str = 'count(*)' fail_calc: str = "count(*)"
warn_if: str = '!= 0' warn_if: str = "!= 0"
error_if: str = '!= 0' error_if: str = "!= 0"
@classmethod @classmethod
def same_contents( def same_contents(cls, unrendered: Dict[str, Any], other: Dict[str, Any]) -> bool:
cls, unrendered: Dict[str, Any], other: Dict[str, Any]
) -> bool:
"""This is like __eq__, except it explicitly checks certain fields.""" """This is like __eq__, except it explicitly checks certain fields."""
modifiers = [ modifiers = [
'severity', "severity",
'where', "where",
'limit', "limit",
'fail_calc', "fail_calc",
'warn_if', "warn_if",
'error_if', "error_if",
'store_failures' "store_failures",
] ]
seen = set() seen = set()
@@ -493,7 +474,8 @@ class TestConfig(NodeAndTestConfig):
@dataclass @dataclass
class EmptySnapshotConfig(NodeConfig): class EmptySnapshotConfig(NodeConfig):
materialized: str = 'snapshot' materialized: str = "snapshot"
unique_key: Optional[str] = None # override NodeConfig unique_key definition
@dataclass @dataclass
@@ -503,35 +485,37 @@ class SnapshotConfig(EmptySnapshotConfig):
target_schema: Optional[str] = None target_schema: Optional[str] = None
target_database: Optional[str] = None target_database: Optional[str] = None
updated_at: Optional[str] = None updated_at: Optional[str] = None
check_cols: Optional[Union[str, List[str]]] = None # Not using Optional because of serialization issues with a Union of str and List[str]
check_cols: Union[str, List[str], None] = None
@classmethod @classmethod
def validate(cls, data): def validate(cls, data):
super().validate(data) super().validate(data)
if not data.get('strategy') or not data.get('unique_key') or not \ if not data.get("strategy") or not data.get("unique_key") or not data.get("target_schema"):
data.get('target_schema'):
raise ValidationError( raise ValidationError(
"Snapshots must be configured with a 'strategy', 'unique_key', " "Snapshots must be configured with a 'strategy', 'unique_key', "
"and 'target_schema'.") "and 'target_schema'."
if data.get('strategy') == 'check': )
if not data.get('check_cols'): if data.get("strategy") == "check":
if not data.get("check_cols"):
raise ValidationError( raise ValidationError(
"A snapshot configured with the check strategy must " "A snapshot configured with the check strategy must "
"specify a check_cols configuration.") "specify a check_cols configuration."
if (isinstance(data['check_cols'], str) and )
data['check_cols'] != 'all'): if isinstance(data["check_cols"], str) and data["check_cols"] != "all":
raise ValidationError( raise ValidationError(
f"Invalid value for 'check_cols': {data['check_cols']}. " f"Invalid value for 'check_cols': {data['check_cols']}. "
"Expected 'all' or a list of strings.") "Expected 'all' or a list of strings."
)
elif data.get('strategy') == 'timestamp': elif data.get("strategy") == "timestamp":
if not data.get('updated_at'): if not data.get("updated_at"):
raise ValidationError( raise ValidationError(
"A snapshot configured with the timestamp strategy " "A snapshot configured with the timestamp strategy "
"must specify an updated_at configuration.") "must specify an updated_at configuration."
if data.get('check_cols'): )
raise ValidationError( if data.get("check_cols"):
"A 'timestamp' snapshot should not have 'check_cols'") raise ValidationError("A 'timestamp' snapshot should not have 'check_cols'")
# If the strategy is not 'check' or 'timestamp' it's a custom strategy, # If the strategy is not 'check' or 'timestamp' it's a custom strategy,
# formerly supported with GenericSnapshotConfig # formerly supported with GenericSnapshotConfig
@@ -553,9 +537,7 @@ RESOURCE_TYPES: Dict[NodeType, Type[BaseConfig]] = {
# base resource types are like resource types, except nothing has mandatory # base resource types are like resource types, except nothing has mandatory
# configs. # configs.
BASE_RESOURCE_TYPES: Dict[NodeType, Type[BaseConfig]] = RESOURCE_TYPES.copy() BASE_RESOURCE_TYPES: Dict[NodeType, Type[BaseConfig]] = RESOURCE_TYPES.copy()
BASE_RESOURCE_TYPES.update({ BASE_RESOURCE_TYPES.update({NodeType.Snapshot: EmptySnapshotConfig})
NodeType.Snapshot: EmptySnapshotConfig
})
def get_config_for(resource_type: NodeType, base=False) -> Type[BaseConfig]: def get_config_for(resource_type: NodeType, base=False) -> Type[BaseConfig]:

View File

@@ -15,22 +15,31 @@ from typing import (
TypeVar, TypeVar,
) )
from dbt.dataclass_schema import ( from dbt.dataclass_schema import dbtClassMixin, ExtensibleDbtClassMixin
dbtClassMixin, ExtensibleDbtClassMixin
)
from dbt.clients.system import write_file from dbt.clients.system import write_file
from dbt.contracts.files import FileHash, MAXIMUM_SEED_SIZE_NAME from dbt.contracts.files import FileHash, MAXIMUM_SEED_SIZE_NAME
from dbt.contracts.graph.unparsed import ( from dbt.contracts.graph.unparsed import (
UnparsedNode, UnparsedDocumentation, Quoting, Docs, UnparsedNode,
UnparsedBaseNode, FreshnessThreshold, ExternalTable, UnparsedDocumentation,
HasYamlMetadata, MacroArgument, UnparsedSourceDefinition, Quoting,
UnparsedSourceTableDefinition, UnparsedColumn, TestDef, Docs,
ExposureOwner, ExposureType, MaturityType UnparsedBaseNode,
FreshnessThreshold,
ExternalTable,
HasYamlMetadata,
MacroArgument,
UnparsedSourceDefinition,
UnparsedSourceTableDefinition,
UnparsedColumn,
TestDef,
ExposureOwner,
ExposureType,
MaturityType,
MetricFilter,
) )
from dbt.contracts.util import Replaceable, AdditionalPropertiesMixin from dbt.contracts.util import Replaceable, AdditionalPropertiesMixin
from dbt.exceptions import warn_or_error from dbt.exceptions import warn_or_error
from dbt.logger import GLOBAL_LOGGER as logger # noqa
from dbt import flags from dbt import flags
from dbt.node_types import NodeType from dbt.node_types import NodeType
@@ -46,13 +55,9 @@ from .model_config import (
@dataclass @dataclass
class ColumnInfo( class ColumnInfo(AdditionalPropertiesMixin, ExtensibleDbtClassMixin, Replaceable):
AdditionalPropertiesMixin,
ExtensibleDbtClassMixin,
Replaceable
):
name: str name: str
description: str = '' description: str = ""
meta: Dict[str, Any] = field(default_factory=dict) meta: Dict[str, Any] = field(default_factory=dict)
data_type: Optional[str] = None data_type: Optional[str] = None
quote: Optional[bool] = None quote: Optional[bool] = None
@@ -64,7 +69,7 @@ class ColumnInfo(
class HasFqn(dbtClassMixin, Replaceable): class HasFqn(dbtClassMixin, Replaceable):
fqn: List[str] fqn: List[str]
def same_fqn(self, other: 'HasFqn') -> bool: def same_fqn(self, other: "HasFqn") -> bool:
return self.fqn == other.fqn return self.fqn == other.fqn
@@ -103,8 +108,8 @@ class HasRelationMetadata(dbtClassMixin, Replaceable):
@classmethod @classmethod
def __pre_deserialize__(cls, data): def __pre_deserialize__(cls, data):
data = super().__pre_deserialize__(data) data = super().__pre_deserialize__(data)
if 'database' not in data: if "database" not in data:
data['database'] = None data["database"] = None
return data return data
@@ -120,21 +125,19 @@ class ParsedNodeMixins(dbtClassMixin):
@property @property
def should_store_failures(self): def should_store_failures(self):
return self.resource_type == NodeType.Test and ( return self.resource_type == NodeType.Test and (
self.config.store_failures if self.config.store_failures is not None self.config.store_failures
if self.config.store_failures is not None
else flags.STORE_FAILURES else flags.STORE_FAILURES
) )
# will this node map to an object in the database? # will this node map to an object in the database?
@property @property
def is_relational(self): def is_relational(self):
return ( return self.resource_type in NodeType.refable() or self.should_store_failures
self.resource_type in NodeType.refable() or
self.should_store_failures
)
@property @property
def is_ephemeral(self): def is_ephemeral(self):
return self.config.materialized == 'ephemeral' return self.config.materialized == "ephemeral"
@property @property
def is_ephemeral_model(self): def is_ephemeral_model(self):
@@ -144,17 +147,16 @@ class ParsedNodeMixins(dbtClassMixin):
def depends_on_nodes(self): def depends_on_nodes(self):
return self.depends_on.nodes return self.depends_on.nodes
def patch(self, patch: 'ParsedNodePatch'): def patch(self, patch: "ParsedNodePatch"):
"""Given a ParsedNodePatch, add the new information to the node.""" """Given a ParsedNodePatch, add the new information to the node."""
# explicitly pick out the parts to update so we don't inadvertently # explicitly pick out the parts to update so we don't inadvertently
# step on the model name or anything # step on the model name or anything
# Note: config should already be updated # Note: config should already be updated
self.patch_path: Optional[str] = patch.file_id self.patch_path: Optional[str] = patch.file_id
# update created_at so process_docs will run in partial parsing # update created_at so process_docs will run in partial parsing
self.created_at = int(time.time()) self.created_at = time.time()
self.description = patch.description self.description = patch.description
self.columns = patch.columns self.columns = patch.columns
self.meta = patch.meta
self.docs = patch.docs self.docs = patch.docs
def get_materialization(self): def get_materialization(self):
@@ -162,13 +164,7 @@ class ParsedNodeMixins(dbtClassMixin):
@dataclass @dataclass
class ParsedNodeMandatory( class ParsedNodeMandatory(UnparsedNode, HasUniqueID, HasFqn, HasRelationMetadata, Replaceable):
UnparsedNode,
HasUniqueID,
HasFqn,
HasRelationMetadata,
Replaceable
):
alias: str alias: str
checksum: FileHash checksum: FileHash
config: NodeConfig = field(default_factory=NodeConfig) config: NodeConfig = field(default_factory=NodeConfig)
@@ -179,12 +175,31 @@ class ParsedNodeMandatory(
@dataclass @dataclass
class ParsedNodeDefaults(ParsedNodeMandatory): class NodeInfoMixin:
_event_status: Dict[str, Any] = field(default_factory=dict)
@property
def node_info(self):
node_info = {
"node_path": getattr(self, "path", None),
"node_name": getattr(self, "name", None),
"unique_id": getattr(self, "unique_id", None),
"resource_type": str(getattr(self, "resource_type", "")),
"materialized": self.config.get("materialized"),
"node_status": str(self._event_status.get("node_status")),
"node_started_at": self._event_status.get("started_at"),
"node_finished_at": self._event_status.get("finished_at"),
}
return node_info
@dataclass
class ParsedNodeDefaults(NodeInfoMixin, ParsedNodeMandatory):
tags: List[str] = field(default_factory=list) tags: List[str] = field(default_factory=list)
refs: List[List[str]] = field(default_factory=list) refs: List[List[str]] = field(default_factory=list)
sources: List[List[str]] = field(default_factory=list) sources: List[List[str]] = field(default_factory=list)
depends_on: DependsOn = field(default_factory=DependsOn) depends_on: DependsOn = field(default_factory=DependsOn)
description: str = field(default='') description: str = field(default="")
columns: Dict[str, ColumnInfo] = field(default_factory=dict) columns: Dict[str, ColumnInfo] = field(default_factory=dict)
meta: Dict[str, Any] = field(default_factory=dict) meta: Dict[str, Any] = field(default_factory=dict)
docs: Docs = field(default_factory=Docs) docs: Docs = field(default_factory=Docs)
@@ -193,37 +208,35 @@ class ParsedNodeDefaults(ParsedNodeMandatory):
build_path: Optional[str] = None build_path: Optional[str] = None
deferred: bool = False deferred: bool = False
unrendered_config: Dict[str, Any] = field(default_factory=dict) unrendered_config: Dict[str, Any] = field(default_factory=dict)
created_at: int = field(default_factory=lambda: int(time.time())) created_at: float = field(default_factory=lambda: time.time())
config_call_dict: Dict[str, Any] = field(default_factory=dict) config_call_dict: Dict[str, Any] = field(default_factory=dict)
def write_node(self, target_path: str, subdirectory: str, payload: str): def write_node(self, target_path: str, subdirectory: str, payload: str):
if (os.path.basename(self.path) == if os.path.basename(self.path) == os.path.basename(self.original_file_path):
os.path.basename(self.original_file_path)):
# One-to-one relationship of nodes to files. # One-to-one relationship of nodes to files.
path = self.original_file_path path = self.original_file_path
else: else:
# Many-to-one relationship of nodes to files. # Many-to-one relationship of nodes to files.
path = os.path.join(self.original_file_path, self.path) path = os.path.join(self.original_file_path, self.path)
full_path = os.path.join( full_path = os.path.join(target_path, subdirectory, self.package_name, path)
target_path, subdirectory, self.package_name, path
)
write_file(full_path, payload) write_file(full_path, payload)
return full_path return full_path
T = TypeVar('T', bound='ParsedNode') T = TypeVar("T", bound="ParsedNode")
@dataclass @dataclass
class ParsedNode(ParsedNodeDefaults, ParsedNodeMixins, SerializableType): class ParsedNode(ParsedNodeDefaults, ParsedNodeMixins, SerializableType):
def _serialize(self): def _serialize(self):
return self.to_dict() return self.to_dict()
def __post_serialize__(self, dct): def __post_serialize__(self, dct):
if 'config_call_dict' in dct: if "config_call_dict" in dct:
del dct['config_call_dict'] del dct["config_call_dict"]
if "_event_status" in dct:
del dct["_event_status"]
return dct return dct
@classmethod @classmethod
@@ -231,39 +244,41 @@ class ParsedNode(ParsedNodeDefaults, ParsedNodeMixins, SerializableType):
# The serialized ParsedNodes do not differ from each other # The serialized ParsedNodes do not differ from each other
# in fields that would allow 'from_dict' to distinguis # in fields that would allow 'from_dict' to distinguis
# between them. # between them.
resource_type = dct['resource_type'] resource_type = dct["resource_type"]
if resource_type == 'model': if resource_type == "model":
return ParsedModelNode.from_dict(dct) return ParsedModelNode.from_dict(dct)
elif resource_type == 'analysis': elif resource_type == "analysis":
return ParsedAnalysisNode.from_dict(dct) return ParsedAnalysisNode.from_dict(dct)
elif resource_type == 'seed': elif resource_type == "seed":
return ParsedSeedNode.from_dict(dct) return ParsedSeedNode.from_dict(dct)
elif resource_type == 'rpc': elif resource_type == "rpc":
return ParsedRPCNode.from_dict(dct) return ParsedRPCNode.from_dict(dct)
elif resource_type == 'test': elif resource_type == "sql":
if 'test_metadata' in dct: return ParsedSqlNode.from_dict(dct)
elif resource_type == "test":
if "test_metadata" in dct:
return ParsedGenericTestNode.from_dict(dct) return ParsedGenericTestNode.from_dict(dct)
else: else:
return ParsedSingularTestNode.from_dict(dct) return ParsedSingularTestNode.from_dict(dct)
elif resource_type == 'operation': elif resource_type == "operation":
return ParsedHookNode.from_dict(dct) return ParsedHookNode.from_dict(dct)
elif resource_type == 'seed': elif resource_type == "seed":
return ParsedSeedNode.from_dict(dct) return ParsedSeedNode.from_dict(dct)
elif resource_type == 'snapshot': elif resource_type == "snapshot":
return ParsedSnapshotNode.from_dict(dct) return ParsedSnapshotNode.from_dict(dct)
else: else:
return cls.from_dict(dct) return cls.from_dict(dct)
def _persist_column_docs(self) -> bool: def _persist_column_docs(self) -> bool:
if hasattr(self.config, 'persist_docs'): if hasattr(self.config, "persist_docs"):
assert isinstance(self.config, NodeConfig) assert isinstance(self.config, NodeConfig)
return bool(self.config.persist_docs.get('columns')) return bool(self.config.persist_docs.get("columns"))
return False return False
def _persist_relation_docs(self) -> bool: def _persist_relation_docs(self) -> bool:
if hasattr(self.config, 'persist_docs'): if hasattr(self.config, "persist_docs"):
assert isinstance(self.config, NodeConfig) assert isinstance(self.config, NodeConfig)
return bool(self.config.persist_docs.get('relation')) return bool(self.config.persist_docs.get("relation"))
return False return False
def same_body(self: T, other: T) -> bool: def same_body(self: T, other: T) -> bool:
@@ -279,12 +294,8 @@ class ParsedNode(ParsedNodeDefaults, ParsedNodeMixins, SerializableType):
if self._persist_column_docs(): if self._persist_column_docs():
# assert other._persist_column_docs() # assert other._persist_column_docs()
column_descriptions = { column_descriptions = {k: v.description for k, v in self.columns.items()}
k: v.description for k, v in self.columns.items() other_column_descriptions = {k: v.description for k, v in other.columns.items()}
}
other_column_descriptions = {
k: v.description for k, v in other.columns.items()
}
if column_descriptions != other_column_descriptions: if column_descriptions != other_column_descriptions:
return False return False
@@ -295,7 +306,7 @@ class ParsedNode(ParsedNodeDefaults, ParsedNodeMixins, SerializableType):
# compares the configured value, rather than the ultimate value (so # compares the configured value, rather than the ultimate value (so
# generate_*_name and unset values derived from the target are # generate_*_name and unset values derived from the target are
# ignored) # ignored)
keys = ('database', 'schema', 'alias') keys = ("database", "schema", "alias")
for key in keys: for key in keys:
mine = self.unrendered_config.get(key) mine = self.unrendered_config.get(key)
others = other.unrendered_config.get(key) others = other.unrendered_config.get(key)
@@ -314,36 +325,40 @@ class ParsedNode(ParsedNodeDefaults, ParsedNodeMixins, SerializableType):
return False return False
return ( return (
self.same_body(old) and self.same_body(old)
self.same_config(old) and and self.same_config(old)
self.same_persisted_description(old) and and self.same_persisted_description(old)
self.same_fqn(old) and and self.same_fqn(old)
self.same_database_representation(old) and and self.same_database_representation(old)
True and True
) )
@dataclass @dataclass
class ParsedAnalysisNode(ParsedNode): class ParsedAnalysisNode(ParsedNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Analysis]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Analysis]})
@dataclass @dataclass
class ParsedHookNode(ParsedNode): class ParsedHookNode(ParsedNode):
resource_type: NodeType = field( resource_type: NodeType = field(metadata={"restrict": [NodeType.Operation]})
metadata={'restrict': [NodeType.Operation]}
)
index: Optional[int] = None index: Optional[int] = None
@dataclass @dataclass
class ParsedModelNode(ParsedNode): class ParsedModelNode(ParsedNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Model]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Model]})
# TODO: rm?
@dataclass
class ParsedRPCNode(ParsedNode):
resource_type: NodeType = field(metadata={"restrict": [NodeType.RPCCall]})
@dataclass @dataclass
class ParsedRPCNode(ParsedNode): class ParsedSqlNode(ParsedNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.RPCCall]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.SqlOperation]})
def same_seeds(first: ParsedNode, second: ParsedNode) -> bool: def same_seeds(first: ParsedNode, second: ParsedNode) -> bool:
@@ -353,31 +368,31 @@ def same_seeds(first: ParsedNode, second: ParsedNode) -> bool:
# if the current checksum is a path, we want to log a warning. # if the current checksum is a path, we want to log a warning.
result = first.checksum == second.checksum result = first.checksum == second.checksum
if first.checksum.name == 'path': if first.checksum.name == "path":
msg: str msg: str
if second.checksum.name != 'path': if second.checksum.name != "path":
msg = ( msg = (
f'Found a seed ({first.package_name}.{first.name}) ' f"Found a seed ({first.package_name}.{first.name}) "
f'>{MAXIMUM_SEED_SIZE_NAME} in size. The previous file was ' f">{MAXIMUM_SEED_SIZE_NAME} in size. The previous file was "
f'<={MAXIMUM_SEED_SIZE_NAME}, so it has changed' f"<={MAXIMUM_SEED_SIZE_NAME}, so it has changed"
) )
elif result: elif result:
msg = ( msg = (
f'Found a seed ({first.package_name}.{first.name}) ' f"Found a seed ({first.package_name}.{first.name}) "
f'>{MAXIMUM_SEED_SIZE_NAME} in size at the same path, dbt ' f">{MAXIMUM_SEED_SIZE_NAME} in size at the same path, dbt "
f'cannot tell if it has changed: assuming they are the same' f"cannot tell if it has changed: assuming they are the same"
) )
elif not result: elif not result:
msg = ( msg = (
f'Found a seed ({first.package_name}.{first.name}) ' f"Found a seed ({first.package_name}.{first.name}) "
f'>{MAXIMUM_SEED_SIZE_NAME} in size. The previous file was in ' f">{MAXIMUM_SEED_SIZE_NAME} in size. The previous file was in "
f'a different location, assuming it has changed' f"a different location, assuming it has changed"
) )
else: else:
msg = ( msg = (
f'Found a seed ({first.package_name}.{first.name}) ' f"Found a seed ({first.package_name}.{first.name}) "
f'>{MAXIMUM_SEED_SIZE_NAME} in size. The previous file had a ' f">{MAXIMUM_SEED_SIZE_NAME} in size. The previous file had a "
f'checksum type of {second.checksum.name}, so it has changed' f"checksum type of {second.checksum.name}, so it has changed"
) )
warn_or_error(msg, node=first) warn_or_error(msg, node=first)
@@ -387,12 +402,12 @@ def same_seeds(first: ParsedNode, second: ParsedNode) -> bool:
@dataclass @dataclass
class ParsedSeedNode(ParsedNode): class ParsedSeedNode(ParsedNode):
# keep this in sync with CompiledSeedNode! # keep this in sync with CompiledSeedNode!
resource_type: NodeType = field(metadata={'restrict': [NodeType.Seed]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Seed]})
config: SeedConfig = field(default_factory=SeedConfig) config: SeedConfig = field(default_factory=SeedConfig)
@property @property
def empty(self): def empty(self):
""" Seeds are never empty""" """Seeds are never empty"""
return False return False
def same_body(self: T, other: T) -> bool: def same_body(self: T, other: T) -> bool:
@@ -402,6 +417,9 @@ class ParsedSeedNode(ParsedNode):
@dataclass @dataclass
class TestMetadata(dbtClassMixin, Replaceable): class TestMetadata(dbtClassMixin, Replaceable):
name: str name: str
# kwargs are the args that are left in the test builder after
# removing configs. They are set from the test builder when
# the test node is created.
kwargs: Dict[str, Any] = field(default_factory=dict) kwargs: Dict[str, Any] = field(default_factory=dict)
namespace: Optional[str] = None namespace: Optional[str] = None
@@ -413,17 +431,22 @@ class HasTestMetadata(dbtClassMixin):
@dataclass @dataclass
class ParsedSingularTestNode(ParsedNode): class ParsedSingularTestNode(ParsedNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Test]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Test]})
# Was not able to make mypy happy and keep the code working. We need to # Was not able to make mypy happy and keep the code working. We need to
# refactor the various configs. # refactor the various configs.
config: TestConfig = field(default_factory=TestConfig) # type: ignore config: TestConfig = field(default_factory=TestConfig) # type: ignore
@property
def test_node_type(self):
return "singular"
@dataclass @dataclass
class ParsedGenericTestNode(ParsedNode, HasTestMetadata): class ParsedGenericTestNode(ParsedNode, HasTestMetadata):
# keep this in sync with CompiledGenericTestNode! # keep this in sync with CompiledGenericTestNode!
resource_type: NodeType = field(metadata={'restrict': [NodeType.Test]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Test]})
column_name: Optional[str] = None column_name: Optional[str] = None
file_key_name: Optional[str] = None
# Was not able to make mypy happy and keep the code working. We need to # Was not able to make mypy happy and keep the code working. We need to
# refactor the various configs. # refactor the various configs.
config: TestConfig = field(default_factory=TestConfig) # type: ignore config: TestConfig = field(default_factory=TestConfig) # type: ignore
@@ -432,11 +455,11 @@ class ParsedGenericTestNode(ParsedNode, HasTestMetadata):
if other is None: if other is None:
return False return False
return ( return self.same_config(other) and self.same_fqn(other) and True
self.same_config(other) and
self.same_fqn(other) and @property
True def test_node_type(self):
) return "generic"
@dataclass @dataclass
@@ -447,13 +470,13 @@ class IntermediateSnapshotNode(ParsedNode):
# defined in config blocks. To fix that, we have an intermediate type that # defined in config blocks. To fix that, we have an intermediate type that
# uses a regular node config, which the snapshot parser will then convert # uses a regular node config, which the snapshot parser will then convert
# into a full ParsedSnapshotNode after rendering. # into a full ParsedSnapshotNode after rendering.
resource_type: NodeType = field(metadata={'restrict': [NodeType.Snapshot]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Snapshot]})
config: EmptySnapshotConfig = field(default_factory=EmptySnapshotConfig) config: EmptySnapshotConfig = field(default_factory=EmptySnapshotConfig)
@dataclass @dataclass
class ParsedSnapshotNode(ParsedNode): class ParsedSnapshotNode(ParsedNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Snapshot]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Snapshot]})
config: SnapshotConfig config: SnapshotConfig
@@ -483,27 +506,27 @@ class ParsedMacroPatch(ParsedPatch):
class ParsedMacro(UnparsedBaseNode, HasUniqueID): class ParsedMacro(UnparsedBaseNode, HasUniqueID):
name: str name: str
macro_sql: str macro_sql: str
resource_type: NodeType = field(metadata={'restrict': [NodeType.Macro]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Macro]})
# TODO: can macros even have tags? # TODO: can macros even have tags?
tags: List[str] = field(default_factory=list) tags: List[str] = field(default_factory=list)
# TODO: is this ever populated? # TODO: is this ever populated?
depends_on: MacroDependsOn = field(default_factory=MacroDependsOn) depends_on: MacroDependsOn = field(default_factory=MacroDependsOn)
description: str = '' description: str = ""
meta: Dict[str, Any] = field(default_factory=dict) meta: Dict[str, Any] = field(default_factory=dict)
docs: Docs = field(default_factory=Docs) docs: Docs = field(default_factory=Docs)
patch_path: Optional[str] = None patch_path: Optional[str] = None
arguments: List[MacroArgument] = field(default_factory=list) arguments: List[MacroArgument] = field(default_factory=list)
created_at: int = field(default_factory=lambda: int(time.time())) created_at: float = field(default_factory=lambda: time.time())
def patch(self, patch: ParsedMacroPatch): def patch(self, patch: ParsedMacroPatch):
self.patch_path: Optional[str] = patch.file_id self.patch_path: Optional[str] = patch.file_id
self.description = patch.description self.description = patch.description
self.created_at = int(time.time()) self.created_at = time.time()
self.meta = patch.meta self.meta = patch.meta
self.docs = patch.docs self.docs = patch.docs
self.arguments = patch.arguments self.arguments = patch.arguments
def same_contents(self, other: Optional['ParsedMacro']) -> bool: def same_contents(self, other: Optional["ParsedMacro"]) -> bool:
if other is None: if other is None:
return False return False
# the only thing that makes one macro different from another with the # the only thing that makes one macro different from another with the
@@ -520,7 +543,7 @@ class ParsedDocumentation(UnparsedDocumentation, HasUniqueID):
def search_name(self): def search_name(self):
return self.name return self.name
def same_contents(self, other: Optional['ParsedDocumentation']) -> bool: def same_contents(self, other: Optional["ParsedDocumentation"]) -> bool:
if other is None: if other is None:
return False return False
# the only thing that makes one doc different from another with the # the only thing that makes one doc different from another with the
@@ -539,11 +562,11 @@ def normalize_test(testdef: TestDef) -> Dict[str, Any]:
class UnpatchedSourceDefinition(UnparsedBaseNode, HasUniqueID, HasFqn): class UnpatchedSourceDefinition(UnparsedBaseNode, HasUniqueID, HasFqn):
source: UnparsedSourceDefinition source: UnparsedSourceDefinition
table: UnparsedSourceTableDefinition table: UnparsedSourceTableDefinition
resource_type: NodeType = field(metadata={'restrict': [NodeType.Source]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Source]})
patch_path: Optional[Path] = None patch_path: Optional[Path] = None
def get_full_source_name(self): def get_full_source_name(self):
return f'{self.source.name}_{self.table.name}' return f"{self.source.name}_{self.table.name}"
def get_source_representation(self): def get_source_representation(self):
return f'source("{self.source.name}", "{self.table.name}")' return f'source("{self.source.name}", "{self.table.name}")'
@@ -568,9 +591,7 @@ class UnpatchedSourceDefinition(UnparsedBaseNode, HasUniqueID, HasFqn):
else: else:
return self.table.columns return self.table.columns
def get_tests( def get_tests(self) -> Iterator[Tuple[Dict[str, Any], Optional[UnparsedColumn]]]:
self
) -> Iterator[Tuple[Dict[str, Any], Optional[UnparsedColumn]]]:
for test in self.tests: for test in self.tests:
yield normalize_test(test), None yield normalize_test(test), None
@@ -588,24 +609,27 @@ class UnpatchedSourceDefinition(UnparsedBaseNode, HasUniqueID, HasFqn):
@dataclass @dataclass
class ParsedSourceDefinition( class ParsedSourceMandatory(
UnparsedBaseNode, UnparsedBaseNode,
HasUniqueID, HasUniqueID,
HasRelationMetadata, HasRelationMetadata,
HasFqn, HasFqn,
): ):
name: str name: str
source_name: str source_name: str
source_description: str source_description: str
loader: str loader: str
identifier: str identifier: str
resource_type: NodeType = field(metadata={'restrict': [NodeType.Source]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Source]})
@dataclass
class ParsedSourceDefinition(NodeInfoMixin, ParsedSourceMandatory):
quoting: Quoting = field(default_factory=Quoting) quoting: Quoting = field(default_factory=Quoting)
loaded_at_field: Optional[str] = None loaded_at_field: Optional[str] = None
freshness: Optional[FreshnessThreshold] = None freshness: Optional[FreshnessThreshold] = None
external: Optional[ExternalTable] = None external: Optional[ExternalTable] = None
description: str = '' description: str = ""
columns: Dict[str, ColumnInfo] = field(default_factory=dict) columns: Dict[str, ColumnInfo] = field(default_factory=dict)
meta: Dict[str, Any] = field(default_factory=dict) meta: Dict[str, Any] = field(default_factory=dict)
source_meta: Dict[str, Any] = field(default_factory=dict) source_meta: Dict[str, Any] = field(default_factory=dict)
@@ -614,38 +638,41 @@ class ParsedSourceDefinition(
patch_path: Optional[Path] = None patch_path: Optional[Path] = None
unrendered_config: Dict[str, Any] = field(default_factory=dict) unrendered_config: Dict[str, Any] = field(default_factory=dict)
relation_name: Optional[str] = None relation_name: Optional[str] = None
created_at: int = field(default_factory=lambda: int(time.time())) created_at: float = field(default_factory=lambda: time.time())
def same_database_representation( def __post_serialize__(self, dct):
self, other: 'ParsedSourceDefinition' if "_event_status" in dct:
) -> bool: del dct["_event_status"]
return dct
def same_database_representation(self, other: "ParsedSourceDefinition") -> bool:
return ( return (
self.database == other.database and self.database == other.database
self.schema == other.schema and and self.schema == other.schema
self.identifier == other.identifier and and self.identifier == other.identifier
True and True
) )
def same_quoting(self, other: 'ParsedSourceDefinition') -> bool: def same_quoting(self, other: "ParsedSourceDefinition") -> bool:
return self.quoting == other.quoting return self.quoting == other.quoting
def same_freshness(self, other: 'ParsedSourceDefinition') -> bool: def same_freshness(self, other: "ParsedSourceDefinition") -> bool:
return ( return (
self.freshness == other.freshness and self.freshness == other.freshness
self.loaded_at_field == other.loaded_at_field and and self.loaded_at_field == other.loaded_at_field
True and True
) )
def same_external(self, other: 'ParsedSourceDefinition') -> bool: def same_external(self, other: "ParsedSourceDefinition") -> bool:
return self.external == other.external return self.external == other.external
def same_config(self, old: 'ParsedSourceDefinition') -> bool: def same_config(self, old: "ParsedSourceDefinition") -> bool:
return self.config.same_contents( return self.config.same_contents(
self.unrendered_config, self.unrendered_config,
old.unrendered_config, old.unrendered_config,
) )
def same_contents(self, old: Optional['ParsedSourceDefinition']) -> bool: def same_contents(self, old: Optional["ParsedSourceDefinition"]) -> bool:
# existing when it didn't before is a change! # existing when it didn't before is a change!
if old is None: if old is None:
return True return True
@@ -659,17 +686,17 @@ class ParsedSourceDefinition(
# metadata/tags changes are not "changes" # metadata/tags changes are not "changes"
# patching/description changes are not "changes" # patching/description changes are not "changes"
return ( return (
self.same_database_representation(old) and self.same_database_representation(old)
self.same_fqn(old) and and self.same_fqn(old)
self.same_config(old) and and self.same_config(old)
self.same_quoting(old) and and self.same_quoting(old)
self.same_freshness(old) and and self.same_freshness(old)
self.same_external(old) and and self.same_external(old)
True and True
) )
def get_full_source_name(self): def get_full_source_name(self):
return f'{self.source_name}_{self.name}' return f"{self.source_name}_{self.name}"
def get_source_representation(self): def get_source_representation(self):
return f'source("{self.source.name}", "{self.table.name}")' return f'source("{self.source.name}", "{self.table.name}")'
@@ -708,7 +735,7 @@ class ParsedSourceDefinition(
@property @property
def search_name(self): def search_name(self):
return f'{self.source_name}.{self.name}' return f"{self.source_name}.{self.name}"
@dataclass @dataclass
@@ -717,7 +744,7 @@ class ParsedExposure(UnparsedBaseNode, HasUniqueID, HasFqn):
type: ExposureType type: ExposureType
owner: ExposureOwner owner: ExposureOwner
resource_type: NodeType = NodeType.Exposure resource_type: NodeType = NodeType.Exposure
description: str = '' description: str = ""
maturity: Optional[MaturityType] = None maturity: Optional[MaturityType] = None
meta: Dict[str, Any] = field(default_factory=dict) meta: Dict[str, Any] = field(default_factory=dict)
tags: List[str] = field(default_factory=list) tags: List[str] = field(default_factory=list)
@@ -725,7 +752,7 @@ class ParsedExposure(UnparsedBaseNode, HasUniqueID, HasFqn):
depends_on: DependsOn = field(default_factory=DependsOn) depends_on: DependsOn = field(default_factory=DependsOn)
refs: List[List[str]] = field(default_factory=list) refs: List[List[str]] = field(default_factory=list)
sources: List[List[str]] = field(default_factory=list) sources: List[List[str]] = field(default_factory=list)
created_at: int = field(default_factory=lambda: int(time.time())) created_at: float = field(default_factory=lambda: time.time())
@property @property
def depends_on_nodes(self): def depends_on_nodes(self):
@@ -735,39 +762,114 @@ class ParsedExposure(UnparsedBaseNode, HasUniqueID, HasFqn):
def search_name(self): def search_name(self):
return self.name return self.name
def same_depends_on(self, old: 'ParsedExposure') -> bool: def same_depends_on(self, old: "ParsedExposure") -> bool:
return set(self.depends_on.nodes) == set(old.depends_on.nodes) return set(self.depends_on.nodes) == set(old.depends_on.nodes)
def same_description(self, old: 'ParsedExposure') -> bool: def same_description(self, old: "ParsedExposure") -> bool:
return self.description == old.description return self.description == old.description
def same_maturity(self, old: 'ParsedExposure') -> bool: def same_maturity(self, old: "ParsedExposure") -> bool:
return self.maturity == old.maturity return self.maturity == old.maturity
def same_owner(self, old: 'ParsedExposure') -> bool: def same_owner(self, old: "ParsedExposure") -> bool:
return self.owner == old.owner return self.owner == old.owner
def same_exposure_type(self, old: 'ParsedExposure') -> bool: def same_exposure_type(self, old: "ParsedExposure") -> bool:
return self.type == old.type return self.type == old.type
def same_url(self, old: 'ParsedExposure') -> bool: def same_url(self, old: "ParsedExposure") -> bool:
return self.url == old.url return self.url == old.url
def same_contents(self, old: Optional['ParsedExposure']) -> bool: def same_contents(self, old: Optional["ParsedExposure"]) -> bool:
# existing when it didn't before is a change! # existing when it didn't before is a change!
# metadata/tags changes are not "changes" # metadata/tags changes are not "changes"
if old is None: if old is None:
return True return True
return ( return (
self.same_fqn(old) and self.same_fqn(old)
self.same_exposure_type(old) and and self.same_exposure_type(old)
self.same_owner(old) and and self.same_owner(old)
self.same_maturity(old) and and self.same_maturity(old)
self.same_url(old) and and self.same_url(old)
self.same_description(old) and and self.same_description(old)
self.same_depends_on(old) and and self.same_depends_on(old)
True and True
)
@dataclass
class ParsedMetric(UnparsedBaseNode, HasUniqueID, HasFqn):
model: str
name: str
description: str
label: str
type: str
sql: Optional[str]
timestamp: Optional[str]
filters: List[MetricFilter]
time_grains: List[str]
dimensions: List[str]
resource_type: NodeType = NodeType.Metric
meta: Dict[str, Any] = field(default_factory=dict)
tags: List[str] = field(default_factory=list)
sources: List[List[str]] = field(default_factory=list)
depends_on: DependsOn = field(default_factory=DependsOn)
refs: List[List[str]] = field(default_factory=list)
created_at: float = field(default_factory=lambda: time.time())
@property
def depends_on_nodes(self):
return self.depends_on.nodes
@property
def search_name(self):
return self.name
def same_model(self, old: "ParsedMetric") -> bool:
return self.model == old.model
def same_dimensions(self, old: "ParsedMetric") -> bool:
return self.dimensions == old.dimensions
def same_filters(self, old: "ParsedMetric") -> bool:
return self.filters == old.filters
def same_description(self, old: "ParsedMetric") -> bool:
return self.description == old.description
def same_label(self, old: "ParsedMetric") -> bool:
return self.label == old.label
def same_type(self, old: "ParsedMetric") -> bool:
return self.type == old.type
def same_sql(self, old: "ParsedMetric") -> bool:
return self.sql == old.sql
def same_timestamp(self, old: "ParsedMetric") -> bool:
return self.timestamp == old.timestamp
def same_time_grains(self, old: "ParsedMetric") -> bool:
return self.time_grains == old.time_grains
def same_contents(self, old: Optional["ParsedMetric"]) -> bool:
# existing when it didn't before is a change!
# metadata/tags changes are not "changes"
if old is None:
return True
return (
self.same_model(old)
and self.same_dimensions(old)
and self.same_filters(old)
and self.same_description(old)
and self.same_label(old)
and self.same_type(old)
and self.same_sql(old)
and self.same_timestamp(old)
and self.same_time_grains(old)
and True
) )
@@ -777,6 +879,7 @@ ManifestNodes = Union[
ParsedHookNode, ParsedHookNode,
ParsedModelNode, ParsedModelNode,
ParsedRPCNode, ParsedRPCNode,
ParsedSqlNode,
ParsedGenericTestNode, ParsedGenericTestNode,
ParsedSeedNode, ParsedSeedNode,
ParsedSnapshotNode, ParsedSnapshotNode,
@@ -788,5 +891,6 @@ ParsedResource = Union[
ParsedMacro, ParsedMacro,
ParsedNode, ParsedNode,
ParsedExposure, ParsedExposure,
ParsedMetric,
ParsedSourceDefinition, ParsedSourceDefinition,
] ]

View File

@@ -4,13 +4,12 @@ from dbt.contracts.util import (
Mergeable, Mergeable,
Replaceable, Replaceable,
) )
# trigger the PathEncoder # trigger the PathEncoder
import dbt.helper_types # noqa:F401 import dbt.helper_types # noqa:F401
from dbt.exceptions import CompilationException from dbt.exceptions import CompilationException
from dbt.dataclass_schema import ( from dbt.dataclass_schema import dbtClassMixin, StrEnum, ExtensibleDbtClassMixin
dbtClassMixin, StrEnum, ExtensibleDbtClassMixin
)
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import timedelta from datetime import timedelta
@@ -27,7 +26,7 @@ class UnparsedBaseNode(dbtClassMixin, Replaceable):
@property @property
def file_id(self): def file_id(self):
return f'{self.package_name}://{self.original_file_path}' return f"{self.package_name}://{self.original_file_path}"
@dataclass @dataclass
@@ -41,18 +40,20 @@ class HasSQL:
@dataclass @dataclass
class UnparsedMacro(UnparsedBaseNode, HasSQL): class UnparsedMacro(UnparsedBaseNode, HasSQL):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Macro]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Macro]})
@dataclass @dataclass
class UnparsedGenericTest(UnparsedBaseNode, HasSQL): class UnparsedGenericTest(UnparsedBaseNode, HasSQL):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Macro]}) resource_type: NodeType = field(metadata={"restrict": [NodeType.Macro]})
@dataclass @dataclass
class UnparsedNode(UnparsedBaseNode, HasSQL): class UnparsedNode(UnparsedBaseNode, HasSQL):
name: str name: str
resource_type: NodeType = field(metadata={'restrict': [ resource_type: NodeType = field(
metadata={
"restrict": [
NodeType.Model, NodeType.Model,
NodeType.Analysis, NodeType.Analysis,
NodeType.Test, NodeType.Test,
@@ -60,7 +61,10 @@ class UnparsedNode(UnparsedBaseNode, HasSQL):
NodeType.Operation, NodeType.Operation,
NodeType.Seed, NodeType.Seed,
NodeType.RPCCall, NodeType.RPCCall,
]}) NodeType.SqlOperation,
]
}
)
@property @property
def search_name(self): def search_name(self):
@@ -69,9 +73,7 @@ class UnparsedNode(UnparsedBaseNode, HasSQL):
@dataclass @dataclass
class UnparsedRunHook(UnparsedNode): class UnparsedRunHook(UnparsedNode):
resource_type: NodeType = field( resource_type: NodeType = field(metadata={"restrict": [NodeType.Operation]})
metadata={'restrict': [NodeType.Operation]}
)
index: Optional[int] = None index: Optional[int] = None
@@ -81,10 +83,9 @@ class Docs(dbtClassMixin, Replaceable):
@dataclass @dataclass
class HasDocs(AdditionalPropertiesMixin, ExtensibleDbtClassMixin, class HasDocs(AdditionalPropertiesMixin, ExtensibleDbtClassMixin, Replaceable):
Replaceable):
name: str name: str
description: str = '' description: str = ""
meta: Dict[str, Any] = field(default_factory=dict) meta: Dict[str, Any] = field(default_factory=dict)
data_type: Optional[str] = None data_type: Optional[str] = None
docs: Docs = field(default_factory=Docs) docs: Docs = field(default_factory=Docs)
@@ -127,11 +128,11 @@ class HasYamlMetadata(dbtClassMixin):
@property @property
def file_id(self): def file_id(self):
return f'{self.package_name}://{self.original_file_path}' return f"{self.package_name}://{self.original_file_path}"
@dataclass @dataclass
class HasConfig(): class HasConfig:
config: Dict[str, Any] = field(default_factory=dict) config: Dict[str, Any] = field(default_factory=dict)
@@ -149,7 +150,7 @@ class UnparsedNodeUpdate(HasConfig, HasColumnTests, HasTests, HasYamlMetadata):
class MacroArgument(dbtClassMixin): class MacroArgument(dbtClassMixin):
name: str name: str
type: Optional[str] = None type: Optional[str] = None
description: str = '' description: str = ""
@dataclass @dataclass
@@ -158,33 +159,39 @@ class UnparsedMacroUpdate(HasConfig, HasDocs, HasYamlMetadata):
class TimePeriod(StrEnum): class TimePeriod(StrEnum):
minute = 'minute' minute = "minute"
hour = 'hour' hour = "hour"
day = 'day' day = "day"
def plural(self) -> str: def plural(self) -> str:
return str(self) + 's' return str(self) + "s"
@dataclass @dataclass
class Time(dbtClassMixin, Replaceable): class Time(dbtClassMixin, Mergeable):
count: int count: Optional[int] = None
period: TimePeriod period: Optional[TimePeriod] = None
def exceeded(self, actual_age: float) -> bool: def exceeded(self, actual_age: float) -> bool:
kwargs = {self.period.plural(): self.count} if self.period is None or self.count is None:
return False
kwargs: Dict[str, int] = {self.period.plural(): self.count}
difference = timedelta(**kwargs).total_seconds() difference = timedelta(**kwargs).total_seconds()
return actual_age > difference return actual_age > difference
def __bool__(self):
return self.count is not None and self.period is not None
@dataclass @dataclass
class FreshnessThreshold(dbtClassMixin, Mergeable): class FreshnessThreshold(dbtClassMixin, Mergeable):
warn_after: Optional[Time] = None warn_after: Optional[Time] = field(default_factory=Time)
error_after: Optional[Time] = None error_after: Optional[Time] = field(default_factory=Time)
filter: Optional[str] = None filter: Optional[str] = None
def status(self, age: float) -> "dbt.contracts.results.FreshnessStatus": def status(self, age: float) -> "dbt.contracts.results.FreshnessStatus":
from dbt.contracts.results import FreshnessStatus from dbt.contracts.results import FreshnessStatus
if self.error_after and self.error_after.exceeded(age): if self.error_after and self.error_after.exceeded(age):
return FreshnessStatus.Error return FreshnessStatus.Error
elif self.warn_after and self.warn_after.exceeded(age): elif self.warn_after and self.warn_after.exceeded(age):
@@ -193,29 +200,24 @@ class FreshnessThreshold(dbtClassMixin, Mergeable):
return FreshnessStatus.Pass return FreshnessStatus.Pass
def __bool__(self): def __bool__(self):
return self.warn_after is not None or self.error_after is not None return bool(self.warn_after) or bool(self.error_after)
@dataclass @dataclass
class AdditionalPropertiesAllowed( class AdditionalPropertiesAllowed(AdditionalPropertiesMixin, ExtensibleDbtClassMixin):
AdditionalPropertiesMixin,
ExtensibleDbtClassMixin
):
_extra: Dict[str, Any] = field(default_factory=dict) _extra: Dict[str, Any] = field(default_factory=dict)
@dataclass @dataclass
class ExternalPartition(AdditionalPropertiesAllowed, Replaceable): class ExternalPartition(AdditionalPropertiesAllowed, Replaceable):
name: str = '' name: str = ""
description: str = '' description: str = ""
data_type: str = '' data_type: str = ""
meta: Dict[str, Any] = field(default_factory=dict) meta: Dict[str, Any] = field(default_factory=dict)
def __post_init__(self): def __post_init__(self):
if self.name == '' or self.data_type == '': if self.name == "" or self.data_type == "":
raise CompilationException( raise CompilationException("External partition columns must have names and data types")
'External partition columns must have names and data types'
)
@dataclass @dataclass
@@ -243,44 +245,40 @@ class UnparsedSourceTableDefinition(HasColumnTests, HasTests):
loaded_at_field: Optional[str] = None loaded_at_field: Optional[str] = None
identifier: Optional[str] = None identifier: Optional[str] = None
quoting: Quoting = field(default_factory=Quoting) quoting: Quoting = field(default_factory=Quoting)
freshness: Optional[FreshnessThreshold] = field( freshness: Optional[FreshnessThreshold] = field(default_factory=FreshnessThreshold)
default_factory=FreshnessThreshold
)
external: Optional[ExternalTable] = None external: Optional[ExternalTable] = None
tags: List[str] = field(default_factory=list) tags: List[str] = field(default_factory=list)
def __post_serialize__(self, dct): def __post_serialize__(self, dct):
dct = super().__post_serialize__(dct) dct = super().__post_serialize__(dct)
if 'freshness' not in dct and self.freshness is None: if "freshness" not in dct and self.freshness is None:
dct['freshness'] = None dct["freshness"] = None
return dct return dct
@dataclass @dataclass
class UnparsedSourceDefinition(dbtClassMixin, Replaceable): class UnparsedSourceDefinition(dbtClassMixin, Replaceable):
name: str name: str
description: str = '' description: str = ""
meta: Dict[str, Any] = field(default_factory=dict) meta: Dict[str, Any] = field(default_factory=dict)
database: Optional[str] = None database: Optional[str] = None
schema: Optional[str] = None schema: Optional[str] = None
loader: str = '' loader: str = ""
quoting: Quoting = field(default_factory=Quoting) quoting: Quoting = field(default_factory=Quoting)
freshness: Optional[FreshnessThreshold] = field( freshness: Optional[FreshnessThreshold] = field(default_factory=FreshnessThreshold)
default_factory=FreshnessThreshold
)
loaded_at_field: Optional[str] = None loaded_at_field: Optional[str] = None
tables: List[UnparsedSourceTableDefinition] = field(default_factory=list) tables: List[UnparsedSourceTableDefinition] = field(default_factory=list)
tags: List[str] = field(default_factory=list) tags: List[str] = field(default_factory=list)
config: Dict[str, Any] = field(default_factory=dict) config: Dict[str, Any] = field(default_factory=dict)
@property @property
def yaml_key(self) -> 'str': def yaml_key(self) -> "str":
return 'sources' return "sources"
def __post_serialize__(self, dct): def __post_serialize__(self, dct):
dct = super().__post_serialize__(dct) dct = super().__post_serialize__(dct)
if 'freshnewss' not in dct and self.freshness is None: if "freshness" not in dct and self.freshness is None:
dct['freshness'] = None dct["freshness"] = None
return dct return dct
@@ -294,9 +292,7 @@ class SourceTablePatch(dbtClassMixin):
loaded_at_field: Optional[str] = None loaded_at_field: Optional[str] = None
identifier: Optional[str] = None identifier: Optional[str] = None
quoting: Quoting = field(default_factory=Quoting) quoting: Quoting = field(default_factory=Quoting)
freshness: Optional[FreshnessThreshold] = field( freshness: Optional[FreshnessThreshold] = field(default_factory=FreshnessThreshold)
default_factory=FreshnessThreshold
)
external: Optional[ExternalTable] = None external: Optional[ExternalTable] = None
tags: Optional[List[str]] = None tags: Optional[List[str]] = None
tests: Optional[List[TestDef]] = None tests: Optional[List[TestDef]] = None
@@ -304,13 +300,13 @@ class SourceTablePatch(dbtClassMixin):
def to_patch_dict(self) -> Dict[str, Any]: def to_patch_dict(self) -> Dict[str, Any]:
dct = self.to_dict(omit_none=True) dct = self.to_dict(omit_none=True)
remove_keys = ('name') remove_keys = "name"
for key in remove_keys: for key in remove_keys:
if key in dct: if key in dct:
del dct[key] del dct[key]
if self.freshness is None: if self.freshness is None:
dct['freshness'] = None dct["freshness"] = None
return dct return dct
@@ -318,13 +314,13 @@ class SourceTablePatch(dbtClassMixin):
@dataclass @dataclass
class SourcePatch(dbtClassMixin, Replaceable): class SourcePatch(dbtClassMixin, Replaceable):
name: str = field( name: str = field(
metadata=dict(description='The name of the source to override'), metadata=dict(description="The name of the source to override"),
) )
overrides: str = field( overrides: str = field(
metadata=dict(description='The package of the source to override'), metadata=dict(description="The package of the source to override"),
) )
path: Path = field( path: Path = field(
metadata=dict(description='The path to the patch-defining yml file'), metadata=dict(description="The path to the patch-defining yml file"),
) )
description: Optional[str] = None description: Optional[str] = None
meta: Optional[Dict[str, Any]] = None meta: Optional[Dict[str, Any]] = None
@@ -332,22 +328,20 @@ class SourcePatch(dbtClassMixin, Replaceable):
schema: Optional[str] = None schema: Optional[str] = None
loader: Optional[str] = None loader: Optional[str] = None
quoting: Optional[Quoting] = None quoting: Optional[Quoting] = None
freshness: Optional[Optional[FreshnessThreshold]] = field( freshness: Optional[Optional[FreshnessThreshold]] = field(default_factory=FreshnessThreshold)
default_factory=FreshnessThreshold
)
loaded_at_field: Optional[str] = None loaded_at_field: Optional[str] = None
tables: Optional[List[SourceTablePatch]] = None tables: Optional[List[SourceTablePatch]] = None
tags: Optional[List[str]] = None tags: Optional[List[str]] = None
def to_patch_dict(self) -> Dict[str, Any]: def to_patch_dict(self) -> Dict[str, Any]:
dct = self.to_dict(omit_none=True) dct = self.to_dict(omit_none=True)
remove_keys = ('name', 'overrides', 'tables', 'path') remove_keys = ("name", "overrides", "tables", "path")
for key in remove_keys: for key in remove_keys:
if key in dct: if key in dct:
del dct[key] del dct[key]
if self.freshness is None: if self.freshness is None:
dct['freshness'] = None dct["freshness"] = None
return dct return dct
@@ -368,7 +362,7 @@ class UnparsedDocumentation(dbtClassMixin, Replaceable):
@property @property
def file_id(self): def file_id(self):
return f'{self.package_name}://{self.original_file_path}' return f"{self.package_name}://{self.original_file_path}"
@property @property
def resource_type(self): def resource_type(self):
@@ -383,9 +377,9 @@ class UnparsedDocumentationFile(UnparsedDocumentation):
# can't use total_ordering decorator here, as str provides an ordering already # can't use total_ordering decorator here, as str provides an ordering already
# and it's not the one we want. # and it's not the one we want.
class Maturity(StrEnum): class Maturity(StrEnum):
low = 'low' low = "low"
medium = 'medium' medium = "medium"
high = 'high' high = "high"
def __lt__(self, other): def __lt__(self, other):
if not isinstance(other, Maturity): if not isinstance(other, Maturity):
@@ -410,17 +404,17 @@ class Maturity(StrEnum):
class ExposureType(StrEnum): class ExposureType(StrEnum):
Dashboard = 'dashboard' Dashboard = "dashboard"
Notebook = 'notebook' Notebook = "notebook"
Analysis = 'analysis' Analysis = "analysis"
ML = 'ml' ML = "ml"
Application = 'application' Application = "application"
class MaturityType(StrEnum): class MaturityType(StrEnum):
Low = 'low' Low = "low"
Medium = 'medium' Medium = "medium"
High = 'high' High = "high"
@dataclass @dataclass
@@ -434,9 +428,33 @@ class UnparsedExposure(dbtClassMixin, Replaceable):
name: str name: str
type: ExposureType type: ExposureType
owner: ExposureOwner owner: ExposureOwner
description: str = '' description: str = ""
maturity: Optional[MaturityType] = None maturity: Optional[MaturityType] = None
meta: Dict[str, Any] = field(default_factory=dict) meta: Dict[str, Any] = field(default_factory=dict)
tags: List[str] = field(default_factory=list) tags: List[str] = field(default_factory=list)
url: Optional[str] = None url: Optional[str] = None
depends_on: List[str] = field(default_factory=list) depends_on: List[str] = field(default_factory=list)
@dataclass
class MetricFilter(dbtClassMixin, Replaceable):
field: str
operator: str
# TODO : Can we make this Any?
value: str
@dataclass
class UnparsedMetric(dbtClassMixin, Replaceable):
model: str
name: str
label: str
type: str
description: str = ""
sql: Optional[str] = None
timestamp: Optional[str] = None
time_grains: List[str] = field(default_factory=list)
dimensions: List[str] = field(default_factory=list)
filters: List[MetricFilter] = field(default_factory=list)
meta: Dict[str, Any] = field(default_factory=dict)
tags: List[str] = field(default_factory=list)

View File

@@ -1,26 +1,41 @@
from dbt.contracts.util import Replaceable, Mergeable, list_str from dbt.contracts.util import Replaceable, Mergeable, list_str
from dbt.contracts.connection import QueryComment, UserConfigContract from dbt.contracts.connection import QueryComment, UserConfigContract
from dbt.helper_types import NoValue from dbt.helper_types import NoValue
from dbt.logger import GLOBAL_LOGGER as logger # noqa
from dbt.dataclass_schema import ( from dbt.dataclass_schema import (
dbtClassMixin, ValidationError, dbtClassMixin,
ValidationError,
HyphenatedDbtClassMixin, HyphenatedDbtClassMixin,
ExtensibleDbtClassMixin, ExtensibleDbtClassMixin,
register_pattern, ValidatedStringMixin register_pattern,
ValidatedStringMixin,
) )
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Optional, List, Dict, Union, Any from typing import Optional, List, Dict, Union, Any
from mashumaro.types import SerializableType from mashumaro.types import SerializableType
PIN_PACKAGE_URL = 'https://docs.getdbt.com/docs/package-management#section-specifying-package-versions' # noqa PIN_PACKAGE_URL = (
"https://docs.getdbt.com/docs/package-management#section-specifying-package-versions" # noqa
)
DEFAULT_SEND_ANONYMOUS_USAGE_STATS = True DEFAULT_SEND_ANONYMOUS_USAGE_STATS = True
class Name(ValidatedStringMixin): class Name(ValidatedStringMixin):
ValidationRegex = r'^[^\d\W]\w*$' ValidationRegex = r"^[^\d\W]\w*$"
@classmethod
def is_valid(cls, value: Any) -> bool:
if not isinstance(value, str):
return False
try:
cls.validate(value)
except ValidationError:
return False
return True
register_pattern(Name, r'^[^\d\W]\w*$') register_pattern(Name, r"^[^\d\W]\w*$")
class SemverString(str, SerializableType): class SemverString(str, SerializableType):
@@ -28,16 +43,15 @@ class SemverString(str, SerializableType):
return self return self
@classmethod @classmethod
def _deserialize(cls, value: str) -> 'SemverString': def _deserialize(cls, value: str) -> "SemverString":
return SemverString(value) return SemverString(value)
# this does not support the full semver (does not allow a trailing -fooXYZ) and # this supports full semver,
# is not restrictive enough for full semver, (allows '1.0'). But it's like # but also allows for 2 group version numbers, (allows '1.0').
# 'semver lite'.
register_pattern( register_pattern(
SemverString, SemverString,
r'^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(\.(?:0|[1-9]\d*))?$', r"^(0|[1-9]\d*)\.(0|[1-9]\d*)(\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?)?$", # noqa
) )
@@ -105,8 +119,7 @@ class ProjectPackageMetadata:
@classmethod @classmethod
def from_project(cls, project): def from_project(cls, project):
return cls(name=project.project_name, return cls(name=project.project_name, packages=project.packages.packages)
packages=project.packages.packages)
@dataclass @dataclass
@@ -124,46 +137,46 @@ class RegistryPackageMetadata(
# A list of all the reserved words that packages may not have as names. # A list of all the reserved words that packages may not have as names.
BANNED_PROJECT_NAMES = { BANNED_PROJECT_NAMES = {
'_sql_results', "_sql_results",
'adapter', "adapter",
'api', "api",
'column', "column",
'config', "config",
'context', "context",
'database', "database",
'env', "env",
'env_var', "env_var",
'exceptions', "exceptions",
'execute', "execute",
'flags', "flags",
'fromjson', "fromjson",
'fromyaml', "fromyaml",
'graph', "graph",
'invocation_id', "invocation_id",
'load_agate_table', "load_agate_table",
'load_result', "load_result",
'log', "log",
'model', "model",
'modules', "modules",
'post_hooks', "post_hooks",
'pre_hooks', "pre_hooks",
'ref', "ref",
'render', "render",
'return', "return",
'run_started_at', "run_started_at",
'schema', "schema",
'source', "source",
'sql', "sql",
'sql_now', "sql_now",
'store_result', "store_result",
'store_raw_result', "store_raw_result",
'target', "target",
'this', "this",
'tojson', "tojson",
'toyaml', "toyaml",
'try_or_compiler_error', "try_or_compiler_error",
'var', "var",
'write', "write",
} }
@@ -202,7 +215,7 @@ class Project(HyphenatedDbtClassMixin, Replaceable):
vars: Optional[Dict[str, Any]] = field( vars: Optional[Dict[str, Any]] = field(
default=None, default=None,
metadata=dict( metadata=dict(
description='map project names to their vars override dicts', description="map project names to their vars override dicts",
), ),
) )
packages: List[PackageSpec] = field(default_factory=list) packages: List[PackageSpec] = field(default_factory=list)
@@ -211,16 +224,17 @@ class Project(HyphenatedDbtClassMixin, Replaceable):
@classmethod @classmethod
def validate(cls, data): def validate(cls, data):
super().validate(data) super().validate(data)
if data['name'] in BANNED_PROJECT_NAMES: if data["name"] in BANNED_PROJECT_NAMES:
raise ValidationError( raise ValidationError(f"Invalid project name: {data['name']} is a reserved word")
f"Invalid project name: {data['name']} is a reserved word"
)
# validate dispatch config # validate dispatch config
if 'dispatch' in data and data['dispatch']: if "dispatch" in data and data["dispatch"]:
entries = data['dispatch'] entries = data["dispatch"]
for entry in entries: for entry in entries:
if ('macro_namespace' not in entry or 'search_order' not in entry or if (
not isinstance(entry['search_order'], list)): "macro_namespace" not in entry
or "search_order" not in entry
or not isinstance(entry["search_order"], list)
):
raise ValidationError(f"Invalid project dispatch config: {entry}") raise ValidationError(f"Invalid project dispatch config: {entry}")
@@ -232,19 +246,20 @@ class UserConfig(ExtensibleDbtClassMixin, Replaceable, UserConfigContract):
printer_width: Optional[int] = None printer_width: Optional[int] = None
write_json: Optional[bool] = None write_json: Optional[bool] = None
warn_error: Optional[bool] = None warn_error: Optional[bool] = None
log_format: Optional[bool] = None log_format: Optional[str] = None
debug: Optional[bool] = None debug: Optional[bool] = None
version_check: Optional[bool] = None version_check: Optional[bool] = None
fail_fast: Optional[bool] = None fail_fast: Optional[bool] = None
use_experimental_parser: Optional[bool] = None use_experimental_parser: Optional[bool] = None
static_parser: Optional[bool] = None static_parser: Optional[bool] = None
indirect_selection: Optional[str] = None
@dataclass @dataclass
class ProfileConfig(HyphenatedDbtClassMixin, Replaceable): class ProfileConfig(HyphenatedDbtClassMixin, Replaceable):
profile_name: str = field(metadata={'preserve_underscore': True}) profile_name: str = field(metadata={"preserve_underscore": True})
target_name: str = field(metadata={'preserve_underscore': True}) target_name: str = field(metadata={"preserve_underscore": True})
user_config: UserConfig = field(metadata={'preserve_underscore': True}) user_config: UserConfig = field(metadata={"preserve_underscore": True})
threads: int threads: int
# TODO: make this a dynamic union of some kind? # TODO: make this a dynamic union of some kind?
credentials: Optional[Dict[str, Any]] credentials: Optional[Dict[str, Any]]
@@ -262,7 +277,7 @@ class ConfiguredQuoting(Quoting, Replaceable):
class Configuration(Project, ProfileConfig): class Configuration(Project, ProfileConfig):
cli_vars: Dict[str, Any] = field( cli_vars: Dict[str, Any] = field(
default_factory=dict, default_factory=dict,
metadata={'preserve_underscore': True}, metadata={"preserve_underscore": True},
) )
quoting: Optional[ConfiguredQuoting] = None quoting: Optional[ConfiguredQuoting] = None

View File

@@ -1,7 +1,8 @@
from collections.abc import Mapping from collections.abc import Mapping
from dataclasses import dataclass from dataclasses import dataclass
from typing import ( from typing import (
Optional, Dict, Optional,
Dict,
) )
from typing_extensions import Protocol from typing_extensions import Protocol
@@ -13,17 +14,17 @@ from dbt.utils import deep_merge
class RelationType(StrEnum): class RelationType(StrEnum):
Table = 'table' Table = "table"
View = 'view' View = "view"
CTE = 'cte' CTE = "cte"
MaterializedView = 'materializedview' MaterializedView = "materializedview"
External = 'external' External = "external"
class ComponentName(StrEnum): class ComponentName(StrEnum):
Database = 'database' Database = "database"
Schema = 'schema' Schema = "schema"
Identifier = 'identifier' Identifier = "identifier"
class HasQuoting(Protocol): class HasQuoting(Protocol):
@@ -68,8 +69,7 @@ class Policy(FakeAPIObject):
return self.identifier return self.identifier
else: else:
raise ValueError( raise ValueError(
'Got a key of {}, expected one of {}' "Got a key of {}, expected one of {}".format(key, list(ComponentName))
.format(key, list(ComponentName))
) )
def replace_dict(self, dct: Dict[ComponentName, bool]): def replace_dict(self, dct: Dict[ComponentName, bool]):
@@ -88,16 +88,12 @@ class Path(FakeAPIObject):
def __post_init__(self): def __post_init__(self):
# handle pesky jinja2.Undefined sneaking in here and messing up rende # handle pesky jinja2.Undefined sneaking in here and messing up rende
if not isinstance(self.database, (type(None), str)): if not isinstance(self.database, (type(None), str)):
raise CompilationException( raise CompilationException("Got an invalid path database: {}".format(self.database))
'Got an invalid path database: {}'.format(self.database)
)
if not isinstance(self.schema, (type(None), str)): if not isinstance(self.schema, (type(None), str)):
raise CompilationException( raise CompilationException("Got an invalid path schema: {}".format(self.schema))
'Got an invalid path schema: {}'.format(self.schema)
)
if not isinstance(self.identifier, (type(None), str)): if not isinstance(self.identifier, (type(None), str)):
raise CompilationException( raise CompilationException(
'Got an invalid path identifier: {}'.format(self.identifier) "Got an invalid path identifier: {}".format(self.identifier)
) )
def get_lowered_part(self, key: ComponentName) -> Optional[str]: def get_lowered_part(self, key: ComponentName) -> Optional[str]:
@@ -115,8 +111,7 @@ class Path(FakeAPIObject):
return self.identifier return self.identifier
else: else:
raise ValueError( raise ValueError(
'Got a key of {}, expected one of {}' "Got a key of {}, expected one of {}".format(key, list(ComponentName))
.format(key, list(ComponentName))
) )
def replace_dict(self, dct: Dict[ComponentName, str]): def replace_dict(self, dct: Dict[ComponentName, str]):

View File

@@ -1,7 +1,5 @@
from dbt.contracts.graph.manifest import CompileResultNode from dbt.contracts.graph.manifest import CompileResultNode
from dbt.contracts.graph.unparsed import ( from dbt.contracts.graph.unparsed import FreshnessThreshold
FreshnessThreshold
)
from dbt.contracts.graph.parsed import ParsedSourceDefinition from dbt.contracts.graph.parsed import ParsedSourceDefinition
from dbt.contracts.util import ( from dbt.contracts.util import (
BaseArtifactMetadata, BaseArtifactMetadata,
@@ -11,10 +9,11 @@ from dbt.contracts.util import (
schema_version, schema_version,
) )
from dbt.exceptions import InternalException from dbt.exceptions import InternalException
from dbt.events.functions import fire_event
from dbt.events.types import TimingInfoCollected
from dbt.logger import ( from dbt.logger import (
TimingProcessor, TimingProcessor,
JsonOnly, JsonOnly,
GLOBAL_LOGGER as logger,
) )
from dbt.utils import lowercase from dbt.utils import lowercase
from dbt.dataclass_schema import dbtClassMixin, StrEnum from dbt.dataclass_schema import dbtClassMixin, StrEnum
@@ -24,7 +23,13 @@ import agate
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import datetime from datetime import datetime
from typing import ( from typing import (
Union, Dict, List, Optional, Any, NamedTuple, Sequence, Union,
Dict,
List,
Optional,
Any,
NamedTuple,
Sequence,
) )
from dbt.clients.system import write_json from dbt.clients.system import write_json
@@ -54,7 +59,13 @@ class collect_timing_info:
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, traceback):
self.timing_info.end() self.timing_info.end()
with JsonOnly(), TimingProcessor(self.timing_info): with JsonOnly(), TimingProcessor(self.timing_info):
logger.debug('finished collecting timing info') fire_event(TimingInfoCollected())
class RunningStatus(StrEnum):
Started = "started"
Compiling = "compiling"
Executing = "executing"
class NodeStatus(StrEnum): class NodeStatus(StrEnum):
@@ -74,6 +85,7 @@ class RunStatus(StrEnum):
class TestStatus(StrEnum): class TestStatus(StrEnum):
__test__ = False
Pass = NodeStatus.Pass Pass = NodeStatus.Pass
Error = NodeStatus.Error Error = NodeStatus.Error
Fail = NodeStatus.Fail Fail = NodeStatus.Fail
@@ -101,10 +113,10 @@ class BaseResult(dbtClassMixin):
@classmethod @classmethod
def __pre_deserialize__(cls, data): def __pre_deserialize__(cls, data):
data = super().__pre_deserialize__(data) data = super().__pre_deserialize__(data)
if 'message' not in data: if "message" not in data:
data['message'] = None data["message"] = None
if 'failures' not in data: if "failures" not in data:
data['failures'] = None data["failures"] = None
return data return data
@@ -116,9 +128,7 @@ class NodeResult(BaseResult):
@dataclass @dataclass
class RunResult(NodeResult): class RunResult(NodeResult):
agate_table: Optional[agate.Table] = field( agate_table: Optional[agate.Table] = field(
default=None, metadata={ default=None, metadata={"serialize": lambda x: None, "deserialize": lambda x: None}
'serialize': lambda x: None, 'deserialize': lambda x: None
}
) )
@property @property
@@ -162,7 +172,7 @@ def process_run_result(result: RunResult) -> RunResultOutput:
execution_time=result.execution_time, execution_time=result.execution_time,
message=result.message, message=result.message,
adapter_response=result.adapter_response, adapter_response=result.adapter_response,
failures=result.failures failures=result.failures,
) )
@@ -185,7 +195,7 @@ class RunExecutionResult(
@dataclass @dataclass
@schema_version('run-results', 3) @schema_version("run-results", 4)
class RunResultsArtifact(ExecutionResult, ArtifactMixin): class RunResultsArtifact(ExecutionResult, ArtifactMixin):
results: Sequence[RunResultOutput] results: Sequence[RunResultOutput]
args: Dict[str, Any] = field(default_factory=dict) args: Dict[str, Any] = field(default_factory=dict)
@@ -203,12 +213,7 @@ class RunResultsArtifact(ExecutionResult, ArtifactMixin):
dbt_schema_version=str(cls.dbt_schema_version), dbt_schema_version=str(cls.dbt_schema_version),
generated_at=generated_at, generated_at=generated_at,
) )
return cls( return cls(metadata=meta, results=processed_results, elapsed_time=elapsed_time, args=args)
metadata=meta,
results=processed_results,
elapsed_time=elapsed_time,
args=args
)
def write(self, path: str): def write(self, path: str):
write_json(path, self.to_dict(omit_none=False)) write_json(path, self.to_dict(omit_none=False))
@@ -221,15 +226,14 @@ class RunOperationResult(ExecutionResult):
@dataclass @dataclass
class RunOperationResultMetadata(BaseArtifactMetadata): class RunOperationResultMetadata(BaseArtifactMetadata):
dbt_schema_version: str = field(default_factory=lambda: str( dbt_schema_version: str = field(
RunOperationResultsArtifact.dbt_schema_version default_factory=lambda: str(RunOperationResultsArtifact.dbt_schema_version)
)) )
@dataclass @dataclass
@schema_version('run-operation-result', 1) @schema_version("run-operation-result", 1)
class RunOperationResultsArtifact(RunOperationResult, ArtifactMixin): class RunOperationResultsArtifact(RunOperationResult, ArtifactMixin):
@classmethod @classmethod
def from_success( def from_success(
cls, cls,
@@ -248,6 +252,7 @@ class RunOperationResultsArtifact(RunOperationResult, ArtifactMixin):
success=success, success=success,
) )
# due to issues with typing.Union collapsing subclasses, this can't subclass # due to issues with typing.Union collapsing subclasses, this can't subclass
# PartialResult # PartialResult
@@ -266,7 +271,7 @@ class SourceFreshnessResult(NodeResult):
class FreshnessErrorEnum(StrEnum): class FreshnessErrorEnum(StrEnum):
runtime_error = 'runtime error' runtime_error = "runtime error"
@dataclass @dataclass
@@ -299,14 +304,11 @@ class PartialSourceFreshnessResult(NodeResult):
return False return False
FreshnessNodeResult = Union[PartialSourceFreshnessResult, FreshnessNodeResult = Union[PartialSourceFreshnessResult, SourceFreshnessResult]
SourceFreshnessResult]
FreshnessNodeOutput = Union[SourceFreshnessRuntimeError, SourceFreshnessOutput] FreshnessNodeOutput = Union[SourceFreshnessRuntimeError, SourceFreshnessOutput]
def process_freshness_result( def process_freshness_result(result: FreshnessNodeResult) -> FreshnessNodeOutput:
result: FreshnessNodeResult
) -> FreshnessNodeOutput:
unique_id = result.node.unique_id unique_id = result.node.unique_id
if result.status == FreshnessStatus.RuntimeErr: if result.status == FreshnessStatus.RuntimeErr:
return SourceFreshnessRuntimeError( return SourceFreshnessRuntimeError(
@@ -318,16 +320,14 @@ def process_freshness_result(
# we know that this must be a SourceFreshnessResult # we know that this must be a SourceFreshnessResult
if not isinstance(result, SourceFreshnessResult): if not isinstance(result, SourceFreshnessResult):
raise InternalException( raise InternalException(
'Got {} instead of a SourceFreshnessResult for a ' "Got {} instead of a SourceFreshnessResult for a "
'non-error result in freshness execution!' "non-error result in freshness execution!".format(type(result))
.format(type(result))
) )
# if we're here, we must have a non-None freshness threshold # if we're here, we must have a non-None freshness threshold
criteria = result.node.freshness criteria = result.node.freshness
if criteria is None: if criteria is None:
raise InternalException( raise InternalException(
'Somehow evaluated a freshness result for a source ' "Somehow evaluated a freshness result for a source " "that has no freshness criteria!"
'that has no freshness criteria!'
) )
return SourceFreshnessOutput( return SourceFreshnessOutput(
unique_id=unique_id, unique_id=unique_id,
@@ -346,9 +346,7 @@ def process_freshness_result(
@dataclass @dataclass
class FreshnessMetadata(BaseArtifactMetadata): class FreshnessMetadata(BaseArtifactMetadata):
dbt_schema_version: str = field( dbt_schema_version: str = field(
default_factory=lambda: str( default_factory=lambda: str(FreshnessExecutionResultArtifact.dbt_schema_version)
FreshnessExecutionResultArtifact.dbt_schema_version
)
) )
@@ -369,7 +367,7 @@ class FreshnessResult(ExecutionResult):
@dataclass @dataclass
@schema_version('sources', 2) @schema_version("sources", 3)
class FreshnessExecutionResultArtifact( class FreshnessExecutionResultArtifact(
ArtifactMixin, ArtifactMixin,
VersionedSchema, VersionedSchema,
@@ -392,8 +390,7 @@ Primitive = Union[bool, str, float, None]
PrimitiveDict = Dict[str, Primitive] PrimitiveDict = Dict[str, Primitive]
CatalogKey = NamedTuple( CatalogKey = NamedTuple(
'CatalogKey', "CatalogKey", [("database", Optional[str]), ("schema", str), ("name", str)]
[('database', Optional[str]), ('schema', str), ('name', str)]
) )
@@ -462,13 +459,13 @@ class CatalogResults(dbtClassMixin):
def __post_serialize__(self, dct): def __post_serialize__(self, dct):
dct = super().__post_serialize__(dct) dct = super().__post_serialize__(dct)
if '_compile_results' in dct: if "_compile_results" in dct:
del dct['_compile_results'] del dct["_compile_results"]
return dct return dct
@dataclass @dataclass
@schema_version('catalog', 1) @schema_version("catalog", 1)
class CatalogArtifact(CatalogResults, ArtifactMixin): class CatalogArtifact(CatalogResults, ArtifactMixin):
metadata: CatalogMetadata metadata: CatalogMetadata
@@ -479,8 +476,8 @@ class CatalogArtifact(CatalogResults, ArtifactMixin):
nodes: Dict[str, CatalogTable], nodes: Dict[str, CatalogTable],
sources: Dict[str, CatalogTable], sources: Dict[str, CatalogTable],
compile_results: Optional[Any], compile_results: Optional[Any],
errors: Optional[List[str]] errors: Optional[List[str]],
) -> 'CatalogArtifact': ) -> "CatalogArtifact":
meta = CatalogMetadata(generated_at=generated_at) meta = CatalogMetadata(generated_at=generated_at)
return cls( return cls(
metadata=meta, metadata=meta,

View File

@@ -1,819 +0,0 @@
import enum
import os
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Optional, Union, List, Any, Dict, Type, Sequence
from dbt.dataclass_schema import dbtClassMixin, StrEnum
from dbt.contracts.graph.compiled import CompileResultNode
from dbt.contracts.graph.manifest import WritableManifest
from dbt.contracts.results import (
RunResult, RunResultsArtifact, TimingInfo,
CatalogArtifact,
CatalogResults,
ExecutionResult,
FreshnessExecutionResultArtifact,
FreshnessResult,
RunOperationResult,
RunOperationResultsArtifact,
RunExecutionResult,
)
from dbt.contracts.util import VersionedSchema, schema_version
from dbt.exceptions import InternalException
from dbt.logger import LogMessage
from dbt.utils import restrict_to
TaskTags = Optional[Dict[str, Any]]
TaskID = uuid.UUID
# Inputs
@dataclass
class RPCParameters(dbtClassMixin):
task_tags: TaskTags
timeout: Optional[float]
@classmethod
def __pre_deserialize__(cls, data, omit_none=True):
data = super().__pre_deserialize__(data)
if 'timeout' not in data:
data['timeout'] = None
if 'task_tags' not in data:
data['task_tags'] = None
return data
@dataclass
class RPCExecParameters(RPCParameters):
name: str
sql: str
macros: Optional[str] = None
@dataclass
class RPCCompileParameters(RPCParameters):
threads: Optional[int] = None
models: Union[None, str, List[str]] = None
select: Union[None, str, List[str]] = None
exclude: Union[None, str, List[str]] = None
selector: Optional[str] = None
state: Optional[str] = None
@dataclass
class RPCListParameters(RPCParameters):
resource_types: Optional[List[str]] = None
models: Union[None, str, List[str]] = None
exclude: Union[None, str, List[str]] = None
select: Union[None, str, List[str]] = None
selector: Optional[str] = None
output: Optional[str] = 'json'
output_keys: Optional[List[str]] = None
@dataclass
class RPCRunParameters(RPCParameters):
threads: Optional[int] = None
models: Union[None, str, List[str]] = None
select: Union[None, str, List[str]] = None
exclude: Union[None, str, List[str]] = None
selector: Optional[str] = None
state: Optional[str] = None
defer: Optional[bool] = None
@dataclass
class RPCSnapshotParameters(RPCParameters):
threads: Optional[int] = None
select: Union[None, str, List[str]] = None
exclude: Union[None, str, List[str]] = None
selector: Optional[str] = None
state: Optional[str] = None
@dataclass
class RPCTestParameters(RPCCompileParameters):
data: bool = False
schema: bool = False
state: Optional[str] = None
defer: Optional[bool] = None
@dataclass
class RPCSeedParameters(RPCParameters):
threads: Optional[int] = None
select: Union[None, str, List[str]] = None
exclude: Union[None, str, List[str]] = None
selector: Optional[str] = None
show: bool = False
state: Optional[str] = None
@dataclass
class RPCDocsGenerateParameters(RPCParameters):
compile: bool = True
state: Optional[str] = None
@dataclass
class RPCBuildParameters(RPCParameters):
resource_types: Optional[List[str]] = None
select: Union[None, str, List[str]] = None
threads: Optional[int] = None
exclude: Union[None, str, List[str]] = None
selector: Optional[str] = None
state: Optional[str] = None
defer: Optional[bool] = None
@dataclass
class RPCCliParameters(RPCParameters):
cli: str
@dataclass
class RPCDepsParameters(RPCParameters):
pass
@dataclass
class KillParameters(RPCParameters):
task_id: TaskID
@dataclass
class PollParameters(RPCParameters):
request_token: TaskID
logs: bool = True
logs_start: int = 0
@dataclass
class PSParameters(RPCParameters):
active: bool = True
completed: bool = False
@dataclass
class StatusParameters(RPCParameters):
pass
@dataclass
class GCSettings(dbtClassMixin):
# start evicting the longest-ago-ended tasks here
maxsize: int
# start evicting all tasks before now - auto_reap_age when we have this
# many tasks in the table
reapsize: int
# a positive timedelta indicating how far back we should go
auto_reap_age: timedelta
@dataclass
class GCParameters(RPCParameters):
"""The gc endpoint takes three arguments, any of which may be present:
- task_ids: An optional list of task ID UUIDs to try to GC
- before: If provided, should be a datetime string. All tasks that finished
before that datetime will be GCed
- settings: If provided, should be a GCSettings object in JSON form. It
will be applied to the task manager before GC starts. By default the
existing gc settings remain.
"""
task_ids: Optional[List[TaskID]] = None
before: Optional[datetime] = None
settings: Optional[GCSettings] = None
@dataclass
class RPCRunOperationParameters(RPCParameters):
macro: str
args: Dict[str, Any] = field(default_factory=dict)
@dataclass
class RPCSourceFreshnessParameters(RPCParameters):
threads: Optional[int] = None
select: Union[None, str, List[str]] = None
exclude: Union[None, str, List[str]] = None
selector: Optional[str] = None
@dataclass
class GetManifestParameters(RPCParameters):
pass
# Outputs
@dataclass
class RemoteResult(VersionedSchema):
logs: List[LogMessage]
@dataclass
@schema_version('remote-list-results', 1)
class RemoteListResults(RemoteResult):
output: List[Any]
generated_at: datetime = field(default_factory=datetime.utcnow)
@dataclass
@schema_version('remote-deps-result', 1)
class RemoteDepsResult(RemoteResult):
generated_at: datetime = field(default_factory=datetime.utcnow)
@dataclass
@schema_version('remote-catalog-result', 1)
class RemoteCatalogResults(CatalogResults, RemoteResult):
generated_at: datetime = field(default_factory=datetime.utcnow)
def write(self, path: str):
artifact = CatalogArtifact.from_results(
generated_at=self.generated_at,
nodes=self.nodes,
sources=self.sources,
compile_results=self._compile_results,
errors=self.errors,
)
artifact.write(path)
@dataclass
class RemoteCompileResultMixin(RemoteResult):
raw_sql: str
compiled_sql: str
node: CompileResultNode
timing: List[TimingInfo]
@dataclass
@schema_version('remote-compile-result', 1)
class RemoteCompileResult(RemoteCompileResultMixin):
generated_at: datetime = field(default_factory=datetime.utcnow)
@property
def error(self):
return None
@dataclass
@schema_version('remote-execution-result', 1)
class RemoteExecutionResult(ExecutionResult, RemoteResult):
results: Sequence[RunResult]
args: Dict[str, Any] = field(default_factory=dict)
generated_at: datetime = field(default_factory=datetime.utcnow)
def write(self, path: str):
writable = RunResultsArtifact.from_execution_results(
generated_at=self.generated_at,
results=self.results,
elapsed_time=self.elapsed_time,
args=self.args,
)
writable.write(path)
@classmethod
def from_local_result(
cls,
base: RunExecutionResult,
logs: List[LogMessage],
) -> 'RemoteExecutionResult':
return cls(
generated_at=base.generated_at,
results=base.results,
elapsed_time=base.elapsed_time,
args=base.args,
logs=logs,
)
@dataclass
class ResultTable(dbtClassMixin):
column_names: List[str]
rows: List[Any]
@dataclass
@schema_version('remote-run-operation-result', 1)
class RemoteRunOperationResult(RunOperationResult, RemoteResult):
generated_at: datetime = field(default_factory=datetime.utcnow)
@classmethod
def from_local_result(
cls,
base: RunOperationResultsArtifact,
logs: List[LogMessage],
) -> 'RemoteRunOperationResult':
return cls(
generated_at=base.metadata.generated_at,
results=base.results,
elapsed_time=base.elapsed_time,
success=base.success,
logs=logs,
)
def write(self, path: str):
writable = RunOperationResultsArtifact.from_success(
success=self.success,
generated_at=self.generated_at,
elapsed_time=self.elapsed_time,
)
writable.write(path)
@dataclass
@schema_version('remote-freshness-result', 1)
class RemoteFreshnessResult(FreshnessResult, RemoteResult):
@classmethod
def from_local_result(
cls,
base: FreshnessResult,
logs: List[LogMessage],
) -> 'RemoteFreshnessResult':
return cls(
metadata=base.metadata,
results=base.results,
elapsed_time=base.elapsed_time,
logs=logs,
)
def write(self, path: str):
writable = FreshnessExecutionResultArtifact.from_result(base=self)
writable.write(path)
@dataclass
@schema_version('remote-run-result', 1)
class RemoteRunResult(RemoteCompileResultMixin):
table: ResultTable
generated_at: datetime = field(default_factory=datetime.utcnow)
RPCResult = Union[
RemoteCompileResult,
RemoteExecutionResult,
RemoteFreshnessResult,
RemoteCatalogResults,
RemoteDepsResult,
RemoteRunOperationResult,
]
# GC types
class GCResultState(StrEnum):
Deleted = 'deleted' # successful GC
Missing = 'missing' # nothing to GC
Running = 'running' # can't GC
@dataclass
@schema_version('remote-gc-result', 1)
class GCResult(RemoteResult):
logs: List[LogMessage] = field(default_factory=list)
deleted: List[TaskID] = field(default_factory=list)
missing: List[TaskID] = field(default_factory=list)
running: List[TaskID] = field(default_factory=list)
def add_result(self, task_id: TaskID, state: GCResultState):
if state == GCResultState.Missing:
self.missing.append(task_id)
elif state == GCResultState.Running:
self.running.append(task_id)
elif state == GCResultState.Deleted:
self.deleted.append(task_id)
else:
raise InternalException(
f'Got invalid state in add_result: {state}'
)
# Task management types
class TaskHandlerState(StrEnum):
NotStarted = 'not started'
Initializing = 'initializing'
Running = 'running'
Success = 'success'
Error = 'error'
Killed = 'killed'
Failed = 'failed'
def __lt__(self, other) -> bool:
"""A logical ordering for TaskHandlerState:
NotStarted < Initializing < Running < (Success, Error, Killed, Failed)
"""
if not isinstance(other, TaskHandlerState):
raise TypeError('cannot compare to non-TaskHandlerState')
order = (self.NotStarted, self.Initializing, self.Running)
smaller = set()
for value in order:
smaller.add(value)
if self == value:
return other not in smaller
return False
def __le__(self, other) -> bool:
# so that ((Success <= Error) is True)
return ((self < other) or
(self == other) or
(self.finished and other.finished))
def __gt__(self, other) -> bool:
if not isinstance(other, TaskHandlerState):
raise TypeError('cannot compare to non-TaskHandlerState')
order = (self.NotStarted, self.Initializing, self.Running)
smaller = set()
for value in order:
smaller.add(value)
if self == value:
return other in smaller
return other in smaller
def __ge__(self, other) -> bool:
# so that ((Success <= Error) is True)
return ((self > other) or
(self == other) or
(self.finished and other.finished))
@property
def finished(self) -> bool:
return self in (self.Error, self.Success, self.Killed, self.Failed)
@dataclass
class TaskTiming(dbtClassMixin):
state: TaskHandlerState
start: Optional[datetime]
end: Optional[datetime]
elapsed: Optional[float]
# These ought to be defaults but superclass order doesn't
# allow that to work
@classmethod
def __pre_deserialize__(cls, data):
data = super().__pre_deserialize__(data)
for field_name in ('start', 'end', 'elapsed'):
if field_name not in data:
data[field_name] = None
return data
@dataclass
class TaskRow(TaskTiming):
task_id: TaskID
request_source: str
method: str
request_id: Union[str, int]
tags: TaskTags = None
timeout: Optional[float] = None
@dataclass
@schema_version('remote-ps-result', 1)
class PSResult(RemoteResult):
rows: List[TaskRow]
class KillResultStatus(StrEnum):
Missing = 'missing'
NotStarted = 'not_started'
Killed = 'killed'
Finished = 'finished'
@dataclass
@schema_version('remote-kill-result', 1)
class KillResult(RemoteResult):
state: KillResultStatus = KillResultStatus.Missing
logs: List[LogMessage] = field(default_factory=list)
@dataclass
@schema_version('remote-manifest-result', 1)
class GetManifestResult(RemoteResult):
manifest: Optional[WritableManifest] = None
# this is kind of carefuly structured: BlocksManifestTasks is implied by
# RequiresConfigReloadBefore and RequiresManifestReloadAfter
class RemoteMethodFlags(enum.Flag):
Empty = 0
BlocksManifestTasks = 1
RequiresConfigReloadBefore = 3
RequiresManifestReloadAfter = 5
Builtin = 8
# Polling types
@dataclass
class PollResult(RemoteResult, TaskTiming):
state: TaskHandlerState
tags: TaskTags
start: Optional[datetime]
end: Optional[datetime]
elapsed: Optional[float]
# These ought to be defaults but superclass order doesn't
# allow that to work
@classmethod
def __pre_deserialize__(cls, data):
data = super().__pre_deserialize__(data)
for field_name in ('start', 'end', 'elapsed'):
if field_name not in data:
data[field_name] = None
return data
@dataclass
@schema_version('poll-remote-deps-result', 1)
class PollRemoteEmptyCompleteResult(PollResult, RemoteResult):
state: TaskHandlerState = field(
metadata=restrict_to(TaskHandlerState.Success,
TaskHandlerState.Failed),
)
generated_at: datetime = field(default_factory=datetime.utcnow)
@classmethod
def from_result(
cls: Type['PollRemoteEmptyCompleteResult'],
base: RemoteDepsResult,
tags: TaskTags,
timing: TaskTiming,
logs: List[LogMessage],
) -> 'PollRemoteEmptyCompleteResult':
return cls(
logs=logs,
tags=tags,
state=timing.state,
start=timing.start,
end=timing.end,
elapsed=timing.elapsed,
generated_at=base.generated_at
)
@dataclass
@schema_version('poll-remote-killed-result', 1)
class PollKilledResult(PollResult):
state: TaskHandlerState = field(
metadata=restrict_to(TaskHandlerState.Killed),
)
@dataclass
@schema_version('poll-remote-execution-result', 1)
class PollExecuteCompleteResult(
RemoteExecutionResult,
PollResult,
):
state: TaskHandlerState = field(
metadata=restrict_to(TaskHandlerState.Success,
TaskHandlerState.Failed),
)
@classmethod
def from_result(
cls: Type['PollExecuteCompleteResult'],
base: RemoteExecutionResult,
tags: TaskTags,
timing: TaskTiming,
logs: List[LogMessage],
) -> 'PollExecuteCompleteResult':
return cls(
results=base.results,
elapsed_time=base.elapsed_time,
logs=logs,
tags=tags,
state=timing.state,
start=timing.start,
end=timing.end,
elapsed=timing.elapsed,
generated_at=base.generated_at,
)
@dataclass
@schema_version('poll-remote-compile-result', 1)
class PollCompileCompleteResult(
RemoteCompileResult,
PollResult,
):
state: TaskHandlerState = field(
metadata=restrict_to(TaskHandlerState.Success,
TaskHandlerState.Failed),
)
@classmethod
def from_result(
cls: Type['PollCompileCompleteResult'],
base: RemoteCompileResult,
tags: TaskTags,
timing: TaskTiming,
logs: List[LogMessage],
) -> 'PollCompileCompleteResult':
return cls(
raw_sql=base.raw_sql,
compiled_sql=base.compiled_sql,
node=base.node,
timing=base.timing,
logs=logs,
tags=tags,
state=timing.state,
start=timing.start,
end=timing.end,
elapsed=timing.elapsed,
generated_at=base.generated_at
)
@dataclass
@schema_version('poll-remote-run-result', 1)
class PollRunCompleteResult(
RemoteRunResult,
PollResult,
):
state: TaskHandlerState = field(
metadata=restrict_to(TaskHandlerState.Success,
TaskHandlerState.Failed),
)
@classmethod
def from_result(
cls: Type['PollRunCompleteResult'],
base: RemoteRunResult,
tags: TaskTags,
timing: TaskTiming,
logs: List[LogMessage],
) -> 'PollRunCompleteResult':
return cls(
raw_sql=base.raw_sql,
compiled_sql=base.compiled_sql,
node=base.node,
timing=base.timing,
logs=logs,
table=base.table,
tags=tags,
state=timing.state,
start=timing.start,
end=timing.end,
elapsed=timing.elapsed,
generated_at=base.generated_at
)
@dataclass
@schema_version('poll-remote-run-operation-result', 1)
class PollRunOperationCompleteResult(
RemoteRunOperationResult,
PollResult,
):
state: TaskHandlerState = field(
metadata=restrict_to(TaskHandlerState.Success,
TaskHandlerState.Failed),
)
@classmethod
def from_result(
cls: Type['PollRunOperationCompleteResult'],
base: RemoteRunOperationResult,
tags: TaskTags,
timing: TaskTiming,
logs: List[LogMessage],
) -> 'PollRunOperationCompleteResult':
return cls(
success=base.success,
results=base.results,
generated_at=base.generated_at,
elapsed_time=base.elapsed_time,
logs=logs,
tags=tags,
state=timing.state,
start=timing.start,
end=timing.end,
elapsed=timing.elapsed,
)
@dataclass
@schema_version('poll-remote-catalog-result', 1)
class PollCatalogCompleteResult(RemoteCatalogResults, PollResult):
state: TaskHandlerState = field(
metadata=restrict_to(TaskHandlerState.Success,
TaskHandlerState.Failed),
)
@classmethod
def from_result(
cls: Type['PollCatalogCompleteResult'],
base: RemoteCatalogResults,
tags: TaskTags,
timing: TaskTiming,
logs: List[LogMessage],
) -> 'PollCatalogCompleteResult':
return cls(
nodes=base.nodes,
sources=base.sources,
generated_at=base.generated_at,
errors=base.errors,
_compile_results=base._compile_results,
logs=logs,
tags=tags,
state=timing.state,
start=timing.start,
end=timing.end,
elapsed=timing.elapsed,
)
@dataclass
@schema_version('poll-remote-in-progress-result', 1)
class PollInProgressResult(PollResult):
pass
@dataclass
@schema_version('poll-remote-get-manifest-result', 1)
class PollGetManifestResult(GetManifestResult, PollResult):
state: TaskHandlerState = field(
metadata=restrict_to(TaskHandlerState.Success,
TaskHandlerState.Failed),
)
@classmethod
def from_result(
cls: Type['PollGetManifestResult'],
base: GetManifestResult,
tags: TaskTags,
timing: TaskTiming,
logs: List[LogMessage],
) -> 'PollGetManifestResult':
return cls(
manifest=base.manifest,
logs=logs,
tags=tags,
state=timing.state,
start=timing.start,
end=timing.end,
elapsed=timing.elapsed,
)
@dataclass
@schema_version('poll-remote-freshness-result', 1)
class PollFreshnessResult(RemoteFreshnessResult, PollResult):
state: TaskHandlerState = field(
metadata=restrict_to(TaskHandlerState.Success,
TaskHandlerState.Failed),
)
@classmethod
def from_result(
cls: Type['PollFreshnessResult'],
base: RemoteFreshnessResult,
tags: TaskTags,
timing: TaskTiming,
logs: List[LogMessage],
) -> 'PollFreshnessResult':
return cls(
logs=logs,
tags=tags,
state=timing.state,
start=timing.start,
end=timing.end,
elapsed=timing.elapsed,
metadata=base.metadata,
results=base.results,
elapsed_time=base.elapsed_time,
)
# Manifest parsing types
class ManifestStatus(StrEnum):
Init = 'init'
Compiling = 'compiling'
Ready = 'ready'
Error = 'error'
@dataclass
@schema_version('remote-status-result', 1)
class LastParse(RemoteResult):
state: ManifestStatus = ManifestStatus.Init
logs: List[LogMessage] = field(default_factory=list)
error: Optional[Dict[str, Any]] = None
timestamp: datetime = field(default_factory=datetime.utcnow)
pid: int = field(default_factory=os.getpid)

View File

@@ -8,7 +8,7 @@ from typing import List, Dict, Any, Union
class SelectorDefinition(dbtClassMixin): class SelectorDefinition(dbtClassMixin):
name: str name: str
definition: Union[str, Dict[str, Any]] definition: Union[str, Dict[str, Any]]
description: str = '' description: str = ""
default: bool = False default: bool = False

90
core/dbt/contracts/sql.py Normal file
View File

@@ -0,0 +1,90 @@
import uuid
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional, List, Any, Dict, Sequence
from dbt.dataclass_schema import dbtClassMixin
from dbt.contracts.graph.compiled import CompileResultNode
from dbt.contracts.results import (
RunResult,
RunResultsArtifact,
TimingInfo,
ExecutionResult,
RunExecutionResult,
)
from dbt.contracts.util import VersionedSchema, schema_version
from dbt.logger import LogMessage
TaskTags = Optional[Dict[str, Any]]
TaskID = uuid.UUID
# Outputs
@dataclass
class RemoteResult(VersionedSchema):
logs: List[LogMessage]
@dataclass
class RemoteCompileResultMixin(RemoteResult):
raw_sql: str
compiled_sql: str
node: CompileResultNode
timing: List[TimingInfo]
@dataclass
@schema_version("remote-compile-result", 1)
class RemoteCompileResult(RemoteCompileResultMixin):
generated_at: datetime = field(default_factory=datetime.utcnow)
@property
def error(self):
return None
@dataclass
@schema_version("remote-execution-result", 1)
class RemoteExecutionResult(ExecutionResult, RemoteResult):
results: Sequence[RunResult]
args: Dict[str, Any] = field(default_factory=dict)
generated_at: datetime = field(default_factory=datetime.utcnow)
def write(self, path: str):
writable = RunResultsArtifact.from_execution_results(
generated_at=self.generated_at,
results=self.results,
elapsed_time=self.elapsed_time,
args=self.args,
)
writable.write(path)
@classmethod
def from_local_result(
cls,
base: RunExecutionResult,
logs: List[LogMessage],
) -> "RemoteExecutionResult":
return cls(
generated_at=base.generated_at,
results=base.results,
elapsed_time=base.elapsed_time,
args=base.args,
logs=logs,
)
@dataclass
class ResultTable(dbtClassMixin):
column_names: List[str]
rows: List[Any]
@dataclass
@schema_version("remote-run-result", 1)
class RemoteRunResult(RemoteCompileResultMixin):
table: ResultTable
generated_at: datetime = field(default_factory=datetime.utcnow)

Some files were not shown because too many files have changed in this diff Show More