Simple SQL parser library that converts SQL statements to AST and back to SQL with support for multiple database engines
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Helper functions for SQL string manipulation, AST processing, and database-specific formatting. These utilities provide lower-level functionality for working with SQL structures and AST nodes.
Create AST nodes for literal values.
/**
* Create value expression AST from JavaScript values
* @param value - JavaScript value to convert
* @returns ValueExpr AST node
*/
createValueExpr(value: any): ValueExpr;
interface ValueExpr<T = string | number | boolean> {
type: "string" | "number" | "boolean" | "bool" | "null" | "expr_list";
value: T;
}Usage Examples:
import { createValueExpr } from 'node-sql-parser/lib/util';
// Create different value types
const stringExpr = createValueExpr('hello');
console.log(stringExpr); // { type: 'string', value: 'hello' }
const numberExpr = createValueExpr(42);
console.log(numberExpr); // { type: 'number', value: 42 }
const boolExpr = createValueExpr(true);
console.log(boolExpr); // { type: 'bool', value: true }
const nullExpr = createValueExpr(null);
console.log(nullExpr); // { type: 'null', value: null }
// Array values create expression lists
const arrayExpr = createValueExpr([1, 2, 3]);
console.log(arrayExpr);
// { type: 'expr_list', value: [{ type: 'number', value: 1 }, ...] }Create AST nodes for binary operations.
/**
* Create binary expression AST
* @param operator - Binary operator string
* @param left - Left operand
* @param right - Right operand
* @returns Binary expression AST node
*/
createBinaryExpr(operator: string, left: any, right: any): Binary;
interface Binary {
type: "binary_expr";
operator: string;
left: ExpressionValue | ExprList;
right: ExpressionValue | ExprList;
}Usage Examples:
import { createBinaryExpr, createValueExpr } from 'node-sql-parser/lib/util';
// Create comparison expression
const leftCol = { type: 'column_ref', table: null, column: 'age' };
const rightVal = createValueExpr(18);
const comparison = createBinaryExpr('>=', leftCol, rightVal);
console.log(comparison);
// {
// type: 'binary_expr',
// operator: '>=',
// left: { type: 'column_ref', table: null, column: 'age' },
// right: { type: 'number', value: 18 }
// }
// Create logical expression
const expr1 = createBinaryExpr('>', leftCol, createValueExpr(0));
const expr2 = createBinaryExpr('<', leftCol, createValueExpr(100));
const logicalExpr = createBinaryExpr('AND', expr1, expr2);
console.log(logicalExpr.operator); // 'AND'Functions for handling SQL string literals and identifiers.
/**
* Escape SQL string literal (currently returns input unchanged)
* @param str - String to escape
* @returns Escaped string
*/
escape(str: string): string;
/**
* Convert literal value to SQL string
* @param literal - Literal value to convert
* @returns SQL string representation
*/
literalToSQL(literal: any): string;
/**
* Convert identifier to SQL with proper quoting
* @param identifier - Identifier to convert
* @param isDual - Whether this is a dual table context
* @param surround - Custom surrounding characters
* @returns Quoted SQL identifier
*/
identifierToSql(identifier: string, isDual?: boolean, surround?: string): string;
/**
* Convert column identifier to SQL
* @param identifier - Column identifier to convert
* @returns Quoted SQL column identifier
*/
columnIdentifierToSql(identifier: string): string;Usage Examples:
import { escape, literalToSQL, identifierToSql, columnIdentifierToSql } from 'node-sql-parser/lib/util';
// String escaping (currently no-op)
const escaped = escape("O'Reilly");
console.log(escaped); // "O'Reilly"
// Literal conversion
const stringLiteral = literalToSQL({ type: 'string', value: 'hello' });
console.log(stringLiteral); // "'hello'"
const numberLiteral = literalToSQL({ type: 'number', value: 42 });
console.log(numberLiteral); // "42"
const boolLiteral = literalToSQL({ type: 'bool', value: true });
console.log(boolLiteral); // "TRUE"
// Identifier quoting (database-specific)
const mysqlId = identifierToSql("user_name");
console.log(mysqlId); // "`user_name`"
const columnId = columnIdentifierToSql("email_address");
console.log(columnId); // "`email_address`"Convert data type definitions to SQL strings.
/**
* Convert data type definition to SQL string
* @param expr - Data type object to convert
* @returns SQL data type string
*/
dataTypeToSQL(expr: DataType): string;
interface DataType {
dataType: string;
length?: number;
parentheses?: boolean;
scale?: number;
suffix?: string[];
}Usage Examples:
import { dataTypeToSQL } from 'node-sql-parser/lib/util';
// Basic data types
const varchar = dataTypeToSQL({ dataType: 'VARCHAR', length: 255, parentheses: true });
console.log(varchar); // "VARCHAR(255)"
const decimal = dataTypeToSQL({
dataType: 'DECIMAL',
length: 10,
scale: 2,
parentheses: true
});
console.log(decimal); // "DECIMAL(10, 2)"
// Data types with suffixes
const unsignedInt = dataTypeToSQL({
dataType: 'INT',
suffix: ['UNSIGNED']
});
console.log(unsignedInt); // "INT UNSIGNED"Functions for managing parser options and settings.
/**
* Get current parser options
* @returns Current parser configuration
*/
getParserOpt(): Option;
/**
* Set parser options
* @param opt - Parser options to set
*/
setParserOpt(opt: Option): void;
/**
* Default parser options
*/
DEFAULT_OPT: Option;
interface Option {
database: string;
type: string;
trimQuery: boolean;
parseOptions: {
includeLocations: boolean;
};
}Usage Examples:
import { getParserOpt, setParserOpt, DEFAULT_OPT } from 'node-sql-parser/lib/util';
// Get current options
const currentOpt = getParserOpt();
console.log(currentOpt.database); // Current database setting
// Set new options
setParserOpt({
database: 'PostgreSQL',
type: 'table',
trimQuery: false,
parseOptions: { includeLocations: true }
});
// Access default options
console.log(DEFAULT_OPT);
// {
// database: 'mysql',
// type: 'table',
// trimQuery: true,
// parseOptions: { includeLocations: false }
// }Replace parameter placeholders in AST with actual values.
/**
* Replace parameters in AST with actual values
* @param ast - AST to process
* @param params - Parameter values to substitute
* @returns Modified AST with parameters replaced
*/
replaceParams(ast: AST, params: any): AST;Usage Examples:
import { Parser } from 'node-sql-parser';
import { replaceParams } from 'node-sql-parser/lib/util';
// Parse SQL with parameters
const parser = new Parser();
const ast = parser.astify('SELECT * FROM users WHERE id = :id AND status = :status');
// Replace parameters
const withParams = replaceParams(ast, {
id: 123,
status: 'active'
});
// Convert back to SQL
const sql = parser.sqlify(withParams);
console.log(sql); // "SELECT * FROM `users` WHERE `id` = 123 AND `status` = 'active'"Utility functions for common operations.
/**
* Check if value exists (truthy check)
* @param val - Value to check
* @returns True if value is truthy
*/
hasVal(val: any): boolean;
/**
* Convert string to uppercase if it exists
* @param val - String to convert
* @returns Uppercase string or undefined
*/
toUpper(val: string): string | undefined;
/**
* Connect keyword with string
* @param keyword - SQL keyword
* @param str - String to connect
* @returns Connected string or undefined
*/
connector(keyword: string, str: string): string | undefined;
/**
* Connect common options with keywords
* @param keyword - SQL keyword
* @param action - Action function
* @param opt - Options object
* @returns Connected string or undefined
*/
commonOptionConnector(keyword: string, action: Function, opt: any): string | undefined;Usage Examples:
import { hasVal, toUpper, connector, commonOptionConnector } from 'node-sql-parser/lib/util';
// Value checking
console.log(hasVal('hello')); // true
console.log(hasVal(null)); // false
console.log(hasVal('')); // false
// String operations
console.log(toUpper('select')); // "SELECT"
// Keyword connection
const orderClause = connector('ORDER BY', 'name ASC');
console.log(orderClause); // "ORDER BY name ASC"
// Option connection
const limitClause = commonOptionConnector(
'LIMIT',
(opt) => opt.count.toString(),
{ count: 10 }
);
console.log(limitClause); // "LIMIT 10"Functions for handling SQL comments.
/**
* Convert comment object to SQL string
* @param comment - Comment object to convert
* @returns SQL comment string
*/
commentToSQL(comment: KeywordComment): string;
interface KeywordComment {
type: "comment";
keyword: "comment";
symbol?: "=";
value: string;
}Specialized functions for specific SQL clauses.
/**
* Convert TOP clause to SQL (SQL Server)
* @param opt - TOP clause options
* @returns SQL TOP clause
*/
topToSQL(opt: TopOptions): string;
interface TopOptions {
value: number | string;
percent?: string;
parentheses?: boolean;
}
/**
* Convert AUTO_INCREMENT to SQL
* @param autoIncrement - Auto increment specification
* @returns SQL auto increment clause
*/
autoIncrementToSQL(autoIncrement: string | AutoIncrementOptions): string;
interface AutoIncrementOptions {
keyword: string;
seed: any;
increment: any;
parentheses?: boolean;
}
/**
* Convert RETURNING clause to SQL
* @param returning - RETURNING clause object
* @returns SQL RETURNING clause
*/
returningToSQL(returning: Returning): string;
interface Returning {
columns: any[];
}
/**
* Convert partitions specification to SQL
* @param expr - Partitions expression
* @returns SQL partitions clause
*/
onPartitionsToSQL(expr: PartitionsExpr): string;
interface PartitionsExpr {
type: string;
partitions: any[];
}
/**
* Convert trigger event to SQL
* @param events - Trigger event objects
* @returns SQL trigger event
*/
triggerEventToSQL(events: TriggerEvent[]): string;
interface TriggerEvent {
keyword: string;
args?: {
keyword: string;
columns: any[];
};
}Functions for handling complex data structures.
/**
* Convert array/struct type to SQL
* @param expr - Array or struct type definition
* @returns SQL array/struct type
*/
arrayStructTypeToSQL(expr: ArrayStructType): string;
interface ArrayStructType {
dataType: string;
definition?: any[];
anglebracket?: boolean;
}
/**
* Convert column order list to SQL
* @param columnOrderList - List of column order specifications
* @returns SQL column order clause
*/
columnOrderListToSQL(columnOrderList: any[]): string;
/**
* Convert common keyword arguments to SQL
* @param kwArgs - Keyword arguments object
* @returns SQL keyword arguments array
*/
commonKeywordArgsToSQL(kwArgs: KeywordArgs): string[];
interface KeywordArgs {
keyword: string;
args: string;
}
/**
* Get common type value
* @param opt - Type value options
* @returns Array of processed values
*/
commonTypeValue(opt: TypeValueOptions): string[];
interface TypeValueOptions {
type: string;
symbol?: string;
value: string | any;
}Usage Examples:
import {
arrayStructTypeToSQL,
columnOrderListToSQL,
commonTypeValue
} from 'node-sql-parser/lib/util';
// Array type processing
const arrayType = arrayStructTypeToSQL({
dataType: 'ARRAY',
definition: [{ field_name: 'id', field_type: { dataType: 'INT' } }],
anglebracket: true
});
console.log(arrayType); // "ARRAY<id INT>"
// Common type value processing
const typeValue = commonTypeValue({
type: 'CHARACTER SET',
symbol: '=',
value: 'utf8'
});
console.log(typeValue); // ['CHARACTER SET', '=', 'UTF8']These utility functions provide the building blocks for more complex SQL processing and can be used to create custom SQL manipulation tools or extend the parser's functionality for specific use cases.