Postgres Types

Postgres AST TypeScript Definitions

TypeScript type definitions for Postgres AST nodes, facilitating type-safe construction, analysis, and manipulation of ASTs. Essential for building robust Postgres query tools with full type safety.

Type-Safe AST

Complete TypeScript definitions for Postgres AST nodes

AST Construction

Build and validate AST nodes with full type safety

Multi-Version Support

Supports Postgres versions 13 through 18

Postgres Types Features

Comprehensive TypeScript definitions for Postgres AST manipulation

Complete Type Safety

Comprehensive TypeScript type definitions for all Postgres AST nodes, ensuring type-safe construction and manipulation.

AST Node Construction

Build Postgres AST nodes with full type safety, IntelliSense support, and compile-time validation.

Multi-Version Postgres Support

Supports Postgres versions 13 through 18 with version-specific type definitions and npm dist-tags.

AST Analysis and Validation

Validate and analyze AST nodes with type-safe interfaces that ensure conformance to Postgres specifications.

Comprehensive Coverage

Covers all Postgres AST node types including statements, expressions, clauses, and data types.

Enhanced Developer Experience

Full IntelliSense support, autocomplete, and type checking for improved productivity and reduced errors.

typescript
import { ColumnDef, ColumnRef, Constraint, CreateStmt, RangeVar, ResTarget, SelectStmt, TypeName } from '@pgsql/types';

// Type-safe CREATE TABLE statement construction
function createTableStatement(
	tableName: string,
	columns: Array<{
		name: string;
		type: string;
		nullable?: boolean;
	}>,
): CreateStmt {
	const tableElements: ColumnDef[] = columns.map((col) => {
		const constraints: Constraint[] = [];

		if (col.nullable === false) {
			constraints.push({
				contype: 'CONSTR_NOTNULL',
				conname: null,
				deferrable: false,
				initdeferred: false,
				location: -1,
			});
		}

		return {
			colname: col.name,
			typeName: { names: [{ String: { sval: col.type } }] },
			constraints,
			is_local: true,
			is_not_null: !col.nullable,
			is_from_type: false,
			storage: '\0',
			raw_default: null,
			cooked_default: null,
			identity: '\0',
			identitySequence: null,
			generated: '\0',
			collClause: null,
			collOid: 0,
			fdwoptions: null,
			location: -1,
		};
	});

	return {
		relation: {
			catalogname: null,
			schemaname: null,
			relname: tableName,
			inh: true,
			relpersistence: 'p',
			alias: null,
			location: -1,
		},
		tableElts: tableElements,
		inhRelations: [],
		partbound: null,
		partspec: null,
		ofTypename: null,
		constraints: [],
		options: [],
		oncommit: 'ONCOMMIT_NOOP',
		tablespacename: null,
		accessMethod: null,
		if_not_exists: false,
	};
}

// Usage
const userTable = createTableStatement('users', [
	{ name: 'id', type: 'serial', nullable: false },
	{ name: 'name', type: 'varchar', nullable: false },
	{ name: 'email', type: 'varchar', nullable: true },
]);

console.log('Created table AST:', userTable);

AST Node Construction and Validation

Build and validate Postgres AST nodes with complete type safety and compile-time error checking.

typescript
import { A_Expr, ColumnRef, RangeVar, ResTarget, SelectStmt } from '@pgsql/types';

// Type-safe SELECT statement construction
function createSelectStatement(
	tableName: string,
	columns: string[],
	whereCondition?: { column: string; operator: string; value: any },
): SelectStmt {
	const targetList: ResTarget[] = columns.map((col) => ({
		name: null,
		indirection: null,
		val: {
			ColumnRef: {
				fields: [{ String: { sval: col } }],
				location: -1,
			},
		},
		location: -1,
	}));

	const fromClause: RangeVar[] = [
		{
			catalogname: null,
			schemaname: null,
			relname: tableName,
			inh: true,
			relpersistence: 'p',
			alias: null,
			location: -1,
		},
	];

	let whereClause = null;
	if (whereCondition) {
		whereClause = {
			A_Expr: {
				kind: 'AEXPR_OP',
				name: [{ String: { sval: whereCondition.operator } }],
				lexpr: {
					ColumnRef: {
						fields: [{ String: { sval: whereCondition.column } }],
						location: -1,
					},
				},
				rexpr: {
					A_Const: {
						isnull: false,
						val: { String: { sval: whereCondition.value.toString() } },
						location: -1,
					},
				},
				location: -1,
			},
		};
	}

	return {
		distinctClause: null,
		targetList,
		fromClause,
		whereClause,
		groupClause: null,
		groupDistinct: false,
		havingClause: null,
		windowClause: null,
		valuesLists: null,
		sortClause: null,
		limitOffset: null,
		limitCount: null,
		limitOption: 'LIMIT_OPTION_DEFAULT',
		lockingClause: null,
		withClause: null,
		op: 'SETOP_NONE',
		all: false,
		larg: null,
		rarg: null,
	};
}

// Usage
const selectQuery = createSelectStatement('users', ['id', 'name', 'email'], {
	column: 'active',
	operator: '=',
	value: true,
});

console.log('Created SELECT AST:', selectQuery);

Type-Safe AST Analysis

Analyze and traverse Postgres ASTs with type-safe interfaces that ensure correct property access and validation.

typescript
import { CreateStmt, InsertStmt, NodeTag, SelectStmt } from '@pgsql/types';

// Type validation utilities
class ASTValidator {
	static isSelectStatement(node: any): node is SelectStmt {
		return node && typeof node === 'object' && 'targetList' in node;
	}

	static isCreateStatement(node: any): node is CreateStmt {
		return node && typeof node === 'object' && 'relation' in node && 'tableElts' in node;
	}

	static isInsertStatement(node: any): node is InsertStmt {
		return node && typeof node === 'object' && 'relation' in node && 'selectStmt' in node;
	}

	static validateStatement(stmt: any): { valid: boolean; type: string; errors: string[] } {
		const errors: string[] = [];

		if (this.isSelectStatement(stmt)) {
			if (!stmt.targetList || stmt.targetList.length === 0) {
				errors.push('SELECT statement must have target list');
			}
			if (!stmt.fromClause || stmt.fromClause.length === 0) {
				errors.push('SELECT statement must have FROM clause');
			}
			return { valid: errors.length === 0, type: 'SELECT', errors };
		}

		if (this.isCreateStatement(stmt)) {
			if (!stmt.relation || !stmt.relation.relname) {
				errors.push('CREATE statement must have table name');
			}
			if (!stmt.tableElts || stmt.tableElts.length === 0) {
				errors.push('CREATE statement must have columns');
			}
			return { valid: errors.length === 0, type: 'CREATE', errors };
		}

		return { valid: false, type: 'UNKNOWN', errors: ['Unknown statement type'] };
	}
}

// Usage
const validation = ASTValidator.validateStatement(selectQuery);
console.log('Validation result:', validation);

Advanced AST Manipulation

Perform complex AST transformations and modifications with full type safety and validation support.