Overview
TheWithSchemaPlugin automatically adds a schema prefix to all table references in your queries. This is useful when working with databases that use multiple schemas and you want all queries to target a specific schema without manually adding the schema to each table reference.
Installation
Constructor
schema- The schema name to add to all table references
Usage Example
Methods
transformQuery
args.queryId- Unique identifier for the queryargs.node- The root operation node to transform
transformResult
args.queryId- Unique identifier for the queryargs.result- The query result
Behavior Details
What Gets Prefixed
The plugin adds the schema prefix to:- Table references in
FROMclauses - Table references in
JOINclauses - Table references in
INTOclauses (for INSERT) - Table references in
UPDATEstatements - References in
REFERENCESclauses (foreign keys) - Table names in DDL statements (CREATE/ALTER/DROP TABLE, etc.)
What Doesn’t Get Prefixed
- Tables that already have an explicit schema
- Common Table Expressions (CTEs) defined in
WITHclauses - Certain schemaless functions like
json_aggandto_json
Example with CTEs
Use Cases
Multi-tenant Applications
Use different schema plugins for different tenants:Development vs Production
Use different schemas for different environments:Per-Query Schema Override
Apply schema plugin to specific queries:Implementation Details
The plugin uses aWithSchemaTransformer that extends OperationNodeTransformer to traverse the query operation node tree. It:
- Collects all CTEs to avoid adding schemas to them
- Collects all schemable identifiers (tables)
- Transforms
SchemableIdentifierNodeinstances by adding the schema - Handles special cases like aggregate functions and select modifiers