mirror of
https://github.com/t8y2/dbx.git
synced 2026-10-31 00:22:30 +00:00
50 lines
1.8 KiB
TypeScript
50 lines
1.8 KiB
TypeScript
import type { DatabaseType } from "../types/database.ts";
|
|
import { isSchemaAware } from "./databaseCapabilities.ts";
|
|
import * as api from "./api.ts";
|
|
|
|
export interface BuildTableSelectSqlOptions {
|
|
databaseType?: DatabaseType;
|
|
schema?: string;
|
|
tableName: string;
|
|
primaryKeys?: string[];
|
|
columns?: string[];
|
|
fallbackOrderColumns?: string[];
|
|
orderBy?: string;
|
|
limit?: number;
|
|
offset?: number;
|
|
whereInput?: string;
|
|
includeRowId?: boolean;
|
|
}
|
|
|
|
export function quoteTableIdentifier(databaseType: DatabaseType | undefined, name: string): string {
|
|
if (databaseType === "mysql" || databaseType === "hive" || databaseType === "tdengine" || databaseType === "access")
|
|
return `\`${name.replace(/`/g, "``")}\``;
|
|
if (databaseType === "informix" && /^[A-Za-z_][A-Za-z0-9_$]*$/.test(name)) return name;
|
|
if (databaseType === "neo4j") return quoteCypherIdentifier(name);
|
|
if (databaseType === "sqlserver") return `[${name.replace(/\]/g, "]]")}]`;
|
|
return `"${name.replace(/"/g, '""')}"`;
|
|
}
|
|
|
|
function quoteCypherIdentifier(name: string): string {
|
|
return `\`${name.replace(/`/g, "``")}\``;
|
|
}
|
|
|
|
export function qualifiedTableName(
|
|
options: Pick<BuildTableSelectSqlOptions, "databaseType" | "schema" | "tableName">,
|
|
): string {
|
|
const { databaseType, schema, tableName } = options;
|
|
if (isSchemaAware(databaseType) && schema) {
|
|
return `${quoteTableIdentifier(databaseType, schema)}.${quoteTableIdentifier(databaseType, tableName)}`;
|
|
}
|
|
return quoteTableIdentifier(databaseType, tableName);
|
|
}
|
|
|
|
export function normalizeWhereInput(whereInput?: string): string {
|
|
const withoutSemicolon = whereInput?.trim().replace(/;+$/, "").trim() ?? "";
|
|
return withoutSemicolon.replace(/^where\b/i, "").trim();
|
|
}
|
|
|
|
export async function buildTableSelectSql(options: BuildTableSelectSqlOptions): Promise<string> {
|
|
return api.buildTableSelectSql(options);
|
|
}
|