INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Patch nodes with the given dict of patches. Note that this consumes the input!
def patch_nodes(self, patches): """Patch nodes with the given dict of patches. Note that this consumes the input! """ # because we don't have any mapping from node _names_ to nodes, and we # only have the node name in the patch, we have to iterate over all the # nodes loo...
Convert the parsed manifest to the 'flat graph' that the compiler expects. Kind of hacky note: everything in the code is happy to deal with macros as ParsedMacro objects (in fact, it's been changed to require that), so those can just be returned without any work. Nodes sadly req...
def to_flat_graph(self): """Convert the parsed manifest to the 'flat graph' that the compiler expects. Kind of hacky note: everything in the code is happy to deal with macros as ParsedMacro objects (in fact, it's been changed to require that), so those can just be returned witho...
Convert list of dictionaries into an Agate table
def table_from_data(data, column_names): "Convert list of dictionaries into an Agate table" # 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 # # If there is no data, create an empty table with the spe...
The get_schema function is set by a few different things: - if there is a 'generate_schema_name' macro in the root project, it will be used. - if that does not exist but there is a 'generate_schema_name' macro in the 'dbt' internal project, that will be used ...
def get_schema_func(self): """The get_schema function is set by a few different things: - if there is a 'generate_schema_name' macro in the root project, it will be used. - if that does not exist but there is a 'generate_schema_name' macro in the 'dbt' int...
The get_alias function is set by a few different things: - if there is a 'generate_alias_name' macro in the root project, it will be used. - if that does not exist but there is a 'generate_alias_name' macro in the 'dbt' internal project, that will be used ...
def get_alias_func(self): """The get_alias function is set by a few different things: - if there is a 'generate_alias_name' macro in the root project, it will be used. - if that does not exist but there is a 'generate_alias_name' macro in the 'dbt' interna...
Update the unparsed node dictionary and build the basis for an intermediate ParsedNode that will be passed into the renderer
def _build_intermediate_node_dict(self, config, node_dict, node_path, package_project_config, tags, fqn, agate_table, archive_config, column_name): """Update the unparsed node dictionary and build t...
Given the parsed node and a SourceConfig to use during parsing, render the node's sql wtih macro capture enabled. Note: this mutates the config object when config() calls are rendered.
def _render_with_context(self, parsed_node, config): """Given the parsed node and a SourceConfig to use during parsing, render the node's sql wtih macro capture enabled. Note: this mutates the config object when config() calls are rendered. """ context = dbt.context.parser.gener...
Given the SourceConfig used for parsing and the parsed node, generate and set the true values to use, overriding the temporary parse values set in _build_intermediate_parsed_node.
def _update_parsed_node_info(self, parsed_node, config): """Given the SourceConfig used for parsing and the parsed node, generate and set the true values to use, overriding the temporary parse values set in _build_intermediate_parsed_node. """ # Special macro defined in the globa...
Parse a node, given an UnparsedNode and any other required information. agate_table should be set if the node came from a seed file. archive_config should be set if the node is an Archive node. column_name should be set if the node is a Test node associated with a particular column.
def parse_node(self, node, node_path, package_project_config, tags=None, fqn_extra=None, fqn=None, agate_table=None, archive_config=None, column_name=None): """Parse a node, given an UnparsedNode and any other required information. agate_table should be set if the ...
Check if we were able to extract toplevel blocks from the given contents. Return True if extraction was successful (no exceptions), False if it fails.
def check_block_parsing(self, name, path, contents): """Check if we were able to extract toplevel blocks from the given contents. Return True if extraction was successful (no exceptions), False if it fails. """ if not dbt.flags.TEST_NEW_PARSER: return True try...
Convert a column to a bigquery schema object.
def column_to_bq_schema(self): """Convert a column to a bigquery schema object. """ kwargs = {} if len(self.fields) > 0: fields = [field.column_to_bq_schema() for field in self.fields] kwargs = {"fields": fields} return google.cloud.bigquery.SchemaField(s...
Do some pre-run cleanup that is usually performed in Task __init__.
def runtime_cleanup(self, selected_uids): """Do some pre-run cleanup that is usually performed in Task __init__. """ self.run_count = 0 self.num_nodes = len(selected_uids) self.node_results = [] self._skipped_children = {} self._skipped_children = {} self....
Parse the given seed file, returning an UnparsedNode and the agate table.
def parse_seed_file(cls, file_match, root_dir, package_name, should_parse): """Parse the given seed file, returning an UnparsedNode and the agate table. """ abspath = file_match['absolute_path'] logger.debug("Parsing {}".format(abspath)) table_name = os.path.basename(absp...
Load and parse seed files in a list of directories. Returns a dict that maps unique ids onto ParsedNodes
def load_and_parse(self, package_name, root_dir, relative_dirs, tags=None): """Load and parse seed files in a list of directories. Returns a dict that maps unique ids onto ParsedNodes""" extension = "[!.#~]*.csv" if dbt.flags.STRICT_MODE: dbt.contracts.project.ProjectList...
Go through source, extracting every key/value pair where the key starts with the given prefix.
def get_stripped_prefix(source, prefix): """Go through source, extracting every key/value pair where the key starts with the given prefix. """ cut = len(prefix) return { k[cut:]: v for k, v in source.items() if k.startswith(prefix) }
Given a dictionary following this layout: { 'encoded:label': 'Encoded', 'encoded:value': 'Yes', 'encoded:description': 'Indicates if the column is encoded', 'encoded:include': True, 'size:label': 'Size', 'size:value': 128, 'si...
def format_stats(stats): """Given a dictionary following this layout: { 'encoded:label': 'Encoded', 'encoded:value': 'Yes', 'encoded:description': 'Indicates if the column is encoded', 'encoded:include': True, 'size:label': 'Size', 's...
Given a list of column dictionaries following this layout: [{ 'column_comment': None, 'column_index': Decimal('1'), 'column_name': 'id', 'column_type': 'integer', 'table_comment': None, 'table_name': 'test_table', 'table_schema...
def unflatten(columns): """Given a list of column dictionaries following this layout: [{ 'column_comment': None, 'column_index': Decimal('1'), 'column_name': 'id', 'column_type': 'integer', 'table_comment': None, 'table_name': 'test_ta...
Update an existing context in-place, adding the given macro map to the appropriate package namespace. Adapter packages get inserted into the global namespace.
def _add_macro_map(context, package_name, macro_map): """Update an existing context in-place, adding the given macro map to the appropriate package namespace. Adapter packages get inserted into the global namespace. """ key = package_name if package_name in PACKAGES: key = GLOBAL_PROJECT...
Generate the common aspects of the config dict.
def generate_base(model, model_dict, config, manifest, source_config, provider, adapter=None): """Generate the common aspects of the config dict.""" if provider is None: raise dbt.exceptions.InternalException( "Invalid provider given to context: {}".format(provider)) t...
Internally, macros can be executed like nodes, with some restrictions: - they don't have have all values available that nodes do: - 'this', 'pre_hooks', 'post_hooks', and 'sql' are missing - 'schema' does not use any 'model' information - they can't be configured with config() directives
def generate_execute_macro(model, config, manifest, provider): """Internally, macros can be executed like nodes, with some restrictions: - they don't have have all values available that nodes do: - 'this', 'pre_hooks', 'post_hooks', and 'sql' are missing - 'schema' does not use any 'model' inf...
Not meant to be called directly. Call with either: dbt.context.parser.generate or dbt.context.runtime.generate
def generate(model, config, manifest, source_config=None, provider=None): """ Not meant to be called directly. Call with either: dbt.context.parser.generate or dbt.context.runtime.generate """ return generate_model(model, config, manifest, source_config, provider)
Create a new object with the desired output schema and write it.
def write(self, path): """Create a new object with the desired output schema and write it.""" meta = { 'generated_at': self.generated_at, 'elapsed_time': self.elapsed_time, } sources = {} for result in self.results: unique_id = result.node.uniq...
Make _ReferenceKeys with lowercase values for the cache so we don't have to keep track of quoting
def _make_key(relation): """Make _ReferenceKeys with lowercase values for the cache so we don't have to keep track of quoting """ return _ReferenceKey(_lower(relation.database), _lower(relation.schema), _lower(relation.identifier))
Recursively collect a set of _ReferenceKeys that would consequentially get dropped if this were dropped via "drop ... cascade". :return Set[_ReferenceKey]: All the relations that would be dropped
def collect_consequences(self): """Recursively collect a set of _ReferenceKeys that would consequentially get dropped if this were dropped via "drop ... cascade". :return Set[_ReferenceKey]: All the relations that would be dropped """ consequences = {self.key()} ...
Non-recursively indicate that an iterable of _ReferenceKey no longer exist. Unknown keys are ignored. :param Iterable[_ReferenceKey] keys: The keys to drop.
def release_references(self, keys): """Non-recursively indicate that an iterable of _ReferenceKey no longer exist. Unknown keys are ignored. :param Iterable[_ReferenceKey] keys: The keys to drop. """ keys = set(self.referenced_by) & set(keys) for key in keys: ...
Rename this cached relation to new_relation. Note that this will change the output of key(), all refs must be updated! :param _CachedRelation new_relation: The new name to apply to the relation
def rename(self, new_relation): """Rename this cached relation to new_relation. Note that this will change the output of key(), all refs must be updated! :param _CachedRelation new_relation: The new name to apply to the relation """ # Relations store this stu...
Rename a reference that may or may not exist. Only handles the reference itself, so this is the other half of what `rename` does. If old_key is not in referenced_by, this is a no-op. :param _ReferenceKey old_key: The old key to be renamed. :param _ReferenceKey new_key: The new key to r...
def rename_key(self, old_key, new_key): """Rename a reference that may or may not exist. Only handles the reference itself, so this is the other half of what `rename` does. If old_key is not in referenced_by, this is a no-op. :param _ReferenceKey old_key: The old key to be renamed. ...
Add a schema to the set of known schemas (case-insensitive) :param str database: The database name to add. :param str schema: The schema name to add.
def add_schema(self, database, schema): """Add a schema to the set of known schemas (case-insensitive) :param str database: The database name to add. :param str schema: The schema name to add. """ self.schemas.add((_lower(database), _lower(schema)))
Remove a schema from the set of known schemas (case-insensitive) If the schema does not exist, it will be ignored - it could just be a temporary table. :param str database: The database name to remove. :param str schema: The schema name to remove.
def remove_schema(self, database, schema): """Remove a schema from the set of known schemas (case-insensitive) If the schema does not exist, it will be ignored - it could just be a temporary table. :param str database: The database name to remove. :param str schema: The schema ...
Add multiple schemas to the set of known schemas (case-insensitive) :param Iterable[str] schemas: An iterable of the schema names to add.
def update_schemas(self, schemas): """Add multiple schemas to the set of known schemas (case-insensitive) :param Iterable[str] schemas: An iterable of the schema names to add. """ self.schemas.update((_lower(d), _lower(s)) for (d, s) in schemas)
Dump a key-only representation of the schema to a dictionary. Every known relation is a key with a value of a list of keys it is referenced by.
def dump_graph(self): """Dump a key-only representation of the schema to a dictionary. Every known relation is a key with a value of a list of keys it is referenced by. """ # we have to hold the lock for the entire dump, if other threads modify # self.relations or any cac...
Add a relation to the cache, or return it if it already exists. :param _CachedRelation relation: The relation to set or get. :return _CachedRelation: The relation stored under the given relation's key
def _setdefault(self, relation): """Add a relation to the cache, or return it if it already exists. :param _CachedRelation relation: The relation to set or get. :return _CachedRelation: The relation stored under the given relation's key """ self.add_schema(relation.d...
Add a link between two relations to the database. Both the old and new entries must alraedy exist in the database. :param _ReferenceKey referenced_key: The key identifying the referenced model (the one that if dropped will drop the dependent model). :param _ReferenceKey dependent_ke...
def _add_link(self, referenced_key, dependent_key): """Add a link between two relations to the database. Both the old and new entries must alraedy exist in the database. :param _ReferenceKey referenced_key: The key identifying the referenced model (the one that if dropped will drop ...
Add a link between two relations to the database. Both the old and new entries must already exist in the database. The dependent model refers _to_ the referenced model. So, given arguments of (jake_test, bar, jake_test, foo): both values are in the schema jake_test and foo is a view tha...
def add_link(self, referenced, dependent): """Add a link between two relations to the database. Both the old and new entries must already exist in the database. The dependent model refers _to_ the referenced model. So, given arguments of (jake_test, bar, jake_test, foo): both va...
Add the relation inner to the cache, under the schema schema and identifier identifier :param BaseRelation relation: The underlying relation.
def add(self, relation): """Add the relation inner to the cache, under the schema schema and identifier identifier :param BaseRelation relation: The underlying relation. """ cached = _CachedRelation(relation) logger.debug('Adding relation: {!s}'.format(cached)) l...
Removes all references to all entries in keys. This does not cascade! :param Iterable[_ReferenceKey] keys: The keys to remove.
def _remove_refs(self, keys): """Removes all references to all entries in keys. This does not cascade! :param Iterable[_ReferenceKey] keys: The keys to remove. """ # remove direct refs for key in keys: del self.relations[key] # then remove all entries...
Drop the given relation and cascade it appropriately to all dependent relations. :param _CachedRelation dropped: An existing _CachedRelation to drop.
def _drop_cascade_relation(self, dropped): """Drop the given relation and cascade it appropriately to all dependent relations. :param _CachedRelation dropped: An existing _CachedRelation to drop. """ if dropped not in self.relations: logger.debug('dropped a nonexiste...
Drop the named relation and cascade it appropriately to all dependent relations. Because dbt proactively does many `drop relation if exist ... cascade` that are noops, nonexistent relation drops cause a debug log and no other actions. :param str schema: The schema of the relati...
def drop(self, relation): """Drop the named relation and cascade it appropriately to all dependent relations. Because dbt proactively does many `drop relation if exist ... cascade` that are noops, nonexistent relation drops cause a debug log and no other actions. :param...
Rename a relation named old_key to new_key, updating references. Return whether or not there was a key to rename. :param _ReferenceKey old_key: The existing key, to rename from. :param _CachedRelation new_key: The new relation, to rename to.
def _rename_relation(self, old_key, new_relation): """Rename a relation named old_key to new_key, updating references. Return whether or not there was a key to rename. :param _ReferenceKey old_key: The existing key, to rename from. :param _CachedRelation new_key: The new relation, to re...
Check the rename constraints, and return whether or not the rename can proceed. If the new key is already present, that is an error. If the old key is absent, we debug log and return False, assuming it's a temp table being renamed. :param _ReferenceKey old_key: The existing key...
def _check_rename_constraints(self, old_key, new_key): """Check the rename constraints, and return whether or not the rename can proceed. If the new key is already present, that is an error. If the old key is absent, we debug log and return False, assuming it's a temp table bein...
Rename the old schema/identifier to the new schema/identifier and update references. If the new schema/identifier is already present, that is an error. If the schema/identifier key is absent, we only debug log and return, assuming it's a temp table being renamed. :param BaseRel...
def rename(self, old, new): """Rename the old schema/identifier to the new schema/identifier and update references. If the new schema/identifier is already present, that is an error. If the schema/identifier key is absent, we only debug log and return, assuming it's a temp table...
Case-insensitively yield all relations matching the given schema. :param str schema: The case-insensitive schema name to list from. :return List[BaseRelation]: The list of relations with the given schema
def get_relations(self, database, schema): """Case-insensitively yield all relations matching the given schema. :param str schema: The case-insensitive schema name to list from. :return List[BaseRelation]: The list of relations with the given schema """ schema = _low...
Clear the cache
def clear(self): """Clear the cache""" with self.lock: self.relations.clear() self.schemas.clear()
Splits sql statements at semicolons into discrete queries
def _split_queries(cls, sql): "Splits sql statements at semicolons into discrete queries" sql_s = dbt.compat.to_string(sql) sql_buf = StringIO(sql_s) split_query = snowflake.connector.util_text.split_statements(sql_buf) return [part[0] for part in split_query]
Get Snowflake private key by path or None.
def _get_private_key(cls, private_key_path, private_key_passphrase): """Get Snowflake private key by path or None.""" if private_key_path is None or private_key_passphrase is None: return None with open(private_key_path, 'rb') as key: p_key = serialization.load_pem_priva...
On snowflake, rolling back the handle of an aborted session raises an exception.
def _rollback_handle(cls, connection): """On snowflake, rolling back the handle of an aborted session raises an exception. """ try: connection.handle.rollback() except snowflake.connector.errors.ProgrammingError as e: msg = dbt.compat.to_string(e) ...
Generator for validate() results called against all given values. On errors, fields are warned about and ignored, unless strict mode is set in which case a compiler error is raised.
def _filter_validate(filepath, location, values, validate): """Generator for validate() results called against all given values. On errors, fields are warned about and ignored, unless strict mode is set in which case a compiler error is raised. """ for value in values: if not isinstance(valu...
Parse all the model dictionaries in models. :param List[dict] models: The `models` section of the schema.yml, as a list of dicts. :param str path: The path to the schema.yml file :param str package_name: The name of the current package :param str root_dir: The root directory...
def parse_all(self, models, path, package_name, root_dir): """Parse all the model dictionaries in models. :param List[dict] models: The `models` section of the schema.yml, as a list of dicts. :param str path: The path to the schema.yml file :param str package_name: The name ...
Parse all the model dictionaries in sources. :param List[dict] sources: The `sources` section of the schema.yml, as a list of dicts. :param str path: The path to the schema.yml file :param str package_name: The name of the current package :param str root_dir: The root direct...
def parse_all(self, sources, path, package_name, root_dir): """Parse all the model dictionaries in sources. :param List[dict] sources: The `sources` section of the schema.yml, as a list of dicts. :param str path: The path to the schema.yml file :param str package_name: The n...
This is common to both v1 and v2 - look through the relative_dirs under root_dir for .yml files yield pairs of filepath and loaded yaml contents.
def find_schema_yml(cls, package_name, root_dir, relative_dirs): """This is common to both v1 and v2 - look through the relative_dirs under root_dir for .yml files yield pairs of filepath and loaded yaml contents. """ extension = "[!.#~]*.yml" file_matches = dbt.clients....
Create and return a new graph that is a shallow copy of graph but with only the nodes in include_nodes. Transitive edges across removed nodes are preserved as explicit new edges.
def _subset_graph(graph, include_nodes): """Create and return a new graph that is a shallow copy of graph but with only the nodes in include_nodes. Transitive edges across removed nodes are preserved as explicit new edges. """ new_graph = nx.algorithms.transitive_closure(graph) include_nodes = ...
Calculate the 'value' of each node in the graph based on how many blocking descendants it has. We use this score for the internal priority queue's ordering, so the quality of this metric is important. The score is stored as a negative number because the internal PriorityQueue picks lowe...
def _calculate_scores(self): """Calculate the 'value' of each node in the graph based on how many blocking descendants it has. We use this score for the internal priority queue's ordering, so the quality of this metric is important. The score is stored as a negative number because the i...
Get a node off the inner priority queue. By default, this blocks. This takes the lock, but only for part of it. :param bool block: If True, block until the inner queue has data :param Optional[float] timeout: If set, block for timeout seconds waiting for data. :return Parse...
def get(self, block=True, timeout=None): """Get a node off the inner priority queue. By default, this blocks. This takes the lock, but only for part of it. :param bool block: If True, block until the inner queue has data :param Optional[float] timeout: If set, block for timeout seconds...
Find any nodes in the graph that need to be added to the internal queue and add them. Callers must hold the lock.
def _find_new_additions(self): """Find any nodes in the graph that need to be added to the internal queue and add them. Callers must hold the lock. """ for node, in_degree in self.graph.in_degree_iter(): if not self._already_known(node) and in_degree == 0: ...
Given a node's unique ID, mark it as done. This method takes the lock. :param str node_id: The node ID to mark as complete.
def mark_done(self, node_id): """Given a node's unique ID, mark it as done. This method takes the lock. :param str node_id: The node ID to mark as complete. """ with self.lock: self.in_progress.remove(node_id) self.graph.remove_node(node_id) ...
Mark the node as 'in progress'. Callers must hold the lock. :param str node_id: The node ID to mark as in progress.
def _mark_in_progress(self, node_id): """Mark the node as 'in progress'. Callers must hold the lock. :param str node_id: The node ID to mark as in progress. """ self.queued.remove(node_id) self.in_progress.add(node_id)
Returns a queue over nodes in the graph that tracks progress of dependecies.
def as_graph_queue(self, manifest, limit_to=None): """Returns a queue over nodes in the graph that tracks progress of dependecies. """ if limit_to is None: graph_nodes = self.graph.nodes() else: graph_nodes = limit_to new_graph = _subset_graph(sel...
indicate that node1 depends on node2
def dependency(self, node1, node2): "indicate that node1 depends on node2" self.graph.add_node(node1) self.graph.add_node(node2) self.graph.add_edge(node2, node1)
Write the graph to a gpickle file. Before doing so, serialize and include all nodes in their corresponding graph entries.
def write_graph(self, outfile, manifest): """Write the graph to a gpickle file. Before doing so, serialize and include all nodes in their corresponding graph entries. """ out_graph = _updated_graph(self.graph, manifest) nx.write_gpickle(out_graph, outfile)
Given the parsed args, initialize the dbt tracking code. It would be nice to re-use this profile later on instead of parsing it twice, but dbt's intialization is not structured in a way that makes that easy.
def initialize_config_values(parsed): """Given the parsed args, initialize the dbt tracking code. It would be nice to re-use this profile later on instead of parsing it twice, but dbt's intialization is not structured in a way that makes that easy. """ try: cfg = UserConfig.from_directo...
Given an absolute `root_path`, a list of relative paths to that absolute root path (`relative_paths_to_search`), and a `file_pattern` like '*.sql', returns information about the files. For example: > find_matching('/root/path', 'models', '*.sql') [ { 'absolute_path': '/root/path/models/model_one.sql...
def find_matching(root_path, relative_paths_to_search, file_pattern): """ Given an absolute `root_path`, a list of relative paths to that absolute root path (`relative_paths_to_search`), and a `file_pattern` like '*.sql', returns information about the files. For examp...
Make a directory and any intermediate directories that don't already exist. This function handles the case where two threads try to create a directory at once.
def make_directory(path): """ Make a directory and any intermediate directories that don't already exist. This function handles the case where two threads try to create a directory at once. """ if not os.path.exists(path): # concurrent writes that try to create the same dir can fail ...
Make a file at `path` assuming that the directory it resides in already exists. The file is saved with contents `contents`
def make_file(path, contents='', overwrite=False): """ Make a file at `path` assuming that the directory it resides in already exists. The file is saved with contents `contents` """ if overwrite or not os.path.exists(path): with open(path, 'w') as fh: fh.write(contents) r...
Create a symlink at `link_path` referring to `source`.
def make_symlink(source, link_path): """ Create a symlink at `link_path` referring to `source`. """ if not supports_symlinks(): dbt.exceptions.system_error('create a symbolic link') return os.symlink(source, link_path)
If path-to_resolve is a relative path, create an absolute path with base_path as the base. If path_to_resolve is an absolute path or a user path (~), just resolve it to an absolute path and return.
def resolve_path_from_base(path_to_resolve, base_path): """ If path-to_resolve is a relative path, create an absolute path with base_path as the base. If path_to_resolve is an absolute path or a user path (~), just resolve it to an absolute path and return. """ return os.path.abspath( ...
Recursively deletes a directory. Includes an error handler to retry with different permissions on Windows. Otherwise, removing directories (eg. cloned via git) can cause rmtree to throw a PermissionError exception
def rmdir(path): """ Recursively deletes a directory. Includes an error handler to retry with different permissions on Windows. Otherwise, removing directories (eg. cloned via git) can cause rmtree to throw a PermissionError exception """ logger.debug("DEBUG** Window rmdir sys.platform: {}".form...
OSError handling for posix systems. Some things that could happen to trigger an OSError: - cwd could not exist - exc.errno == ENOENT - exc.filename == cwd - cwd could have permissions that prevent the current user moving to it - exc.errno == EACCES - ...
def _handle_posix_error(exc, cwd, cmd): """OSError handling for posix systems. Some things that could happen to trigger an OSError: - cwd could not exist - exc.errno == ENOENT - exc.filename == cwd - cwd could have permissions that prevent the current user moving to it ...
Interpret an OSError exc and raise the appropriate dbt exception.
def _interpret_oserror(exc, cwd, cmd): """Interpret an OSError exc and raise the appropriate dbt exception. """ if len(cmd) == 0: raise dbt.exceptions.CommandError(cwd, cmd) # all of these functions raise unconditionally if os.name == 'nt': _handle_windows_error(exc, cwd, cmd) ...
Define an error handler to pass to shutil.rmtree. On Windows, when a file is marked read-only as git likes to do, rmtree will fail. To handle that, on errors try to make the file writable. We want to retry most operations here, but listdir is one that we know will be useless.
def chmod_and_retry(func, path, exc_info): """Define an error handler to pass to shutil.rmtree. On Windows, when a file is marked read-only as git likes to do, rmtree will fail. To handle that, on errors try to make the file writable. We want to retry most operations here, but listdir is one that we kno...
A re-implementation of shutil.move that properly removes the source directory on windows when it has read-only files in it and the move is between two drives. 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 ...
def move(src, dst): """A re-implementation of shutil.move that properly removes the source directory on windows when it has read-only files in it and the move is between two drives. This is almost identical to the real shutil.move, except it uses our rmtree and skips handling non-windows OSes since...
Return an ordered iterator of key/value pairs for pretty-printing.
def connection_info(self): """Return an ordered iterator of key/value pairs for pretty-printing. """ for key in self._connection_keys(): if key in self._contents: yield key, self._contents[key]
Return a function that takes a row and decides if the row should be included in the catalog output.
def _catalog_filter_schemas(manifest): """Return a function that takes a row and decides if the row should be included in the catalog output. """ schemas = frozenset((d.lower(), s.lower()) for d, s in manifest.get_used_schemas()) def test(row): table_database = _expe...
If dt has a timezone, return a new datetime that's in UTC. Otherwise, assume the datetime is already for UTC and add the timezone.
def _utc(dt, source, field_name): """If dt has a timezone, return a new datetime that's in UTC. Otherwise, assume the datetime is already for UTC and add the timezone. """ if dt is None: raise dbt.exceptions.raise_database_error( "Expected a non-null value when querying field '{}' of...
Override jinja's compilation to stash the rendered source inside the python linecache for debugging.
def _compile(self, source, filename): """Override jinja's compilation to stash the rendered source inside the python linecache for debugging. """ if filename == '<template>': # make a better filename filename = 'dbt-{}'.format( codecs.encode(os.ura...
Using the SCHEMA property, validate the attributes of this instance. If any attributes are missing or invalid, raise a ValidationException.
def validate(self): """ Using the SCHEMA property, validate the attributes of this instance. If any attributes are missing or invalid, raise a ValidationException. """ validator = Draft7Validator(self.SCHEMA) errors = set() # make errors a set to avoid duplicate...
Try to release a connection. If an exception is hit, log and return the error string.
def _safe_release_connection(self): """Try to release a connection. If an exception is hit, log and return the error string. """ try: self.adapter.release_connection() except Exception as exc: logger.debug( 'Error releasing connection for n...
Calculate the status of a run. :param dict target_freshness: The target freshness dictionary. It must match the freshness spec. :param timedelta freshness: The actual freshness of the data, as calculated from the database's timestamps
def _calculate_status(self, target_freshness, freshness): """Calculate the status of a run. :param dict target_freshness: The target freshness dictionary. It must match the freshness spec. :param timedelta freshness: The actual freshness of the data, as calculated from t...
Instantiate a RuntimeConfig from its components. :param profile Profile: A parsed dbt Profile. :param project Project: A parsed dbt Project. :param args argparse.Namespace: The parsed command-line arguments. :returns RuntimeConfig: The new configuration.
def from_parts(cls, project, profile, args): """Instantiate a RuntimeConfig from its components. :param profile Profile: A parsed dbt Profile. :param project Project: A parsed dbt Project. :param args argparse.Namespace: The parsed command-line arguments. :returns RuntimeConfig:...
Given a new project root, read in its project dictionary, supply the existing project's profile info, and create a new project file. :param project_root str: A filepath to a dbt project. :raises DbtProfileError: If the profile is invalid. :raises DbtProjectError: If project is missing o...
def new_project(self, project_root): """Given a new project root, read in its project dictionary, supply the existing project's profile info, and create a new project file. :param project_root str: A filepath to a dbt project. :raises DbtProfileError: If the profile is invalid. ...
Serialize the full configuration to a single dictionary. For any instance that has passed validate() (which happens in __init__), it matches the Configuration contract. Note that args are not serialized. :returns dict: The serialized configuration.
def serialize(self): """Serialize the full configuration to a single dictionary. For any instance that has passed validate() (which happens in __init__), it matches the Configuration contract. Note that args are not serialized. :returns dict: The serialized configuration. ...
Validate the configuration against its contract. :raises DbtProjectError: If the configuration fails validation.
def validate(self): """Validate the configuration against its contract. :raises DbtProjectError: If the configuration fails validation. """ try: Configuration(**self.serialize()) except ValidationException as e: raise DbtProjectError(str(e)) if g...
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 load. :param args argparse.Namespace: The arguments as parsed from the cli. :raises DbtProjectError: If the project is invalid or missing. ...
def from_args(cls, args): """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 load. :param args argparse.Namespace: The arguments as parsed from the cli. :raises DbtProjectError: If the pr...
Determine if a qualfied name matches an fqn, given the set of package names in the graph. :param List[str] qualified_name: The components of the selector or node name, split on '.'. :param Set[str] package_names: The set of pacakge names in the graph. :param List[str] fqn: The node's fully qual...
def _node_is_match(qualified_name, package_names, fqn): """Determine if a qualfied name matches an fqn, given the set of package names in the graph. :param List[str] qualified_name: The components of the selector or node name, split on '.'. :param Set[str] package_names: The set of pacakge name...
Yield all nodes in the graph that match the qualified_name_selector. :param str qualified_name_selector: The selector or node name
def get_nodes_by_qualified_name(self, graph, qualified_name_selector): """Yield all nodes in the graph that match the qualified_name_selector. :param str qualified_name_selector: The selector or node name """ qualified_name = qualified_name_selector.split(".") package_names = ge...
yields nodes from graph that have the specified tag
def get_nodes_by_tag(self, graph, tag_name): """ yields nodes from graph that have the specified tag """ for node, real_node in self.parsed_nodes(graph): if tag_name in real_node.tags: yield node
yields nodes from graph are the specified source.
def get_nodes_by_source(self, graph, source_full_name): """yields nodes from graph are the specified source.""" parts = source_full_name.split('.') if len(parts) == 1: target_source, target_table = parts[0], None elif len(parts) == 2: target_source, target_table =...
Add a query to the current transaction. A thin wrapper around ConnectionManager.add_query. :param str sql: The SQL query to add :param bool auto_begin: If set and there is no transaction in progress, begin a new one. :param Optional[List[object]]: An optional list of binding...
def add_query(self, sql, auto_begin=True, bindings=None, abridge_sql_log=False): """Add a query to the current transaction. A thin wrapper around ConnectionManager.add_query. :param str sql: The SQL query to add :param bool auto_begin: If set and there is no transactio...
1. Create a new column (w/ temp name and correct type) 2. Copy data over to it 3. Drop the existing column (cascade!) 4. Rename the new column to existing column
def alter_column_type(self, relation, column_name, new_column_type): """ 1. Create a new column (w/ temp name and correct type) 2. Copy data over to it 3. Drop the existing column (cascade!) 4. Rename the new column to existing column """ kwargs = { 'r...
Return True if the unique ID matches the given name, package, and type. If package is None, any package is allowed. nodetypes should be a container of NodeTypes that implements the 'in' operator.
def id_matches(unique_id, target_name, target_package, nodetypes, model): """Return True if the unique ID matches the given name, package, and type. If package is None, any package is allowed. nodetypes should be a container of NodeTypes that implements the 'in' operator. """ node_type = model....
Find an entry in a subgraph by name. Any mapping that implements .items() and maps unique id -> something can be used as the subgraph. Names are like: '{nodetype}.{target_package}.{target_name}' You can use `None` for the package name as a wildcard.
def find_in_subgraph_by_name(subgraph, target_name, target_package, nodetype): """Find an entry in a subgraph by name. Any mapping that implements .items() and maps unique id -> something can be used as the subgraph. Names are like: '{nodetype}.{target_package}.{target_name}' You can use `None...
Find an entry in the given list by name.
def find_in_list_by_name(haystack, target_name, target_package, nodetype): """Find an entry in the given list by name.""" for model in haystack: name = model.get('unique_id') if id_matches(name, target_name, target_package, nodetype, model): return model return None
>>> dbt.utils.deep_merge({'a': 1, 'b': 2, 'c': 3}, {'a': 2}, {'a': 3, 'b': 1}) # noqa {'a': 3, 'b': 1, 'c': 3}
def deep_merge(*args): """ >>> dbt.utils.deep_merge({'a': 1, 'b': 2, 'c': 3}, {'a': 2}, {'a': 3, 'b': 1}) # noqa {'a': 3, 'b': 1, 'c': 3} """ if len(args) == 0: return None if len(args) == 1: return copy.deepcopy(args[0]) lst = list(args) last = copy.deepcopy(lst.pop(l...
map the function func() onto each non-container value in 'value' recursively, returning a new value. As long as func does not manipulate value, then deep_map will also not manipulate it. value should be a value returned by `yaml.safe_load` or `json.load` - the only expected types are list, dict, native...
def deep_map(func, value): """map the function func() onto each non-container value in 'value' recursively, returning a new value. As long as func does not manipulate value, then deep_map will also not manipulate it. value should be a value returned by `yaml.safe_load` or `json.load` - the only exp...
Given a dict of keyword arguments and a dict mapping aliases to their canonical values, canonicalize the keys in the kwargs dict. :return: A dict continaing all the values in kwargs referenced by their canonical key. :raises: `AliasException`, if a canonical key is defined more than once.
def translate_aliases(kwargs, aliases): """Given a dict of keyword arguments and a dict mapping aliases to their canonical values, canonicalize the keys in the kwargs dict. :return: A dict continaing all the values in kwargs referenced by their canonical key. :raises: `AliasException`, if a can...
Performs a shallow clone of the repository into the downloads directory. This function can be called repeatedly. If the project has already been checked out at this version, it will be a no-op. Returns the path to the checked out directory.
def _checkout(self, project): """Performs a shallow clone of the repository into the downloads directory. This function can be called repeatedly. If the project has already been checked out at this version, it will be a no-op. Returns the path to the checked out directory.""" if ...
In Redshift, DROP TABLE ... CASCADE should not be used inside a transaction. Redshift doesn't prevent the CASCADE part from conflicting with concurrent transactions. If we do attempt to drop two tables with CASCADE at once, we'll often get the dreaded: table was dropped by a...
def drop_relation(self, relation): """ In Redshift, DROP TABLE ... CASCADE should not be used inside a transaction. Redshift doesn't prevent the CASCADE part from conflicting with concurrent transactions. If we do attempt to drop two tables with CASCADE at once, we'll often ...
Load and parse documentation in a list of projects. Returns a list of ParsedNodes.
def load_file(cls, package_name, root_dir, relative_dirs): """Load and parse documentation in a list of projects. Returns a list of ParsedNodes. """ extension = "[!.#~]*.md" file_matches = dbt.clients.system.find_matching( root_dir, relative_dirs, ...
Config resolution order: if this is a dependency model: - own project config - in-model config - active project config if this is a top-level model: - active project config - in-model config
def config(self): """ Config resolution order: if this is a dependency model: - own project config - in-model config - active project config if this is a top-level model: - active project config - in-model config """ ...
Expect a comment end and return the match object.
def expect_comment_end(self): """Expect a comment end and return the match object. """ match = self._expect_match('#}', COMMENT_END_PATTERN) self.advance(match.end())
Handle a block. The current state of the parser should be after the open block is completed: {% blk foo %}my data {% endblk %} ^ right here
def handle_block(self, match, block_start=None): """Handle a block. The current state of the parser should be after the open block is completed: {% blk foo %}my data {% endblk %} ^ right here """ # we have to handle comments inside blocks because you ...