Member Junction
    Preparing search index...

    Abstract base class for the dialects of the platforms MJ itself runs on.

    A QueryDialect (lexical rules, grammar facts, writer, types, binding) plus the DDL facet MJ needs to create and run its own schema. Every member below is kept for existing callers and delegates to one of the facets. This is a pure string/logic layer with zero database driver dependencies.

    Hierarchy (View Summary)

    Implements

    Index

    Constructors

    Accessors

    Methods

    Constructors

    Accessors

    • get CallerSQLForbiddenFunctions(): readonly string[]

      Functions SQL a caller supplied (ad-hoc SQL, TestQuerySQL, query specs, client RunView clauses) may not call, lower case; a trailing * matches every name with that prefix. They run SQL passed as a string, read files or other databases, act on the server, or pause the query, so neither the check of which tables the SQL reads nor a read-only transaction stops them.

      Returns readonly string[]

    • get DisplayName(): string

      Human-readable name for this dialect, as it should appear to a person — or to an LLM being told which SQL to write.

      Abstract on purpose: the name is dialect knowledge, so a new dialect declares it once here rather than every prompt/UI keeping its own map.

      Returns string

    • get FixedWidthStringTypeNames(): readonly string[]

      Subset of StringTypeNames that represents fixed-width / space-padded character types. SQL Server char/nchar and PostgreSQL char/bpchar/character (without varying) all right-pad stored values with spaces up to the declared length and return that padding in result sets. Variable-width types (varchar, nvarchar, text, etc.) do not.

      Used by BaseEntity to rtrim padding on load so dirty-checks and downstream consumers see the logical value, not the storage form.

      Returns readonly string[]

    • get FormatterLanguage(): string

      The sql-formatter language key for this dialect (e.g. 'tsql', 'postgresql'). Callers that pretty-print generated SQL read this instead of hardcoding a language, so formatting follows the tenant's actual platform.

      Returns string

    • get MaxColumnCount(): number | null

      Hard maximum number of columns per table, or null when effectively unbounded for our purposes. SQL Server: 1024. PostgreSQL: 1600. Default: null.

      Returns number | null

    • get MaxInRowSizeBytes(): number | null

      Maximum bytes that can be stored in-row for a single row, or null when the dialect has no in-row size limit. SQL Server enforces a hard ~8060-byte in-row limit; PostgreSQL has none (TOAST stores oversized variable-length values out-of-line). Consumed by schema materialization to avoid emitting a table whose minimum in-row footprint can never satisfy an INSERT. Default: null (no in-row size limit).

      Returns number | null

    • get MaxKeyStringLength(): number

      Maximum string length usable in an INDEX KEY column (PRIMARY KEY / UNIQUE constraint) on this dialect. A PK string column wider than this can't be indexed, so callers (e.g. the integration schema builder) cap PK string columns at this value. Default: no practical declare-time cap — a dialect overrides it where one exists. SQL Server's 900-byte index-key limit = 450 NVARCHAR chars; PostgreSQL enforces its (larger) btree limit on the stored value at write time, not the declared length, so it keeps the no-cap default.

      Returns number

    • get NullLiteral(): string

      Returns the dialect's literal representation of NULL as it would appear in generated SQL (e.g. as the result of a default-value formatter). Both SQL Server and PostgreSQL use the bare keyword NULL, but a future dialect could differ — codegen comparisons should route through this rather than hard-coding the string.

      Returns string

    • get PagingRequiresOrderBy(): boolean

      Whether skipping rows for a page needs an ORDER BY (OFFSET … FETCH does on SQL Server). When true, a page taken from a derived table is ordered by DefaultPagingOrderBy. SQL Server: true, PostgreSQL: false

      Returns boolean

    • get PromptGuidance(): string

      A syntax briefing for this dialect, composed ENTIRELY from this class's own primitives — nothing here is a hand-maintained per-dialect prose table. Implementing the dialect is therefore sufficient to get correct guidance; there is no second list to remember to update.

      Consumed by the _SQL_DIALECT_RULES system placeholder, which makes it available to EVERY AI prompt template without any template having to be registered anywhere. That is the point: the set of SQL-generating templates is a predicate ("does it ask for SQL?"), never a list of IDs.

      Returns string

    • get SelectListPagingOrderBy(): string | null

      The ORDER BY expression for paging a set operation (UNION / INTERSECT / EXCEPT) or a SELECT DISTINCT that has no ORDER BY of its own, on a platform that only accepts select-list items there. null when DefaultPagingOrderBy is accepted for those shapes too. SQL Server: '1' (the first column), PostgreSQL: null

      Returns string | null

    • get UnseparatedStatementKeywords(): readonly string[]

      Upper-case keywords that start a new statement wherever they appear as a bare word at the top level of another one, because the platform needs no separator between statements; empty or absent when statements must be separated. SQL Server: the statement keywords; PostgreSQL: none.

      Returns readonly string[]

    Methods

    • Wraps a single DML statement so the number of rows it affected comes back as a one-row, one-column result set — the portable way to read an affected-row count without relying on a driver-specific rowsAffected field.

      SQL Server appends SELECT @@ROWCOUNT. PostgreSQL has no @@ROWCOUNT at all, so it wraps the statement in a data-modifying CTE and counts the RETURNING rows.

      dmlStatement must be exactly one INSERT/UPDATE/DELETE and carry no trailing semicolon: the PostgreSQL form is a CTE, which cannot wrap a statement batch.

      Parameters

      • dmlStatement: string
      • alias: string

      Returns string

    • Returns ALTER COLUMN clause(s) for type/nullability changes. SQL Server: ALTER TABLE t ALTER COLUMN [col] newType NULL/NOT NULL; PostgreSQL: ALTER TABLE t ALTER COLUMN "col" TYPE newType, ALTER COLUMN "col" SET/DROP NOT NULL;

      Parameters

      Returns string

    • Wraps a list of statements in ONE all-or-nothing transaction batch for this platform, ready to run as a single ExecuteSQL(script) call. Owns the platform-specific session/transaction setup so callers don't sniff PlatformKey themselves:

      • SQL Server: SET QUOTED_IDENTIFIER ON / SET ANSI_NULLS ON (required for UPDATE/DELETE against tables with filtered / computed-column indexes or indexed views — Msg 1934 otherwise)
        • SET XACT_ABORT ON (any failure rolls the whole batch back) + BEGIN/COMMIT TRANSACTION.
      • PostgreSQL: plain BEGIN … COMMIT — no session pragmas (QUOTED_IDENTIFIER/ANSI_NULLS are SQL-Server concepts) and PostgreSQL already aborts the whole transaction on any error.

      Returns an empty string for an empty statement list (nothing to run).

      Parameters

      • statements: string[]

        individual SQL statements (each WITHOUT a trailing ;)

      Returns string

    • Returns the auto-increment PK expression for DDL. SQL Server: IDENTITY(1,1), PostgreSQL: GENERATED ALWAYS AS IDENTITY

      Returns string

    • Returns a boolean literal for the platform. SQL Server: "1"/"0", PostgreSQL: "true"/"false"

      Parameters

      • value: boolean

      Returns string

    • Returns the SQL type token for a boolean parameter in a stored-procedure / function signature. Used by codegen when emitting tolerant-SP _Clear companion parameters and other boolean-typed params.

      SQL Server: bit (BIT type, 0/1) PostgreSQL: boolean (BOOLEAN type, TRUE/FALSE)

      Hardcoding bit everywhere worked on SQL Server but produced sprocs that PG rejected as operator does not exist: boolean = integer when the generated CASE compared a bit-declared parameter with = 1.

      Returns string

    • The value to bind for a boolean query parameter. SQL Server: 1 / 0 (BIT), PostgreSQL: true / false.

      Parameters

      • value: boolean

      Returns number | boolean

    • Canonicalizes a SCHEMA name to the form the platform actually stores when the name appears UNQUOTED in DDL. PostgreSQL folds unquoted identifiers to lowercase, so __mj_BizAppsCommon physically becomes __mj_bizappscommon; SQL Server is case-insensitive and stores the name as-given. Routing every schema CREATE/DROP/USE through this keeps the engine's (quoted) operations aligned with what unquoted migration DDL produces — so a mixed-case schema name can't split into two physical schemas (one quoted-mixed, one folded-lowercase).

      Parameters

      • name: string

      Returns string

    • Cap a column type if it cannot be used in a UNIQUE/index constraint. SQL Server: NVARCHAR(MAX) → NVARCHAR(450) (MAX columns cannot be indexed). PostgreSQL: no-op (TEXT can be indexed). Override in platform-specific dialects.

      Parameters

      • rawSqlType: string

      Returns string

    • Returns a CAST to a bounded-width string type. Used when the result needs to be comparable against an indexed column (SQL Server cannot compare/index NVARCHAR(MAX)) or against a fixed-width text column such as MJ's RecordID (NVARCHAR(450) on SQL Server).

      Implemented by composing ResolveAbstractType({ type: 'string', maxLength }), which dialects already supply — SQL Server emits NVARCHAR(N) and PostgreSQL emits VARCHAR(N). Defaults to MJ's standard 450-char width to match the cap on indexable string columns in SQL Server.

      Parameters

      • expr: string
      • maxLength: number = 450

      Returns string

    • Returns a CAST-to-text expression. SQL Server: CAST(expr AS NVARCHAR(MAX)), PostgreSQL: CAST(expr AS TEXT)

      Parameters

      • expr: string

      Returns string

    • Returns a CAST-to-UUID expression. SQL Server: CAST(expr AS UNIQUEIDENTIFIER), PostgreSQL: CAST(expr AS UUID)

      Parameters

      • expr: string

      Returns string

    • Returns the platform's n-ary null-coalescing expression. SQL Server and PostgreSQL both spell this COALESCE(...); the dialect's writer owns the spelling.

      Parameters

      • expr: string
      • fallback: string

      Returns string

    • Returns description metadata SQL for a column. SQL Server: EXEC sp_addextendedproperty with

      Parameters

      • schema: string
      • table: string
      • column: string
      • comment: string

      Returns string

      = 'COLUMN' PostgreSQL: COMMENT ON COLUMN schema."table"."column" IS '...';

      This extends CommentOnObject to support the 3-part column reference that CommentOnObject doesn't handle.

    • CommentOnColumn that is safe to re-run. Default returns the standard statement (PostgreSQL COMMENT ON COLUMN already includes its terminator and is idempotent). SQL Server overrides to guard sp_addextendedproperty.

      Parameters

      • schema: string
      • table: string
      • column: string
      • comment: string

      Returns string

    • Returns a COMMENT ON statement (PostgreSQL) or sp_addextendedproperty (SQL Server).

      Parameters

      • objectType: string
      • schema: string
      • name: string
      • comment: string

      Returns string

    • CommentOnObject that is safe to re-run (no error if the description already exists). Default returns the standard statement terminated with ';' — adequate where the comment statement is inherently idempotent (PostgreSQL COMMENT ON replaces in place). SQL Server overrides to guard sp_addextendedproperty with a fn_listextendedproperty check.

      Parameters

      • objectType: string
      • schema: string
      • name: string
      • comment: string

      Returns string

    • Returns a conditional IF/ELSE block in platform-appropriate procedural SQL. SQL Server: IF (condition) BEGIN thenSQL END ELSE BEGIN elseSQL END PostgreSQL: DO $$ BEGIN IF condition THEN thenSQL; ELSE elseSQL; END IF; END $$;

      Parameters

      • condition: string

        SQL boolean condition

      • thenSQL: string

        SQL to execute when condition is true

      • OptionalelseSQL: string

        Optional SQL to execute when condition is false

      Returns string

    • Whether the platform supports CREATE OR REPLACE for a given object type. PostgreSQL supports it for FUNCTION, VIEW. SQL Server does not.

      Parameters

      • objectType: string

      Returns boolean

    • SQL that marks a nested transaction savepoint. SQL Server: SAVE TRANSACTION name. PostgreSQL: SAVEPOINT name.

      Parameters

      • name: string

      Returns string

    • Returns CREATE SCHEMA IF NOT EXISTS SQL. SQL Server: IF NOT EXISTS (...) EXEC('CREATE SCHEMA [name]'); GO PostgreSQL: CREATE SCHEMA IF NOT EXISTS "name";

      Parameters

      • schemaName: string

      Returns string

    • A full CREATE TABLE that runs only if the table is absent, as a SINGLE statement. Default (PostgreSQL et al.): CREATE TABLE IF NOT EXISTS <fullTable> (...); SQL Server overrides with an IF OBJECT_ID(...) IS NULL guard (it has no native CREATE TABLE IF NOT EXISTS).

      Parameters

      • fullTable: string

        Already-quoted schema.table identifier

      • columnsBody: string

        The column/constraint lines that go between the parentheses

      Returns string

    • Returns a full CREATE TABLE wrapped in a "create if not exists" guard. SQL Server: IF NOT EXISTS (sys.tables check) BEGIN CREATE TABLE ... END; PostgreSQL: CREATE TABLE IF NOT EXISTS ...;

      Parameters

      • schema: string

        Schema name

      • tableName: string

        Table name

      • columnsDDL: string

        The column definitions (everything between the parentheses)

      Returns string

    • Returns a date/time arithmetic expression. SQL Server: DATEADD(MINUTE, 30, GETUTCDATE()) PostgreSQL: (NOW() AT TIME ZONE 'UTC') + INTERVAL '30 minutes'

      Parameters

      • unit: DateAddUnit

        Time unit

      • amount: number

        Number of units to add (can be negative)

      • baseExpr: string

        Base timestamp expression (e.g., from CurrentTimestampUTC())

      Returns string

    • Returns the empty-GUID sentinel literal (00000000-0000-0000-0000-000000000000) formatted for use in a CASE-comparison expression. The base class returns the literal as a plain quoted string — SQL Server's implicit conversion accepts that directly. Dialects with strict typing (PostgreSQL) override to add the explicit cast their grammar requires.

      Returns string

    • Splits ${...} inside SQL string literals so Flyway doesn't treat them as placeholders. Each ${name} becomes a concat-split that round-trips back to ${name} at execution but contains no adjacent ${ in the file text. Form is platform-specific (concat operator, truncation rules) — see each dialect's implementation.

      Parameters

      • sql: string

      Returns string

    • Escapes the characters a LIKE pattern treats specially, so text matches literally with the platform's default escape rules (no ESCAPE clause). Quotes are not escaped here; the caller still doubles them for the string literal. SQL Server: [, % and _ become [[], [%] and [_]. PostgreSQL: \, % and _ are escaped with a backslash.

      Parameters

      • text: string

      Returns string

    • Minimum in-row byte footprint of a column of the given raw SQL type. Off-row-capable variable-length / LOB types contribute only their in-row pointer; fixed-length types contribute their full size. Only meaningful for dialects that report a MaxInRowSizeBytes. Default: 24 (a conservative off-row-pointer floor).

      Parameters

      • rawSqlType: string

      Returns number

    • Returns SQL to check if a database object exists.

      Parameters

      • objectType: string

        "TABLE", "VIEW", "FUNCTION", "PROCEDURE", "TRIGGER"

      • schema: string

        Schema name

      • name: string

        Object name

      Returns string

    • Returns the platform's fallback type for unknown/unmapped abstract types. SQL Server: NVARCHAR(MAX) PostgreSQL: TEXT

      Returns string

    • Returns a ready-to-run (no bind parameters) query that enumerates the foreign-key graph of a single schema, for FK-cascade planning (e.g. Open-App metadata teardown).

      Unlike SchemaIntrospectionQueries.listForeignKeys (a placeholder template), this embeds the schema literal directly (via QuoteStringLiteral) so it can be executed with ExecuteSQL(sql) on any provider without a dialect-specific bind convention. It also returns two extra columns the cascade planner needs:

      • childNullable — whether the referencing (child) column allows NULL, which decides UPDATE … SET NULL (nullable) vs. DELETE + recurse (NOT NULL).
      • colCount — the number of columns in the FK constraint, so a caller can exclude composite FKs (colCount > 1).

      Every row is one FK column. Column aliases are IDENTICAL across dialects: parentTable, parentRefCol, childTable, childCol, childNullable, fkName, colCount (both the referenced/parent and referencing/child tables are within schema).

      Parameters

      • schema: string

        the schema whose intra-schema FK edges to enumerate (e.g. __mj)

      Returns string

    • Returns DDL to create a full-text index. SQL Server: FULLTEXT CATALOG + FULLTEXT INDEX PostgreSQL: tsvector column + GIN index

      Parameters

      • table: string
      • columns: string[]
      • Optionalcatalog: string

      Returns string

    • Returns a full-text search predicate expression. SQL Server: CONTAINS(column, searchTerm) PostgreSQL: column @@ plainto_tsquery('english', searchTerm)

      Parameters

      • column: string
      • searchTerm: string

      Returns string

    • Returns a GRANT statement for the platform.

      Parameters

      • permission: string
      • objectType: string
      • schema: string
      • object: string
      • role: string

      Returns string

    • Returns an IIF/CASE equivalent expression. SQL Server: IIF(condition, trueVal, falseVal) PostgreSQL: CASE WHEN condition THEN trueVal ELSE falseVal END

      Parameters

      • condition: string
      • trueVal: string
      • falseVal: string

      Returns string

    • Returns true if the given error represents an infrastructure-level connection failure (timeout, refused, pool closed, etc.) as opposed to a query-level error (bad SQL, constraint violation).

      Each dialect implements this using its driver's structured error types:

      • SQL Server (mssql): error.name === 'ConnectionError'
      • PostgreSQL (pg): Node.js network error codes on plain Error

      Used by GenericDatabaseProvider to re-throw connection errors from RunView/RunQuery instead of swallowing them into { Success: false }.

      Parameters

      • e: unknown

      Returns boolean

    • Returns the platform's two-argument null-coalescing expression. SQL Server: ISNULL(expr, fallback), PostgreSQL: COALESCE(expr, fallback). The dialect's writer declares the keyword.

      Parameters

      • expr: string
      • fallback: string

      Returns string

    • Returns true if value is the dialect's representation of a NULL literal in generated SQL. Comparison is case-insensitive after trimming whitespace. Subclasses may override if a dialect uses a non-keyword form (none currently do).

      Parameters

      • value: string

      Returns boolean

    • Returns a JSON value extraction expression. SQL Server: JSON_VALUE(column, path) PostgreSQL: column->>'path' or jsonb_extract_path_text

      Parameters

      • column: string
      • path: string

      Returns string

    • Wraps an expression in the dialect's lowercase function — used for case-insensitive comparison when authoring filters that must work on both SS (default case-insensitive collation) and PG (case-sensitive).

      Both SQL Server and PostgreSQL implement LOWER() per the ANSI SQL standard, so the default returns LOWER(${expr}). A subclass would override only for an exotic dialect (e.g. one that exposes lc() or needs a CAST first).

      Use this instead of hardcoding LOWER(...) in callers — keeps the dialect-aware SQL surface in one place per the SQLDialect contract.

      Parameters

      • expr: string

      Returns string

    • Convenience: maps a SQL Server type to this dialect's equivalent.

      Parameters

      • sqlServerType: string
      • Optionallength: number
      • Optionalprecision: number
      • Optionalscale: number

      Returns MappedType

    • Convenience: maps a SQL Server type to a full type string.

      Parameters

      • sqlServerType: string
      • Optionallength: number
      • Optionalprecision: number
      • Optionalscale: number

      Returns string

    • Returns the default-value clause appended to a parameter declaration. SQL Server: = NULL (or = 0, etc.), PostgreSQL: DEFAULT NULL. value should be a SQL literal already formatted by the caller (e.g. the dialect's NullLiteral, a quoted string, a numeric literal).

      Parameters

      • value: string

      Returns string

    • Returns a parameter placeholder for the given index. SQL Server: @p0, @p1, ... PostgreSQL: $1, $2, ...

      Parameters

      • index: number

      Returns string

    • Returns the parameter-reference syntax used by this dialect's stored-procedure / function bodies. SQL Server: @MyName, PostgreSQL functions: p_my_name. Codegen should call this rather than hard-coding '@' + name.

      Parameters

      • name: string

      Returns string

    • Returns the SQL syntax for calling a stored procedure or function. SQL Server: EXEC [schema].[name] @p0,

      Parameters

      • schema: string
      • name: string
      • params: string[]

      Returns string

      PostgreSQL: SELECT * FROM schema.name($1, $2)

    • Quotes a column alias used in SELECT ... AS <alias>. SQL Server is case-insensitive and accepts a bare identifier; PostgreSQL folds unquoted identifiers to lowercase, so we must quote the alias when the caller cares about preserving case (e.g. matching a TypeScript property name in the result row).

      Parameters

      • aliasName: string

      Returns string

    • Produces a schema-qualified object reference. SQL Server: [schema].[object], PostgreSQL: schema."object"

      Parameters

      • schema: string
      • object: string

      Returns string

    • Quotes a value as a SQL string literal. Both SQL Server and PostgreSQL use single quotes with '' doubling to escape internal apostrophes. Use this instead of reinventing the value.replace(/'/g, "''") pattern; the dialect's writer owns the escape rule.

      Parameters

      • value: string

      Returns string

    • Returns a non-fatal signal/notice statement detectable in CLI output. Used for signaling conditions (e.g., "lock held") without aborting the script. SQL Server: RAISERROR('message', 16, 1) — appears in sqlcmd stdout PostgreSQL: RAISE NOTICE 'message' — appears in psql stderr

      Note: For PostgreSQL, this must be used inside a ConditionalBlock (DO $$ context).

      Parameters

      • message: string

        Signal message to emit (used for detection in CLI output)

      Returns string

    • SQL that discards a savepoint after a nested commit, or null when the platform has no release (SQL Server savepoints live until the outer TX ends). PostgreSQL: RELEASE SAVEPOINT name.

      Parameters

      • name: string

      Returns string | null

    • Resolves an abstract schema field type to a concrete SQL type string. Used by SchemaEngine for DDL generation from platform-agnostic definitions. SQL Server: 'string' -> 'NVARCHAR(255)', 'boolean' -> 'BIT' PostgreSQL: 'string' -> 'VARCHAR(255)', 'boolean' -> 'BOOLEAN'

      Parameters

      Returns string

    • Returns the clause used to get inserted values back. SQL Server: OUTPUT INSERTED.col1, INSERTED.col2 PostgreSQL: RETURNING col1, col2

      Parameters

      • Optionalcolumns: string[]

      Returns string

    • SQL that undoes work after a savepoint. SQL Server: ROLLBACK TRANSACTION name. PostgreSQL: ROLLBACK TO SAVEPOINT name.

      Parameters

      • name: string

      Returns string

    • Returns the row count variable/expression for the last statement. SQL Server: @@ROWCOUNT, PostgreSQL: (via GET DIAGNOSTICS or FOUND)

      Returns string

    • Returns the expression to get the last inserted identity value. SQL Server: SCOPE_IDENTITY(), PostgreSQL: lastval()

      Returns string

    • Splits an oversized SQL batch into individual statements on ;+EOL boundaries so a caller (e.g. the RSU migration executor) can re-group them into smaller chunks that each fit under a client request timeout.

      Base implementation = the naive split(/;\s*\n/g) semantics: split on a ; followed by optional inline whitespace and a newline, trim each fragment, drop empties, and ensure each returned statement ends with ;. This is correct for SQL Server (no dollar-quoted blocks).

      PostgreSQL overrides this with a dollar-quote-aware split that never tears apart DO $$ … $$ / $tag$ … $tag$ blocks whose bodies legitimately contain ;+newline.

      Parameters

      • batch: string

      Returns string[]

    • The prefix a string literal holding text needs so the database keeps every character, or '' when a plain literal does. SQL Server: N when the text has characters outside ASCII, which a plain literal would lose to the database code page. PostgreSQL: always ''.

      Parameters

      • text: string

      Returns string

    • Returns a STRING_SPLIT or equivalent expression. SQL Server: STRING_SPLIT(value, delimiter) PostgreSQL: string_to_array(value, delimiter) or regexp_split_to_table

      Parameters

      • value: string
      • delimiter: string

      Returns string

    • Returns the default expression for a UUID primary key. SQL Server: NEWSEQUENTIALID(), PostgreSQL: gen_random_uuid()

      Returns string