text
stringlengths
81
112k
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` ...
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, c...
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 ...
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 - ...
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...
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, ...
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 ...
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()) ...
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. """ ...
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>': ...
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 inval...
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() excep...
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_freshnes...
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, pr...
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...
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): """Seri...
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: Configu...
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. ...
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...
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 qualifie...
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(par...
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...
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 cor...
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 ...
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_n...
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): ...
>>> 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 ...
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...
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 tran...
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 sh...
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...
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 ...
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 resolutio...
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 ...
This is suspiciously similar to _process_macro_default_arg, probably want to figure out how to merge the two. Process the rval of an assignment statement or a do-block def _process_rval_components(self): """This is suspiciously similar to _process_macro_default_arg, probably want to fi...
Handle the bit after an '=' in a macro default argument. This is probably the trickiest thing. The goal here is to accept all strings jinja would accept and always handle block start/end correctly: It's fine to have false positives, jinja can fail later. Return True if there are more ar...
Macro args are pretty tricky! Arg names themselves are simple, but you can set arbitrary default values, including doing stuff like: {% macro my_macro(arg="x" + ("}% {# {% endmacro %}" * 2)) %} Which makes you a jerk, but is valid jinja. def _process_macro_args(self): """Macro args are...
Render an entry, in case it's jinja. This is meant to be passed to deep_map. If the parsed entry is a string and has the name 'port', this will attempt to cast it to an int, and on failure will return the parsed string. :param value Any: The value to potentially render ...
Render the parsed data, returning a new dict (or whatever was read). def render_project(self, as_parsed): """Render the parsed data, returning a new dict (or whatever was read). """ try: return deep_map(self._render_project_entry, as_parsed) except RecursionException: ...
Render the chosen profile entry, as it was parsed. def render_profile_data(self, as_parsed): """Render the chosen profile entry, as it was parsed.""" try: return deep_map(self._render_profile_data, as_parsed) except RecursionException: raise DbtProfileError( ...
Load and parse archives in a list of projects. Returns a dict that maps unique ids onto ParsedNodes def load_and_parse(self): """Load and parse archives in a list of projects. Returns a dict that maps unique ids onto ParsedNodes""" archives = [] to_return = {} fo...
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 existing one. :param serialize_credentials bool: If True, serialize the credentials. Otherwise, the Credentials object will be copied. :r...
Create a profile from an existing set of Credentials and the remaining information. :param credentials dict: The credentials dict for this profile. :param threads int: The number of threads to use for connections. :param profile_name str: The profile name used for this profile. ...
This is a containment zone for the hateful way we're rendering profiles. def render_profile(cls, raw_profile, profile_name, target_override, cli_vars): """This is a containment zone for the hateful way we're rendering profiles. """ renderer = ConfigRendere...
Create a profile from its raw profile information. (this is an intermediate step, mostly useful for unit testing) :param raw_profile dict: The profile data for a single profile, from disk as yaml and its values rendered with jinja. :param profile_name str: The profile name used. ...
:param raw_profiles dict: The profile data, from disk as yaml. :param profile_name str: The profile name to use. :param cli_vars dict: The command-line variables passed as arguments, as a dict. :param target_override Optional[str]: The target to use, if provided on the co...
Given the raw profiles as read from disk and the name of the desired profile if specified, return the profile component of the runtime config. :param args argparse.Namespace: The arguments as parsed from the cli. :param project_profile_name Optional[str]: The profile name, if ...
Return a function that will process `doc()` references in jinja, look them up in the manifest, and return the appropriate block contents. def docs(node, manifest, config, column_name=None): """Return a function that will process `doc()` references in jinja, look them up in the manifest, and return the appr...
Resolve the given documentation. This follows the same algorithm as resolve_ref except the is_enabled checks are unnecessary as docs are always enabled. def resolve_doc(cls, manifest, target_doc_name, target_doc_package, current_project, node_package): """Resolve the given d...
Given a ParsedNode, add some fields that might be missing. Return a reference to the dict that refers to the given column, creating it if it doesn't yet exist. def _get_node_column(cls, node, column_name): """Given a ParsedNode, add some fields that might be missing. Return a reference ...
Given a manifest and a node in that manifest, process its refs def process_refs_for_node(cls, manifest, current_project, node): """Given a manifest and a node in that manifest, process its refs""" target_model = None target_model_name = None target_model_package = None for ref ...
Given a new node that is not in the manifest, copy the manifest and insert the new node into it as if it were part of regular ref processing def add_new_refs(cls, manifest, current_project, node, macros): """Given a new node that is not in the manifest, copy the manifest and insert the ...
Parse multiple versions as read from disk. The versions value may be any one of: - a single version string ('>0.12.1') - a single string specifying multiple comma-separated versions ('>0.11.1,<=0.12.2') - an array of single-version strings (['>0.11.1', '<=0.12.2']) Regardles...
Pre-process certain special keys to convert them from None values into empty containers, and to turn strings into arrays of strings. def _preprocess(project_dict): """Pre-process certain special keys to convert them from None values into empty containers, and to turn strings into arrays of stri...
Create a project from its project and package configuration, as read by yaml.safe_load(). :param project_dict dict: The dictionary as read from disk :param packages_dict Optional[dict]: If it exists, the packages file as read from disk. :raises DbtProjectError: If the projec...
Return a dict representation of the config that could be written to disk with `yaml.safe_dump` to get this configuration. :param with_packages bool: If True, include the serialized packages file in the root. :returns dict: The serialized profile. def to_project_config(self, with_pa...
Create a project from a root directory. Reads in dbt_project.yml and packages.yml, if it exists. :param project_root str: The path to the project root to load. :raises DbtProjectError: If the project is missing or invalid, or if the packages file exists and is invalid. :retu...
Return a list of lists of strings, where each inner list of strings represents a type + FQN path of a resource configuration that is not used. def get_unused_resource_config_paths(self, resource_fqns, disabled): """Return a list of lists of strings, where each inner list of strings repr...
Ensure this package works with the installed version of dbt. def validate_version(self): """Ensure this package works with the installed version of dbt.""" installed = get_installed_version() if not versions_compatible(*self.dbt_version): msg = IMPOSSIBLE_VERSION_ERROR.format( ...
returns True if this column can be expanded to the size of the other column def can_expand_to(self, other_column): """returns True if this column can be expanded to the size of the other column""" if not self.is_string() or not other_column.is_string(): return False ...
On entrance to this context manager, hold an exclusive lock and create a fresh transaction for redshift, then commit and begin a new one before releasing the lock on exit. See drop_relation in RedshiftAdapter for more information. :param Optional[str] name: The name of the connection t...
Fetches temporary login credentials from AWS. The specified user must already exist in the database, or else an error will occur def fetch_cluster_credentials(cls, db_user, db_name, cluster_id, duration_s): """Fetches temporary login credentials from AWS. The specified...
Load and parse models 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, resource_type, tags=None): """Load and parse models in a list of directories. Returns a dict that map...
Wait for results off the queue. If there is a timeout set, and it is exceeded, raise an RPCTimeoutException. def _wait_for_results(self): """Wait for results off the queue. If there is a timeout set, and it is exceeded, raise an RPCTimeoutException. """ while True: g...
Add a queue log handler to the global logger. def add_queue_handler(queue): """Add a queue log handler to the global logger.""" handler = QueueLogHandler(queue) handler.setFormatter(QueueFormatter()) handler.setLevel(DEBUG) GLOBAL_LOGGER.addHandler(handler)
Raise a CompilationException when an adapter method available to macros has changed. def invalid_type_error(method_name, arg_name, got_value, expected_type, version='0.13.0'): """Raise a CompilationException when an adapter method available to macros has changed. """ got_type...
`ctes` is a dict of CTEs in the form: { "cte_id_1": "__dbt__CTE__ephemeral as (select * from table)", "cte_id_2": "__dbt__CTE__events as (select id, type from events)" } Given `sql` like: "with internal_cte as (select * from sessions) select * from internal_cte" This...
This is the equivalent of what self.extra_ctes[cte_id] = sql would do if extra_ctes were an OrderedDict def set_cte(self, cte_id, sql): """This is the equivalent of what self.extra_ctes[cte_id] = sql would do if extra_ctes were an OrderedDict """ for cte in self.extra_ctes: ...
Build out the directory skeleton and python namespace files: dbt/ __init__.py adapters/ ${adapter_name} __init__.py include/ ${adapter_name} __init__.py def build_namespace(self)...
A decorator that marks a function as available, but also prints a deprecation warning. Use like @available_deprecated('my_new_method') def my_old_method(self, arg, model_name=None): args = compatability_shim(arg) return self.my_new_method(*args, model_name=None) To make `adapter.my_old...
Translates BQ SchemaField dicts into dbt BigQueryColumn objects def _get_dbt_columns_from_bq_table(self, table): "Translates BQ SchemaField dicts into dbt BigQueryColumn objects" columns = [] for col in table.schema: # BigQuery returns type labels that are not valid type specifiers...
Convert agate.Table with column names to a list of bigquery schemas. def _agate_to_schema(self, agate_table, column_override): """Convert agate.Table with column names to a list of bigquery schemas. """ bq_schema = [] for idx, col_name in enumerate(agate_table.column_names): ...
An iterator over the flattened columns for a given schema and table. Resolves child columns as having the name "parent.child". def _flat_columns_in_table(self, table): """An iterator over the flattened columns for a given schema and table. Resolves child columns as having the name "parent.child...
Construct a tuple of the column names for stats. Each stat has 4 columns of data. def _get_stats_column_names(cls): """Construct a tuple of the column names for stats. Each stat has 4 columns of data. """ columns = [] stats = ('num_bytes', 'num_rows', 'location', 'partit...
Given a table, return an iterator of key/value pairs for stats column names/values. def _get_stats_columns(cls, table, relation_type): """Given a table, return an iterator of key/value pairs for stats column names/values. """ column_names = cls._get_stats_column_names() ...
If the caller has passed the magic 'single-threaded' flag, call the function directly instead of pool.apply_async. The single-threaded flag is intended for gathering more useful performance information about what appens beneath `call_runner`, since python's default profiling tools ignor...
Given a pool, submit jobs from the queue to the pool. def run_queue(self, pool): """Given a pool, submit jobs from the queue to the pool. """ def callback(result): """Note: mark_done, at a minimum, must happen here or dbt will deadlock during ephemeral result error handl...
Mark the result as completed, insert the `CompiledResultNode` into the manifest, and mark any descendants (potentially with a 'cause' if the result was an ephemeral model) as skipped. def _handle_result(self, result): """Mark the result as completed, insert the `CompiledResultNode` into ...
Run dbt for the query, based on the graph. def run(self): """ Run dbt for the query, based on the graph. """ self._runtime_initialize() if len(self._flattened_nodes) == 0: logger.warning("WARNING: Nothing to do. Try checking your model " "...
Base64 decode a string. This should only be used for sql in calls. :param str sql: The base64 encoded form of the original utf-8 string :return str: The decoded utf-8 string def decode_sql(self, sql): """Base64 decode a string. This should only be used for sql in calls. :param str sql...
Create a bigquery table. The caller must supply a callback that takes one argument, a `google.cloud.bigquery.Table`, and mutates it. def create_bigquery_table(self, database, schema, table_name, callback, sql): """Create a bigquery table. The caller must supply a c...
Get a bigquery table for a schema/model. def get_bq_table(self, database, schema, identifier): """Get a bigquery table for a schema/model.""" conn = self.get_thread_connection() table_ref = self.table_ref(database, schema, identifier, conn) return conn.handle.get_table(table_ref)
This is only used for some error handling def read_profiles(profiles_dir=None): """This is only used for some error handling""" if profiles_dir is None: profiles_dir = PROFILES_DIR raw_profiles = read_profile(profiles_dir) if raw_profiles is None: profiles = {} else: profi...
Create a task that calls ``compute fn`` (along with additional arguments ``*compute_args`` and ``**compute_kwargs``), then applies the returned value to :meth:`.Bot.answerInlineQuery` to answer the inline query. If a preceding task is already working for a user, that task is cancelled, t...
Process new updates in infinity loop :param relax: float :param offset: int :param timeout: int :param allowed_updates: bool async def run_forever(self, relax=0.1, offset=None, timeout=20, allowed_updates=None): """ Process new updates in infinity loop :param r...
Return flavor of message or event. A message's flavor may be one of these: - ``chat`` - ``callback_query`` - ``inline_query`` - ``chosen_inline_result`` - ``shipping_query`` - ``pre_checkout_query`` An event's flavor is determined by the single top-level key. def flavor(msg): """...
Extract "headline" info about a message. Use parameter ``long`` to control whether a short or long tuple is returned. When ``flavor`` is ``chat`` (``msg`` being a `Message <https://core.telegram.org/bots/api#message>`_ object): - short: (content_type, ``msg['chat']['type']``, ``msg['chat']['id']``) ...
A combination of :meth:`telepot.flavor` and :meth:`telepot.glance`, return a 2-tuple (flavor, headline_info), where *headline_info* is whatever extracted by :meth:`telepot.glance` depending on the message flavor and the ``long`` parameter. def flance(msg, long=False): """ A combination of :meth:`telepo...
See: https://core.telegram.org/bots/api#sendmessage def sendMessage(self, chat_id, text, parse_mode=None, disable_web_page_preview=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): "...
See: https://core.telegram.org/bots/api#forwardmessage def forwardMessage(self, chat_id, from_chat_id, message_id, disable_notification=None): """ See: https://core.telegram.org/bots/api#forwardmessage """ p = _strip(locals()) return self._api_request('forwardMessage', _r...
See: https://core.telegram.org/bots/api#sendvoice :param voice: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto` def sendVoice(self, chat_id, voice, caption=None, parse_mode=None, duration=None, disable_notification=None, ...
See: https://core.telegram.org/bots/api#sendvideonote :param video_note: Same as ``photo`` in :meth:`telepot.Bot.sendPhoto` :param length: Although marked as optional, this method does not seem to work without it being specified. Supply any integer you want. It seems to have no...
See: https://core.telegram.org/bots/api#sendmediagroup :type media: array of `InputMedia <https://core.telegram.org/bots/api#inputmedia>`_ objects :param media: To indicate media locations, each InputMedia object's ``media`` field should be one of these: - string: `...
See: https://core.telegram.org/bots/api#sendlocation def sendLocation(self, chat_id, latitude, longitude, live_period=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://core.telegram...
See: https://core.telegram.org/bots/api#sendgame def sendGame(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://core.telegram.org/bots/api#sendgame """ p = _strip(locals()) ...
See: https://core.telegram.org/bots/api#sendinvoice def sendInvoice(self, chat_id, title, description, payload, provider_token, start_parameter, currency, prices, provider_data=None, photo_url=None, photo_size=None, pho...