Skip to content

Commit

Permalink
support raw based holder
Browse files Browse the repository at this point in the history
  • Loading branch information
invisal committed Nov 21, 2024
1 parent 40ce6e8 commit b977e9c
Show file tree
Hide file tree
Showing 3 changed files with 166 additions and 13 deletions.
13 changes: 2 additions & 11 deletions src/connections/postgre/postgresql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,16 @@ import { QueryResult } from '..';
import { Query } from '../../query';
import { AbstractDialect } from './../../query-builder';
import { PostgresDialect } from './../../query-builder/dialects/postgres';
import { QueryType } from './../../query-params';
import {
createErrorResult,
transformArrayBasedResult,
} from './../../utils/transformer';
import { PostgreBaseConnection } from './base';

function replacePlaceholders(query: string): string {
let index = 1;
return query.replace(/\?/g, () => `$${index++}`);
}

export class PostgreSQLConnection extends PostgreBaseConnection {
client: Client;
dialect: AbstractDialect = new PostgresDialect();
queryType: QueryType = QueryType.positional;
protected numberedPlaceholder = true;

constructor(pgClient: any) {
super();
Expand All @@ -38,10 +32,7 @@ export class PostgreSQLConnection extends PostgreBaseConnection {
): Promise<QueryResult<T>> {
try {
const { rows, fields } = await this.client.query({
text:
query.parameters?.length === 0
? query.query
: replacePlaceholders(query.query),
text: query.query,
rowMode: 'array',
values: query.parameters as unknown[],
});
Expand Down
33 changes: 31 additions & 2 deletions src/connections/sql-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@ import {
} from '..';
import { AbstractDialect, ColumnDataType } from './../query-builder';
import { TableColumn, TableColumnDefinition } from './../models/database';
import {
namedPlaceholder,
toNumberedPlaceholders,
} from './../utils/placeholder';

export abstract class SqlConnection extends Connection {
abstract dialect: AbstractDialect;
protected numberedPlaceholder = false;

abstract query<T = Record<string, unknown>>(
query: Query
Expand All @@ -21,8 +26,32 @@ export abstract class SqlConnection extends Connection {
return dataType;
}

async raw(query: string): Promise<QueryResult> {
return await this.query({ query });
async raw(
query: string,
params?: Record<string, unknown> | unknown[]
): Promise<QueryResult> {
if (!params) return await this.query({ query });

// Positional placeholder
if (Array.isArray(params)) {
if (this.numberedPlaceholder) {
const { query: newQuery, bindings } = toNumberedPlaceholders(
query,
params
);

return await this.query({
query: newQuery,
parameters: bindings,
});
}

return await this.query({ query, parameters: params });
}

// Named placeholder
const { query: newQuery, bindings } = namedPlaceholder(query, params!);
return await this.query({ query: newQuery, parameters: bindings });
}

async select(
Expand Down
133 changes: 133 additions & 0 deletions src/utils/placeholder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
const RE_PARAM = /(?:\?)|(?::(\d+|(?:[a-zA-Z][a-zA-Z0-9_]*)))/g,
DQUOTE = 34,
SQUOTE = 39,
BSLASH = 92;

/**
* This code is based on https://github.com/mscdex/node-mariasql/blob/master/lib/Client.js#L296-L420
* License: https://github.com/mscdex/node-mariasql/blob/master/LICENSE
*
* @param query
* @returns
*/
function parse(query: string): [string] | [string[], (string | number)[]] {
let ppos = RE_PARAM.exec(query);
let curpos = 0;
let start = 0;
let end;
const parts = [];
let inQuote = false;
let escape = false;
let qchr;
const tokens = [];
let qcnt = 0;
let lastTokenEndPos = 0;
let i;

if (ppos) {
do {
for (i = curpos, end = ppos.index; i < end; ++i) {
let chr = query.charCodeAt(i);
console.log(i, query[i], inQuote, qchr);
if (chr === BSLASH) escape = !escape;
else {
if (escape) {
escape = false;
continue;
}
if (inQuote && chr === qchr) {
if (query.charCodeAt(i + 1) === qchr) {
// quote escaped via "" or ''
++i;
continue;
}
inQuote = false;
} else if (!inQuote && (chr === DQUOTE || chr === SQUOTE)) {
inQuote = true;
qchr = chr;
}
}
}
if (!inQuote) {
parts.push(query.substring(start, end));
tokens.push(ppos[0].length === 1 ? qcnt++ : ppos[1]);
start = end + ppos[0].length;
lastTokenEndPos = start;
}
curpos = end + ppos[0].length;
} while ((ppos = RE_PARAM.exec(query)));

if (tokens.length) {
if (curpos < query.length) {
parts.push(query.substring(lastTokenEndPos));
}
return [parts, tokens];
}
}
return [query];
}

export function namedPlaceholder(
query: string,
params: Record<string, unknown>,
numbered = false
): { query: string; bindings: unknown[] } {
const parts = parse(query);

if (parts.length === 1) {
return { query, bindings: [] };
}

const bindings = [];
let newQuery = '';

const [sqlFragments, placeholders] = parts;

for (let i = 0; i < sqlFragments.length; i++) {
newQuery += sqlFragments[i];

if (i < placeholders.length) {
const key = placeholders[i];

if (numbered) {
newQuery += `$${key}`;
} else {
newQuery += `?`;
}

bindings.push(params[key]);
}
}

return { query: newQuery, bindings };
}

export function toNumberedPlaceholders(
query: string,
params: unknown[]
): {
query: string;
bindings: unknown[];
} {
const parts = parse(query);

if (parts.length === 1) {
return { query, bindings: [] };
}

const bindings = [];
let newQuery = '';

const [sqlFragments, placeholders] = parts;

for (let i = 0; i < sqlFragments.length; i++) {
newQuery += sqlFragments[i];

if (i < placeholders.length) {
newQuery += `$${i + 1}`;
bindings.push(params[i]);
}
}

return { query: newQuery, bindings };
}

0 comments on commit b977e9c

Please sign in to comment.