text stringlengths 81 112k |
|---|
Get an instance to read information from Microsoft planner
def planner(self, *, resource=''):
""" Get an instance to read information from Microsoft planner """
if not isinstance(self.protocol, MSGraphProtocol):
# TODO: Custom protocol accessing OneDrive/Sharepoint Api fails here
... |
Downloads this file to the local drive. Can download the
file in chunks with multiple requests to the server.
:param to_path: a path to store the downloaded file
:type to_path: str or Path
:param str name: the name you want the stored file to have.
:param int chunk_size: number ... |
Checks the api endpoint to check if the async job progress
def _request_status(self):
""" Checks the api endpoint to check if the async job progress """
if self.item_id:
return True
response = self.con.get(self.monitor_url)
if not response:
return False
... |
Checks the api endpoint in a loop
:param delay: number of seconds to wait between api calls.
Note Connection 'requests_delay' also apply.
:return: tuple of status and percentage complete
:rtype: tuple(str, float)
def check_status(self, delay=0):
""" Checks the api endpoint in ... |
Restores this DriveItem Version.
You can not restore the current version (last one).
:return: Success / Failure
:rtype: bool
def restore(self):
""" Restores this DriveItem Version.
You can not restore the current version (last one).
:return: Success / Failure
:... |
Downloads this version.
You can not download the current version (last one).
:return: Success / Failure
:rtype: bool
def download(self, to_path=None, name=None, chunk_size='auto',
convert_to_pdf=False):
""" Downloads this version.
You can not download the curre... |
Updates the roles of this permission
:return: Success / Failure
:rtype: bool
def update_roles(self, roles='view'):
""" Updates the roles of this permission
:return: Success / Failure
:rtype: bool
"""
if not self.object_id:
return False
url ... |
the parent of this DriveItem
:return: Parent of this item
:rtype: Drive or drive.Folder
def get_parent(self):
""" the parent of this DriveItem
:return: Parent of this item
:rtype: Drive or drive.Folder
"""
if self._parent and self._parent.object_id == self.pare... |
Returns this Item Thumbnails. Thumbnails are not supported on
SharePoint Server 2016.
:param size: request only the specified size: ej: "small",
Custom 300x400 px: "c300x400", Crop: "c300x400_Crop"
:return: Thumbnail Data
:rtype: dict
def get_thumbnails(self, size=None):
... |
Updates this item
:param kwargs: all the properties to be updated.
only name and description are allowed at the moment.
:return: Success / Failure
:rtype: bool
def update(self, **kwargs):
""" Updates this item
:param kwargs: all the properties to be updated.
... |
Moves this item to the Recycle Bin
:return: Success / Failure
:rtype: bool
def delete(self):
""" Moves this item to the Recycle Bin
:return: Success / Failure
:rtype: bool
"""
if not self.object_id:
return False
url = self.build_url(
... |
Moves this DriveItem to another Folder.
Can't move between different Drives.
:param target: a Folder, Drive item or Item Id string.
If it's a drive the item will be moved to the root folder.
:type target: drive.Folder or DriveItem or str
:return: Success / Failure
:rtyp... |
Asynchronously creates a copy of this DriveItem and all it's
child elements.
:param target: target location to move to.
If it's a drive the item will be moved to the root folder.
:type target: drive.Folder or Drive
:param name: a new name for the copy.
:rtype: CopyOpera... |
Returns a list of available versions for this item
:return: list of versions
:rtype: list[DriveItemVersion]
def get_versions(self):
""" Returns a list of available versions for this item
:return: list of versions
:rtype: list[DriveItemVersion]
"""
if not self.... |
Returns a version for specified id
:return: a version object of specified id
:rtype: DriveItemVersion
def get_version(self, version_id):
""" Returns a version for specified id
:return: a version object of specified id
:rtype: DriveItemVersion
"""
if not self.ob... |
Creates or returns a link you can share with others
:param str share_type: 'view' to allow only view access,
'edit' to allow editions, and
'embed' to allow the DriveItem to be embedded
:param str share_scope: 'anonymous': anyone with the link can access.
'organization' Only o... |
Sends an invitation to access or edit this DriveItem
:param recipients: a string or Contact or a list of the former
representing recipients of this invitation
:type recipients: list[str] or list[Contact] or str or Contact
:param bool require_sign_in: if True the recipients
inv... |
Returns a list of DriveItemPermissions with the
permissions granted for this DriveItem.
:return: List of Permissions
:rtype: list[DriveItemPermission]
def get_permissions(self):
""" Returns a list of DriveItemPermissions with the
permissions granted for this DriveItem.
... |
Creates a Child Folder
:param str name: the name of the new child folder
:param str description: the description of the new child folder
:return: newly created folder
:rtype: drive.Folder
def create_child_folder(self, name, description=None):
""" Creates a Child Folder
... |
This will download each file and folder sequentially.
Caution when downloading big folder structures
:param drive.Folder to_folder: folder where to store the contents
def download_contents(self, to_folder=None):
""" This will download each file and folder sequentially.
Caution when dow... |
Uploads a file
:param item: path to the item you want to upload
:type item: str or Path
:param chunk_size: Only applies if file is bigger than 4MB.
Chunk size for uploads. Must be a multiple of 327.680 bytes
:return: uploaded file
:rtype: DriveItem
def upload_file(self... |
Returns a collection of drive items
def _base_get_list(self, url, limit=None, *, query=None, order_by=None,
batch=None):
""" Returns a collection of drive items """
if limit is None or limit > self.protocol.max_top_value:
batch = self.protocol.max_top_value
... |
Returns a collection of drive items from the root folder
:param int limit: max no. of items to get. Over 999 uses batch.
:param query: applies a OData filter to the request
:type query: Query or str
:param order_by: orders the result set based on this condition
:type order_by: Q... |
Returns a DriveItem by it's Id
:return: one item
:rtype: DriveItem
def get_item(self, item_id):
""" Returns a DriveItem by it's Id
:return: one item
:rtype: DriveItem
"""
if self.object_id:
# reference the current drive_id
url = self.bui... |
Returns the specified Special Folder
:return: a special Folder
:rtype: drive.Folder
def get_special_folder(self, name):
""" Returns the specified Special Folder
:return: a special Folder
:rtype: drive.Folder
"""
name = name if \
isinstance(name, On... |
Updates this drive with data from the server
:return: Success / Failure
:rtype: bool
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(sel... |
Returns a Drive instance
:param request_drive: True will make an api call to retrieve the drive
data
:return: default One Drive
:rtype: Drive
def get_default_drive(self, request_drive=False):
""" Returns a Drive instance
:param request_drive: True will make an api cal... |
Returns a Drive instance
:param drive_id: the drive_id to be retrieved
:return: Drive for the id
:rtype: Drive
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
... |
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 c... |
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({
... |
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, e... |
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())
... |
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.Macr... |
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_... |
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.
"""
... |
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 n... |
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 m... |
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])
... |
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
# o... |
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... |
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 th... |
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
... |
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
... |
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... |
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 durin... |
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 ... |
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.
de... |
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... |
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}
... |
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._sk... |
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']
lo... |
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"... |
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... |
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... |
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... |
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 pack... |
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 provid... |
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... |
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
... |
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 = {}
fo... |
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),
... |
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
... |
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 a... |
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.
... |
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... |
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 databas... |
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, sch... |
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 ... |
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 ... |
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 ... |
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... |
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... |
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 ... |
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 t... |
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.
... |
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... |
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):
... |
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... |
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... |
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 rel... |
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)
... |
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:
... |
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.... |
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 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... |
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... |
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 r... |
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 ... |
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... |
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... |
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.
"""
... |
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 comp... |
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.
... |
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()
... |
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.
... |
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 co... |
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... |
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 wh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.