### Install Dependencies and Set Up Environment Source: https://motherduck.com/docs/cookbook/vercel-nextjs Installs project dependencies, copies the example environment file, and prompts to set the MotherDuck access token. Starts the development server. ```sh npm install cp .env.local.example .env.local # then set MOTHERDUCK_TOKEN npm run dev # http://localhost:3000 ``` -------------------------------- ### Install Dependencies and Run Local Server Source: https://motherduck.com/docs/cookbook/vercel-agent-analytics Installs project dependencies, sets environment variables for local development, and starts the local server. ```bash npm install export VERCEL_DRAIN_SECRET=dev-secret export MOTHERDUCK_TOKEN=... npm run dev # starts src/local-server.ts on :8787 ./scripts/test-local.sh # signs and POSTs scripts/sample-payload.ndjson ``` -------------------------------- ### Install Dependencies and Start Local Dev Server Source: https://motherduck.com/docs/cookbook/cloudflare-workers-duckoffee Installs project dependencies and starts the local development server for Cloudflare Workers. Ensure your MotherDuck token is set in `.dev.vars`. ```sh npm install # Local dev: put your token in .dev.vars, then start the dev server printf 'MOTHERDUCK_TOKEN="ey...MY_TOKEN"\n' > .dev.vars npx wrangler dev ``` -------------------------------- ### Local Development Setup Source: https://motherduck.com/docs/cookbook/cloudflare-workers Configures local development by placing the MotherDuck token in a .dev.vars file and starting the development server. ```sh # MOTHERDUCK_TOKEN="ey...MY_TOKEN" npx wrangler dev ``` -------------------------------- ### Setup Sample Data for Time Travel Source: https://motherduck.com/docs/key-tasks/database-operations/time-travel Creates a sample database 'shop_db' with 'customers' and 'orders' tables. Use this to follow along with time travel examples. ```sql CREATE DATABASE IF NOT EXISTS shop_db; USE shop_db; -- Customers table CREATE OR REPLACE TABLE customers AS SELECT * FROM (VALUES (1, 'Alice Johnson', 'alice@example.com', 'US-West', '2025-11-01'::DATE), (2, 'Bob Smith', 'bob@example.com', 'US-East', '2025-11-15'::DATE), (3, 'Carol Williams', 'carol@example.com', 'EU-West', '2025-12-01'::DATE) ) AS t(customer_id, name, email, region, created_at); -- Orders table CREATE OR REPLACE TABLE orders AS SELECT * FROM (VALUES (101, 1, 250.00, '2026-01-15'::DATE, 'completed'), (102, 2, 89.99, '2026-01-16'::DATE, 'completed'), (103, 3, 450.00, '2026-01-20'::DATE, 'completed'), (104, 1, 125.50, '2026-02-01'::DATE, 'completed'), (105, 2, 67.25, '2026-02-10'::DATE, 'completed'), (106, 3, 215.75, '2026-02-14'::DATE, 'pending'), (107, 1, 175.00, '2026-02-15'::DATE, 'pending') ) AS t(order_id, customer_id, amount, order_date, status); ``` -------------------------------- ### Setup and Run dbt Commands Source: https://motherduck.com/docs/cookbook/dbt-ai-prompt Installs dbt and DuckDB, sets the MotherDuck token, and runs dbt build and test commands. Ensure you have a MotherDuck account and a read/write MOTHERDUCK_TOKEN. ```sh uv venv --python 3.13 uv pip install dbt-duckdb duckdb==1.4.3 source .venv/bin/activate export MOTHERDUCK_TOKEN="your_token_here" dbt run dbt test dbt show --select reviews_attributes_by_product ``` -------------------------------- ### Setup MotherDuck Grafana Environment Source: https://motherduck.com/docs/cookbook/motherduck-grafana Set the MotherDuck token and run the setup script to launch Grafana with the MotherDuck datasource and example dashboards. Ensure Docker is running. ```bash export motherduck_token= cd motherduck-grafana ./setup.sh ``` -------------------------------- ### Get Dive Guide for ChatGPT Source: https://motherduck.com/docs/sql-reference/mcp/get-dive-guide Call get_dive_guide with the 'chatgpt' client to load instructions for building Dives using ChatGPT. ```json { "client": "chatgpt" } ``` -------------------------------- ### PostgreSQL Replication Setup and Chunked Insert Source: https://motherduck.com/docs/key-tasks/data-warehousing/replication/postgres This snippet demonstrates the initial setup for replicating data from PostgreSQL to MotherDuck. It includes installing and loading the PostgreSQL extension, setting client configuration parameters, attaching to the PostgreSQL source in read-only mode, creating a target table, and inserting data in chunks based on a date range. Tune `pg_connection_limit` and `pg_pages_per_task` based on source database performance. ```sql INSTALL postgres; LOAD postgres; SET threads = 4; SET memory_limit = '4GB'; SET pg_connection_limit = 4; SET pg_pages_per_task = 250; ATTACH 'dbname=postgres user=postgres host=127.0.0.1' AS pg_db (TYPE POSTGRES, READ_ONLY); ATTACH 'md:'; USE my_db; CREATE TABLE IF NOT EXISTS main.postgres_table AS SELECT * FROM pg_db.public.some_table WHERE 1 = 0; INSERT INTO main.postgres_table SELECT * FROM pg_db.public.some_table WHERE updated_at >= TIMESTAMP '2026-01-01' AND updated_at < TIMESTAMP '2026-02-01'; ``` -------------------------------- ### Install dlt and Initialize Salesforce Pipeline Source: https://motherduck.com/docs/integrations/ingestion/salesforce Installs the dlt library with MotherDuck support, creates a new pipeline directory, initializes a Salesforce to MotherDuck pipeline, installs dependencies, and runs the pipeline script. ```bash pip install "dlt[motherduck]" mkdir salesforce_pipeline cd salesforce_pipeline dlt init salesforce motherduck pip install -r requirements.txt python salesforce_pipeline.py ``` -------------------------------- ### Install psycopg with Pool Support Source: https://motherduck.com/docs/getting-started/interfaces/client-apis/python/postgres-endpoint Install the psycopg library with the necessary dependencies for connection pooling. ```bash pip install "psycopg[pool]" ``` -------------------------------- ### Install Dependencies and Deploy to Vercel Source: https://motherduck.com/docs/cookbook/vercel-agent-analytics Installs project dependencies and deploys the function to Vercel, printing the deployment URL. ```bash npm install vercel # deploy; prints https://.vercel.app/api/drain ``` -------------------------------- ### Install Dependencies with uv Source: https://motherduck.com/docs/cookbook/dbt-metricflow Installs dbt-core, dbt-duckdb, and dbt-metricflow using uv. Ensure you are in the dbt-metricflow directory. ```bash cd dbt-metricflow uv venv uv pip install -r requirements.txt ``` -------------------------------- ### Install dbt-duckdb with uv Source: https://motherduck.com/docs/cookbook/dbt-dual-execution Installs the dbt-duckdb package into a managed virtual environment using uv. ```bash uv sync ``` -------------------------------- ### Install SQLAlchemy and psycopg Source: https://motherduck.com/docs/integrations/language-apis-and-drivers/python/sqlalchemy Install the required Python libraries for SQLAlchemy and PostgreSQL connectivity. Ensure you have the latest versions. ```bash pip install --upgrade sqlalchemy psycopg ``` -------------------------------- ### Example: Creating and Managing Databases Source: https://motherduck.com/docs/key-tasks/database-operations/basics-operations This example demonstrates creating tables in different databases, showing the databases, and verifying table contents. ```sql > SHOW DATABASES; test01 -- Let's put two different t1 tables into into two different databases > CREATE TABLE dbname.t1 AS (SELECT range AS r FROM range(12)); > SELECT * FROM t1; -- now for the other database > CREATE DATABASE test02; > CREATE TABLE test02.t1 AS (SELECT 'test02' AS dbname) -- show the databases we've created > SHOW DATABASES; test01 test02 ``` -------------------------------- ### Feel Specification Example Source: https://motherduck.com/docs/key-tasks/ai-and-motherduck/dives/theming-and-styling-dives Example of providing a one-line mood descriptor to guide the overall aesthetic of a Dive. ```text Feel: Midnight studio — data glowing in the dark ``` -------------------------------- ### Example Dockerfile for Tableau Bridge with MotherDuck Source: https://motherduck.com/docs/integrations/bi-tools/tableau/tableau-bridge This Dockerfile installs Tableau Bridge, downloads the DuckDB JDBC driver and MotherDuck connector taco file, and sets up environment variables for Bridge configuration. It's a starting point and may require adjustments for specific environments or software versions. ```dockerfile FROM registry.access.redhat.com/ubi8/ubi:latest RUN yum update -y RUN yum install -y glibc-langpack-en # This is the latest version of Tableau Bridge that is known working with the Motherloid connector RUN curl -o /tmp/TableauBridge.rpm -L \ https://downloads.tableau.com/tssoftware/TableauBridge-20243.25.0114.1153.x86_64.rpm && \ ACCEPT_EULA=y yum install -y /tmp/TableauBridge.rpm && \ rm /tmp/TableauBridge.rpm # Drivers RUN mkdir -p /opt/tableau/tableau_driver/jdbc # Connectors (tacos) RUN mkdir -p /root/Documents/My_Tableau_Bridge_Repository/Connectors # Download DuckDB JDBC driver and signed taco RUN curl -o /opt/tableau/tableau_driver/jdbc/duckdb_jdbc-1.3.0.0.jar \ -L https://repo1.maven.org/maven2/org/duckdb/duckdb_jdbc/1.3.0.0/duckdb_jdbc-1.3.0.0.jar && \ curl -o /root/Documents/My_Tableau_Bridge_Repository/Connectors/duckdb_jdbc-v1.1.1-signed.taco \ -L https://github.com/motherduckdb/duckdb-tableau-connector/releases/download/v1.1.1/duckdb_jdbc-v1.1.1-signed.taco ENV TZ=Europe/Berlin ENV LC_ALL=en_US.UTF-8 # ----- user specific settings ----- ENV USER_EMAIL="" ENV PAT_ID=BridgeToken ENV CLIENT_NAME="" ENV SITE_NAME="" ENV POOL_ID="" # ----------------------------------- CMD /opt/tableau/tableau_bridge/bin/run-bridge.sh -e \ --patTokenId=$PAT_ID \ --userEmail=$USER_EMAIL \ --client=$CLIENT_NAME \ --site=$SITE_NAME \ --patTokenFile="/home/documents/token.txt" \ --poolId=$POOL_ID ``` -------------------------------- ### Initial dbt Project Setup and Build Source: https://motherduck.com/docs/cookbook/dbt-duckdb-dwh-starter This snippet shows the initial steps to set up and build the dbt project. It includes syncing dependencies, setting the MotherDuck token, and running dbt debug, parse, and build commands. ```sh uv sync export MOTHERDUCK_TOKEN="..." # Validate, then build the warehouse (dev target by default) uv run dbt debug --profiles-dir . uv run dbt parse --profiles-dir . uv run dbt build --profiles-dir . ``` -------------------------------- ### Create Table and Index Example Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/create-index Demonstrates creating a table, inserting data, and then creating an index on the 'id' column for faster lookups. ```sql -- Create a table and an index CREATE TABLE users (id INTEGER, name VARCHAR); INSERT INTO users VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie'); CREATE INDEX idx_user_id ON users(id); -- Point lookup uses the index SELECT * FROM users WHERE id = 1; ``` -------------------------------- ### Get Flight Guide Output Schema Source: https://motherduck.com/docs/sql-reference/mcp/get-flight-guide This is the expected output schema when calling the get_flight_guide tool. It indicates success and returns the guide content in Markdown format. ```json { "success": boolean, "guide": string // Markdown content of the guide } ``` -------------------------------- ### Install Dependencies and Set Up Environment Source: https://motherduck.com/docs/cookbook/nodejs-motherduck Install Node.js dependencies and configure your MotherDuck access token and database name by copying and editing the .env file. ```bash npm install cp .env.template .env # Edit .env: set MOTHERDUCK_TOKEN, optionally MOTHERDUCK_DATABASE ``` -------------------------------- ### Get Dive Guide for Other Clients Source: https://motherduck.com/docs/sql-reference/mcp/get-dive-guide Call get_dive_guide with the 'other' client for any other AI client or custom integration. ```json { "client": "other" } ``` -------------------------------- ### Example: Create, Query, and Show Results Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/result Illustrates a complete workflow: creating a result set from a SELECT query, querying its limited output, and then displaying all active results. ```sql CREATE RESULT top_urls AS SELECT url, count(*) AS requests FROM pypi_downloads GROUP BY url; FROM top_urls LIMIT 10; SHOW ALL RESULTS; ``` -------------------------------- ### Access Stats Endpoint Locally Source: https://motherduck.com/docs/key-tasks/authenticating-and-connecting-to-motherduck/postgres-endpoint/cloudflare-workers Example of accessing the stats endpoint with start and end dates for local testing. ```text http://localhost:8787/stats?start=2022-11-01&end=2022-12-01 ``` -------------------------------- ### Starter Dive Queries for MotherDuck Source: https://motherduck.com/docs/cookbook/vercel-agent-analytics Example SQL queries provided as starter tiles for MotherDuck Dive, useful for analyzing the collected logs. ```sql -- sql/02_dive_queries.sql -- Total requests over time SELECT date_trunc('hour', "timestamp") AS hour, count(*) AS requests FROM "MotherDuck"."." GROUP BY 1 ORDER BY 1; -- Top user agents SELECT "user_agent", count(*) AS requests FROM "MotherDuck"."." GROUP BY 1 ORDER BY 2 DESC LIMIT 10; -- AI requests breakdown SELECT "user_agent", count(*) AS requests FROM "MotherDuck"."ai_requests" GROUP BY 1 ORDER BY 2 DESC LIMIT 10; ``` -------------------------------- ### Get Dive Guide for Claude Source: https://motherduck.com/docs/sql-reference/mcp/get-dive-guide Call get_dive_guide with the 'claude' client to load instructions for building Dives using Claude. ```json { "client": "claude" } ``` -------------------------------- ### Example: Drop and Undrop Database Source: https://motherduck.com/docs/concepts/data-recovery This example demonstrates the process of dropping a database and then recovering it using the UNDROP command. Ensure you are not on the database you intend to drop. ```sql -- You cannot drop the currently active database USE some_other_db; DROP DATABASE recovery_demo; UNDROP DATABASE recovery_demo; ``` -------------------------------- ### Install Dependencies and Load Data Source: https://motherduck.com/docs/cookbook/sqlmesh-demo Installs dlt, sqlmesh, and yfinance using uv, then loads raw stock data into MotherDuck via a Python script. ```bash # from sqlmesh-demo/ uv sync # create the venv and install dlt + sqlmesh + yfinance # point dlt at MotherDuck (token goes in .dlt/secrets.toml; see dlt docs link below) # then load the raw stock data into MotherDuck: uv run python load/stock_data_pipeline.py ``` -------------------------------- ### Get Dive Guide for Claude Code Source: https://motherduck.com/docs/sql-reference/mcp/get-dive-guide Call get_dive_guide with the 'claude_code' client to load instructions for building Dives using Claude Code. ```json { "client": "claude_code" } ``` -------------------------------- ### MotherDuck Table Setup SQL Source: https://motherduck.com/docs/cookbook/vercel-agent-analytics Reference DDL for creating the MotherDuck table and an `ai_requests` view. The function runs these statements on cold start. ```sql -- sql/01_setup.sql CREATE TABLE IF NOT EXISTS "MotherDuck"."." ( "timestamp" TIMESTAMP, "raw_payload" JSON, "anonymized_ip" VARCHAR, "user_agent" VARCHAR, -- Add other relevant fields here "request_path" VARCHAR, "status_code" INTEGER ); CREATE OR REPLACE VIEW "MotherDuck"."ai_requests" AS SELECT "timestamp", "raw_payload", "anonymized_ip", "user_agent", "request_path", "status_code" FROM "MotherDuck"."." WHERE ("user_agent" ILIKE '%GPT%' OR "user_agent" ILIKE '%ChatGPT%' OR "user_agent" ILIKE '%Claude%' OR "user_agent" ILIKE '%Bard%'); ``` -------------------------------- ### Get Full Flight Version History Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-list-flight-versions Use this example to retrieve all historical versions of a Flight, including source code and requirements. Replace '' with the actual identifier of your Flight. ```sql SELECT flight_version, source_code, requirements_txt FROM MD_LIST_FLIGHT_VERSIONS(flight_id := ''); ``` -------------------------------- ### Run Connection Pool Example with Concurrent Queries Source: https://motherduck.com/docs/cookbook/nodejs-motherduck Execute the connection pool example to demonstrate concurrent query execution and connection management with MotherDuck. ```bash npm run pool ``` -------------------------------- ### Example: Batch Job and Immediate Shutdown Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/shutdown-terminate This example demonstrates running a batch job and then immediately shutting down the Duckling using `SHUTDOWN` to minimize costs by avoiding the default cooldown period. The billing is based on actual query time plus a 1-minute minimum. ```sql -- Run your batch job CREATE TABLE my_db.results AS SELECT * FROM my_db.raw_events WHERE event_date >= '2025-01-01' GROUP BY ALL; -- Shut down the Duckling immediately (billed for 1 min minimum) SHUTDOWN; ``` -------------------------------- ### Run DLT Pipeline with uv Source: https://motherduck.com/docs/cookbook/dlt-db-replication Execute the dlt pipeline using `uv run` to create the environment, install dependencies, and run the Python script. This is the recommended way to start the replication process. ```bash uv run sql_database_pipeline.py ``` -------------------------------- ### Drop, Undrop, and Attach a MotherDuck Database Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/undrop-database This example demonstrates the process of dropping a database, then undropping it, and finally attaching it to the current session. ```sql DROP DATABASE test_db; UNDROP DATABASE test_db; ATTACH 'md:test_db'; ``` -------------------------------- ### Example Usage of get_flight_guide Source: https://motherduck.com/docs/sql-reference/mcp/get-flight-guide When a user requests Flight-related actions, call get_flight_guide first to retrieve necessary documentation before proceeding with other Flight tools like create_flight. ```text Create a Flight that ingests Postgres data into MotherDuck hourly. ``` -------------------------------- ### Run pg_duckdb Docker Container Source: https://motherduck.com/docs/integrations/transformation/dbt-cloud This command starts a PostgreSQL proxy with pg_duckdb installed, configured to connect to MotherDuck using environment variables for credentials. It maps the default PostgreSQL port and mounts a volume for persistent data. ```bash docker run -d \ --name pgduckdb \ -p 5432:5432 \ -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \ -e MOTHERDUCK_TOKEN="$MOTHERDUCK_TOKEN" \ -v ~/pgduckdb_data_v17:/var/lib/postgresql/data \ --restart unless-stopped \ --memory=12288m \ pgduckdb/pgduckdb:17-main ``` -------------------------------- ### Display Setup Completion and Connection Information Source: https://motherduck.com/docs/integrations/transformation/dbt-cloud Confirms the setup is complete, shows the PostgreSQL container status, and provides connection details and useful commands for managing the PostgreSQL instance. ```bash # Final status check echo "=== Setup Complete ===" echo "PostgreSQL with DuckDB is now running." echo "Container status:" sudo docker ps -a -f name=pgduckdb echo -e "\n=== Connection Information ===" echo "Host: localhost" echo "Port: 5432" echo "User: postgres" echo "Password: [The password you provided]" echo "Database: postgres" echo -e "\n=== Useful Commands ===" echo "Monitor status: ./monitor_pg.sh" echo "Start after reboot: ./start_pg.sh" echo "Connect to PostgreSQL: docker exec -it pgduckdb psql -U postgres" echo "View logs: docker logs pgduckdb" echo -e "\n=== Note ===" echo "You may need to log out and log back in for the docker group changes to take effect." echo "After that, you can run docker commands without sudo." ``` -------------------------------- ### Get Flight Version via Run Number Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-get-flight-version Fetches the source code and requirements text for a flight version identified by a run number. This example first finds the correct flight version using MD_LIST_FLIGHT_RUNS and then retrieves the version details. ```sql WITH r AS ( SELECT flight_version FROM MD_LIST_FLIGHT_RUNS(flight_id := '') WHERE run_number = ) SELECT v.source_code, v.requirements_txt FROM r, MD_GET_FLIGHT_VERSION(flight_id := '', version_number := r.flight_version) v; ``` -------------------------------- ### Connect to MotherDuck and Query Databases Source: https://motherduck.com/docs/integrations/language-apis-and-drivers/r Load the MotherDuck extension, attach to MotherDuck databases, and execute a query to show available databases. This example connects to all databases by default. ```r library("DBI") con <- dbConnect(duckdb::duckdb()) dbExecute(con, "INSTALL 'motherduck'") dbExecute(con, "LOAD 'motherduck'") dbExecute(con, "ATTACH 'md:'") dbExecute(con, "USE my_db") res <- dbGetQuery(con, "SHOW DATABASES") print(res) ``` -------------------------------- ### PROMPT_SQL with Column Regex Patterns Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-sql Use the include_tables parameter with column regex patterns to include columns matching specific patterns within a table. This example includes columns starting with 'cust_' and an exact column 'order_id' from the 'transactions' table. ```sql CALL prompt_sql('Find all transactions with customer IDs and order details.', include_tables={'transactions': ['cust_.*', 'order_id']}); ``` -------------------------------- ### get_dive_guide Source: https://motherduck.com/docs/sql-reference/mcp Loads instructions for creating MotherDuck Dives. ```APIDOC ## get_dive_guide ### Description Load instructions for creating MotherDuck Dives. ### Method GET ### Endpoint /sql-reference/mcp/get-dive-guide ``` -------------------------------- ### Loading PyArrow Table Data in Chunks to MotherDuck Source: https://motherduck.com/docs/key-tasks/loading-data-into-motherduck/loading-data-md-python This example demonstrates how to use the `ArrowTableLoadingBuffer` class to load a PyArrow table into MotherDuck. It shows the setup for PyArrow schema, sample data, DuckDB schema definition, and initializing the loader with MotherDuck as the destination. ```python import pyarrow as pa # Define the explicit PyArrow schema pyarrow_schema = pa.schema([ ('id', pa.int32()), ('name', pa.string()) ]) # Sample data to create a PyArrow table based on the schema data = { 'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'] } arrow_table = pa.table(data, schema=pyarrow_schema) # Define the DuckDB schema as a DDL statement duckdb_schema = "CREATE TABLE IF NOT EXISTS my_table (id INTEGER, name VARCHAR)" # Initialize the loading buffer loader = ArrowTableLoadingBuffer( duckdb_schema=duckdb_schema, pyarrow_schema=pyarrow_schema, database_name="my_db", # The DuckDB database filename or MotherDuck database name table_name="my_table", # The name of the table in DuckDB or MotherDuck destination="md", # Set "md" for MotherDuck or "local" for a local DuckDB database chunk_size=2 # Example chunk size for illustration ) # Load the data loader.insert(arrow_table) ``` -------------------------------- ### Create and Use a Connection Pool Source: https://motherduck.com/docs/getting-started/interfaces/client-apis/python/postgres-endpoint Demonstrates creating a connection pool with specific configurations for size, timeouts, and connection lifetime, and then using it to execute a query. ```python import os from psycopg_pool import ConnectionPool pool = ConnectionPool( conninfo=( "host=pg.us-east-1-aws.motherduck.com " "port=5432 " "dbname=md: " "user=postgres " "sslmode=verify-full " "sslrootcert=system" ), kwargs={"password": os.environ["MOTHERDUCK_TOKEN"]}, min_size=0, max_size=10, timeout=5, max_idle=30, max_lifetime=300, ) with pool.connection() as conn: with conn.cursor() as cur: cur.execute( "SELECT title, score FROM sample_data.hn.hacker_news WHERE type='story' LIMIT 10" ) print(cur.fetchall()) ``` -------------------------------- ### Install and Load BigQuery Extension Source: https://motherduck.com/docs/integrations/databases/bigquery Installs and loads the duckdb-bigquery community extension. Ensure you have DuckDB installed. ```sql INSTALL bigquery FROM community; LOAD bigquery; ``` -------------------------------- ### Create and Restore Database to a Named Snapshot Source: https://motherduck.com/docs/concepts/data-recovery Demonstrates creating a database, taking multiple named snapshots, simulating data loss, and then restoring the database to a specific named snapshot. ```sql CREATE DATABASE example_db; USE example_db; CREATE TABLE one AS SELECT 1; CREATE SNAPSHOT one OF example_db; CREATE TABLE two AS SELECT 2; CREATE SNAPSHOT two OF example_db; CREATE TABLE three AS SELECT 3; CREATE SNAPSHOT three OF example_db; -- Accidentally drop data! DROP TABLE two; -- Restore a previous snapshot of the DB and check it's what you want CREATE DATABASE example_restore FROM example_db (SNAPSHOT_NAME 'three'); -- The snapshot looks correct! SELECT * FROM example_restore.two; -- Restore the database to the old valid snapshot ALTER DATABASE example_db SET SNAPSHOT TO (SNAPSHOT_NAME 'three'); -- We have successfully restored our data! SELECT * FROM two; ``` -------------------------------- ### Install dbt for DuckDB Transformations Source: https://motherduck.com/docs/key-tasks/flights/packages-and-runtime Install the dbt-duckdb adapter for running transformations on MotherDuck data. Ensure duckdb is also installed. ```bash duckdb==1.5.3 dbt-duckdb==1.10.1 ``` -------------------------------- ### Install dbt and DuckDB Source: https://motherduck.com/docs/integrations/transformation/dbt Install dbt and the dbt-duckdb adapter using pip. This command installs both the dbt core library and the necessary DuckDB adapter. ```bash pip3 install dbt-duckdb ``` -------------------------------- ### Run Basic MotherDuck Query Walkthrough Source: https://motherduck.com/docs/cookbook/nodejs-motherduck Execute the basic query example to interact with MotherDuck using Node.js. ```bash npm run basic ``` -------------------------------- ### Create PostgreSQL Startup Script Source: https://motherduck.com/docs/integrations/transformation/dbt-cloud Creates a bash script to start the PostgreSQL container and display its status. ```bash # Create startup script echo "Creating startup script..." cat > ~/start_pg.sh << 'EOF' #!/bin/bash echo "Starting PostgreSQL container..." docker start pgduckdb echo "Container status:" docker ps -a -f name=pgduckdb EOF chmod +x ~/start_pg.sh ``` -------------------------------- ### Install Drizzle and pg Packages Source: https://motherduck.com/docs/key-tasks/authenticating-and-connecting-to-motherduck/postgres-endpoint/drizzle Install the necessary Drizzle ORM packages and the `pg` driver for Node.js. Also, install the TypeScript types for `pg` if you are using TypeScript. ```bash npm install drizzle-orm pg ``` ```bash npm install --save-dev @types/pg ``` -------------------------------- ### Install Marimo with SQL Support Source: https://motherduck.com/docs/integrations/data-science-ai/marimo Install Marimo with SQL support using pip. This command installs the necessary packages to enable SQL functionality within Marimo notebooks. ```bash pip install "marimo[sql]" ``` -------------------------------- ### Install and Load Postgres Extension Source: https://motherduck.com/docs/integrations/databases/planetscale Installs and loads the Postgres extension in DuckDB. Then, it attaches a PlanetScale database using a connection string. ```sql INSTALL postgres; LOAD postgres; ATTACH '' AS postgres_db (TYPE postgres); ``` -------------------------------- ### Create Table with Sample Currency Data Source: https://motherduck.com/docs/getting-started/e2e-tutorial/part-3 Populates the 'docs_playground' database with sample currency exchange rate data. This is a prerequisite for sharing the dataset. ```sql CREATE TABLE docs_playground.currency_rates AS SELECT 'USD' as currency_code, 'US Dollar' as currency_name, 1.0 as rate_to_usd, '2024-01-15' as rate_date UNION ALL SELECT 'EUR', 'Euro', 0.85, '2024-01-15' UNION ALL SELECT 'GBP', 'British Pound', 0.75, '2024-01-15' UNION ALL SELECT 'JPY', 'Japanese Yen', 110.0, '2024-01-15'; ``` -------------------------------- ### Install Dependencies Source: https://motherduck.com/docs/cookbook/cloudflare-workers Installs the necessary Node.js packages for your Cloudflare Worker project. ```sh npm install ``` -------------------------------- ### Attach Sample Data Database Source: https://motherduck.com/docs/getting-started/sample-data-queries/datasets Use this SQL command to attach the sample_data database. Replace the share URL with the one corresponding to your Organization's cloud region. ```sql ATTACH 'md:_share/sample_data/cec44d04-1b52-425d-9bcb-9be943d4c7b8' AS sample_data; ```