Skip to content

Database rules

Database rules

Rules to read (extract) dataframes from SQL databases and write (load) them to SQL tables.

Importing the rules

The rules are implemented by each backend. Import them from the package of the backend you use, e.g. from etlrules.backends.pandas import ReadSQLQueryRule (or etlrules.backends.polars, etlrules.backends.dask, etlrules.backends.pyarrow). The arguments and the behaviour are the same in all the backends, unless stated otherwise.

ReadSQLQueryRule

Runs a SQL query and reads the results back into a dataframe.

Basic usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# reads all the data from a sqlite db called mydb.db, from the table MyTable
# saves the dataframe as the main output of the rule which subsequent rules can use as their main input
rule = ReadSQLQueryRule("sqlite:///mydb.db", "SELECT * FROM MyTable")
rule.apply(data)

# reads all the data from a sqlite db called mydb.db, from the table MyTable
# saves the dataframe as the a named output called MyData which subsequent rules can use by name
rule = ReadSQLQueryRule("sqlite:///mydb.db", "SELECT * FROM MyTable", named_output="MyData")
rule.apply(data)

# same as the first example, but uses column types rather than relying on type inferrence
rule = ReadSQLQueryRule("sqlite:///mydb.db", "SELECT * FROM MyTable", column_types={"ColA": "int64", "ColB": "string"})
rule.apply(data)

Parameters:

Name Type Description Default
sql_engine str

A sqlalchemy engine string. This is typically in the form: dialect+driver://username:password@host:port/database For more information, please refer to the sqlalchemy documentation here: https://docs.sqlalchemy.org/en/20/core/engines.html

In order to support users and passwords in the sql_engine string, substitutions of environment variables is supported using the {env.VARIABLE_NAME} form. For example, adding the USER and PASSWORD environment variables in the sql string could be done as: sql_engine = "postgres://{env.USER}:{env.PASSWORD}@{env.DB_HOST}/mydb In this example, when you run, env.USER, env.PASSWORD and env.DB_HOST will be replaced with the respective environment variables, allowing you to not hardcode them in the plan for security reasons but also for configurability. A similar substition can be achieved using the plan context using the context.property, e.g. sql_engine = "postgres://{context.USER}:{env.PASSWORD}@{context.DB_HOST}/mydb It's not recommended to store passwords in plain text in the plan.

required
sql_query str

A SQL SELECT statement that will specify the columns, table and optionally any WHERE, GROUP BY, ORDER BY clauses. The SQL statement must be valid for the SQL engine specified in the sql_engine parameter.

The env and context substitution work in the sql_query too. E.g.: SELECT * from {env.SCHEMA}.{context.TABLE_NAME} WHERE {context.FILTER} This allows you to parameterize the plan at run time.

required
column_types Optional[Mapping[str, str]]

A mapping of column names and their types. Column types are inferred from the data when this parameter is not specified. For empty result sets, this inferrence is not possible, so specifying the column types allows the users to control the types in that scenario and not fallback onto backends defaults.

None
batch_size int

An optional batch size (number of rows) to use when reading the results. Defaults: 50000. Some backends ignore this option, otherwise use it to partition the data.

50000
named_output Optional[str]

Give the output of this rule a name so it can be used by another rule as a named input. Optional. When not set, the result of this rule will be available as the main output. When set to a name (string), the result will be available as that named output.

None
name Optional[str]

Give the rule a name. Optional. Named rules are more descriptive as to what they're trying to do/the intent.

None
description Optional[str]

Describe in detail what the rules does, how it does it. Optional. Together with the name, the description acts as the documentation of the rule.

None
strict bool

When set to True, the rule does a stricter valiation. Default: True

True

Raises:

Type Description
SQLError

raised if there's an error running the sql statement.

UnsupportedTypeError

raised if column_types are specified and any of them are not supported.

Note

The implementation uses sqlalchemy, which must be installed as an optional dependency of etlrules.

WriteSQLTableRule

Writes the data from the input dataframe into a SQL table in a database.

The rule is a final rule, which means it produces no additional outputs, it takes any of the existing outputs and writes it to the DB. If the named_input is specified, the input with that name is written, otherwise, it takes the main output of the preceding rule.

Basic usage:

1
2
3
4
5
6
7
8
9
# writes the main input to a table called MyTable in a sqlite DB called mydb.db
# If the table already exists, it replaces it
rule = WriteSQLTableRule("sqlite:///mydb.db", "MyTable", if_exists="replace")
rule.apply(data)

# writes the dataframe input called 'input_data' to a table MyTable in a sqlite DB mydb.db
# If the table already exists, it appends the data to it
rule = WriteSQLTableRule("sqlite:///mydb.db", "MyTable", if_exists="append", named_input="input_data")
rule.apply(data)

Parameters:

Name Type Description Default
sql_engine str

A sqlalchemy engine string. This is typically in the form: dialect+driver://username:password@host:port/database For more information, please refer to the sqlalchemy documentation here: https://docs.sqlalchemy.org/en/20/core/engines.html

In order to support users and passwords in the sql_engine string, substitutions of environment variables is supported using the {env.VARIABLE_NAME} form. For example, adding the USER and PASSWORD environment variables in the sql string could be done as: sql_engine = "postgres://{env.USER}:{env.PASSWORD}@{env.DB_HOST}/mydb In this example, when you run, env.USER, env.PASSWORD and env.DB_HOST will be replaced with the respective environment variables, allowing you to not hardcode them in the plan for security reasons but also for configurability.

required
sql_table str

The name of the sql table to write to.

required
if_exists str

Specifies what to do in case the table already exists in the database. The options are: - replace: drops all the existing data and inserts the data in the input dataframe - append: adds the data in the input dataframe to the existing data in the table - fail: Raises a ValueError exception Default: fail.

'fail'
named_input Optional[str]

Select by name the dataframe to write from the input data. Optional. When not specified, the main output of the previous rule will be written.

None
name Optional[str]

Give the rule a name. Optional. Named rules are more descriptive as to what they're trying to do/the intent.

None
description Optional[str]

Describe in detail what the rules does, how it does it. Optional. Together with the name, the description acts as the documentation of the rule.

None
strict bool

When set to True, the rule does a stricter valiation. Default: True.

True

Raises:

Type Description
ValueError

raised if the table already exists when the if_exists is fail. ValueError is also raised if any of the arguments passed into the rule are not strings or empty strings.

SQLError

raised if there's any problem writing the data into the database. For example: If the schema doesn't match the schema of the table written to (for existing tables).