Skip to main content

Overview

The WithSchemaPlugin 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

Parameters:
  • schema - The schema name to add to all table references
Example:
Source: ~/workspace/source/src/plugin/with-schema/with-schema-plugin.ts:14

Usage Example

Methods

transformQuery

Transforms the query operation node tree by adding the schema prefix to all table references that don’t already have a schema. Parameters:
  • args.queryId - Unique identifier for the query
  • args.node - The root operation node to transform
Returns: The transformed operation node with schema prefixes added Source: ~/workspace/source/src/plugin/with-schema/with-schema-plugin.ts:18

transformResult

Passes through the result unchanged. This plugin only modifies queries, not results. Parameters:
  • args.queryId - Unique identifier for the query
  • args.result - The query result
Returns: The original, unmodified result Source: ~/workspace/source/src/plugin/with-schema/with-schema-plugin.ts:22

Behavior Details

What Gets Prefixed

The plugin adds the schema prefix to:
  • Table references in FROM clauses
  • Table references in JOIN clauses
  • Table references in INTO clauses (for INSERT)
  • Table references in UPDATE statements
  • References in REFERENCES clauses (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 WITH clauses
  • Certain schemaless functions like json_agg and to_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 a WithSchemaTransformer that extends OperationNodeTransformer to traverse the query operation node tree. It:
  1. Collects all CTEs to avoid adding schemas to them
  2. Collects all schemable identifiers (tables)
  3. Transforms SchemableIdentifierNode instances by adding the schema
  4. Handles special cases like aggregate functions and select modifiers

See Also