Skip to content

Commit

Permalink
feat: stringify sql with options
Browse files Browse the repository at this point in the history
  • Loading branch information
SkeLLLa committed Aug 13, 2024
1 parent 3ef8ccc commit ca1d8a0
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './utils/format';
export * from './utils/tag';
export * from './utils/sql-utils';
export * from './client/clients';
export * from './client/broker/transport/transports';
export * from './client/errors/pinot';
31 changes: 31 additions & 0 deletions src/utils/sql-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Sql } from '@no-esm/sql-template-tag';
import { IPinotQueryOptions } from '../client/clients';
import { SqlFormat } from './format';

export class SqlUtils {
static formatOptions(options?: IPinotQueryOptions): string {
if (!options) {
return '';
}
return Object.entries(options)
.map(([key, value]) => {
switch (typeof value) {
case 'string':
return `SET ${key} = '${value}';`;
case 'number':
return `SET ${key} = ${value};`;
case 'boolean':
return `SET ${key} = ${value};`;
default:
return `SET ${key} = '${value}';`;
}
})
.join('\n');
}

static stringifyQuery(query: Sql, options?: IPinotQueryOptions) {
const sql = SqlFormat.format(query.sql, query.values);

return [SqlUtils.formatOptions(options), sql].filter((x) => !!x).join('\n');
}
}
28 changes: 28 additions & 0 deletions test/sql-utils.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as assert from 'node:assert';
import { describe, test } from 'node:test';
import { IPinotQueryOptions, sql, SqlUtils } from '../src';

void describe('Sql Utils', async () => {
await test('generates query with no options', () => {
const query = sql`SELECT * FROM table WHERE id = ${1}`;

assert.strictEqual(
SqlUtils.stringifyQuery(query),
'SELECT * FROM table WHERE id = 1',
);
});

await test('generates query with options', () => {
const query = sql`SELECT * FROM table WHERE id = ${1}`;
const options: IPinotQueryOptions = {
useMultistageEngine: true,
timeoutMs: 100,
inPredicateLookupAlgorithm: 'SCAN',
};

assert.strictEqual(
SqlUtils.stringifyQuery(query, options),
`SET useMultistageEngine = true;\nSET timeoutMs = 100;\nSET inPredicateLookupAlgorithm = 'SCAN';\nSELECT * FROM table WHERE id = 1`,
);
});
});

0 comments on commit ca1d8a0

Please sign in to comment.