CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sql-formatter

Format whitespace in a SQL query to make it more readable with support for multiple SQL dialects

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities

Helper functions for expanding SQL syntax patterns and handling configuration validation.

Capabilities

Expand Phrases

Utility function for expanding SQL syntax patterns with optional and alternative elements.

/**
 * Performs expandSinglePhrase() on array of phrases
 * @param phrases - Array of syntax description strings
 * @returns Array of all possible combinations
 */
function expandPhrases(phrases: string[]): string[];

/**
 * Expands a single syntax description into all possible combinations
 * @param phrase - Syntax description with optional [] and alternative {} elements
 * @returns Array of all possible phrase combinations
 */
function expandSinglePhrase(phrase: string): string[];

This function is used internally by dialect definitions to expand syntax patterns like "CREATE [OR REPLACE] [TEMP|TEMPORARY] TABLE" into all possible combinations.

Syntax Pattern Rules:

  • [OPTIONAL] - Optional elements (can be present or absent)
  • {REQUIRED|ALTERNATIVE} - Required choice between alternatives
  • [OPTIONAL {CHOICE1|CHOICE2}] - Nested patterns supported
  • Elements can be nested to any depth

Usage Examples:

import { expandPhrases } from "sql-formatter";

// Simple optional element
const result1 = expandPhrases(["CREATE [TEMPORARY] TABLE"]);
// Result: ["CREATE TABLE", "CREATE TEMPORARY TABLE"]

// Required alternatives
const result2 = expandPhrases(["DROP {TABLE|VIEW}"]);
// Result: ["DROP TABLE", "DROP VIEW"]

// Complex nested pattern
const result3 = expandPhrases([
  "CREATE [OR REPLACE] [TEMP|TEMPORARY] TABLE"
]);
// Result: [
//   "CREATE TABLE",
//   "CREATE TEMP TABLE", 
//   "CREATE TEMPORARY TABLE",
//   "CREATE OR REPLACE TABLE",
//   "CREATE OR REPLACE TEMP TABLE",
//   "CREATE OR REPLACE TEMPORARY TABLE"
// ]

// Multiple patterns
const result4 = expandPhrases([
  "SELECT [ALL | DISTINCT]",
  "INSERT [IGNORE] [INTO]"
]);
// Result: [
//   "SELECT", "SELECT ALL", "SELECT DISTINCT",
//   "INSERT", "INSERT IGNORE", "INSERT INTO", "INSERT IGNORE INTO"  
// ]

Advanced Pattern Examples:

import { expandPhrases } from "sql-formatter";

// Nested optional with alternatives
const patterns = expandPhrases([
  "FOR [OF {UNIQUE | MANDATORY} TABLES]"
]);
// Result: [
//   "FOR",
//   "FOR OF UNIQUE TABLES", 
//   "FOR OF MANDATORY TABLES"
// ]

// Complex MySQL-style patterns
const mysqlPatterns = expandPhrases([
  "UPDATE [LOW_PRIORITY] [IGNORE]",
  "DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM"
]);

Configuration Error

Error class for configuration validation failures.

class ConfigError extends Error {
  constructor(message: string);
}

This error is thrown when invalid configuration options are provided to formatting functions.

Common Configuration Errors:

  • Unsupported SQL dialect
  • Invalid expressionWidth (must be positive)
  • Deprecated configuration options
  • Invalid parameter configuration

Usage Examples:

import { format, ConfigError } from "sql-formatter";

try {
  const result = format("SELECT * FROM users", {
    language: "invalid-dialect"
  });
} catch (error) {
  if (error instanceof ConfigError) {
    console.error("Configuration error:", error.message);
    // Output: "Configuration error: Unsupported SQL dialect: invalid-dialect"
  }
}

try {
  const result = format("SELECT * FROM users", {
    expressionWidth: -10
  });
} catch (error) {
  if (error instanceof ConfigError) {
    console.error("Invalid expression width:", error.message);
  }
}

Configuration Validation

Internal validation function for format options.

/**
 * Validates and normalizes configuration options
 * @param cfg - Configuration object to validate
 * @returns Validated configuration object
 * @throws ConfigError for invalid configuration
 */
function validateConfig(cfg: FormatOptions): FormatOptions;

This function is used internally but can be useful for validating configuration before formatting.

Validation Rules:

  • expressionWidth must be a positive number
  • Parameter values should be strings (shows warning if not)
  • Custom parameter regex cannot be empty
  • Removed options trigger ConfigError

Usage Examples:

import { validateConfig, ConfigError } from "sql-formatter";

try {
  const validatedConfig = validateConfig({
    tabWidth: 4,
    keywordCase: "upper",
    expressionWidth: 80
  });
  console.log("Configuration is valid");
} catch (error) {
  if (error instanceof ConfigError) {
    console.error("Invalid configuration:", error.message);
  }
}

// Check for deprecated options
try {
  const config = validateConfig({
    tabWidth: 2,
    multilineLists: true // Deprecated option
  });
} catch (error) {
  if (error instanceof ConfigError) {
    console.error("Deprecated option:", error.message);
    // Output: "multilineLists config is no more supported."
  }
}

Internal Utility Types

These types are used internally but exported for advanced usage:

interface IdentChars {
  /** Additional characters for first character of identifier */
  first?: string;
  /** Additional characters after first character */
  rest?: string;
  /** Allow single dashes inside identifiers */
  dashes?: boolean;
  /** Allow identifier to begin with number */
  allowFirstCharNumber?: boolean;
}

type PlainQuoteType = keyof typeof quotePatterns;

interface PrefixedQuoteType {
  quote: PlainQuoteType;
  prefixes: string[];
  requirePrefix?: boolean;
}

interface RegexPattern {
  regex: string;
}

type QuoteType = PlainQuoteType | PrefixedQuoteType | RegexPattern;
type VariableType = RegexPattern | PrefixedQuoteType;

These types are primarily used in dialect definitions and tokenizer configuration.

Install with Tessl CLI

npx tessl i tessl/npm-sql-formatter

docs

cli.md

configuration.md

core-formatting.md

dialects.md

index.md

parameters.md

utilities.md

tile.json