8000 GitHub - openivm/openivm: Incremental View Maintenance on DuckDB · GitHub
[go: up one dir, main page]

Skip to content
openivmPublic

About

Incremental View Maintenance on DuckDB

Topics

Resources

Stars

129 stars

Watchers

2 watching

Forks

Repository files navigation

OpenIVM

A DuckDB extension for incremental view maintenance (IVM). Define materialized views in SQL, compose them into pipelines, and refresh supported queries incrementally.

Based on the OpenIVM paper (SIGMOD 2024).

Quick start

This is the first release of OpenIVM, under the MIT license. We have extensively tested and benchmarked it. We're still learning how OpenIVM behaves on production workloads, but if you’d like to try it on one of your pipelines and have any question or problem, feel free to email me at ilaria@cwi.nl. We aim to publish a bug-fix release by the end of 2026; in the meantime, issues and feature requests are welcome.

Install and load OpenIVM in DuckDB v2.0.1. You can also build OpenIVM yourself by following the source build guide.

INSTALL openivm FROM community;
LOAD openivm;

Run the following SQL in the DuckDB prompt.

-- Create a base table and a materialized view
CREATE TABLE sales (region VARCHAR, product VARCHAR, amount INT);
INSERT INTO sales VALUES ('US', 'Widget', 100), ('EU', 'Gadget', 200);

CREATE MATERIALIZED VIEW regional_totals AS
    SELECT region, SUM(amount) AS total, COUNT(*) AS cnt
    FROM sales
    GROUP BY region;

-- Insert new data
INSERT INTO sales VALUES ('US', 'Bolt', 50), ('JP', 'Gear', 300);

-- Refresh the view after the insert
PRAGMA refresh('regional_totals');

SELECT * FROM regional_totals ORDER BY region;
-- EU  | 200 | 1
-- JP  | 300 | 1
-- US  | 150 | 2

Run these statements at the prompt, from a SQL file, or in one multi-statement DuckDB client call. DuckDB executes the preceding CREATE MATERIALIZED VIEW and INSERT before it expands PRAGMA refresh.

For native DuckDB source tables, use connections with OpenIVM loaded for inserts, updates, and deletes so it can capture the changes. See the build and setup guide.

Base table schema changes (ADD, DROP, RENAME COLUMN) are propagated by OpenIVM. Delta tables are synced, referenced renames update MV metadata, and referenced drops are blocked with an error. See schema evolution.

Data pipelines and DuckLake

Materialized views can be stacked into pipelines, including over DuckLake tables. DuckLake's snapshot-based time travel enables delta computation through native change tracking, avoiding storage duplication. See DuckLake IVM integration.

INSTALL ducklake;
LOAD ducklake;
ATTACH ':memory:' AS dl (TYPE ducklake);

CREATE TABLE dl.orders (id INT, product VARCHAR, region VARCHAR, amount INT);
INSERT INTO dl.orders VALUES (1, 'Widget', 'US', 500), (2, 'Gadget', 'EU', 200), (3, 'Widget', 'EU', 800);

-- REFRESH EVERY schedules refreshes through a background daemon.
-- First materialized view groups orders by product.
CREATE MATERIALIZED VIEW dl.product_totals REFRESH EVERY '5 minutes' AS
    SELECT product, SUM(amount) AS total, COUNT(*) AS cnt FROM dl.orders GROUP BY product;

-- Second MV: built on top of the first
CREATE MATERIALIZED VIEW dl.top_products REFRESH EVERY '10 minutes' AS
    SELECT product, total FROM dl.product_totals WHERE total > 1000;

-- Cascade modes (controls automatic refresh propagation):
SET openivm_cascade_refresh = 'downstream';  -- default: refreshing product_totals also refreshes top_products
SET openivm_cascade_refresh = 'upstream';    -- refreshing top_products first refreshes product_totals
SET openivm_cascade_refresh = 'both';        -- refresh in both directions
SET openivm_cascade_refresh = 'off';         -- no cascade, each view refreshes independently

Scheduled refreshes run while the DuckDB database is open. OpenIVM may support trigger-based refresh in the future. DuckLake currently lacks table triggers. See automatic refresh.

Note: without cascading refresh, views refreshing independently may see stale upstream data — results are consistent but not fresh until the next ordered refresh. See pipelines.

SQL syntax

CREATE [OR REPLACE] MATERIALIZED VIEW [catalog.][schema.]name
    [REFRESH EVERY '<interval>']
    AS <query>;

ALTER MATERIALIZED VIEW [catalog.][schema.]name
    SET REFRESH EVERY '<interval>';

ALTER MATERIALIZED VIEW [catalog.][schema.]name
    SET REFRESH MANUAL;

DROP MATERIALIZED VIEW [IF EXISTS] [catalog.][schema.]name
    [CASCADE];

DROP MATERIALIZED VIEW aliases DROP VIEW. Both remove the view, its internal tables, and its metadata. See parser syntax and limitations for details.

Performance

In our TPC-DI SF100 benchmark, dbt batches with 1% and 0.01% inserts ran 2.9× and 3.0× faster, respectively, than with DuckDB full refresh. Creating a materialized view adds some upfront cost to set up change tracking, record metadata, and populate hidden columns used during refresh.

Incremental refresh is especially useful when each batch changes a small fraction of a large dataset. We regularly benchmark OpenIVM across TPC-DI, AI-generated queries, and production-like workloads. Explore the benchmark results.

Supported operators

Many query shapes that cannot be maintained incrementally use full refresh. See limitations for unsupported cases.

Operator Strategy Documentation
SELECT ... FROM, WHERE, expressions Incremental Projection & filter
GROUP BY + SUM, COUNT, AVG Incremental Grouped aggregates
STDDEV, VARIANCE (all variants) Incremental Grouped aggregates
MIN, MAX Incremental (insert-only) / group-recompute Grouped aggregates
HAVING Incremental Grouped aggregates
Ungrouped aggregates Incremental Ungrouped aggregates
INNER JOIN, CROSS JOIN, arbitrary join predicates Incremental Inner join
LEFT JOIN, RIGHT JOIN Incremental Left join
FULL OUTER JOIN Incremental (MERGE + recompute) Full outer join
SEMI JOIN, ANTI JOIN, EXISTS, NOT EXISTS Aux-state incremental for supported projection shapes Semi & anti join
UNION ALL Incremental Union all
DISTINCT Incremental Distinct
ORDER BY ... LIMIT k (top-k) Incremental, with top-k selected at publication Top-k
Window functions (ROW_NUMBER, RANK, etc.) Partition-level recompute Window functions
LIST aggregates Incremental List aggregates
WITH (CTEs), decorrelated subqueries, scalar correlated subqueries Incremental when the lowered plan uses supported operators; scalar SINGLE delim shapes use affected-key recompute CTEs & subqueries

Settings

Setting Type Default Description Documentation
openivm_cascade_refresh VARCHAR downstream Cascade mode: off, upstream, downstream, both Pipelines
openivm_refresh_mode VARCHAR incremental full forces full recompute; incremental (or auto) uses the strategy chosen at creation Refresh strategies
openivm_disable_daemon BOOLEAN false Do not start the background refresh daemon at extension load; set later, the daemon skips its cycles Automatic refresh
openivm_daemon_wake_seconds BIGINT 30 Seconds between the refresh daemon's checks for due views Automatic refresh
openivm_profile_refresh BOOLEAN false Record per-step refresh timings in openivm_refresh_profile Automatic refresh
openivm_profile_retention_days BIGINT 31 Delete profile rows older than this many days when profiling writes new rows Automatic refresh
openivm_metadata_schema VARCHAR empty Schema for OpenIVM control metadata in each native catalog. Empty keeps existing metadata where it is (main for new metadata); a schema name moves existing metadata there on the next CREATE MATERIALIZED VIEW or refresh Metadata placement
openivm_internal_schema VARCHAR empty Schema for internal maintenance tables (backing, publication, auxiliary-state and delta tables) within each data catalog. Empty keeps them beside the MV and its sources; applies to objects created while set Metadata placement
openivm_files_path VARCHAR — Directory for compiled SQL reference files (off when unset) Build: inspect SQL
openivm_archive_compiled_sql BOOLEAN false Store executed CREATE and refresh programs in metadata tables; independent of file export Compiled SQL archive
openivm_compiled_sql_retention BIGINT 10 Latest distinct archived programs per view and operation; at least 1 Compiled SQL archive
openivm_metadata_catalog VARCHAR "" Database-wide attached catalog for OpenIVM metadata (native DuckDB, or PostgreSQL via TYPE postgres); empty keeps metadata next to each native view catalog Metadata placement
openivm_metadata_lease_seconds BIGINT 600 Refresh lease for clients sharing a PostgreSQL metadata catalog Metadata placement
openivm_input_dialect VARCHAR duckdb Dialect of incoming CREATE MATERIALIZED VIEW bodies: duckdb or spark (e.g. VERSION AS OF) Parser
Optimization and compilation toggles
Setting Type Default Description Documentation
openivm_skip_empty_deltas BOOLEAN true Skip refresh work or join terms when deltas are empty Empty delta skip
openivm_compact_deltas BOOLEAN true Compact raw delta rows into net Z-set deltas before refresh Delta consolidation
openivm_skip_aggregate_delete BOOLEAN true Skip the zero-row DELETE for grouped aggregates when deltas are insert-only Append-only
openivm_skip_projection_delete BOOLEAN true Skip DELETE and consolidation for projections when deltas are insert-only Append-only
openivm_minmax_incremental BOOLEAN true Use GREATEST/LEAST for MIN/MAX when deltas are insert-only Append-only
openivm_fk_pruning BOOLEAN true Prune inclusion-exclusion join terms using FK constraints FK-aware pruning
openivm_ducklake_nterm BOOLEAN true Use N-term telescoping for DuckLake joins instead of 2^N−1 inclusion-exclusion DuckLake
openivm_having_merge BOOLEAN true Use MERGE for HAVING views (store all groups, filter in the view) instead of group-recompute Limitations
openivm_left_join_merge BOOLEAN true Use incremental MERGE for supported LEFT/RIGHT JOIN aggregates instead of group-recompute Left join
openivm_full_outer_merge BOOLEAN true Use incremental MERGE for FULL OUTER JOIN aggregates instead of group-recompute Full outer join
openivm_distinct_aux_state BOOLEAN false Use aux-state maintenance for supported inner-DISTINCT-under-aggregate shapes Distinct
openivm_stateful_auxstate BOOLEAN false Use persisted aux state for stateful aggregates such as COUNT(DISTINCT) instead of group-recompute —
openivm_running_window_incremental BOOLEAN false Extend cumulative running-window aggregates for append-only suffix batches —
openivm_enable_data_dependent_optimizers BOOLEAN true Optimize the executed refresh plan using current delta statistics —
openivm_regular_nterm BOOLEAN true Use N-term telescoping for eligible regular-table inner joins compiled for external engines Inner join
openivm_regular_nterm_left BOOLEAN true Extend compile-only N-term telescoping to LEFT JOIN projection views —
openivm_emit_spark_hints BOOLEAN false Emit Spark optimizer hints in target_dialect=spark compiled refresh SQL Spark

Pragmas and functions

Call Description Documentation
PRAGMA refresh('view_name') Refresh a materialized view; accepts schema.view, catalog.view, or catalog.schema.view Refresh strategies
PRAGMA refresh_options(catalog, schema, view_name) Refresh with explicit catalog/schema —
PRAGMA refresh_cross_system(view_catalog, view_schema, attached_catalog, attached_schema, view_name) Refresh with an explicit view location and fallback source location Cross-system refresh
PRAGMA refresh_pipeline('view_name', ...) Refresh one or more MVs and their cascade dependencies as one ordered run Pipelines
PRAGMA refresh_status('view_name') Show refresh interval, last/next refresh, daemon status, and refresh strategy Automatic refresh
PRAGMA refresh_cost('view_name') Show incremental refresh vs full recompute cost estimate (static + calibrated) Cost model
PRAGMA refresh_history('view_name') Show refresh execution history (for learned cost model) Refresh strategies
PRAGMA refresh_start_daemon (Re)start the current database's background refresh daemon; not allowed inside a transaction —
PRAGMA openivm_files('view_name') Show paths and status of the compiled SQL reference files Build: inspect SQL
openivm_compile_with_facts(view_name, facts_json) Table function: compile a refresh program as rows without executing it Bui 6E88 ld: compiled SQL

Schemas, metadata, and compiled SQL

  • Use PRAGMA refresh('catalog.schema.view') when a view name is ambiguous.
  • OpenIVM manages its own tables for refresh state. For persistent DuckLake views, reopen the same DuckDB frontend and reattach the lake under the same name. See DuckLake setup and metadata placement.
  • To inspect generated SQL, use compiled SQL export. To compile a refresh without running it, use openivm_compile_with_facts.

Documentation

  • DuckLake integration — IVM over DuckLake tables with native change tracking
  • Spark support — Spark input dialect (VERSION AS OF), compile-only Spark output, Spark hints, and add_months
  • Operators — How each SQL operator is incrementalized
  • Refresh — Refresh strategies, automatic refresh, pipelines, and refresh hooks
  • Optimizations — Delta consolidation, FK pruning, empty-delta skip, append-only, indexing
  • Internals — Delta tables, parser, concurrency, cost model, schema evolution
  • Concurrency and operations — What concurrent readers, writers and refreshes can rely on; running the daemon, upgrading, troubleshooting
  • Limitations — Unsupported operators, known restrictions
  • Build — Building, testing, benchmarks

About

Incremental View Maintenance on DuckDB

Topics

Resources

Stars

129 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages

0