rawsql-ts
Version:
[beta]High-performance SQL parser and AST analyzer written in TypeScript. Provides fast parsing and advanced transformation capabilities.
79 lines (78 loc) • 2.84 kB
TypeScript
import { SimpleSelectQuery } from '../models/SimpleSelectQuery';
/**
* Universal JSON mapping definition for creating any level of JSON structures.
* Supports flat arrays, nested objects, and unlimited hierarchical structures.
*/
export interface JsonMapping {
rootName: string;
rootEntity: {
id: string;
name: string;
columns: {
[jsonKey: string]: string;
};
};
nestedEntities: Array<{
id: string;
name: string;
parentId: string;
propertyName: string;
relationshipType?: "object" | "array";
columns: {
[jsonKey: string]: string;
};
}>;
useJsonb?: boolean;
resultFormat?: "array" | "single";
emptyResult?: string;
}
/**
* PostgreSQL JSON query builder that transforms SimpleSelectQuery into queries
* that return JSON arrays or single JSON objects using PostgreSQL JSON functions.
*/
export declare class PostgreJsonQueryBuilder {
private selectValueCollector;
private objectEntityCteBuilder;
private arrayEntityCteBuilder;
constructor();
/**
* Validates the JSON mapping and the original query.
* @param query Original query to transform
* @param mapping JSON mapping configuration
*/
private validateMapping;
/**
* Build JSON query from original query and mapping configuration.
* @param originalQuery Original query to transform
* @param mapping JSON mapping configuration
* @returns Transformed query with JSON aggregation
*/
buildJson(originalQuery: SimpleSelectQuery, mapping: JsonMapping): SimpleSelectQuery;
/**
* Builds the JSON structure using a unified CTE-based strategy.
* @param originalQuery Original query
* @param mapping JSON mapping configuration
* @returns Query with CTE-based JSON aggregation
*/
private buildJsonWithCteStrategy;
/**
* Creates the initial Common Table Expression (CTE) from the original query.
* @param originalQuery The base SimpleSelectQuery.
* @returns An object containing the initial CTE and its alias.
*/
private createInitialCte;
/**
* Builds the final SELECT query that constructs the root JSON object (or array of objects).
* This query uses all previously generated CTEs.
* @param finalCtesList The complete list of all CTEs (initial and array CTEs).
* @param lastCteAliasForFromClause Alias of the final CTE from which the root object will be built.
* @param allEntities Map of all processable entities.
* @param mapping JSON mapping configuration.
* @returns The final SimpleSelectQuery.
*/
private buildFinalSelectQuery;
/**
* Build JSON object for entity, using parent JSON columns when available
*/
private buildEntityJsonObject;
}