Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add --date-parser flag to control Postgres DATE type #210

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/cli/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { join } from 'path';
import { describe, it } from 'vitest';
import packageJson from '../../package.json';
import { LogLevel } from '../generator/logger/log-level';
import { DateParser, DEFAULT_DATE_PARSER } from '../introspector/dialects/postgres/date-parser';
import { DEFAULT_NUMERIC_PARSER } from '../introspector/dialects/postgres/numeric-parser';
import type { CliOptions } from './cli';
import { Cli } from './cli';
Expand All @@ -14,6 +15,7 @@ describe(Cli.name, () => {

const DEFAULT_CLI_OPTIONS: CliOptions = {
camelCase: false,
dateParser: DEFAULT_DATE_PARSER,
dialectName: undefined,
domains: false,
envFile: undefined,
Expand Down Expand Up @@ -52,6 +54,8 @@ describe(Cli.name, () => {
};

assert(['--camel-case'], { camelCase: true });
assert(['--date-parser=timestamp'], { dateParser: DateParser.TIMESTAMP });
assert(['--date-parser=string'], { dateParser: DateParser.STRING });
assert(['--dialect=mysql'], { dialectName: 'mysql' });
assert(['--domains'], { domains: true });
assert(['--exclude-pattern=public._*'], { excludePattern: 'public._*' });
Expand Down
22 changes: 20 additions & 2 deletions src/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { RuntimeEnumsStyle } from '../generator/generator/runtime-enums-style';
import { LogLevel } from '../generator/logger/log-level';
import { Logger } from '../generator/logger/logger';
import type { Overrides } from '../generator/transformer/transform';
import { DateParser, DEFAULT_DATE_PARSER } from '../introspector/dialects/postgres/date-parser';
import {
DEFAULT_NUMERIC_PARSER,
NumericParser,
Expand All @@ -21,6 +22,7 @@ import { FLAGS, serializeFlags } from './flags';

export type CliOptions = {
camelCase?: boolean;
dateParser?: DateParser;
dialectName?: DialectName;
domains?: boolean;
envFile?: string;
Expand Down Expand Up @@ -49,6 +51,7 @@ export class Cli {

async generate(options: CliOptions) {
const camelCase = !!options.camelCase;
const dateParser = options.dateParser;
const excludePattern = options.excludePattern;
const includePattern = options.includePattern;
const numericParser = options.numericParser;
Expand Down Expand Up @@ -81,6 +84,7 @@ export class Cli {
}

const dialectManager = new DialectManager({
dateParser: options.dateParser ?? DEFAULT_DATE_PARSER,
domains: !!options.domains,
numericParser: options.numericParser ?? DEFAULT_NUMERIC_PARSER,
partitions: !!options.partitions,
Expand All @@ -96,6 +100,7 @@ export class Cli {

await generate({
camelCase,
dateParser,
db,
dialect,
excludePattern,
Expand All @@ -121,6 +126,17 @@ export class Cli {
return !!input && input !== 'false';
}

#parseDateParser(input: any) {
switch (input) {
case 'string':
return DateParser.STRING;
case 'timestamp':
return DateParser.TIMESTAMP;
default:
return DEFAULT_DATE_PARSER;
}
}

#parseLogLevel(input: any) {
switch (input) {
case 'silent':
Expand Down Expand Up @@ -185,6 +201,7 @@ export class Cli {

const _: string[] = argv._;
const camelCase = this.#parseBoolean(argv['camel-case']);
const dateParser = this.#parseDateParser(argv['date-parser']);
const dialectName = this.#parseString(argv.dialect) as DialectName;
const domains = this.#parseBoolean(argv.domains);
const envFile = this.#parseString(argv['env-file']);
Expand Down Expand Up @@ -242,13 +259,14 @@ export class Cli {
if (!url) {
throw new TypeError(
"Parameter '--url' must be a valid connection string. Examples:\n\n" +
' --url=postgres://username:password@mydomain.com/database\n' +
' --url=env(DATABASE_URL)',
' --url=postgres://username:password@mydomain.com/database\n' +
' --url=env(DATABASE_URL)',
);
}

return {
camelCase,
dateParser,
dialectName,
domains,
envFile,
Expand Down
6 changes: 6 additions & 0 deletions src/cli/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ export const FLAGS = [
description: 'Use the Kysely CamelCasePlugin.',
longName: 'camel-case',
},
{
default: 'timestamp',
description: 'Specify which parser to use for PostgreSQL date values.',
longName: 'date-parser',
values: ['string', 'timestamp'],
},
{
description: 'Set the SQL dialect.',
longName: 'dialect',
Expand Down
2 changes: 2 additions & 0 deletions src/generator/dialect-manager.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { DateParser } from '../introspector/dialects/postgres/date-parser';
import type { NumericParser } from '../introspector/dialects/postgres/numeric-parser';
import type { GeneratorDialect } from './dialect';
import { KyselyBunSqliteDialect } from './dialects/kysely-bun-sqlite/kysely-bun-sqlite-dialect';
Expand All @@ -19,6 +20,7 @@ export type DialectName =
| 'worker-bun-sqlite';

type DialectManagerOptions = {
dateParser?: DateParser;
domains?: boolean;
numericParser?: NumericParser;
partitions?: boolean;
Expand Down
8 changes: 8 additions & 0 deletions src/generator/dialects/postgres/postgres-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { DateParser } from '../../../introspector/dialects/postgres/date-parser';
import { NumericParser } from '../../../introspector/dialects/postgres/numeric-parser';
import { Adapter } from '../../adapter';
import { ColumnTypeNode } from '../../ast/column-type-node';
Expand All @@ -15,6 +16,7 @@ import {
} from '../../transformer/definitions';

type PostgresAdapterOptions = {
dateParser?: DateParser;
numericParser?: NumericParser;
};

Expand Down Expand Up @@ -137,6 +139,12 @@ export class PostgresAdapter extends Adapter {
constructor(options?: PostgresAdapterOptions) {
super();

if (options?.dateParser === DateParser.STRING) {
this.scalars.date = new IdentifierNode('string');
} else {
this.scalars.date = new IdentifierNode('Timestamp');
}

if (options?.numericParser === NumericParser.NUMBER) {
this.definitions.Numeric = new ColumnTypeNode(
new IdentifierNode('number'),
Expand Down
6 changes: 4 additions & 2 deletions src/generator/dialects/postgres/postgres-dialect.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { DateParser } from '../../../introspector/dialects/postgres/date-parser';
import type { NumericParser } from '../../../introspector/dialects/postgres/numeric-parser';
import { PostgresIntrospectorDialect } from '../../../introspector/dialects/postgres/postgres-dialect';
import type { GeneratorDialect } from '../../dialect';
import { PostgresAdapter } from './postgres-adapter';

type PostgresDialectOptions = {
dateParser?: DateParser;
defaultSchemas?: string[];
domains?: boolean;
numericParser?: NumericParser;
Expand All @@ -12,14 +14,14 @@ type PostgresDialectOptions = {

export class PostgresDialect
extends PostgresIntrospectorDialect
implements GeneratorDialect
{
implements GeneratorDialect {
readonly adapter: PostgresAdapter;

constructor(options?: PostgresDialectOptions) {
super(options);

this.adapter = new PostgresAdapter({
dateParser: this.options.dateParser,
numericParser: this.options.numericParser,
});
}
Expand Down
2 changes: 2 additions & 0 deletions src/generator/generator/generate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { strictEqual } from 'assert';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { describe, test } from 'vitest';
import { DateParser } from '../../introspector/dialects/postgres/date-parser';
import { NumericParser } from '../../introspector/dialects/postgres/numeric-parser';
import {
addExtraColumn,
Expand Down Expand Up @@ -33,6 +34,7 @@ const TESTS: Test[] = [
{
connectionString: 'postgres://user:password@localhost:5433/database',
dialect: new PostgresDialect({
dateParser: DateParser.TIMESTAMP,
numericParser: NumericParser.NUMBER_OR_STRING,
}),
},
Expand Down
2 changes: 2 additions & 0 deletions src/generator/generator/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { promises as fs } from 'fs';
import type { Kysely } from 'kysely';
import { parse, relative, sep } from 'path';
import { performance } from 'perf_hooks';
import type { DateParser } from '../../introspector/dialects/postgres/date-parser';
import type { NumericParser } from '../../introspector/dialects/postgres/numeric-parser';
import type { GeneratorDialect } from '../dialect';
import type { Logger } from '../logger/logger';
Expand All @@ -12,6 +13,7 @@ import { Serializer } from './serializer';

export type GenerateOptions = {
camelCase?: boolean;
dateParser?: DateParser;
db: Kysely<any>;
dialect: GeneratorDialect;
excludePattern?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export type Timestamp = ColumnType<Date, Date | string, Date | string>;
export interface FooBar {
array: string[] | null;
childDomain: number | null;
date: string | null;
defaultedNullablePosInt: Generated<number | null>;
defaultedRequiredPosInt: Generated<number>;
/**
Expand Down
1 change: 1 addition & 0 deletions src/generator/generator/snapshots/postgres.snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export type Timestamp = ColumnType<Date, Date | string, Date | string>;
export interface FooBar {
array: string[] | null;
childDomain: number | null;
date: string | null;
defaultedNullablePosInt: Generated<number | null>;
defaultedRequiredPosInt: Generated<number>;
/**
Expand Down
44 changes: 43 additions & 1 deletion src/generator/transformer/transform.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { deepStrictEqual } from 'assert';
import { describe, it } from 'vitest';
import { DateParser } from '../../introspector/dialects/postgres/date-parser';
import { NumericParser } from '../../introspector/dialects/postgres/numeric-parser';
import { EnumCollection } from '../../introspector/enum-collection';
import { ColumnMetadata } from '../../introspector/metadata/column-metadata';
Expand Down Expand Up @@ -34,19 +35,21 @@ describe(transform.name, () => {

const transformWithDefaults = ({
camelCase,
dateParser,
numericParser,
runtimeEnums,
tables,
}: {
camelCase?: boolean;
dateParser?: DateParser;
numericParser?: NumericParser;
runtimeEnums?: boolean;
runtimeEnumsStyle?: RuntimeEnumsStyle;
tables: TableMetadata[];
}) => {
return transform({
camelCase,
dialect: new PostgresDialect({ numericParser }),
dialect: new PostgresDialect({ dateParser, numericParser }),
metadata: new DatabaseMetadata({ enums, tables }),
overrides: {
columns: {
Expand Down Expand Up @@ -260,6 +263,45 @@ describe(transform.name, () => {
]);
});

it('should be able to transform using an alternative Postgres date parser', () => {
const nodes = transformWithDefaults({
dateParser: DateParser.STRING,
tables: [
new TableMetadata({
columns: [
new ColumnMetadata({
dataType: 'date',
name: 'date',
}),
],
name: 'table',
}),
],
});

deepStrictEqual(nodes, [
new ExportStatementNode(
new InterfaceDeclarationNode(
'Table',
new ObjectExpressionNode([
new PropertyNode(
'date',
new IdentifierNode('string'),
),
]),
),
),
new ExportStatementNode(
new InterfaceDeclarationNode(
'DB',
new ObjectExpressionNode([
new PropertyNode('table', new IdentifierNode('Table')),
]),
),
),
]);
});

it('should be able to transform using an alternative Postgres numeric parser', () => {
const nodes = transformWithDefaults({
numericParser: NumericParser.NUMBER,
Expand Down
6 changes: 6 additions & 0 deletions src/introspector/dialects/postgres/date-parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const enum DateParser {
STRING = 'string',
TIMESTAMP = 'timestamp'
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wasn't sure if it made sense to call this TIMESTAMP or DATE, but I went with TIMESTAMP to match the existing generated types.

}

export const DEFAULT_DATE_PARSER = DateParser.TIMESTAMP;
7 changes: 7 additions & 0 deletions src/introspector/dialects/postgres/postgres-dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import type { CreateKyselyDialectOptions } from '../../dialect';
import { IntrospectorDialect } from '../../dialect';
import { DEFAULT_NUMERIC_PARSER, NumericParser } from './numeric-parser';
import { PostgresIntrospector } from './postgres-introspector';
import { DateParser, DEFAULT_DATE_PARSER } from './date-parser';

type PostgresDialectOptions = {
dateParser?: DateParser;
defaultSchemas?: string[];
domains?: boolean;
numericParser?: NumericParser;
Expand All @@ -24,6 +26,7 @@ export class PostgresIntrospectorDialect extends IntrospectorDialect {
partitions: options?.partitions,
});
this.options = {
dateParser: options?.dateParser ?? DEFAULT_DATE_PARSER,
defaultSchemas: options?.defaultSchemas,
domains: options?.domains ?? true,
numericParser: options?.numericParser ?? DEFAULT_NUMERIC_PARSER,
Expand All @@ -45,6 +48,10 @@ export class PostgresIntrospectorDialect extends IntrospectorDialect {
});
}

if (this.options.dateParser === DateParser.STRING) {
pg.types.setTypeParser(1082, (date) => date);
}

return new KyselyPostgresDialect({
pool: new pg.Pool({
connectionString: options.connectionString,
Expand Down
1 change: 1 addition & 0 deletions src/introspector/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export * from './dialects/mysql/mysql-db';
export * from './dialects/mysql/mysql-dialect';
export * from './dialects/mysql/mysql-introspector';
export * from './dialects/mysql/mysql-parser';
export * from './dialects/postgres/date-parser';
export * from './dialects/postgres/numeric-parser';
export * from './dialects/postgres/postgres-db';
export * from './dialects/postgres/postgres-dialect';
Expand Down
1 change: 1 addition & 0 deletions src/introspector/introspector.fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ const up = async (db: Kysely<any>, dialect: IntrospectorDialect) => {
} else if (dialect instanceof PostgresIntrospectorDialect) {
builder = builder
.addColumn('id', 'serial')
.addColumn('date', 'date')
.addColumn('user_status', sql`status`)
.addColumn('user_status_2', sql`test.status`)
.addColumn('array', sql`text[]`)
Expand Down
Loading