Repository navigation
feat(materialize): Official Support for Materialize Database - #45651
BobbyAdiSalim wants to merge 23 commits into
Conversation
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
7634f7d to
5a30c85
Compare
63898b1 to
a5fdeb5
Compare
d1efe95 to
2282aa8
Compare
| if isinstance(sqla_type, DateTime): | ||
| dttm_formatted = dttm.isoformat(sep=" ", timespec="microseconds") | ||
| return f"CAST('{dttm_formatted}' AS TIMESTAMP)" |
There was a problem hiding this comment.
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
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 fixThere was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
Fixed! Implemented a minimal fix: aware datetimes use TIMESTAMPTZ; naive datetimes retain TIMESTAMP
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
| "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 " |
There was a problem hiding this comment.
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
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 fixThere was a problem hiding this comment.
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.
There was a problem hiding this comment.
✅ 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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
✅ 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
44ca972 to
95db586
Compare
ef8b919 to
a2d53b7
Compare
rusackas
left a comment
There was a problem hiding this comment.
LGTM, thanks for the thorough tests! Two tiny nits as suggestions.
389801b to
a0e04d1
Compare
rebenitez1802
left a comment
There was a problem hiding this comment.
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).
1690162 to
42516a5
Compare
…at_activity table
Co-authored-by: Evan Rusackas <evan@preset.io>
Co-authored-by: Evan Rusackas <evan@preset.io>
34d3c04 to
3ad7b9f
Compare
SUMMARY
Adds Materialize database support to Superset using the
sqlalchemy-materializedialect with thepsycopg2driver.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, orto_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-materializedialect extends SQLAlchemy’s PostgreSQL dialect to adapt inspection queries to Materialize’s supported catalogs.What we added on our side:
sqlalchemy-materializeWe 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_materializeWhat this PR changes:
pyproject.toml: adds amaterializeextra withsqlalchemy-materialize>=0.1.3andpsycopg2-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.
MaterializeEngineSpecextendsPostgresEngineSpec, inheriting PostgreSQL behavior unless explicitly overridden.engine = "materialize"anddefault_driver = "psycopg2".6875, required packages, and the Materialize homepage.sqlalchemy_uri_placeholderand documentation connection string usingmaterialize+psycopg2://, withoptions=--cluster%3Dquickstartto select thequickstartcluster.supports_file_upload = False.prepare_connection()enables autocommit so statements execute independently unless an explicit transaction is opened.get_schema_names()queriespg_namespaceto discover schemas, excluding system built-in schemas names i.e. names prefixed withpg_ormz_, along withinformation_schema.get_search_path()replaces PostgreSQL-specific relation lookup (it usesto_regclass()which is not supported in Materialize) with Materialize catalog queries.current_schemas(true), the configuredsearch_path, and the current user._named_schemas()helper to include configured schemas that do not yet exist.mz_catalog.mz_relations,mz_catalog.mz_schemas, andmz_catalog.mz_databases._table_spellings()to account for identifier quoting, preserving quoted names and lowercasing unquoted names.convert_dttm()converts Python datetime values into explicit SQL literals usingCAST()get_cancel_query_id()retrieves the connection’s backend PID usingpg_backend_pid()and commits the lookup transaction before the user’s query runs. This avoids keeping the query pinned tomz_catalog_server.cancel_query()validates that the cancellation identifier contains only digits, then callspg_terminate_backend()for the matching PID inpg_stat_activity. This terminates the backend session to stop its query; the method returnsFalseif validation fails or execution raises an exception.build_sqlalchemy_uri()builds the connection URI from the form parameters. If a cluster is given, it addsoptions=--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 theoptionsvalue starts with--cluster=, it removesoptionsfrom the query parameters and returns the cluster name asmaterializedb_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, placeholdere.g. quickstart) to the connection form. It's typed intypes.ts, registered and ordered inconstants.ts, and labelled inValidatedInputField.tsx, and it renders only for engines whose parameter schema exposes it.The connection URI takes the following form:
BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
1. Connect to Materialize using the connection form.










2. Connect to Materialize using a SQLAlchemy connection string.
3. Run a query in SQL Lab.
4. Insert 10,000 random rows with randomized timestamps and DML enabled.
5. Browse schemas, tables, and column data types.
6. Verify date and timestamp columns are marked as temporal.
7. Display a line chart grouped by hour.
8. Display a line chart grouped into 15-minute intervals.
9. Display a line chart grouped by day.
10. Arrange the charts in a dashboard layout.
TESTING INSTRUCTIONS
Install the connector from this branch:
Equivalently
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:
SHOW cluster;andSHOW search_path;separately. Verify the configured values, leaving the schema selector unset when checking the connection’s search path.pg_ormz_, plusinformation_schema, are excluded from the schema list.DATEorTIMESTAMPcolumns. Verify temporal columns are recognized and a time-series chart with a time-range filter renders.We have also ran following manual tests were run against a Materialize database to verify connection setup, schema discovery, and SQL Lab functionality:
options=--cluster%3D<name>.SELECT 1.SELECT count(*) FROM generate_series(1, 100000) a, generate_series(1, 100000) b) and click Stop. Verify that SQL Lab shows Stopped andmz_internal.mz_recent_activity_logshows the statement ascanceled. Then runSELECT 1in the same tab and verify that it succeeds. Repeat with asynchronous query execution on and off.SHOW cluster;that queries run on the selected cluster.options=--search_path%3Ds1. Verify whether both the cluster and the search path take effect.--search_pathin the URIoptionsand verify that an unqualified query follows the configured order.get_search_path(), withRLS_IN_SQLLABenabled, add an RLS rule on a dataset overs1.t. As a user the rule applies to, run an unqualifiedSELECT * FROM twiths1first, thens2first, on the search path. Verify that the rule applies only whentresolves tos1.t.ADDITIONAL INFORMATION