INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns the specified Special Folder
def get_special_folder(self, name): """ Returns the specified Special Folder :return: a special Folder :rtype: drive.Folder """ name = name if \ isinstance(name, OneDriveWellKnowFolderNames) \ else OneDriveWellKnowFolderNames(name.lower()) name =...
Updates this drive with data from the server
def refresh(self): """ Updates this drive with data from the server :return: Success / Failure :rtype: bool """ if self.object_id is None: url = self.build_url(self._endpoints.get('default_drive')) else: url = self.build_url( self...
Returns a Drive instance
def get_default_drive(self, request_drive=False): """ Returns a Drive instance :param request_drive: True will make an api call to retrieve the drive data :return: default One Drive :rtype: Drive """ if request_drive is False: return Drive(con=self.c...
Returns a Drive instance
def get_drive(self, drive_id): """ Returns a Drive instance :param drive_id: the drive_id to be retrieved :return: Drive for the id :rtype: Drive """ if not drive_id: return None url = self.build_url( self._endpoints.get('get_drive').form...
Returns a collection of drives
def get_drives(self): """ Returns a collection of drives""" url = self.build_url(self._endpoints.get('list_drives')) response = self.con.get(url) if not response: return [] data = response.json() # Everything received from cloud must be passed as self._clo...
Given a ParsedNodePatch add the new information to the node.
def patch(self, patch): """Given a ParsedNodePatch, add the new information to the node.""" # explicitly pick out the parts to update so we don't inadvertently # step on the model name or anything self._contents.update({ 'patch_path': patch.original_file_path, 'de...
Build the forward and backward edges on the given list of ParsedNodes and return them as two separate dictionaries each mapping unique IDs to lists of edges.
def build_edges(nodes): """Build the forward and backward edges on the given list of ParsedNodes and return them as two separate dictionaries, each mapping unique IDs to lists of edges. """ backward_edges = {} # pre-populate the forward edge dict for simplicity forward_edges = {node.unique_i...
Convert the parsed manifest to a nested dict structure that we can safely serialize to JSON.
def serialize(self): """Convert the parsed manifest to a nested dict structure that we can safely serialize to JSON. """ forward_edges, backward_edges = build_edges(self.nodes.values()) return { 'nodes': {k: v.serialize() for k, v in self.nodes.items()}, ...
Find a macro in the graph by its name and package name or None for any package.
def find_macro_by_name(self, name, package): """Find a macro in the graph by its name and package name, or None for any package. """ return self._find_by_name(name, package, 'macros', [NodeType.Macro])
Find any valid target for ref () in the graph by its name and package name or None for any package.
def find_refable_by_name(self, name, package): """Find any valid target for "ref()" in the graph by its name and package name, or None for any package. """ return self._find_by_name(name, package, 'nodes', NodeType.refable())
Find any valid target for source () in the graph by its name and package name or None for any package.
def find_source_by_name(self, source_name, table_name, package): """Find any valid target for "source()" in the graph by its name and package name, or None for any package. """ name = '{}.{}'.format(source_name, table_name) return self._find_by_name(name, package, 'nodes', [NodeT...
Given a subgraph of the manifest and a predicate filter the subgraph using that predicate. Generates a list of nodes.
def _filter_subgraph(self, subgraph, predicate): """ Given a subgraph of the manifest, and a predicate, filter the subgraph using that predicate. Generates a list of nodes. """ to_return = [] for unique_id, item in subgraph.items(): if predicate(item): ...
Given a schema and table find matching models and return their unique_ids. A schema and table may have more than one match if the relation matches both a source and a seed for instance.
def get_unique_ids_for_schema_and_table(self, schema, table): """ Given a schema and table, find matching models, and return their unique_ids. A schema and table may have more than one match if the relation matches both a source and a seed, for instance. """ def predicate...
Add the given dict of new nodes to the manifest.
def add_nodes(self, new_nodes): """Add the given dict of new nodes to the manifest.""" for unique_id, node in new_nodes.items(): if unique_id in self.nodes: raise_duplicate_resource_name(node, self.nodes[unique_id]) self.nodes[unique_id] = node
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.
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 - if neither of those exist ( unit tests? ) a function that returns t...
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 - if neither of those exist ( unit tests? ) a function that returns the ...
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.
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.
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:
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:
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:
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.
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.
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!
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.
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 )
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 )
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 )
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.
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.
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.
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
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 =...