Skip to content

feat(materialize): Official Support for Materialize Database - #45651

Open
BobbyAdiSalim wants to merge 23 commits into
apache:masterfrom
BobbyAdiSalim:feat/materialize
Open

BobbyAdiSalim wants to merge 23 commits into
apache:masterfrom
BobbyAdiSalim:feat/materialize

Conversation

@BobbyAdiSalim

@BobbyAdiSalim BobbyAdiSalim commented Oct 23, 2026 •

Copy link
Copy Markdown

SUMMARY

Adds Materialize database support to Superset using the sqlalchemy-materialize dialect with the psycopg2 driver.

Materialize is wire-compatible with PostgreSQL but supports only a subset of PostgreSQL’s system catalogs and functions. For example, it does not support pg_opclass, which PostgreSQL’s SQLAlchemy dialect uses during column inspection, or to_regclass(), which Superset’s PostgreSQL engine specification uses to resolve relation names.

This integration extends Superset’s PostgreSQL engine specification and overrides schema discovery, search-path resolution, query cancellation, and connection handling where Materialize requires different behavior. The accompanying sqlalchemy-materialize dialect extends SQLAlchemy’s PostgreSQL dialect to adapt inspection queries to Materialize’s supported catalogs.

What we added on our side:

  • sqlalchemy-materialize
    We created an SQLAlchemy dialect for Materialize by extending PostgreSQL's dialect and overriding functionalities that require unsupported catalog queries from pg_catalog. It is available on PyPi: sqlalchemy_materialize

What this PR changes:

  • pyproject.toml: adds a materialize extra with sqlalchemy-materialize>=0.1.3 and psycopg2-binary==2.9.13.

  • superset/db_engine_specs/materialize.py:
    Materialize has their own 'cluster' definition. In Materialize, a 'cluster' is an isolated pool of compute resources. When connecting to Materialize's database, user can choose on which cluster to use by providing the cluster name.

    • MaterializeEngineSpec extends PostgresEngineSpec, inheriting PostgreSQL behavior unless explicitly overridden.
      • Sets engine = "materialize" and default_driver = "psycopg2".
      • Defines documentation metadata with default port 6875, required packages, and the Materialize homepage.
      • Provides a sqlalchemy_uri_placeholder and documentation connection string using materialize+psycopg2://, with options=--cluster%3Dquickstart to select the quickstart cluster.
      • Sets supports_file_upload = False.
    • prepare_connection() enables autocommit so statements execute independently unless an explicit transaction is opened.
    • get_schema_names() queries pg_namespace to discover schemas, excluding system built-in schemas names i.e. names prefixed with pg_ or mz_, along with information_schema.
    • get_search_path() replaces PostgreSQL-specific relation lookup (it uses to_regclass() which is not supported in Materialize) with Materialize catalog queries.
      • Reads current_schemas(true), the configured search_path, and the current user.
      • Uses the inherited _named_schemas() helper to include configured schemas that do not yet exist.
      • Looks up relations through mz_catalog.mz_relations, mz_catalog.mz_schemas, and mz_catalog.mz_databases.
      • Limits matches to the current database or shared schemas and the effective schema search path.
      • Uses _table_spellings() to account for identifier quoting, preserving quoted names and lowercasing unquoted names.
      • Returns the schema search path and the first matching schema for each candidate spelling.
    • convert_dttm() converts Python datetime values into explicit SQL literals using CAST()
    • get_cancel_query_id() retrieves the connection’s backend PID using pg_backend_pid() and commits the lookup transaction before the user’s query runs. This avoids keeping the query pinned to mz_catalog_server.
    • cancel_query() validates that the cancellation identifier contains only digits, then calls pg_terminate_backend() for the matching PID in pg_stat_activity. This terminates the backend session to stop its query; the method returns False if validation fails or execution raises an exception.
    • build_sqlalchemy_uri() builds the connection URI from the form parameters. If a cluster is given, it adds options=--cluster=<name> to the URI query string, keeping any other query parameters, and then defers to the inherited PostgreSQL implementation (which also defaults the port when it's blank).
    • get_parameters_from_uri() does the reverse when an existing connection is opened in the form. It parses the URI with the inherited implementation; if the options value starts with --cluster=, it removes options from the query parameters and returns the cluster name as materializedb_cluster, so the form's Cluster field is filled in and the option isn't added twice on save.
  • docs/src/data/databases.json:

  • tests/unit_tests/db_engine_specs/test_materialize.py: Covers connection URI construction and encoding, optional cluster parameters and default ports, preservation of existing connection options, autocommit handling, date and timestamp casts, system schema filtering, search-path resolution with quoted identifiers and missing schemas, committing the backend PID lookup transaction, and query cancellation with valid IDs, invalid IDs, and execution failures. Tests use mocked connections and do not require a running Materialize instance.

  • messages.pot: Added translatable strings for the Materialize connection form.

  • Frontend (DatabaseModal): adds a Cluster field (materializedb_cluster, placeholder e.g. quickstart) to the connection form. It's typed in types.ts, registered and ordered in constants.ts, and labelled in ValidatedInputField.tsx, and it renders only for engines whose parameter schema exposes it.

The connection URI takes the following form:

materialize+psycopg2://USERNAME:PASSWORD@HOST:6875/DATABASE?sslmode=require&options=--cluster%3DCLUSTER

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

1. Connect to Materialize using the connection form.
image_01
2. Connect to Materialize using a SQLAlchemy connection string.
image_02
3. Run a query in SQL Lab.
image_03
4. Insert 10,000 random rows with randomized timestamps and DML enabled.
image_04
5. Browse schemas, tables, and column data types.
image_05
6. Verify date and timestamp columns are marked as temporal.
image_06
7. Display a line chart grouped by hour.
image_07
8. Display a line chart grouped into 15-minute intervals.
image_08
9. Display a line chart grouped by day.
image_09
10. Arrange the charts in a dashboard layout.
image_10

TESTING INSTRUCTIONS

Install the connector from this branch:

pip install -e ".[materialize]"

Equivalently

pip install sqlalchemy-materialize

Restart Superset after installation.

By hand, against a Materialize database:

TESTING INSTRUCTIONS

Install the connector from this branch:

pip install -e ".[materialize]"

Alternatively, install the connector into your Superset environment:

pip install "sqlalchemy-materialize>=1.0.0"

Restart Superset after installation.

By hand, against a Materialize database:

  1. Add a Materialize connection using the connection form. Enter valid credentials, database, and cluster. Verify Test connection succeeds and the connection saves.
  2. Set Cluster to an existing cluster. In Additional parameters, enter:
    options=--search_path%3Danalytics%2Cpublic
    
    Use schemas available in your database. Verify the connection succeeds.
  3. Reopen the saved connection. Verify the cluster appears in its dedicated field and the search-path option remains in Additional parameters.
  4. In SQL Lab, run SHOW cluster; and SHOW search_path; separately. Verify the configured values, leaving the schema selector unset when checking the connection’s search path.
  5. Browse schemas and relations. Verify user schemas appear, while schemas beginning with pg_ or mz_, plus information_schema, are excluded from the schema list.
  6. Query an existing table or materialized view containing data. Verify rows and column names display correctly.
  7. Create a dataset containing DATE or TIMESTAMP columns. Verify temporal columns are recognized and a time-series chart with a time-range filter renders.
  8. Run a sufficiently long query and cancel it from SQL Lab. Verify cancellation completes and a subsequent query succeeds.
  9. Verify the connection settings do not offer Allow file uploads to database.

We have also ran following manual tests were run against a Materialize database to verify connection setup, schema discovery, and SQL Lab functionality:

Test Result
Add a database using the URI above and specify a valid cluster. Verify that testing and saving the connection succeed. Pass
Add a database using the connection form fields (host, port, database, username, password, cluster). Verify that testing and saving succeed and the generated URI includes options=--cluster%3D<name>. Pass
In SQL Lab, run SELECT 1. Pass
Verify that user schemas are available and system schemas are excluded. Pass
Select a table in the SQL Lab left panel. Verify that its columns and types appear and the table preview returns rows. Pass
Query an existing relation. Repeat with an unqualified relation name resolved through the connection's search path. Pass
Run a query that returns no rows and verify that "The query returned no data" appears. Pass
Create a dataset from a Materialize relation. Pass
Build a chart with a date or timestamp column, a time range, and a daily time grain. Check the returned dates and aggregation. Pass
Add the chart to a dashboard and verify that it loads. Pass
Insert new rows in Materialize, then use Force refresh on the dashboard. Verify that the chart shows the updated values. Pass
Run a long query (e.g. SELECT count(*) FROM generate_series(1, 100000) a, generate_series(1, 100000) b) and click Stop. Verify that SQL Lab shows Stopped and mz_internal.mz_recent_activity_log shows the statement as canceled. Then run SELECT 1 in the same tab and verify that it succeeds. Repeat with asynchronous query execution on and off. Pass
Verify that file uploads are unavailable for the Materialize database. Pass
Connect using a non-default cluster and verify with SHOW cluster; that queries run on the selected cluster. Pass
Save the database connection, reopen its configuration, and verify that the cluster setting is preserved. Pass
Set the cluster field on a URI that already has options=--search_path%3Ds1. Verify whether both the cluster and the search path take effect. Pass
Test invalid credentials. Verify that the connection test fails with an authentication error. Pass
Connect with a nonexistent cluster. Verify that Superset reports an error when querying a relation. Pass
Query relations with mixed-case names or spaces using quoted identifiers. Pass
Create relations with the same name in two schemas. Set --search_path in the URI options and verify that an unqualified query follows the configured order. Pass
With our get_search_path(), with RLS_IN_SQLLAB enabled, add an RLS rule on a dataset over s1.t. As a user the rule applies to, run an unqualified SELECT * FROM t with s1 first, then s2 first, on the search path. Verify that the rule applies only when t resolves to s1.t. Pass

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

@BobbyAdiSalim BobbyAdiSalim changed the title (WIP) Adding Official Support for the Materialize Database Official Support for Materialize Database Oct 23, 2026
@netlify

netlify Bot commented Oct 23, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 289fd78
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6adae1f61bad48e0dd6fc086
😎 Deploy Preview https://deploy-preview-45651--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.69421% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.98%. Comparing base (f4c26d8) to head (7d53ac2).
⚠️ Report is 6 commits behind head on master.

Files with missing lines Patch % Lines
superset/db_engine_specs/materialize.py 96.66% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##           master   #45651    +/-   ##
========================================
  Coverage   85.97%   85.98%            
========================================
  Files        3127     3129     +2     
  Lines      217726   217894   +168     
  Branches    51618    51646    +28     
========================================
+ Hits       187183   187347   +164     
- Misses      27119    27122     +3     
- Partials     3424     3425     +1     
Flag Coverage Δ
hive 33.81% <32.23%> (-0.02%) ⬇️
javascript 82.79% <ø> (+<0.01%) ⬆️
mysql 51.61% <32.23%> (-0.01%) ⬇️
postgres 51.63% <32.23%> (-0.01%) ⬇️
presto 35.51% <32.23%> (+<0.01%) ⬆️
python 88.48% <96.69%> (+0.01%) ⬆️
sqlite 51.31% <32.23%> (-0.01%) ⬇️
unit 83.98% <96.69%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@rusackas rusackas added the utsc2026 UTSC 2026 course contributions label Oct 27, 2026
@pull-request-size pull-request-size Bot added size/L and removed size/M labels Nov 22, 2026
@github-actions github-actions Bot added doc Namespace | Anything related to documentation dependencies:python labels Nov 22, 2026
@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Nov 22, 2026
@BobbyAdiSalim
BobbyAdiSalim marked this pull request as ready for review November 23, 2026 17:34
Comment thread superset/db_engine_specs/materialize.py Outdated
Comment on lines +173 to +175
if isinstance(sqla_type, DateTime):
dttm_formatted = dttm.isoformat(sep=" ", timespec="microseconds")
return f"CAST('{dttm_formatted}' AS TIMESTAMP)"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: For a timezone-aware DateTime, isoformat() retains the offset but this casts it to timezone-naive TIMESTAMP; filters can therefore compare a different instant.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Logic error

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/db_engine_specs/materialize.py
**Line:** 173:175
**Comment:**
	*Logic Error: For a timezone-aware `DateTime`, `isoformat()` retains the offset but this casts it to timezone-naive `TIMESTAMP`; filters can therefore compare a different instant.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of d4f7595.

Timezone-aware datetimes now use TIMESTAMPTZ in the cast, while naive datetimes continue to use TIMESTAMP.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed! Implemented a minimal fix: aware datetimes use TIMESTAMPTZ; naive datetimes retain TIMESTAMP

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of ef8b919.

Timezone-aware datetimes now use TIMESTAMPTZ in the cast, while naive datetimes continue to use TIMESTAMP.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of a2d53b7.

Timezone-aware datetimes now use TIMESTAMPTZ in the cast, while naive datetimes continue to use TIMESTAMP.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of cb38c5f.

Timezone-aware datetimes are now cast as TIMESTAMPTZ; naive datetimes remain cast as TIMESTAMP.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 1690162.

Timezone-aware datetimes are now cast as TIMESTAMPTZ; naive datetimes remain cast as TIMESTAMP.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 42516a5.

Timezone-aware datetimes are now cast as TIMESTAMPTZ; naive datetimes remain cast as TIMESTAMP.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 34d3c04.

Timezone-aware datetimes are now cast as TIMESTAMPTZ; naive datetimes remain cast as TIMESTAMP.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 3ad7b9f.

Timezone-aware datetimes are now cast as TIMESTAMPTZ; naive datetimes remain cast as TIMESTAMP.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Comment on lines +240 to +243
"JOIN mz_catalog.mz_relations AS r ON r.name = CASE "
"WHEN left(sp.spelling, 1) = '\"' THEN replace("
"substr(sp.spelling, 2, length(sp.spelling) - 2), '\"\"', '\"') "
"ELSE lower(sp.spelling) END "

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: lower() applies Unicode case folding, unlike PostgreSQL's ASCII-only unquoted identifier folding; it can resolve an unrelated relation and associate the table with the wrong RLS scope.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Security

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/db_engine_specs/materialize.py
**Line:** 240:243
**Comment:**
	*Security: `lower()` applies Unicode case folding, unlike PostgreSQL's ASCII-only unquoted identifier folding; it can resolve an unrelated relation and associate the table with the wrong RLS scope.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@danielstevanus88 danielstevanus88 Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Materialize (the database we are adding the support to) differs from PostgreSQL here: its identifier lexer and SQL lower() both use Rust’s Unicode to_lowercase(). The lookup matches Materialize’s identifier normalization, so ASCII-only folding would be incorrect.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Customized review instruction saved!

Instruction:

For Materialize relation lookups, Unicode lowercasing matches Materialize’s identifier normalization; do not flag it as incorrect based on PostgreSQL’s ASCII-only folding behavior.

Applied to:

  • superset/db_engine_specs/materialize.py

💡 To manage or update this instruction, visit: CodeAnt AI Settings

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This behavior is correct for Materialize, which differs from PostgreSQL.

Materialize’s identifier lexer(https://github.com/MaterializeInc/materialize/blob/main/src/sql-lexer/src/lexer.rs) and SQL lower() implementation (https://github.com/MaterializeInc/materialize/blob/main/src/expr/src/scalar/func/impls/string.rs) both use Rust’s Unicode to_lowercase().

Verified with:

    WITH t AS (SELECT 1 AS VENTÉ)
    SELECT "venté" FROM t;

This returns 1 in Materialize but fails in PostgreSQL, where the identifier becomes ventÉ. Materialize’s lower('VENTÉ') also returns venté.

Therefore, lower() matches Materialize’s identifier folding for this case. Replacing it with ASCII-only folding would introduce a mismatch.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Customized review instruction saved!

Instruction:

For Materialize identifier handling, preserve Unicode lowercasing for unquoted identifiers to match Materialize semantics; do not flag it as a PostgreSQL mismatch.

Applied to:

  • superset/db_engine_specs/materialize.py

💡 To manage or update this instruction, visit: CodeAnt AI Settings

@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟢  Low Risk

  • The PR appears safe to merge; the timezone-aware timestamp handling is corrected, and Unicode identifier folding matches Materialize semantics.

Assessed commit: 3ad7b9f37d8b

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Nov 23, 2026
@github-actions github-actions Bot added the i18n Namespace | Anything related to localization label Nov 23, 2026
@BobbyAdiSalim BobbyAdiSalim changed the title Official Support for Materialize Database feat: Official Support for Materialize Database Nov 23, 2026
@BobbyAdiSalim BobbyAdiSalim changed the title feat: Official Support for Materialize Database feat(materialize): Official Support for Materialize Database Nov 23, 2026

@rusackas rusackas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks for the thorough tests! Two tiny nits as suggestions.

Comment thread superset/db_engine_specs/materialize.py Resolved
Comment thread pyproject.toml Resolved

@rebenitez1802 rebenitez1802 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve: no blockers. I ran the spec against a live Materialize (v26.52, Docker emulator), and every override is needed and works: search-path resolution, CAST dttm literals, pg_cancel_backend cancel, autocommit + PID-lookup commit, schema filtering and the cluster URI round-trip. A few non-blocking suggestions are inline; the combined suggestions pass test_materialize.py/test_postgres.py, ruff and mypy.

Note: CI hasn't run on the last two pushes (workflows awaiting maintainer approval).

Comment thread superset/db_engine_specs/materialize.py Resolved
Comment thread superset/db_engine_specs/materialize.py Resolved
Comment thread superset/db_engine_specs/materialize.py Resolved
Comment thread docs/src/data/databases.json Resolved
@danielstevanus88
danielstevanus88 force-pushed the feat/materialize branch 3 times, most recently from 1690162 to 42516a5 Compare November 27, 2026 21:08
danielstevanus88 and others added 23 commits November 27, 2026 19:28
Co-authored-by: Evan Rusackas <evan@preset.io>
Co-authored-by: Evan Rusackas <evan@preset.io>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies:python doc Namespace | Anything related to documentation i18n Namespace | Anything related to localization review:draft size/XL utsc2026 UTSC 2026 course contributions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants