Loading Data from Microsoft SQL Server
to Google Cloud Storage
with dlt
in Python
Join our Slack community or book a call with our support engineer Violetta.
Loading data from Microsoft SQL Server
to Google Cloud Storage
is a common task for building data lakes and leveraging cloud storage capabilities. Microsoft SQL Server
is a Relational Database Management System (RDBMS) developed by Microsoft, based on a Relational Model architecture. On the other hand, Google Cloud Storage
is a filesystem destination on the Google Cloud Platform that allows you to store data in various formats such as JSONL, Parquet, or CSV. Using the open-source Python library dlt
, you can efficiently transfer your data between these systems. More information about Microsoft SQL Server
can be found here.
dlt
Key Features
- Governance Support:
dlt
pipelines offer robust governance support through mechanisms like pipeline metadata utilization, schema enforcement and curation, and schema change alerts. Learn more about Governance Support. - Scaling and Finetuning:
dlt
provides several configuration options to scale up and finetune pipelines, including running extraction, normalization, and load in parallel. Read more about Scaling and Finetuning. - DuckDB Integration: Easily integrate with DuckDB to load data using large INSERT VALUES statements by default. Learn how to set up DuckDB Integration.
- Microsoft SQL Server Integration: Set up and load data to Microsoft SQL Server with comprehensive support for write dispositions and data loading methods. Check the Microsoft SQL Server Integration guide.
- Snowflake and Cloud Storage Staging: Use Snowflake with S3 or Google Cloud Storage as a staging destination for efficient data loading. Find out more about Snowflake and Cloud Storage Staging.
Getting started with your pipeline locally
0. Prerequisites
dlt
requires Python 3.8 or higher. Additionally, you need to have the pip
package manager installed, and we recommend using a virtual environment to manage your dependencies. You can learn more about preparing your computer for dlt in our installation reference.
1. Install dlt
First you need to install the dlt
library with the correct extras for Google Cloud Storage
:
pip install "dlt[filesystem]"
The dlt
cli has a useful command to get you started with any combination of source and destination. For this example, we want to load data from Microsoft SQL Server
to Google Cloud Storage
. You can run the following commands to create a starting point for loading data from Microsoft SQL Server
to Google Cloud Storage
:
# create a new directory
mkdir sql_database_mssql_pipeline
cd sql_database_mssql_pipeline
# initialize a new pipeline with your source and destination
dlt init sql_database filesystem
# install the required dependencies
pip install -r requirements.txt
The last command will install the required dependencies for your pipeline. The dependencies are listed in the requirements.txt
:
sqlalchemy>=1.4
dlt[filesystem]>=0.4.7
You now have the following folder structure in your project:
sql_database_mssql_pipeline/
├── .dlt/
│ ├── config.toml # configs for your pipeline
│ └── secrets.toml # secrets for your pipeline
├── sql_database/ # folder with source specific files
│ └── ...
├── sql_database_pipeline.py # your main pipeline script
├── requirements.txt # dependencies for your pipeline
└── .gitignore # ignore files for git (not required)
2. Configuring your source and destination credentials
The dlt
cli will have created a .dlt
directory in your project folder. This directory contains a config.toml
file and a secrets.toml
file that you can use to configure your pipeline. The automatically created version of these files look like this:
generated config.toml
# put your configuration values here
[runtime]
log_level="WARNING" # the system log level of dlt
# use the dlthub_telemetry setting to enable/disable anonymous usage data reporting, see https://dlthub.com/docs/telemetry
dlthub_telemetry = true
generated secrets.toml
# put your secret values and credentials here. do not share this file and do not push it to github
[sources.sql_database.credentials]
drivername = "drivername" # please set me up!
database = "database" # please set me up!
password = "password" # please set me up!
username = "username" # please set me up!
host = "host" # please set me up!
port = 0 # please set me up!
[destination.filesystem]
dataset_name = "dataset_name" # please set me up!
bucket_url = "bucket_url" # please set me up!
[destination.filesystem.credentials]
aws_access_key_id = "aws_access_key_id" # please set me up!
aws_secret_access_key = "aws_secret_access_key" # please set me up!
2.1. Adjust the generated code to your usecase
The default filesystem destination is configured to connect to AWS S3. To load to Google Cloud Storage, update the [destination.filesystem.credentials]
section in your secrets.toml
.
[destination.filesystem.credentials]
client_email="Please set me up!"
private_key="Please set me up!"
project_id="Please set me up!"
By default, the filesystem destination will store your files as JSONL
. You can tell your pipeline to choose a different format with the loader_file_format
property that you can set directly on the pipeline or via your config.toml
. Available values are jsonl
, parquet
and csv
:
[pipeline] # in ./dlt/config.toml
loader_file_format="parquet"
The default sql_database
pipeline is configured to connect to an example postgres database. The sql_database
source supports all sql dialects
supported by SQLAlchemy. Please refer to the MS SQL Server Section
of the SQLAlchemy docs for additional info about SQLAlchemy and MS SQL Server.
To connect to MS SQL Server with this example pipeline, you'll need to install an MS SQL Server Python DB API driver:
pip install pymssql
And use an MS SQL Server connection String in your code:
credentials = ConnectionStringCredentials(
"mssql+pymssql://username:password@host:1433/database"
)
Or your secrets.toml
:
[sources.sql_database.credentials]
drivername = "mssql+pymssql"
database = "database"
password = "password"
username = "username"
host = "host"
port = 1433
3. Running your pipeline for the first time
The dlt
cli has also created a main pipeline script for you at sql_database_pipeline.py
, as well as a folder sql_database
that contains additional python files for your source. These files are your local copies which you can modify to fit your needs. In some cases you may find that you only need to do small changes to your pipelines or add some configurations, in other cases these files can serve as a working starting point for your code, but will need to be adjusted to do what you need them to do.
The main pipeline script will look something like this:
import sqlalchemy as sa
import humanize
import dlt
from dlt.common import pendulum
from dlt.sources.credentials import ConnectionStringCredentials
from sql_database import sql_database, sql_table, Table
def load_select_tables_from_database() -> None:
"""Use the sql_database source to reflect an entire database schema and load select tables from it.
This example sources data from the public Rfam MySQL database.
"""
# Create a pipeline
pipeline = dlt.pipeline(
pipeline_name="rfam", destination='filesystem', dataset_name="rfam_data"
)
# Credentials for the sample database.
# Note: It is recommended to configure credentials in `.dlt/secrets.toml` under `sources.sql_database.credentials`
credentials = ConnectionStringCredentials(
"mysql+pymysql://rfamro@mysql-rfam-public.ebi.ac.uk:4497/Rfam"
)
# To pass the credentials from `secrets.toml`, comment out the above credentials.
# And the credentials will be automatically read from `secrets.toml`.
# Configure the source to load a few select tables incrementally
source_1 = sql_database(credentials).with_resources("family", "clan")
# Add incremental config to the resources. "updated" is a timestamp column in these tables that gets used as a cursor
source_1.family.apply_hints(incremental=dlt.sources.incremental("updated"))
source_1.clan.apply_hints(incremental=dlt.sources.incremental("updated"))
# Run the pipeline. The merge write disposition merges existing rows in the destination by primary key
info = pipeline.run(source_1, write_disposition="merge")
print(info)
# Load some other tables with replace write disposition. This overwrites the existing tables in destination
source_2 = sql_database(credentials).with_resources("features", "author")
info = pipeline.run(source_2, write_disposition="replace")
print(info)
# Load a table incrementally with append write disposition
# this is good when a table only has new rows inserted, but not updated
source_3 = sql_database(credentials).with_resources("genome")
source_3.genome.apply_hints(incremental=dlt.sources.incremental("created"))
info = pipeline.run(source_3, write_disposition="append")
print(info)
def load_entire_database() -> None:
"""Use the sql_database source to completely load all tables in a database"""
pipeline = dlt.pipeline(
pipeline_name="rfam", destination='filesystem', dataset_name="rfam_data"
)
# By default the sql_database source reflects all tables in the schema
# The database credentials are sourced from the `.dlt/secrets.toml` configuration
source = sql_database()
# Run the pipeline. For a large db this may take a while
info = pipeline.run(source, write_disposition="replace")
print(
humanize.precisedelta(
pipeline.last_trace.finished_at - pipeline.last_trace.started_at
)
)
print(info)
def load_standalone_table_resource() -> None:
"""Load a few known tables with the standalone sql_table resource, request full schema and deferred
table reflection"""
pipeline = dlt.pipeline(
pipeline_name="rfam_database",
destination='filesystem',
dataset_name="rfam_data",
full_refresh=True,
)
# Load a table incrementally starting at a given date
# Adding incremental via argument like this makes extraction more efficient
# as only rows newer than the start date are fetched from the table
# we also use `detect_precision_hints` to get detailed column schema
# and defer_table_reflect to reflect schema only during execution
family = sql_table(
credentials="mysql+pymysql://rfamro@mysql-rfam-public.ebi.ac.uk:4497/Rfam",
table="family",
incremental=dlt.sources.incremental(
"updated",
),
detect_precision_hints=True,
defer_table_reflect=True,
)
# columns will be empty here due to defer_table_reflect set to True
print(family.compute_table_schema())
# Load all data from another table
genome = sql_table(
credentials="mysql+pymysql://rfamro@mysql-rfam-public.ebi.ac.uk:4497/Rfam",
table="genome",
detect_precision_hints=True,
defer_table_reflect=True,
)
# Run the resources together
info = pipeline.extract([family, genome], write_disposition="merge")
print(info)
# Show inferred columns
print(pipeline.default_schema.to_pretty_yaml())
def select_columns() -> None:
"""Uses table adapter callback to modify list of columns to be selected"""
pipeline = dlt.pipeline(
pipeline_name="rfam_database",
destination='filesystem',
dataset_name="rfam_data_cols",
full_refresh=True,
)
def table_adapter(table: Table) -> None:
print(table.name)
if table.name == "family":
# this is SqlAlchemy table. _columns are writable
# let's drop updated column
table._columns.remove(table.columns["updated"])
family = sql_table(
credentials="mysql+pymysql://rfamro@mysql-rfam-public.ebi.ac.uk:4497/Rfam",
table="family",
chunk_size=10,
detect_precision_hints=True,
table_adapter_callback=table_adapter,
)
# also we do not want the whole table, so we add limit to get just one chunk (10 records)
pipeline.run(family.add_limit(1))
# only 10 rows
print(pipeline.last_trace.last_normalize_info)
# no "updated" column in "family" table
print(pipeline.default_schema.to_pretty_yaml())
def select_with_end_value_and_row_order() -> None:
"""Gets data from a table withing a specified range and sorts rows descending"""
pipeline = dlt.pipeline(
pipeline_name="rfam_database",
destination='filesystem',
dataset_name="rfam_data",
full_refresh=True,
)
# gets data from this range
start_date = pendulum.now().subtract(years=1)
end_date = pendulum.now()
family = sql_table(
credentials="mysql+pymysql://rfamro@mysql-rfam-public.ebi.ac.uk:4497/Rfam",
table="family",
incremental=dlt.sources.incremental( # declares desc row order
"updated", initial_value=start_date, end_value=end_date, row_order="desc"
),
chunk_size=10,
)
# also we do not want the whole table, so we add limit to get just one chunk (10 records)
pipeline.run(family.add_limit(1))
# only 10 rows
print(pipeline.last_trace.last_normalize_info)
def my_sql_via_pyarrow() -> None:
"""Uses pyarrow backend to load tables from mysql"""
# uncomment line below to get load_id into your data (slows pyarrow loading down)
# dlt.config["normalize.parquet_normalizer.add_dlt_load_id"] = True
# Create a pipeline
pipeline = dlt.pipeline(
pipeline_name="rfam_cx",
destination='filesystem',
dataset_name="rfam_data_arrow_4",
)
def _double_as_decimal_adapter(table: sa.Table) -> None:
"""Return double as double, not decimals"""
for column in table.columns.values():
if isinstance(column.type, sa.Double):
column.type.asdecimal = False
sql_alchemy_source = sql_database(
"mysql+pymysql://rfamro@mysql-rfam-public.ebi.ac.uk:4497/Rfam?&binary_prefix=true",
backend="pyarrow",
table_adapter_callback=_double_as_decimal_adapter,
).with_resources("family", "genome")
info = pipeline.run(sql_alchemy_source)
print(info)
def create_unsw_flow() -> None:
"""Uploads UNSW_Flow dataset to postgres via csv stream skipping dlt normalizer.
You need to download the dataset from https://github.com/rdpahalavan/nids-datasets
"""
from pyarrow.parquet import ParquetFile
# from dlt.destinations import postgres
# use those config to get 3x speedup on parallelism
# [sources.data_writer]
# file_max_bytes=3000000
# buffer_max_items=200000
# [normalize]
# workers=3
data_iter = ParquetFile("UNSW-NB15/Network-Flows/UNSW_Flow.parquet").iter_batches(
batch_size=128 * 1024
)
pipeline = dlt.pipeline(
pipeline_name="unsw_upload",
# destination=postgres("postgres://loader:loader@localhost:5432/dlt_data"),
destination='filesystem',
progress="log",
)
pipeline.run(
data_iter,
dataset_name="speed_test",
table_name="unsw_flow_7",
loader_file_format="csv",
)
def test_connectorx_speed() -> None:
"""Uses unsw_flow dataset (~2mln rows, 25+ columns) to test connectorx speed"""
import os
# from dlt.destinations import filesystem
unsw_table = sql_table(
"postgresql://loader:loader@localhost:5432/dlt_data",
"unsw_flow_7",
"speed_test",
# this is ignored by connectorx
chunk_size=100000,
backend="connectorx",
# keep source data types
detect_precision_hints=True,
# just to demonstrate how to setup a separate connection string for connectorx
backend_kwargs={"conn": "postgresql://loader:loader@localhost:5432/dlt_data"},
)
pipeline = dlt.pipeline(
pipeline_name="unsw_download",
destination='filesystem',
# destination=filesystem(os.path.abspath("../_storage/unsw")),
progress="log",
full_refresh=True,
)
info = pipeline.run(
unsw_table,
dataset_name="speed_test",
table_name="unsw_flow",
loader_file_format="parquet",
)
print(info)
def test_pandas_backend_verbatim_decimals() -> None:
pipeline = dlt.pipeline(
pipeline_name="rfam_cx",
destination='filesystem',
dataset_name="rfam_data_pandas_2",
)
def _double_as_decimal_adapter(table: sa.Table) -> None:
"""Emits decimals instead of floats."""
for column in table.columns.values():
if isinstance(column.type, sa.Float):
column.type.asdecimal = True
sql_alchemy_source = sql_database(
"mysql+pymysql://rfamro@mysql-rfam-public.ebi.ac.uk:4497/Rfam?&binary_prefix=true",
backend="pandas",
table_adapter_callback=_double_as_decimal_adapter,
chunk_size=100000,
# set coerce_float to False to represent them as string
backend_kwargs={"coerce_float": False, "dtype_backend": "numpy_nullable"},
# preserve full typing info. this will parse
detect_precision_hints=True,
).with_resources("family", "genome")
info = pipeline.run(sql_alchemy_source)
print(info)
if __name__ == "__main__":
# Load selected tables with different settings
load_select_tables_from_database()
# load a table and select columns
# select_columns()
# load_entire_database()
# select_with_end_value_and_row_order()
# Load tables with the standalone table resource
# load_standalone_table_resource()
# Load all tables from the database.
# Warning: The sample database is very large
# load_entire_database()
Provided you have set up your credentials, you can run your pipeline like a regular python script with the following command:
python sql_database_pipeline.py
4. Inspecting your load result
You can now inspect the state of your pipeline with the dlt
cli:
dlt pipeline sql_database info
You can also use streamlit to inspect the contents of your Google Cloud Storage
destination for this:
# install streamlit
pip install streamlit
# run the streamlit app for your pipeline with the dlt cli:
dlt pipeline sql_database show
5. Next steps to get your pipeline running in production
One of the beauties of dlt
is, that we are just a plain Python library, so you can run your pipeline in any environment that supports Python >= 3.8. We have a couple of helpers and guides in our docs to get you there:
The Deploy section will show you how to deploy your pipeline to
- Deploy with GitHub Actions: Use GitHub Actions to set up CI/CD for your
dlt
pipeline. Follow the guide to learn how to deploy your pipeline with GitHub Actions. - Deploy with Airflow and Google Composer: Learn how to deploy your
dlt
pipeline using Airflow and Google Composer by following this detailed guide. - Deploy with Google Cloud Functions: Set up your
dlt
pipeline to run on Google Cloud Functions by following the instructions here. - Explore Other Deployment Options: Discover various other methods to deploy your
dlt
pipeline by exploring the deployment walkthroughs.
The running in production section will teach you about:
- How to Monitor your pipeline: Learn how to effectively monitor your
dlt
pipeline in production to ensure smooth operation and quick troubleshooting. How to Monitor your pipeline - Set up alerts: Set up alerts to get notified of any issues or important events in your
dlt
pipeline, helping you to respond quickly and maintain reliability. Set up alerts - Set up tracing: Implement tracing to gain detailed insights into the execution of your
dlt
pipeline, making it easier to debug and optimize performance. Set up tracing
Additional pipeline guides
- Load data from Qualtrics to BigQuery in python with dlt
- Load data from MongoDB to CockroachDB in python with dlt
- Load data from Fivetran to DuckDB in python with dlt
- Load data from Cisco Meraki to Azure Cloud Storage in python with dlt
- Load data from Imgur to Azure Cosmos DB in python with dlt
- Load data from MongoDB to DuckDB in python with dlt
- Load data from Shopify to Azure Cloud Storage in python with dlt
- Load data from Google Cloud Storage to Neon Serverless Postgres in python with dlt
- Load data from Apple App-Store Connect to Azure Cloud Storage in python with dlt
- Load data from MySQL to PostgreSQL in python with dlt