bauplan package
Submodules
- bauplan.exceptions module
AccessDeniedError
ApiMethodError
ApiRouteError
BauplanError
BauplanInternalError
InvalidDataError
InvalidPlanError
JobError
MismatchedPythonVersionsError
MissingMagicCellError
MissingPandasError
NoResultsFoundError
ObjectCannotBeSerializedError
ObjectTooBigError
ResourceNotFoundError
TableCreatePlanApplyStatusError
TableCreatePlanError
TableCreatePlanStatusError
TooManyRequestsError
UnauthorizedError
UnhandledRuntimeError
UpdateConflictError
UserObjectKeyNotExistsError
UserObjectWithKeyExistsError
- bauplan.helpers module
- bauplan.schema module
APIMetadata
APIResponse
Branch
Entry
Namespace
PartitionField
Ref
RefMetadata
RefMetadata.author_time
RefMetadata.authors
RefMetadata.commit_time
RefMetadata.committer
RefMetadata.common_ancestor_hash
RefMetadata.from_dict()
RefMetadata.message
RefMetadata.model_computed_fields
RefMetadata.model_config
RefMetadata.model_fields
RefMetadata.num_commits_ahead
RefMetadata.num_commits_behind
RefMetadata.num_total_commits
RefMetadata.parent_commit_hashes
Table
TableField
TableMetadata
TableMetadata.current_schema_id
TableMetadata.current_snapshot_id
TableMetadata.fields
TableMetadata.id
TableMetadata.last_updated_ms
TableMetadata.metadata_location
TableMetadata.model_computed_fields
TableMetadata.model_config
TableMetadata.model_fields
TableMetadata.name
TableMetadata.namespace
TableMetadata.partitions
TableMetadata.raw
TableMetadata.records
TableMetadata.size
TableMetadata.snapshots
- bauplan.standard_expectations module
expect_column_accepted_values()
expect_column_all_null()
expect_column_all_unique()
expect_column_equal_concatenation()
expect_column_mean_greater_or_equal_than()
expect_column_mean_greater_than()
expect_column_mean_smaller_or_equal_than()
expect_column_mean_smaller_than()
expect_column_no_nulls()
expect_column_not_unique()
expect_column_some_null()
- bauplan.state module
ApplyPlanState
CommonRunState
PlanImportState
ReRunExecutionContext
ReRunExecutionContext.cache
ReRunExecutionContext.debug
ReRunExecutionContext.dry_run
ReRunExecutionContext.model_computed_fields
ReRunExecutionContext.model_config
ReRunExecutionContext.model_fields
ReRunExecutionContext.namespace
ReRunExecutionContext.preview
ReRunExecutionContext.re_run_job_id
ReRunExecutionContext.ref
ReRunExecutionContext.strict
ReRunExecutionContext.transaction
ReRunState
RunExecutionContext
RunExecutionContext.cache
RunExecutionContext.debug
RunExecutionContext.dry_run
RunExecutionContext.model_computed_fields
RunExecutionContext.model_config
RunExecutionContext.model_fields
RunExecutionContext.namespace
RunExecutionContext.preview
RunExecutionContext.project_dir
RunExecutionContext.ref
RunExecutionContext.snapshot_id
RunExecutionContext.snapshot_uri
RunExecutionContext.strict
RunExecutionContext.transaction
RunState
TableCreatePlanApplyContext
TableCreatePlanApplyState
TableCreatePlanContext
TableCreatePlanContext.branch_name
TableCreatePlanContext.debug
TableCreatePlanContext.model_computed_fields
TableCreatePlanContext.model_config
TableCreatePlanContext.model_fields
TableCreatePlanContext.namespace
TableCreatePlanContext.search_string
TableCreatePlanContext.table_name
TableCreatePlanContext.table_replace
TableCreatePlanState
TableDataImportContext
TableDataImportContext.best_effort
TableDataImportContext.branch_name
TableDataImportContext.continue_on_error
TableDataImportContext.debug
TableDataImportContext.import_duplicate_files
TableDataImportContext.model_computed_fields
TableDataImportContext.model_config
TableDataImportContext.model_fields
TableDataImportContext.namespace
TableDataImportContext.preview
TableDataImportContext.search_string
TableDataImportContext.table_name
TableDataImportContext.transformation_query
TableDataImportState
- bauplan.store module
Module contents
- class bauplan.Client(api_key: str | None = None, profile: str | None = None, namespace: str | None = None, **kwargs)
Bases:
object
A consistent interface to access Bauplan operations.
Using the client
import bauplan client = bauplan.Client() # query the table and return result set as an arrow Table my_table = client.query('SELECT sum(trips) trips FROM travel_table', branch_name='main') # efficiently cast the table to a pandas DataFrame df = my_table.to_pandas()
Notes on authentication
# by default, authenticate from BAUPLAN_API_KEY >> BAUPLAN_PROFILE >> ~/.bauplan/config.yml client = bauplan.Client() # client used ~/.bauplan/config.yml profile 'default' os.environ['BAUPLAN_PROFILE'] = "someprofile" client = bauplan.Client() # >> client now uses profile 'someprofile' os.environ['BAUPLAN_API_KEY'] = "mykey" client = bauplan.Client() # >> client now authenticates with api_key value "mykey", because api key > profile # specify authentication directly - this supercedes BAUPLAN_API_KEY in the environment client = bauplan.Client(api_key='MY_KEY') # specify a profile from ~/.bauplan/config.yml - this supercedes BAUPLAN_PROFILE in the environment client = bauplan.Client(profile='default')
Handling Exceptions
Catalog operations (branch/table methods) raise a subclass of
bauplan.exceptions.BauplanError
that mirror HTTP status codes.400: InvalidDataError
401: UnauthorizedError
403: AccessDeniedError
404: ResourceNotFoundError e.g .ID doesn’t match any records
404: ApiRouteError e.g. the given route doesn’t exist
405: ApiMethodError e.g. POST on a route with only GET defined
409: UpdateConflictError e.g. creating a record with a name that already exists
429: TooManyRequestsError
Run/Query/Scan/Import operations raise a subclass of
bauplan.exceptions.BauplanError
that represents, and also return aRunState
object containing details and logs:JobError
e.g. something went wrong in a run/query/import/scan; includes error details
Run/import operations also return a state object that includes a
job_status
and other details. There are two ways to check status for run/import operations:try/except the JobError exception
check the
state.job_status
attribute
Examples:
try: state = client.run(...) state = client.query(...) state = client.scan(...) state = client.plan_table_creation(...) except bauplan.exceptions.JobError as e: ... state = client.run(...) if state.job_status != "success": ...
- Parameters:
api_key – (optional) Your unique Bauplan API key; mutually exclusive with
profile
. If not provided, fetch precedence is 1) environment BAUPLAN_API_KEY 2) .bauplan/config.ymlprofile – (optional) The Bauplan config profile name to use to determine api_key; mutually exclusive with
api_key
.namespace – (optional) The default namespace to use for queries and runs.
- apply_table_creation_plan(plan: Dict | TableCreatePlanState, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None) TableCreatePlanApplyState
Apply a plan for creating a table. It is done automaticaly during th table plan creation if no schema conflicts exist. Otherwise, if schema conflicts exist, then this function is used to apply them after the schema conflicts are resolved. Most common schema conflict is a two parquet files with the same column name but different datatype
- Parameters:
plan – The plan to apply.
debug – Whether to enable or disable debug mode for the query.
args – dict of arbitrary args to pass to the backend.
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Raises:
TableCreatePlanApplyStatusError – if the table creation plan apply fails.
:return The plan state.
- branch_exists(branch: str | Branch) bool
Check if a branch exists.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() assert client.branch_exists('main')
- Parameters:
branch – The name of the branch to check.
- Returns:
A boolean for if the branch exists.
- create_branch(branch: str | Branch, from_ref: str | Branch | Ref) Branch
Create a new branch at a given ref.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() assert client.create_branch( branch='myzone.newbranch', from_ref='main' )
- Parameters:
branch – The name of the new branch.
from_ref – The name of the base branch; either a branch like “main” or ref like “main@[sha]”.
- Returns:
The created branch object.
- create_namespace(namespace: str | Namespace, into_branch: str | Branch) Namespace
Create a new namespace at a given branch.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() assert client.create_namespace( branch='myzone.newbranch', name='main' )
- Parameters:
namespace – The name of the namespace.
into_branch – The name of the branch to create the namespace on.
- Returns:
The created namespace.
- create_table(table: str | Table, search_uri: str, branch: str | Branch | None = None, namespace: str | Namespace | None = None, replace: bool | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None) Table
Create a table from an S3 location.
This operation will attempt to create a table based of schemas of N parquet files found by a given search uri.
import bauplan client = bauplan.Client() plan_state = client.create_table( table='newtablename', search_uri='s3://path/to/my/files/*.parquet', branch='main', ) if plan_state.error: plan_error_action(...) success_action(plan_state.plan)
- Parameters:
table – The table which will be created.
search_uri – The location of the files to scan for schema.
branch – The branch name in which to create the table in.
namespace – Optional argument specifying the namespace. If not. specified, it will be inferred based on table location or the default. namespace
replace – Replace the table if it already exists.
debug – Whether to enable or disable debug mode for the query.
args – dict of arbitrary args to pass to the backend.
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Raises:
TableCreatePlanStatusError – if the table creation plan fails.
TableCreatePlanApplyStatusError – if the table creation plan apply fails.
- Returns:
The plan state.
- delete_branch(branch: str | Branch) bool
Delete a branch.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() assert client.delete_branch(branch='mybranch')
- Parameters:
branch – The name of the branch to delete.
- Returns:
A boolean for if the branch was deleted.
- delete_namespace(namespace: str | Namespace, form_branch: str | Branch) bool
Delete a namespace.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() assert client.delete_namespace( branch='mybranch', name='mynamespace', )
- Parameters:
namespace – The name of the namespace to delete.
form_branch – The name of the branch to delete the namespace from.
- Returns:
A boolean for if the namespace was deleted.
- delete_table(table: str | Table, branch: str | Branch) bool
Drop a table.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() assert client.delete_table(table='mytable', branch='mybranch')
- Parameters:
table – The table to delete.
branch – The branch on which the table is stored.
- Returns:
A boolean for if the table was deleted.
- get_branch(branch: str | Branch) Branch
Get the branch.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() # retrieve only the tables as tuples of (name, kind) branch = client.get_branch('main') print(branch.hash)
- Parameters:
branch – The name of the branch to retrieve.
- Returns:
A Branch object.
- get_branches(name: str | None = None, user: str | None = None, limit: int | None = None, itersize: int | None = None) Generator[Branch, None, None]
Get the available data branches in the Bauplan catalog.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() for branch in client.get_branches(): print(branch.name, branch.hash)
- Parameters:
name – Filter the branches by name.
user – Filter the branches by user.
itersize – int 1-500.
limit – int > 0.
- Yield:
A Branch object.
- get_namespace(namespace: str | Namespace, ref: str | Branch | Ref) Namespace
Get a namespace.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() namespace = client.get_namespace('my_namespace', 'main')
- Parameters:
namespace – The name of the namespace to get.
ref – The ref or branch to check the namespace on.
- Returns:
A Namespace object.
- get_namespaces(ref: str | Branch | Ref, filter_by_name: str | None = None, itersize: int | None = None, limit: int | None = None) Generator[Namespace, None, None]
Get the available data namespaces in the Bauplan catalog branch.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() for namespace in client.get_namespaces(): print(namespace.name)
- Parameters:
ref – The ref or branch to retrieve the namespaces from.
filter_by_name – Filter the namespaces by name.
itersize – int 1-500.
limit – int > 0.
- Yield:
A Namespace object.
- get_table(table: str | Table, branch: str | Branch, include_raw: bool = False) Table
Get the table data and metadata for a table in the target branch.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() # get the fields and metadata for the taxi_zones table in the main branch table = client.get_table_with_metadata(branch='main', table='taxi_zones') # loop through the fields and print their name, required, and type for c in table.fields: print(c.name, c.required, c.type) # show the number of records in the table print(table.records)
- Parameters:
branch – The branch to get the table from.
table – The table to retrieve.
include_raw – Whether or not to include the raw metadata.json object as a nested dict.
- Returns:
a TableWithMetadata object, optionally including the raw metadata.json object.
- get_tables(ref: str | Branch | Ref, namespace: str | Namespace | None = None, limit: int | None = None, itersize: int | None = None) Generator[Table, None, None]
Get the tables and views in the target branch.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() # retrieve only the tables as tuples of (name, kind) tables = client.get_tables('main') for table in tables: print(table.name, table.kind)
- Parameters:
ref – The ref or branch to get the tables from.
namespace – The namespace to get the tables from.
limit – int > 0.
itersize – int 1-500.
- Yield:
A Table object.
- import_data(table: str | Table, search_uri: str, branch: str | Branch | None = None, namespace: str | Namespace | None = None, continue_on_error: bool = False, import_duplicate_files: bool = False, best_effort: bool = False, preview: bool | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None) TableDataImportState
Imports data into an already existing table.
import bauplan client = bauplan.Client() s3_path = 's3://path/to/my/files/*.parquet' plan_state = client.data_import( table='newtablename', search_uri=s3_path, branch='main' ) if plan_state.error: plan_error_action(...) success_action(plan_state.plan)
- Parameters:
table – Previously created table in into which data will be imported.
search_uri – Uri which to scan for files to import.
branch – Branch in which to import the table.
namespace – Namespace of the table. If not specified, namespace will be infered from table name or default settings.
continue_on_error – Do not fail the import even if 1 data import fails.
import_duplicate_files – Ignore prevention of importing s3 files that were already imported.
best_effort – Don’t fail if schema of table does not match.
transformation_query – Optional duckdb compliant query applied on each parquet file. Use original_table as the table in the query.
preview – Whether to enable or disable preview mode for the query.
debug – Whether to enable or disable debug mode for the query.
args – dict of arbitrary args to pass to the backend.
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Returns:
The plan state.
- merge_branch(source_ref: str | Branch | Ref, into_branch: str | Branch) bool
Merge one branch into another.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() assert merge_branch( into_branch='myzone.somebranch', source_ref='myzone.oldbranch' )
- Parameters:
source_ref – The name of the merge source; either a branch like “main” or ref like “main@[sha]”.
into_branch – The name of the merge target.
- Returns:
a boolean for whether the merge worked.
- namespace_exists(namespace: str | Namespace, ref: str | Branch | Ref) bool
Check if a namespace exists.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() assert client.namespace_exists('my_namespace', 'main')
- Parameters:
namespace – The name of the namespace to check.
ref – The ref or branch to check the namespace on.
- Returns:
A boolean for if the namespace exists.
- plan_table_creation(table: str | Table, search_uri: str, branch: str | Branch | None = None, namespace: str | Namespace | None = None, replace: bool | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None) TableCreatePlanState
Create a table import plan from an S3 location.
This operation will attempt to create a table based of schemas of N parquet files found by a given search uri. A YAML file containing the schema and plan is returns and if there are no conflicts, it is automatically applied.
import bauplan client = bauplan.Client() plan_state = client.plan_table_creation( search_uri='s3://path/to/my/files/*.parquet', table='newtablename', branch='main', ) if plan_state.error: plan_error_action(...) success_action(plan_state.plan)
- Parameters:
table – The table which will be created.
search_uri – The location of the files to scan for schema.
branch – The branch name in which to create the table in.
namespace – Optional argument specifying the namespace. If not. specified, it will be inferred based on table location or the default. namespace
replace – Replace the table if it already exists.
debug – Whether to enable or disable debug mode for the query.
args – dict of arbitrary args to pass to the backend.
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Raises:
TableCreatePlanStatusError – if the table creation plan fails.
- Returns:
The plan state.
- query(query: str, ref: str | Branch | Ref | None = None, max_rows: int | None = None, cache: Literal['on', 'off'] | None = None, connector: str | None = None, connector_config_key: str | None = None, connector_config_uri: str | None = None, namespace: str | Namespace | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None) Table
Execute a SQL query and return the results as a pyarrow.Table. Note that this function uses Arrow also internally, resulting in a fast data transfer.
If you prefer to return the results as a pandas DataFrame, use the
to_pandas
function of pyarrow.Table.import bauplan client = bauplan.Client() # query the table and return result set as an arrow Table my_table = client.query('SELECT c1 FROM my_table', ref='main') # efficiently cast the table to a pandas DataFrame df = mytable.to_pandas()
- Parameters:
query – The Bauplan query to execute.
ref – The ref or branch name to read data from.
max_rows – The maximum number of rows to return; default:
None
(no limit).cache – Whether to enable or disable caching for the query.
connector – The connector type for the model (defaults to Bauplan). Allowed values are ‘snowflake’ and ‘dremio’.
connector_config_key – The key name if the SSM key is custom with the pattern bauplan/connectors/<connector_type>/<key>.
connector_config_uri – Full SSM uri if completely custom path, e.g. ssm://us-west-2/123456789012/baubau/dremio.
namespace – The Namespace to run the query in. If not set, the query will be run in the default namespace for your account.
debug – Whether to enable or disable debug mode for the query.
args – Additional arguments to pass to the query (default: None).
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Returns:
The query results as a
pyarrow.Table
.
- query_to_csv_file(filename: str, query: str, ref: str | Branch | Ref | None = None, max_rows: int | None = None, cache: Literal['on', 'off'] | None = None, connector: str | None = None, connector_config_key: str | None = None, connector_config_uri: str | None = None, namespace: str | Namespace | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None, **kwargs: Any) str
Export the results of a SQL query to a file in CSV format.
import bauplan client = bauplan.Client() # query the table and iterate through the results one row at a time client.query_to_csv_file('./my.csv', 'SELECT c1 FROM my_table'):
- Parameters:
filename – The name or path of the file csv to write the results to.
query – The Bauplan query to execute.
ref – The ref or branch name to read data from.
max_rows – The maximum number of rows to return; default:
None
(no limit).cache – Whether to enable or disable caching for the query.
connector – The connector type for the model (defaults to Bauplan). Allowed values are ‘snowflake’ and ‘dremio’.
connector_config_key – The key name if the SSM key is custom with the pattern bauplan/connectors/<connector_type>/<key>.
connector_config_uri – Full SSM uri if completely custom path, e.g. ssm://us-west-2/123456789012/baubau/dremio.
namespace – The Namespace to run the query in. If not set, the query will be run in the default namespace for your account.
debug – Whether to enable or disable debug mode for the query.
args – Additional arguments to pass to the query (default: None).
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Returns:
The path of the file written.
- query_to_generator(query: str, ref: str | Branch | Ref | None = None, max_rows: int | None = None, cache: Literal['on', 'off'] | None = None, connector: str | None = None, connector_config_key: str | None = None, connector_config_uri: str | None = None, namespace: str | Namespace | None = None, debug: bool | None = None, as_json: bool | None = False, args: Dict[str, str] | None = None, client_timeout: int | float | None = None) Generator[Dict[str, Any], None, None]
Execute a SQL query and return the results as a generator, where each row is a Python dictionary.
import bauplan client = bauplan.Client() # query the table and iterate through the results one row at a time for row in client.query_to_generator('SELECT c1 FROM my_table', ref='main'): # do logic
- Parameters:
query – The Bauplan query to execute.
ref – The ref or branch name to read data from.
max_rows – The maximum number of rows to return; default:
None
(no limit).cache – Whether to enable or disable caching for the query.
connector – The connector type for the model (defaults to Bauplan). Allowed values are ‘snowflake’ and ‘dremio’.
connector_config_key – The key name if the SSM key is custom with the pattern bauplan/connectors/<connector_type>/<key>.
connector_config_uri – Full SSM uri if completely custom path, e.g. ssm://us-west-2/123456789012/baubau/dremio.
namespace – The Namespace to run the query in. If not set, the query will be run in the default namespace for your account.
debug – Whether to enable or disable debug mode for the query.
as_json – Whether to return the results as a JSON-compatible string (default:
False
).args – Additional arguments to pass to the query (default:
None
).client_timeout – seconds to timeout; this also cancels the remote job execution.
- Yield:
A dictionary representing a row of query results.
- query_to_json_file(filename: str, query: str, file_format: Literal['json', 'jsonl'] | None = 'json', ref: str | Branch | Ref | None = None, max_rows: int | None = None, cache: Literal['on', 'off'] | None = None, connector: str | None = None, connector_config_key: str | None = None, connector_config_uri: str | None = None, namespace: str | Namespace | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None) str
Export the results of a SQL query to a file in JSON format.
import bauplan client = bauplan.Client() # query the table and iterate through the results one row at a time client.query_to_file('./my.json', 'SELECT c1 FROM my_table'):
- Parameters:
filename – The name or path of the file json to write the results to.
query – The Bauplan query to execute.
file_format – The format to write the results in; default:
json
. Allowed values are ‘json’ and ‘jsonl’.ref – The ref or branch name to read data from.
max_rows – The maximum number of rows to return; default:
None
(no limit).cache – Whether to enable or disable caching for the query.
connector – The connector type for the model (defaults to Bauplan). Allowed values are ‘snowflake’ and ‘dremio’.
connector_config_key – The key name if the SSM key is custom with the pattern bauplan/connectors/<connector_type>/<key>.
connector_config_uri – Full SSM uri if completely custom path, e.g. ssm://us-west-2/123456789012/baubau/dremio.
namespace – The Namespace to run the query in. If not set, the query will be run in the default namespace for your account.
debug – Whether to enable or disable debug mode for the query.
args – Additional arguments to pass to the query (default: None).
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Returns:
The path of the file written.
- query_to_parquet_file(filename: str, query: str, ref: str | Branch | Ref | None = None, max_rows: int | None = None, cache: Literal['on', 'off'] | None = None, connector: str | None = None, connector_config_key: str | None = None, connector_config_uri: str | None = None, namespace: str | Namespace | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None, **kwargs: Any) str
Export the results of a SQL query to a file in Parquet format.
import bauplan client = bauplan.Client() # query the table and iterate through the results one row at a time client.query_to_file('./my.json', 'SELECT c1 FROM my_table'):
- Parameters:
filename – The name or path of the file parquet to write the results to.
query – The Bauplan query to execute.
ref – The ref or branch name to read data from.
max_rows – The maximum number of rows to return; default:
None
(no limit).cache – Whether to enable or disable caching for the query.
connector – The connector type for the model (defaults to Bauplan). Allowed values are ‘snowflake’ and ‘dremio’.
connector_config_key – The key name if the SSM key is custom with the pattern bauplan/connectors/<connector_type>/<key>.
connector_config_uri – Full SSM uri if completely custom path, e.g. ssm://us-west-2/123456789012/baubau/dremio.
namespace – The Namespace to run the query in. If not set, the query will be run in the default namespace for your account.
debug – Whether to enable or disable debug mode for the query.
args – Additional arguments to pass to the query (default: None).
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Returns:
The path of the file written.
- rerun(job_id: str, ref: str | Branch | Ref | None = None, namespace: str | Namespace | None = None, cache: Literal['on', 'off'] | None = None, transaction: Literal['on', 'off'] | None = None, dry_run: bool | None = None, strict: Literal['on', 'off'] | None = None, preview: bool | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None) RunState
Re run a Bauplan project by its ID and return the state of the run. This is the equivalent of running through the CLI the
bauplan rerun
command.- Parameters:
job_id – The Job ID of the previous run. This can be used to re-run a previous run, e.g., on a different branch.
ref – The ref or branch name to read.
namespace – The Namespace to run the job in. If not set, the job will be run in the default namespace.
cache – Whether to enable or disable caching for the run.
transaction – Whether to enable or disable transaction mode for the run.
dry_run – Whether to enable or disable dry-run mode for the run; models are not materialized.
strict – Whether to enable or disable strict schema validation.
preview – Whether to enable or disable preview mode for the run.
debug – Whether to enable or disable debug mode for the run.
args – Additional arguments (optional).
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Returns:
The state of the run.
- run(project_dir: str | None = None, ref: str | Branch | Ref | None = None, namespace: str | Namespace | None = None, parameters: Dict[str, str | int | float | bool] | None = None, cache: Literal['on', 'off'] | None = None, transaction: Literal['on', 'off'] | None = None, dry_run: bool | None = None, strict: Literal['on', 'off'] | None = None, preview: bool | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None) RunState
Run a Bauplan project and return the state of the run. This is the equivalent of running through the CLI the
bauplan run
command.- Parameters:
project_dir – The directory of the project (where the
bauplan_project.yml
file is located).ref – The ref or branch name to read.
namespace – The Namespace to run the job in. If not set, the job will be run in the default namespace.
parameters – Parameters for templating into SQL or Python models.
cache – Whether to enable or disable caching for the run.
transaction – Whether to enable or disable transaction mode for the run.
dry_run – Whether to enable or disable dry-run mode for the run; models are not materialized.
strict – Whether to enable or disable strict schema validation.
preview – Whether to enable or disable preview mode for the run.
debug – Whether to enable or disable debug mode for the run.
args – Additional arguments (optional).
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Returns:
The state of the run.
- scan(table: str | Table, ref: str | Branch | Ref | None = None, columns: List[str] | None = None, filters: str | None = None, limit: int | None = None, cache: Literal['on', 'off'] | None = None, connector: str | None = None, connector_config_key: str | None = None, connector_config_uri: str | None = None, namespace: str | Namespace | None = None, debug: bool | None = None, args: Dict[str, str] | None = None, client_timeout: int | float | None = None, **kwargs: Any) Table
Execute a table scan (with optional filters) and return the results as an arrow Table.
Note that this function uses SQLGlot to compose a safe SQL query, and then internally defer to the query_to_arrow function for the actual scan.
import bauplan client = bauplan.Client() # run a table scan over the data lake # filters are passed as a string my_table = client.scan( table='my_table', ref='main', columns=['c1'], filter='c2 > 10', )
- Parameters:
table – The table to scan.
ref – The ref or branch name to read data from.
columns – The columns to return (default:
None
).filters – The filters to apply (default:
None
).limit – The maximum number of rows to return (default:
None
).cache – Whether to enable or disable caching for the query.
connector – The connector type for the model (defaults to Bauplan). Allowed values are ‘snowflake’ and ‘dremio’.
connector_config_key – The key name if the SSM key is custom with the pattern bauplan/connectors/<connector_type>/<key>.
connector_config_uri – Full SSM uri if completely custom path, e.g. ssm://us-west-2/123456789012/baubau/dremio.
namespace – The Namespace to run the scan in. If not set, the scan will be run in the default namespace for your account.
debug – Whether to enable or disable debug mode for the query.
args – dict of arbitrary args to pass to the backend.
client_timeout – seconds to timeout; this also cancels the remote job execution.
- Returns:
The scan results as a
pyarrow.Table
.
- table_exists(table: str | Table, branch: str | Branch) bool
Check if a table exists.
Upon failure, raises
bauplan.exceptions.BauplanError
import bauplan client = bauplan.Client() assert client.table_exists('table_foo', 'main')
- Parameters:
branch – The branch to get the table from.
table – The table to retrieve.
- Returns:
A boolean for if the table exists.
- class bauplan.JobStatus(canceled: 'str' = 'CANCELLED', cancelled: 'str' = 'CANCELLED', failed: 'str' = 'FAILED', rejected: 'str' = 'REJECTED', success: 'str' = 'SUCCESS', timeout: 'str' = 'TIMEOUT', unknown: 'str' = 'UNKNOWN')
Bases:
object
- canceled: str = 'CANCELLED'
- cancelled: str = 'CANCELLED'
- failed: str = 'FAILED'
- rejected: str = 'REJECTED'
- success: str = 'SUCCESS'
- timeout: str = 'TIMEOUT'
- unknown: str = 'UNKNOWN'
- class bauplan.Model(name: str, columns: List[str] | None = None, filter: str | None = None, ref: str | None = None, connector: str | None = None, connector_config_key: str | None = None, connector_config_uri: str | None = None, **kwargs: Any)
Bases:
object
Represents a model (dataframe/table representing a DAG step) as an input to a function.
e.g.
@bauplan.model() def some_parent_model(): return pyarrow.Table.from_pydict({'bar': [1, 2, 3]}) @bauplan.model() def your_cool_model( # parent models are passed as inputs, using bauplan.Model # class parent_0=bauplan.Model( 'some_parent_model', columns=['bar'], filter='bar > 1', ) ): # Can return a pandas dataframe or a pyarrow table return pyarrow.Table.from_pandas( pd.DataFrame({ 'foo': parent_0['bar'] * 2, }) )
Bauplan can wrap other engines for the processing of some models, exposing a common interface and unified API for the user while dispatching the relevant operations to the underlying engine.
The authentication and authorization happens securely and transparently through ssm; the user is asked to specify a connector type and the credentials through the relevant keywords:
@bauplan.model() def your_cool_model( parent_0=bauplan.Model( 'some_parent_model', columns=['bar'], filter='bar > 1', connector='dremio', connector_config_key='bauplan', ) ): # parent_0 inside the function body # will still be an Arrow table: the user code # should still be the same as the data is moved # transparently by Bauplan from an engine to the function. return pyarrow.Table.from_pandas( pd.DataFrame({ 'foo': parent_0['bar'] * 2, }) )
- Parameters:
name – The name of the model.
columns – The list of columns in the model. If the arg is not provided, the model will load all columns.
filter – The optional filter for the model. Defaults to None.
ref – The optional reference to the model. Defaults to None.
connector – The connector type for the model (defaults to Bauplan SQL). Allowed values are ‘snowflake’ and ‘dremio’.
connector_config_key – The key name if the SSM key is custom with the pattern bauplan/connectors/<connector_type>/<key>.
connector_config_uri – Full SSM uri if completely custom path, e.g. ssm://us-west-2/123456789012/baubau/dremio.
- bauplan.expectation(**kwargs: Any) Callable
Decorator that defines a Bauplan expectation.
An expectation is a function from one (or more) dataframe-like object(s) to a boolean: it is commonly used to perform data validation and data quality checks when running a pipeline. Expectations takes as input the table(s) they are validating and return a boolean indicating whether the expectation is met or not. A Python expectation needs a Python environment to run, which is defined using the python decorator, e.g.:
@bauplan.expectation() @bauplan.python('3.10') def test_joined_dataset( data=bauplan.Model( 'join_dataset', columns=['anomaly'] ) ): # your data validation code here return expect_column_no_nulls(data, 'anomaly')
- Parameters:
f – The function to decorate.
- bauplan.model(name: str | None = None, columns: List[str] | None = None, materialize: bool | None = None, internet_access: bool | None = None, partitioned_by: str | List[str] | Tuple[str, ...] | None = None, materialization_strategy: Literal['NONE', 'REPLACE', 'APPEND'] | None = None, cache_strategy: Literal['NONE', 'DEFAULT'] | None = None, **kwargs: Any) Callable
Decorator that specifies a Bauplan model.
A model is a function from one (or more) dataframe-like object(s) to another dataframe-like object: it is used to define a transformation in a pipeline. Models are chained together implicitly by using them as inputs to their children. A Python model needs a Python environment to run, which is defined using the python decorator, e.g.:
@bauplan.model( columns=['*'], materialize=False ) @bauplan.python('3.11') def source_scan( data=bauplan.Model( 'iot_kaggle', columns=['*'], filter="motion='false'" ) ): # your code here return data
- Parameters:
name – the name of the model (e.g. ‘users’); if missing the function name is used.
columns – the columns of the output dataframe after the model runs (e.g. [‘id’, ‘name’, ‘email’]). Use [‘*’] as a wildcard.
materialize – whether the model should be materialized.
internet_access – whether the model requires internet access.
partitioned_by – the columns to partition the data by.
materialization_strategy – the materialization strategy to use.
cache_strategy – the cache strategy to use.
- bauplan.pyspark(version: str | None = None, conf: Dict[str, str] | None = None, **kwargs: Any) Callable
Decorator that makes a pyspark session available to a Bauplan function (a model or an expectation). Add a spark=None parameter to the function model args
- Parameters:
version – the version string of pyspark
conf – A dict containing the pyspark config
- bauplan.python(version: str | None = None, pip: Dict[str, str] | None = None, **kwargs: Any) Callable
Decorator that defines a Python environment for a Bauplan function (e.g. a model or expectation). It is used to specify directly in code the configuration of the Python environment required to run the function, i.e. the Python version and the Python packages required.
- Parameters:
version – The python version for the interpreter (e.g.
'3.11'
).pip – A dictionary of dependencies (and versions) required by the function (e.g.
{'requests': '2.26.0'}
).
- bauplan.resources(cpus: int | float | None = None, memory: int | str | None = None, memory_swap: int | str | None = None, timeout: int | None = None, **kwargs: Any) Callable
Decorator that defines the resources required by a Bauplan function (e.g. a model or expectation). It is used to specify directly in code the configuration of the resources required to run the function.
- Parameters:
cpus – The number of CPUs required by the function (e.g:
`0.5`
)memory – The amount of memory required by the function (e.g:
`1G`
,`1000`
)memory_swap – The amount of swap memory required by the function (e.g:
`1G`
,`1000`
)timeout – The maximum time the function is allowed to run (e.g:
`60`
)