@vanit-co/sql-ts 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +488 -364
- package/dist/generate.d.mts +19 -0
- package/dist/generate.d.ts +19 -0
- package/dist/generate.js +83 -0
- package/dist/generate.js.map +1 -0
- package/dist/generate.mjs +80 -0
- package/dist/generate.mjs.map +1 -0
- package/dist/index.d.mts +54 -18
- package/dist/index.d.ts +54 -18
- package/dist/index.js +44 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +43 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +24 -1
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
declare const postgresColumns = "select c.table_schema ,c.table_name ,c.column_name ,c.ordinal_position ,c.is_nullable ,c.data_type ,c.udt_name\n ,(select array_agg(e.enumlabel::text order by e.enumsortorder)\n from pg_catalog.pg_type t\n join pg_catalog.pg_enum e on e.enumtypid = t.oid\n join pg_catalog.pg_namespace n on n.oid = t.typnamespace\n where n.nspname = c.udt_schema\n and t.typname = case when c.data_type = 'ARRAY' then substr(c.udt_name ,2) else c.udt_name end) as enum_labels\nfrom information_schema.columns c\nwhere c.table_schema = any($1::text[])\norder by c.table_schema ,c.table_name ,c.ordinal_position";
|
|
2
|
+
type ColumnInfo = {
|
|
3
|
+
readonly table_schema: string;
|
|
4
|
+
readonly table_name: string;
|
|
5
|
+
readonly column_name: string;
|
|
6
|
+
readonly ordinal_position?: number | string;
|
|
7
|
+
readonly is_nullable: string | boolean;
|
|
8
|
+
readonly data_type: string;
|
|
9
|
+
readonly udt_name: string;
|
|
10
|
+
readonly enum_labels?: ReadonlyArray<string> | null;
|
|
11
|
+
};
|
|
12
|
+
type GenerateOptions = {
|
|
13
|
+
readonly types?: Readonly<Record<string, string>>;
|
|
14
|
+
readonly typeName?: string;
|
|
15
|
+
};
|
|
16
|
+
declare const generate: (columns: ReadonlyArray<ColumnInfo>, options?: GenerateOptions) => string;
|
|
17
|
+
|
|
18
|
+
export { generate, postgresColumns };
|
|
19
|
+
export type { ColumnInfo, GenerateOptions };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
declare const postgresColumns = "select c.table_schema ,c.table_name ,c.column_name ,c.ordinal_position ,c.is_nullable ,c.data_type ,c.udt_name\n ,(select array_agg(e.enumlabel::text order by e.enumsortorder)\n from pg_catalog.pg_type t\n join pg_catalog.pg_enum e on e.enumtypid = t.oid\n join pg_catalog.pg_namespace n on n.oid = t.typnamespace\n where n.nspname = c.udt_schema\n and t.typname = case when c.data_type = 'ARRAY' then substr(c.udt_name ,2) else c.udt_name end) as enum_labels\nfrom information_schema.columns c\nwhere c.table_schema = any($1::text[])\norder by c.table_schema ,c.table_name ,c.ordinal_position";
|
|
2
|
+
type ColumnInfo = {
|
|
3
|
+
readonly table_schema: string;
|
|
4
|
+
readonly table_name: string;
|
|
5
|
+
readonly column_name: string;
|
|
6
|
+
readonly ordinal_position?: number | string;
|
|
7
|
+
readonly is_nullable: string | boolean;
|
|
8
|
+
readonly data_type: string;
|
|
9
|
+
readonly udt_name: string;
|
|
10
|
+
readonly enum_labels?: ReadonlyArray<string> | null;
|
|
11
|
+
};
|
|
12
|
+
type GenerateOptions = {
|
|
13
|
+
readonly types?: Readonly<Record<string, string>>;
|
|
14
|
+
readonly typeName?: string;
|
|
15
|
+
};
|
|
16
|
+
declare const generate: (columns: ReadonlyArray<ColumnInfo>, options?: GenerateOptions) => string;
|
|
17
|
+
|
|
18
|
+
export { generate, postgresColumns };
|
|
19
|
+
export type { ColumnInfo, GenerateOptions };
|
package/dist/generate.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Writes the type records `schema<R>()` takes, from what the database says its
|
|
4
|
+
// columns are. No driver is imported: run `postgresColumns` with your own and
|
|
5
|
+
// hand the rows to `generate`.
|
|
6
|
+
// $1 is the list of schemas to read, as text[]. Tables and views: materialized
|
|
7
|
+
// views are not in information_schema. A domain reads as its base type.
|
|
8
|
+
const postgresColumns = `select c.table_schema ,c.table_name ,c.column_name ,c.ordinal_position ,c.is_nullable ,c.data_type ,c.udt_name
|
|
9
|
+
,(select array_agg(e.enumlabel::text order by e.enumsortorder)
|
|
10
|
+
from pg_catalog.pg_type t
|
|
11
|
+
join pg_catalog.pg_enum e on e.enumtypid = t.oid
|
|
12
|
+
join pg_catalog.pg_namespace n on n.oid = t.typnamespace
|
|
13
|
+
where n.nspname = c.udt_schema
|
|
14
|
+
and t.typname = case when c.data_type = 'ARRAY' then substr(c.udt_name ,2) else c.udt_name end) as enum_labels
|
|
15
|
+
from information_schema.columns c
|
|
16
|
+
where c.table_schema = any($1::text[])
|
|
17
|
+
order by c.table_schema ,c.table_name ,c.ordinal_position`;
|
|
18
|
+
// What node-postgres hands back with its default parsers (pg-types). A type it
|
|
19
|
+
// has no parser for arrives as the text postgres sent, so that is the fallback.
|
|
20
|
+
const scalarTypes = {
|
|
21
|
+
int2: 'number', int4: 'number', oid: 'number', float4: 'number', float8: 'number',
|
|
22
|
+
int8: 'string', numeric: 'string', money: 'string',
|
|
23
|
+
bool: 'boolean',
|
|
24
|
+
date: 'Date', timestamp: 'Date', timestamptz: 'Date',
|
|
25
|
+
json: 'unknown', jsonb: 'unknown', interval: 'unknown',
|
|
26
|
+
bytea: 'Buffer',
|
|
27
|
+
point: '{ x: number; y: number }',
|
|
28
|
+
circle: '{ x: number; y: number; radius: number }'
|
|
29
|
+
};
|
|
30
|
+
// Only these arrays are parsed; any other comes back as its literal ('{a,b}').
|
|
31
|
+
// Not always the scalar's type: numeric[] parses to numbers.
|
|
32
|
+
const arrayTypes = {
|
|
33
|
+
_bool: 'Array<boolean>',
|
|
34
|
+
_int2: 'Array<number>', _int4: 'Array<number>', _oid: 'Array<number>',
|
|
35
|
+
_float4: 'Array<number>', _float8: 'Array<number>', _numeric: 'Array<number>',
|
|
36
|
+
_int8: 'Array<string>',
|
|
37
|
+
_bpchar: 'Array<string>', _varchar: 'Array<string>', _text: 'Array<string>', _regproc: 'Array<string>',
|
|
38
|
+
_macaddr: 'Array<string>', _inet: 'Array<string>', _cidr: 'Array<string>', _uuid: 'Array<string>',
|
|
39
|
+
_money: 'Array<string>', _time: 'Array<string>', _timetz: 'Array<string>', _numrange: 'Array<string>',
|
|
40
|
+
_date: 'Array<Date>', _timestamp: 'Array<Date>', _timestamptz: 'Array<Date>',
|
|
41
|
+
_interval: 'Array<unknown>', _json: 'Array<unknown>', _jsonb: 'Array<unknown>',
|
|
42
|
+
_bytea: 'Array<Buffer>',
|
|
43
|
+
_point: 'Array<{ x: number; y: number }>'
|
|
44
|
+
};
|
|
45
|
+
const isNullable = (c) => c.is_nullable === true || c.is_nullable === 'YES';
|
|
46
|
+
const literalUnion = (labels) => labels.map(l => JSON.stringify(l)).join(' | ');
|
|
47
|
+
const tsType = (types) => (c) => {
|
|
48
|
+
const isArray = c.data_type === 'ARRAY';
|
|
49
|
+
const labels = c.enum_labels && c.enum_labels.length > 0 ? c.enum_labels : undefined;
|
|
50
|
+
const base = types[c.udt_name]
|
|
51
|
+
?? (isArray ? arrayTypes[c.udt_name] : undefined)
|
|
52
|
+
?? (!isArray && labels ? literalUnion(labels) : undefined)
|
|
53
|
+
?? (isArray ? 'string' : scalarTypes[c.udt_name] ?? 'string');
|
|
54
|
+
return isNullable(c) ? `${base} | null` : base;
|
|
55
|
+
};
|
|
56
|
+
const key = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
|
|
57
|
+
const byOrdinal = (a, b) => Number(a.ordinal_position ?? 0) - Number(b.ordinal_position ?? 0);
|
|
58
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
59
|
+
// The text of a module exporting one type: table → column → TypeScript type.
|
|
60
|
+
// A table is keyed `schema.table` only when the columns span several schemas.
|
|
61
|
+
const generate = (columns, options = {}) => {
|
|
62
|
+
const typeOf = tsType(options.types ?? {});
|
|
63
|
+
const qualify = new Set(columns.map(c => c.table_schema)).size > 1;
|
|
64
|
+
const tableKey = (c) => qualify ? `${c.table_schema}.${c.table_name}` : c.table_name;
|
|
65
|
+
const tables = columns.reduce((m, c) => m.set(tableKey(c), [...(m.get(tableKey(c)) ?? []), c]), new Map());
|
|
66
|
+
const body = [...tables.keys()].sort(compare).map(t => [
|
|
67
|
+
` ${key(t)}: {`,
|
|
68
|
+
...[...tables.get(t)].sort(byOrdinal).map(c => ` ${key(c.column_name)}: ${typeOf(c)}`),
|
|
69
|
+
' }'
|
|
70
|
+
].join('\n')).join('\n');
|
|
71
|
+
return [
|
|
72
|
+
'// generated by @vanit-co/sql-ts from the database: do not edit',
|
|
73
|
+
'',
|
|
74
|
+
`export type ${options.typeName ?? 'Rows'} = {`,
|
|
75
|
+
...(body ? [body] : []),
|
|
76
|
+
'}',
|
|
77
|
+
''
|
|
78
|
+
].join('\n');
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
exports.generate = generate;
|
|
82
|
+
exports.postgresColumns = postgresColumns;
|
|
83
|
+
//# sourceMappingURL=generate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate.js","sources":["../src/generate.ts"],"sourcesContent":["// Writes the type records `schema<R>()` takes, from what the database says its\n// columns are. No driver is imported: run `postgresColumns` with your own and\n// hand the rows to `generate`.\n\n// $1 is the list of schemas to read, as text[]. Tables and views: materialized\n// views are not in information_schema. A domain reads as its base type.\nconst postgresColumns = `select c.table_schema ,c.table_name ,c.column_name ,c.ordinal_position ,c.is_nullable ,c.data_type ,c.udt_name\n ,(select array_agg(e.enumlabel::text order by e.enumsortorder)\n from pg_catalog.pg_type t\n join pg_catalog.pg_enum e on e.enumtypid = t.oid\n join pg_catalog.pg_namespace n on n.oid = t.typnamespace\n where n.nspname = c.udt_schema\n and t.typname = case when c.data_type = 'ARRAY' then substr(c.udt_name ,2) else c.udt_name end) as enum_labels\nfrom information_schema.columns c\nwhere c.table_schema = any($1::text[])\norder by c.table_schema ,c.table_name ,c.ordinal_position`\n\ntype ColumnInfo = {\n readonly table_schema: string\n readonly table_name: string\n readonly column_name: string\n readonly ordinal_position?: number | string\n // information_schema says 'YES' or 'NO'\n readonly is_nullable: string | boolean\n readonly data_type: string\n readonly udt_name: string\n readonly enum_labels?: ReadonlyArray<string> | null\n}\n\ntype GenerateOptions = {\n // TypeScript type by udt_name (`timestamptz`, `_int4` for an array), for a\n // driver or a parser that reads a type differently from the defaults\n readonly types?: Readonly<Record<string, string>>\n readonly typeName?: string\n}\n\n// What node-postgres hands back with its default parsers (pg-types). A type it\n// has no parser for arrives as the text postgres sent, so that is the fallback.\nconst scalarTypes: Readonly<Record<string, string>> = {\n int2: 'number' ,int4: 'number' ,oid: 'number' ,float4: 'number' ,float8: 'number'\n ,int8: 'string' ,numeric: 'string' ,money: 'string'\n ,bool: 'boolean'\n ,date: 'Date' ,timestamp: 'Date' ,timestamptz: 'Date'\n ,json: 'unknown' ,jsonb: 'unknown' ,interval: 'unknown'\n ,bytea: 'Buffer'\n ,point: '{ x: number; y: number }'\n ,circle: '{ x: number; y: number; radius: number }'\n}\n\n// Only these arrays are parsed; any other comes back as its literal ('{a,b}').\n// Not always the scalar's type: numeric[] parses to numbers.\nconst arrayTypes: Readonly<Record<string, string>> = {\n _bool: 'Array<boolean>'\n ,_int2: 'Array<number>' ,_int4: 'Array<number>' ,_oid: 'Array<number>'\n ,_float4: 'Array<number>' ,_float8: 'Array<number>' ,_numeric: 'Array<number>'\n ,_int8: 'Array<string>'\n ,_bpchar: 'Array<string>' ,_varchar: 'Array<string>' ,_text: 'Array<string>' ,_regproc: 'Array<string>'\n ,_macaddr: 'Array<string>' ,_inet: 'Array<string>' ,_cidr: 'Array<string>' ,_uuid: 'Array<string>'\n ,_money: 'Array<string>' ,_time: 'Array<string>' ,_timetz: 'Array<string>' ,_numrange: 'Array<string>'\n ,_date: 'Array<Date>' ,_timestamp: 'Array<Date>' ,_timestamptz: 'Array<Date>'\n ,_interval: 'Array<unknown>' ,_json: 'Array<unknown>' ,_jsonb: 'Array<unknown>'\n ,_bytea: 'Array<Buffer>'\n ,_point: 'Array<{ x: number; y: number }>'\n}\n\nconst isNullable = (c: ColumnInfo) => c.is_nullable === true || c.is_nullable === 'YES'\n\nconst literalUnion = (labels: ReadonlyArray<string>) => labels.map(l => JSON.stringify(l)).join(' | ')\n\nconst tsType = (types: Readonly<Record<string, string>>) => (c: ColumnInfo): string => {\n const isArray = c.data_type === 'ARRAY'\n const labels = c.enum_labels && c.enum_labels.length > 0 ? c.enum_labels : undefined\n\n const base =\n types[c.udt_name]\n ?? (isArray ? arrayTypes[c.udt_name] : undefined)\n ?? (!isArray && labels ? literalUnion(labels) : undefined)\n ?? (isArray ? 'string' : scalarTypes[c.udt_name] ?? 'string')\n\n return isNullable(c) ? `${base} | null` : base\n}\n\nconst key = (name: string) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name)\n\nconst byOrdinal = (a: ColumnInfo ,b: ColumnInfo) =>\n Number(a.ordinal_position ?? 0) - Number(b.ordinal_position ?? 0)\n\nconst compare = (a: string ,b: string) => a < b ? -1 : a > b ? 1 : 0\n\n// The text of a module exporting one type: table → column → TypeScript type.\n// A table is keyed `schema.table` only when the columns span several schemas.\nconst generate = (columns: ReadonlyArray<ColumnInfo> ,options: GenerateOptions = {}): string => {\n const typeOf = tsType(options.types ?? {})\n const qualify = new Set(columns.map(c => c.table_schema)).size > 1\n const tableKey = (c: ColumnInfo) => qualify ? `${c.table_schema}.${c.table_name}` : c.table_name\n\n const tables = columns.reduce<Map<string, Array<ColumnInfo>>>(\n (m ,c) => m.set(tableKey(c) ,[...(m.get(tableKey(c)) ?? []) ,c])\n ,new Map()\n )\n\n const body = [...tables.keys()].sort(compare).map(t => [\n ` ${key(t)}: {`\n ,...[...tables.get(t)!].sort(byOrdinal).map(c => ` ${key(c.column_name)}: ${typeOf(c)}`)\n ,' }'\n ].join('\\n')).join('\\n')\n\n return [\n '// generated by @vanit-co/sql-ts from the database: do not edit'\n ,''\n ,`export type ${options.typeName ?? 'Rows'} = {`\n ,...(body ? [body] : [])\n ,'}'\n ,''\n ].join('\\n')\n}\n\nexport type { ColumnInfo ,GenerateOptions }\nexport { generate ,postgresColumns }\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AAEA;AACA;AACA,MAAM,eAAe,GAAG,CAAA;;;;;;;;;;AA8BxB;AACA;AACA,MAAM,WAAW,GAAqC;AACpD,IAAA,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ;IAChF,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ;AAClD,IAAA,IAAI,EAAE,SAAS;IACf,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM;IACpD,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS;AACtD,IAAA,KAAK,EAAE,QAAQ;AACf,IAAA,KAAK,EAAE,0BAA0B;AACjC,IAAA,MAAM,EAAE;CACV;AAED;AACA;AACA,MAAM,UAAU,GAAqC;AACnD,IAAA,KAAK,EAAE,gBAAgB;IACtB,KAAK,EAAE,eAAe,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,eAAe;IACrE,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,eAAe;AAC7E,IAAA,KAAK,EAAE,eAAe;AACtB,IAAA,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,eAAe,EAAE,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,eAAe;AACtG,IAAA,QAAQ,EAAE,eAAe,EAAE,KAAK,EAAE,eAAe,EAAE,KAAK,EAAE,eAAe,EAAE,KAAK,EAAE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CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI;AACrD,QAAA,CAAA,EAAA,EAAK,GAAG,CAAC,CAAC,CAAC,CAAA,GAAA,CAAK;AACf,QAAA,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAA,IAAA,EAAO,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1F;KACF,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;IAExB,OAAO;QACL,iEAAiE;QAChE,EAAE;AACF,QAAA,CAAA,YAAA,EAAe,OAAO,CAAC,QAAQ,IAAI,MAAM,CAAA,IAAA,CAAM;AAC/C,QAAA,IAAI,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,GAAG;QACH;AACF,KAAA,CAAC,IAAI,CAAC,IAAI,CAAC;AACd;;;;;"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Writes the type records `schema<R>()` takes, from what the database says its
|
|
2
|
+
// columns are. No driver is imported: run `postgresColumns` with your own and
|
|
3
|
+
// hand the rows to `generate`.
|
|
4
|
+
// $1 is the list of schemas to read, as text[]. Tables and views: materialized
|
|
5
|
+
// views are not in information_schema. A domain reads as its base type.
|
|
6
|
+
const postgresColumns = `select c.table_schema ,c.table_name ,c.column_name ,c.ordinal_position ,c.is_nullable ,c.data_type ,c.udt_name
|
|
7
|
+
,(select array_agg(e.enumlabel::text order by e.enumsortorder)
|
|
8
|
+
from pg_catalog.pg_type t
|
|
9
|
+
join pg_catalog.pg_enum e on e.enumtypid = t.oid
|
|
10
|
+
join pg_catalog.pg_namespace n on n.oid = t.typnamespace
|
|
11
|
+
where n.nspname = c.udt_schema
|
|
12
|
+
and t.typname = case when c.data_type = 'ARRAY' then substr(c.udt_name ,2) else c.udt_name end) as enum_labels
|
|
13
|
+
from information_schema.columns c
|
|
14
|
+
where c.table_schema = any($1::text[])
|
|
15
|
+
order by c.table_schema ,c.table_name ,c.ordinal_position`;
|
|
16
|
+
// What node-postgres hands back with its default parsers (pg-types). A type it
|
|
17
|
+
// has no parser for arrives as the text postgres sent, so that is the fallback.
|
|
18
|
+
const scalarTypes = {
|
|
19
|
+
int2: 'number', int4: 'number', oid: 'number', float4: 'number', float8: 'number',
|
|
20
|
+
int8: 'string', numeric: 'string', money: 'string',
|
|
21
|
+
bool: 'boolean',
|
|
22
|
+
date: 'Date', timestamp: 'Date', timestamptz: 'Date',
|
|
23
|
+
json: 'unknown', jsonb: 'unknown', interval: 'unknown',
|
|
24
|
+
bytea: 'Buffer',
|
|
25
|
+
point: '{ x: number; y: number }',
|
|
26
|
+
circle: '{ x: number; y: number; radius: number }'
|
|
27
|
+
};
|
|
28
|
+
// Only these arrays are parsed; any other comes back as its literal ('{a,b}').
|
|
29
|
+
// Not always the scalar's type: numeric[] parses to numbers.
|
|
30
|
+
const arrayTypes = {
|
|
31
|
+
_bool: 'Array<boolean>',
|
|
32
|
+
_int2: 'Array<number>', _int4: 'Array<number>', _oid: 'Array<number>',
|
|
33
|
+
_float4: 'Array<number>', _float8: 'Array<number>', _numeric: 'Array<number>',
|
|
34
|
+
_int8: 'Array<string>',
|
|
35
|
+
_bpchar: 'Array<string>', _varchar: 'Array<string>', _text: 'Array<string>', _regproc: 'Array<string>',
|
|
36
|
+
_macaddr: 'Array<string>', _inet: 'Array<string>', _cidr: 'Array<string>', _uuid: 'Array<string>',
|
|
37
|
+
_money: 'Array<string>', _time: 'Array<string>', _timetz: 'Array<string>', _numrange: 'Array<string>',
|
|
38
|
+
_date: 'Array<Date>', _timestamp: 'Array<Date>', _timestamptz: 'Array<Date>',
|
|
39
|
+
_interval: 'Array<unknown>', _json: 'Array<unknown>', _jsonb: 'Array<unknown>',
|
|
40
|
+
_bytea: 'Array<Buffer>',
|
|
41
|
+
_point: 'Array<{ x: number; y: number }>'
|
|
42
|
+
};
|
|
43
|
+
const isNullable = (c) => c.is_nullable === true || c.is_nullable === 'YES';
|
|
44
|
+
const literalUnion = (labels) => labels.map(l => JSON.stringify(l)).join(' | ');
|
|
45
|
+
const tsType = (types) => (c) => {
|
|
46
|
+
const isArray = c.data_type === 'ARRAY';
|
|
47
|
+
const labels = c.enum_labels && c.enum_labels.length > 0 ? c.enum_labels : undefined;
|
|
48
|
+
const base = types[c.udt_name]
|
|
49
|
+
?? (isArray ? arrayTypes[c.udt_name] : undefined)
|
|
50
|
+
?? (!isArray && labels ? literalUnion(labels) : undefined)
|
|
51
|
+
?? (isArray ? 'string' : scalarTypes[c.udt_name] ?? 'string');
|
|
52
|
+
return isNullable(c) ? `${base} | null` : base;
|
|
53
|
+
};
|
|
54
|
+
const key = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
|
|
55
|
+
const byOrdinal = (a, b) => Number(a.ordinal_position ?? 0) - Number(b.ordinal_position ?? 0);
|
|
56
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
57
|
+
// The text of a module exporting one type: table → column → TypeScript type.
|
|
58
|
+
// A table is keyed `schema.table` only when the columns span several schemas.
|
|
59
|
+
const generate = (columns, options = {}) => {
|
|
60
|
+
const typeOf = tsType(options.types ?? {});
|
|
61
|
+
const qualify = new Set(columns.map(c => c.table_schema)).size > 1;
|
|
62
|
+
const tableKey = (c) => qualify ? `${c.table_schema}.${c.table_name}` : c.table_name;
|
|
63
|
+
const tables = columns.reduce((m, c) => m.set(tableKey(c), [...(m.get(tableKey(c)) ?? []), c]), new Map());
|
|
64
|
+
const body = [...tables.keys()].sort(compare).map(t => [
|
|
65
|
+
` ${key(t)}: {`,
|
|
66
|
+
...[...tables.get(t)].sort(byOrdinal).map(c => ` ${key(c.column_name)}: ${typeOf(c)}`),
|
|
67
|
+
' }'
|
|
68
|
+
].join('\n')).join('\n');
|
|
69
|
+
return [
|
|
70
|
+
'// generated by @vanit-co/sql-ts from the database: do not edit',
|
|
71
|
+
'',
|
|
72
|
+
`export type ${options.typeName ?? 'Rows'} = {`,
|
|
73
|
+
...(body ? [body] : []),
|
|
74
|
+
'}',
|
|
75
|
+
''
|
|
76
|
+
].join('\n');
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export { generate, postgresColumns };
|
|
80
|
+
//# sourceMappingURL=generate.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate.mjs","sources":["../src/generate.ts"],"sourcesContent":["// Writes the type records `schema<R>()` takes, from what the database says its\n// columns are. No driver is imported: run `postgresColumns` with your own and\n// hand the rows to `generate`.\n\n// $1 is the list of schemas to read, as text[]. Tables and views: materialized\n// views are not in information_schema. A domain reads as its base type.\nconst postgresColumns = `select c.table_schema ,c.table_name ,c.column_name ,c.ordinal_position ,c.is_nullable ,c.data_type ,c.udt_name\n ,(select array_agg(e.enumlabel::text order by e.enumsortorder)\n from pg_catalog.pg_type t\n join pg_catalog.pg_enum e on e.enumtypid = t.oid\n join pg_catalog.pg_namespace n on n.oid = t.typnamespace\n where n.nspname = c.udt_schema\n and t.typname = case when c.data_type = 'ARRAY' then substr(c.udt_name ,2) else c.udt_name end) as enum_labels\nfrom information_schema.columns c\nwhere c.table_schema = any($1::text[])\norder by c.table_schema ,c.table_name ,c.ordinal_position`\n\ntype ColumnInfo = {\n readonly table_schema: string\n readonly table_name: string\n readonly column_name: string\n readonly ordinal_position?: number | string\n // information_schema says 'YES' or 'NO'\n readonly is_nullable: string | boolean\n readonly data_type: string\n readonly udt_name: string\n readonly enum_labels?: ReadonlyArray<string> | null\n}\n\ntype GenerateOptions = {\n // TypeScript type by udt_name (`timestamptz`, `_int4` for an array), for a\n // driver or a parser that reads a type differently from the defaults\n readonly types?: Readonly<Record<string, string>>\n readonly typeName?: string\n}\n\n// What node-postgres hands back with its default parsers (pg-types). A type it\n// has no parser for arrives as the text postgres sent, so that is the fallback.\nconst scalarTypes: Readonly<Record<string, string>> = {\n int2: 'number' ,int4: 'number' ,oid: 'number' ,float4: 'number' ,float8: 'number'\n ,int8: 'string' ,numeric: 'string' ,money: 'string'\n ,bool: 'boolean'\n ,date: 'Date' ,timestamp: 'Date' ,timestamptz: 'Date'\n ,json: 'unknown' ,jsonb: 'unknown' ,interval: 'unknown'\n ,bytea: 'Buffer'\n ,point: '{ x: number; y: number }'\n ,circle: '{ x: number; y: number; radius: number }'\n}\n\n// Only these arrays are parsed; any other comes back as its literal ('{a,b}').\n// Not always the scalar's type: numeric[] parses to numbers.\nconst arrayTypes: Readonly<Record<string, string>> = {\n _bool: 'Array<boolean>'\n ,_int2: 'Array<number>' ,_int4: 'Array<number>' ,_oid: 'Array<number>'\n ,_float4: 'Array<number>' ,_float8: 'Array<number>' ,_numeric: 'Array<number>'\n ,_int8: 'Array<string>'\n ,_bpchar: 'Array<string>' ,_varchar: 'Array<string>' ,_text: 'Array<string>' ,_regproc: 'Array<string>'\n ,_macaddr: 'Array<string>' ,_inet: 'Array<string>' ,_cidr: 'Array<string>' ,_uuid: 'Array<string>'\n ,_money: 'Array<string>' ,_time: 'Array<string>' ,_timetz: 'Array<string>' ,_numrange: 'Array<string>'\n ,_date: 'Array<Date>' ,_timestamp: 'Array<Date>' ,_timestamptz: 'Array<Date>'\n ,_interval: 'Array<unknown>' ,_json: 'Array<unknown>' ,_jsonb: 'Array<unknown>'\n ,_bytea: 'Array<Buffer>'\n ,_point: 'Array<{ x: number; y: number }>'\n}\n\nconst isNullable = (c: ColumnInfo) => c.is_nullable === true || c.is_nullable === 'YES'\n\nconst literalUnion = (labels: ReadonlyArray<string>) => labels.map(l => JSON.stringify(l)).join(' | ')\n\nconst tsType = (types: Readonly<Record<string, string>>) => (c: ColumnInfo): string => {\n const isArray = c.data_type === 'ARRAY'\n const labels = c.enum_labels && c.enum_labels.length > 0 ? c.enum_labels : undefined\n\n const base =\n types[c.udt_name]\n ?? (isArray ? arrayTypes[c.udt_name] : undefined)\n ?? (!isArray && labels ? literalUnion(labels) : undefined)\n ?? (isArray ? 'string' : scalarTypes[c.udt_name] ?? 'string')\n\n return isNullable(c) ? `${base} | null` : base\n}\n\nconst key = (name: string) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name)\n\nconst byOrdinal = (a: ColumnInfo ,b: ColumnInfo) =>\n Number(a.ordinal_position ?? 0) - Number(b.ordinal_position ?? 0)\n\nconst compare = (a: string ,b: string) => a < b ? -1 : a > b ? 1 : 0\n\n// The text of a module exporting one type: table → column → TypeScript type.\n// A table is keyed `schema.table` only when the columns span several schemas.\nconst generate = (columns: ReadonlyArray<ColumnInfo> ,options: GenerateOptions = {}): string => {\n const typeOf = tsType(options.types ?? {})\n const qualify = new Set(columns.map(c => c.table_schema)).size > 1\n const tableKey = (c: ColumnInfo) => qualify ? `${c.table_schema}.${c.table_name}` : c.table_name\n\n const tables = columns.reduce<Map<string, Array<ColumnInfo>>>(\n (m ,c) => m.set(tableKey(c) ,[...(m.get(tableKey(c)) ?? []) ,c])\n ,new Map()\n )\n\n const body = [...tables.keys()].sort(compare).map(t => [\n ` ${key(t)}: {`\n ,...[...tables.get(t)!].sort(byOrdinal).map(c => ` ${key(c.column_name)}: ${typeOf(c)}`)\n ,' }'\n ].join('\\n')).join('\\n')\n\n return [\n '// generated by @vanit-co/sql-ts from the database: do not edit'\n ,''\n ,`export type ${options.typeName ?? 'Rows'} = {`\n ,...(body ? [body] : [])\n ,'}'\n ,''\n ].join('\\n')\n}\n\nexport type { ColumnInfo ,GenerateOptions }\nexport { generate ,postgresColumns }\n"],"names":[],"mappings":"AAAA;AACA;AACA;AAEA;AACA;AACA,MAAM,eAAe,GAAG,CAAA;;;;;;;;;;AA8BxB;AACA;AACA,MAAM,WAAW,GAAqC;AACpD,IAAA,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,QAA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AI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;IAExB,OAAO;QACL,iEAAiE;QAChE,EAAE;AACF,QAAA,CAAA,YAAA,EAAe,OAAO,CAAC,QAAQ,IAAI,MAAM,CAAA,IAAA,CAAM;AAC/C,QAAA,IAAI,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,GAAG;QACH;AACF,KAAA,CAAC,IAAI,CAAC,IAAI,CAAC;AACd;;;;"}
|
package/dist/index.d.mts
CHANGED
|
@@ -14,16 +14,6 @@ type PostgresResult = {
|
|
|
14
14
|
declare const toMysql: (s: Fragment) => MysqlResult;
|
|
15
15
|
declare const toPostgres: (s: Fragment) => PostgresResult;
|
|
16
16
|
|
|
17
|
-
type Result = {
|
|
18
|
-
append: (s: Fragment) => Result;
|
|
19
|
-
name?: string;
|
|
20
|
-
sql: string;
|
|
21
|
-
text: string;
|
|
22
|
-
values: Array<any>;
|
|
23
|
-
} & Fragment;
|
|
24
|
-
declare const preparedStatementName: (r: Result, n: string) => Result;
|
|
25
|
-
declare const concat: (right: Fragment) => (left: Fragment) => Result;
|
|
26
|
-
|
|
27
17
|
type Table = {
|
|
28
18
|
readonly name: string;
|
|
29
19
|
readonly alias: string;
|
|
@@ -91,12 +81,57 @@ declare function as(col: {
|
|
|
91
81
|
declare function alias<T extends string, R, NA extends string>(t: TypedTable<T, string, R>, newAlias: NA): TypedTable<T, NA, R>;
|
|
92
82
|
declare function alias<T extends string>(t: SchemaTable<T>, newAlias: string): SchemaTable<T>;
|
|
93
83
|
|
|
94
|
-
declare const
|
|
95
|
-
declare const
|
|
96
|
-
declare const
|
|
84
|
+
declare const RESULT_ROW: unique symbol;
|
|
85
|
+
declare const COLUMNS: unique symbol;
|
|
86
|
+
declare const EXPR: unique symbol;
|
|
87
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
88
|
+
type Merge<A, B> = IsAny<A> extends true ? B : IsAny<B> extends true ? A : A & B;
|
|
89
|
+
type Rowed<R> = {
|
|
90
|
+
readonly [RESULT_ROW]?: R;
|
|
91
|
+
};
|
|
92
|
+
type Columns<X> = {
|
|
93
|
+
readonly content: any;
|
|
94
|
+
readonly [COLUMNS]: X;
|
|
95
|
+
};
|
|
96
|
+
type Expr<N extends string, V> = {
|
|
97
|
+
readonly content: any;
|
|
98
|
+
readonly [EXPR]: {
|
|
99
|
+
readonly name: N;
|
|
100
|
+
readonly type: V;
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
type HasUntyped<X> = true extends (X extends unknown ? ([Metas<X>] extends [never] ? true : false) : never) ? true : false;
|
|
104
|
+
type ColumnsRow<X, M> = HasUntyped<X> extends true ? Record<string, any> : M extends 'as' ? SelectAsRow<X> : Row<X>;
|
|
105
|
+
type Contribution<E, M> = E extends {
|
|
106
|
+
readonly [COLUMNS]: infer X;
|
|
107
|
+
} ? ColumnsRow<X, M> : E extends {
|
|
108
|
+
readonly [EXPR]: {
|
|
109
|
+
readonly name: infer N extends string;
|
|
110
|
+
readonly type: infer V;
|
|
111
|
+
};
|
|
112
|
+
} ? {
|
|
113
|
+
[K in N]: V;
|
|
114
|
+
} : any;
|
|
115
|
+
type RowOfBinds<B extends ReadonlyArray<unknown>, M> = B extends readonly [infer H, ...infer T] ? Merge<Contribution<H, M>, RowOfBinds<T, M>> : any;
|
|
116
|
+
type RowOf<Q> = Q extends Rowed<infer R> ? (IsAny<Exclude<R, undefined>> extends true ? Record<string, any> : Exclude<R, undefined>) : never;
|
|
117
|
+
|
|
118
|
+
type Result<R = any> = {
|
|
119
|
+
append: <S = any>(s: Fragment & Rowed<S>) => Result<Merge<R, S>>;
|
|
120
|
+
name?: string;
|
|
121
|
+
sql: string;
|
|
122
|
+
text: string;
|
|
123
|
+
values: Array<any>;
|
|
124
|
+
} & Fragment & Rowed<R>;
|
|
125
|
+
declare const preparedStatementName: <R>(r: Result<R>, n: string) => Result<R>;
|
|
126
|
+
declare const concat: <S = any>(right: Fragment & Rowed<S>) => <R = any>(left: Fragment & Rowed<R>) => Result<Merge<R, S>>;
|
|
127
|
+
|
|
128
|
+
declare const sql: <B extends Array<unknown>>(strings: TemplateStringsArray, ...binds: B) => Result<RowOfBinds<B, "bare">>;
|
|
129
|
+
declare const select: <B extends Array<unknown>>(strings: TemplateStringsArray, ...binds: B) => Result<RowOfBinds<B, "bare">>;
|
|
130
|
+
declare const selectAs: <B extends Array<unknown>>(strings: TemplateStringsArray, ...binds: B) => Result<RowOfBinds<B, "as">>;
|
|
97
131
|
declare const empty: Result;
|
|
98
132
|
declare const insert: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, ...colsVals: Array<{ [K in T]?: any; }>) => Result;
|
|
99
133
|
declare const update: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, colsVals: { [K in T]?: any; }) => Result;
|
|
134
|
+
declare const updateAs: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, colsVals: { [K in T]?: any; }) => Result;
|
|
100
135
|
|
|
101
136
|
type Value = {
|
|
102
137
|
readonly [K in symbol]: boolean;
|
|
@@ -104,11 +139,12 @@ type Value = {
|
|
|
104
139
|
content: any;
|
|
105
140
|
};
|
|
106
141
|
|
|
107
|
-
declare const all:
|
|
108
|
-
declare const pick:
|
|
142
|
+
declare const all: <T extends Array<SchemaTable<string>>>(...tables: T) => Columns<T[number]>;
|
|
143
|
+
declare const pick: <C extends Array<{
|
|
109
144
|
[key: symbol]: Column;
|
|
110
|
-
}
|
|
145
|
+
}>>(...columns: C) => Columns<C[number]>;
|
|
146
|
+
declare const expr: <V>() => <N extends string>(fragment: Fragment, name: N) => Expr<N, V>;
|
|
111
147
|
declare const raw: (content: string) => Value;
|
|
112
148
|
|
|
113
|
-
export { alias, all, as, concat, empty, select as g, select as groupBy, select as h, select as having, insert, select as j, select as join, select as o, select as orderBy, pick, preparedStatementName, raw, select as s, selectAs as sa, schema, select, selectAs, sql, toMysql, toPostgres, update, select as w, select as where };
|
|
114
|
-
export type { Fragment, Result, Row, SchemaTable, SelectAsRow, TypedTable };
|
|
149
|
+
export { alias, all, as, concat, empty, expr, select as g, select as groupBy, select as h, select as having, insert, select as j, select as join, select as o, select as orderBy, pick, preparedStatementName, raw, select as s, selectAs as sa, schema, select, selectAs, sql, toMysql, toPostgres, update, updateAs, select as w, select as where };
|
|
150
|
+
export type { Fragment, Result, Row, RowOf, SchemaTable, SelectAsRow, TypedTable };
|
package/dist/index.d.ts
CHANGED
|
@@ -14,16 +14,6 @@ type PostgresResult = {
|
|
|
14
14
|
declare const toMysql: (s: Fragment) => MysqlResult;
|
|
15
15
|
declare const toPostgres: (s: Fragment) => PostgresResult;
|
|
16
16
|
|
|
17
|
-
type Result = {
|
|
18
|
-
append: (s: Fragment) => Result;
|
|
19
|
-
name?: string;
|
|
20
|
-
sql: string;
|
|
21
|
-
text: string;
|
|
22
|
-
values: Array<any>;
|
|
23
|
-
} & Fragment;
|
|
24
|
-
declare const preparedStatementName: (r: Result, n: string) => Result;
|
|
25
|
-
declare const concat: (right: Fragment) => (left: Fragment) => Result;
|
|
26
|
-
|
|
27
17
|
type Table = {
|
|
28
18
|
readonly name: string;
|
|
29
19
|
readonly alias: string;
|
|
@@ -91,12 +81,57 @@ declare function as(col: {
|
|
|
91
81
|
declare function alias<T extends string, R, NA extends string>(t: TypedTable<T, string, R>, newAlias: NA): TypedTable<T, NA, R>;
|
|
92
82
|
declare function alias<T extends string>(t: SchemaTable<T>, newAlias: string): SchemaTable<T>;
|
|
93
83
|
|
|
94
|
-
declare const
|
|
95
|
-
declare const
|
|
96
|
-
declare const
|
|
84
|
+
declare const RESULT_ROW: unique symbol;
|
|
85
|
+
declare const COLUMNS: unique symbol;
|
|
86
|
+
declare const EXPR: unique symbol;
|
|
87
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
88
|
+
type Merge<A, B> = IsAny<A> extends true ? B : IsAny<B> extends true ? A : A & B;
|
|
89
|
+
type Rowed<R> = {
|
|
90
|
+
readonly [RESULT_ROW]?: R;
|
|
91
|
+
};
|
|
92
|
+
type Columns<X> = {
|
|
93
|
+
readonly content: any;
|
|
94
|
+
readonly [COLUMNS]: X;
|
|
95
|
+
};
|
|
96
|
+
type Expr<N extends string, V> = {
|
|
97
|
+
readonly content: any;
|
|
98
|
+
readonly [EXPR]: {
|
|
99
|
+
readonly name: N;
|
|
100
|
+
readonly type: V;
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
type HasUntyped<X> = true extends (X extends unknown ? ([Metas<X>] extends [never] ? true : false) : never) ? true : false;
|
|
104
|
+
type ColumnsRow<X, M> = HasUntyped<X> extends true ? Record<string, any> : M extends 'as' ? SelectAsRow<X> : Row<X>;
|
|
105
|
+
type Contribution<E, M> = E extends {
|
|
106
|
+
readonly [COLUMNS]: infer X;
|
|
107
|
+
} ? ColumnsRow<X, M> : E extends {
|
|
108
|
+
readonly [EXPR]: {
|
|
109
|
+
readonly name: infer N extends string;
|
|
110
|
+
readonly type: infer V;
|
|
111
|
+
};
|
|
112
|
+
} ? {
|
|
113
|
+
[K in N]: V;
|
|
114
|
+
} : any;
|
|
115
|
+
type RowOfBinds<B extends ReadonlyArray<unknown>, M> = B extends readonly [infer H, ...infer T] ? Merge<Contribution<H, M>, RowOfBinds<T, M>> : any;
|
|
116
|
+
type RowOf<Q> = Q extends Rowed<infer R> ? (IsAny<Exclude<R, undefined>> extends true ? Record<string, any> : Exclude<R, undefined>) : never;
|
|
117
|
+
|
|
118
|
+
type Result<R = any> = {
|
|
119
|
+
append: <S = any>(s: Fragment & Rowed<S>) => Result<Merge<R, S>>;
|
|
120
|
+
name?: string;
|
|
121
|
+
sql: string;
|
|
122
|
+
text: string;
|
|
123
|
+
values: Array<any>;
|
|
124
|
+
} & Fragment & Rowed<R>;
|
|
125
|
+
declare const preparedStatementName: <R>(r: Result<R>, n: string) => Result<R>;
|
|
126
|
+
declare const concat: <S = any>(right: Fragment & Rowed<S>) => <R = any>(left: Fragment & Rowed<R>) => Result<Merge<R, S>>;
|
|
127
|
+
|
|
128
|
+
declare const sql: <B extends Array<unknown>>(strings: TemplateStringsArray, ...binds: B) => Result<RowOfBinds<B, "bare">>;
|
|
129
|
+
declare const select: <B extends Array<unknown>>(strings: TemplateStringsArray, ...binds: B) => Result<RowOfBinds<B, "bare">>;
|
|
130
|
+
declare const selectAs: <B extends Array<unknown>>(strings: TemplateStringsArray, ...binds: B) => Result<RowOfBinds<B, "as">>;
|
|
97
131
|
declare const empty: Result;
|
|
98
132
|
declare const insert: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, ...colsVals: Array<{ [K in T]?: any; }>) => Result;
|
|
99
133
|
declare const update: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, colsVals: { [K in T]?: any; }) => Result;
|
|
134
|
+
declare const updateAs: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, colsVals: { [K in T]?: any; }) => Result;
|
|
100
135
|
|
|
101
136
|
type Value = {
|
|
102
137
|
readonly [K in symbol]: boolean;
|
|
@@ -104,11 +139,12 @@ type Value = {
|
|
|
104
139
|
content: any;
|
|
105
140
|
};
|
|
106
141
|
|
|
107
|
-
declare const all:
|
|
108
|
-
declare const pick:
|
|
142
|
+
declare const all: <T extends Array<SchemaTable<string>>>(...tables: T) => Columns<T[number]>;
|
|
143
|
+
declare const pick: <C extends Array<{
|
|
109
144
|
[key: symbol]: Column;
|
|
110
|
-
}
|
|
145
|
+
}>>(...columns: C) => Columns<C[number]>;
|
|
146
|
+
declare const expr: <V>() => <N extends string>(fragment: Fragment, name: N) => Expr<N, V>;
|
|
111
147
|
declare const raw: (content: string) => Value;
|
|
112
148
|
|
|
113
|
-
export { alias, all, as, concat, empty, select as g, select as groupBy, select as h, select as having, insert, select as j, select as join, select as o, select as orderBy, pick, preparedStatementName, raw, select as s, selectAs as sa, schema, select, selectAs, sql, toMysql, toPostgres, update, select as w, select as where };
|
|
114
|
-
export type { Fragment, Result, Row, SchemaTable, SelectAsRow, TypedTable };
|
|
149
|
+
export { alias, all, as, concat, empty, expr, select as g, select as groupBy, select as h, select as having, insert, select as j, select as join, select as o, select as orderBy, pick, preparedStatementName, raw, select as s, selectAs as sa, schema, select, selectAs, sql, toMysql, toPostgres, update, updateAs, select as w, select as where };
|
|
150
|
+
export type { Fragment, Result, Row, RowOf, SchemaTable, SelectAsRow, TypedTable };
|
package/dist/index.js
CHANGED
|
@@ -7,6 +7,8 @@ const SYM_TABLE = Symbol('sql-ts/table');
|
|
|
7
7
|
// for fragment
|
|
8
8
|
const SYM_RAW = Symbol('sql-ts/raw');
|
|
9
9
|
const SYM_IDENTIFIER = Symbol('sql-ts/identifier');
|
|
10
|
+
// for wildcard
|
|
11
|
+
const SYM_EXPR = Symbol('sql-ts/expr');
|
|
10
12
|
|
|
11
13
|
const zipLongest = (l1, l2) => {
|
|
12
14
|
const maxLength = Math.max(l1.length, l2.length);
|
|
@@ -94,6 +96,21 @@ function alias$1(t, newAlias) {
|
|
|
94
96
|
|
|
95
97
|
const identifier = (content) => ({ [SYM_IDENTIFIER]: true, content });
|
|
96
98
|
|
|
99
|
+
// joins whatever string follows it onto the one before: rendering merges a raw
|
|
100
|
+
// into the strings, and `values` leaves it out
|
|
101
|
+
const glue = { [SYM_RAW]: true, content: '' };
|
|
102
|
+
const isFragment = (x) => Array.isArray(x.strings) && Array.isArray(x.binds);
|
|
103
|
+
// A fragment interpolated into a tag is spliced in, not bound: its strings join
|
|
104
|
+
// the outer ones and its binds, already resolved by its own tag, keep their
|
|
105
|
+
// place. The glue joins its last string onto whatever comes after it.
|
|
106
|
+
const splice = (s, f) => [
|
|
107
|
+
...f.binds.map((b, i) => [i === 0 ? s + f.strings[0] : f.strings[i], b]),
|
|
108
|
+
[f.binds.length === 0 ? s + f.strings[0] : f.strings[f.binds.length], glue]
|
|
109
|
+
];
|
|
110
|
+
const exprColumn = (s, { fragment, name }) => [
|
|
111
|
+
...splice(s + '(', fragment),
|
|
112
|
+
[') as ', identifier(name)]
|
|
113
|
+
];
|
|
97
114
|
const transformer = (table, column) => ([ss, bs]) => {
|
|
98
115
|
if (bs === undefined)
|
|
99
116
|
return [[ss]];
|
|
@@ -106,6 +123,10 @@ const transformer = (table, column) => ([ss, bs]) => {
|
|
|
106
123
|
if (bs[SYM_MULTIPLE_COLUMNS])
|
|
107
124
|
return bs.content
|
|
108
125
|
.flatMap((c, i) => i === 0 ? column(ss, c) : column(' ,', c));
|
|
126
|
+
if (bs[SYM_EXPR])
|
|
127
|
+
return exprColumn(ss, bs.content);
|
|
128
|
+
if (isFragment(bs))
|
|
129
|
+
return splice(ss, bs);
|
|
109
130
|
return [[ss, bs]];
|
|
110
131
|
};
|
|
111
132
|
const tableWithAlias = (s, t) => [
|
|
@@ -139,6 +160,9 @@ const dropUndefined = (strings, binds) => {
|
|
|
139
160
|
});
|
|
140
161
|
return [outStrings, outBinds];
|
|
141
162
|
};
|
|
163
|
+
// M is how the tag names the columns it selects: 'as' for selectAs
|
|
164
|
+
// (`alias_column`), 'bare' for the rest (`column`). The row it returns is
|
|
165
|
+
// inferred from the binds (see row.ts).
|
|
142
166
|
const buildTag = (fn) => (strings, ...binds) => {
|
|
143
167
|
const [ss, bs] = dropUndefined(strings, binds);
|
|
144
168
|
const pairs = zipLongest(ss, bs).flatMap(fn);
|
|
@@ -162,13 +186,22 @@ const insert = (table, ...colsVals) => {
|
|
|
162
186
|
}, [[], []]);
|
|
163
187
|
return result(fragment(['insert into ', ...colStrings, ...valStrings, ')'], [identifier(tableName), ...colBinds, ...valBinds]));
|
|
164
188
|
};
|
|
165
|
-
|
|
166
|
-
|
|
189
|
+
// The set list is the same whatever names the target, so both update builders
|
|
190
|
+
// share it and only hand over how the statement opens. Set columns stay
|
|
191
|
+
// unqualified: PostgreSQL rejects `set "u"."email"`.
|
|
192
|
+
const buildUpdate = (head) => (table, colsVals) => {
|
|
167
193
|
const entries = Object.entries(colsVals).filter(([, v]) => v !== undefined);
|
|
168
|
-
const [strings, binds] = entries.reduce(([ss, bs], [colName, v], i) => [[...ss, i === 0 ? ' set ' : ' ,', ' = '], [...bs, identifier(colName), value(v)]], [
|
|
194
|
+
const [strings, binds] = entries.reduce(([ss, bs], [colName, v], i) => [[...ss, i === 0 ? ' set ' : ' ,', ' = '], [...bs, identifier(colName), value(v)]], head(table[SYM_TABLE]));
|
|
169
195
|
return result(fragment([...strings, ''], binds));
|
|
170
196
|
};
|
|
197
|
+
const update = buildUpdate(t => [['update '], [identifier(t.name)]]);
|
|
198
|
+
// The target carries the table's alias, so a where built with the `where` tag,
|
|
199
|
+
// whose columns are qualified with that alias, resolves against it. `as` is
|
|
200
|
+
// spelled out because SQLite only accepts the alias with it.
|
|
201
|
+
const updateAs = buildUpdate(t => [['update ', ' as '], [identifier(t.name), identifier(t.alias)]]);
|
|
171
202
|
|
|
203
|
+
// The runtime value is the same as ever; the return type also carries what was
|
|
204
|
+
// passed, so the tags can infer the row a query selects (see row.ts).
|
|
172
205
|
const all = (...tables) => ({
|
|
173
206
|
[SYM_MULTIPLE_COLUMNS]: true,
|
|
174
207
|
content: tables.flatMap(t => Object.values(t).map(x => x[SYM_COLUMN]))
|
|
@@ -177,6 +210,12 @@ const pick = (...columns) => ({
|
|
|
177
210
|
[SYM_MULTIPLE_COLUMNS]: true,
|
|
178
211
|
content: columns.map(x => x[SYM_COLUMN])
|
|
179
212
|
});
|
|
213
|
+
// A computed column: `(<fragment>) as "name"`, and `name: V` in the inferred
|
|
214
|
+
// row. Curried like schema<R>() so V is given and the name is inferred.
|
|
215
|
+
const expr = () => (fragment, name) => ({
|
|
216
|
+
[SYM_EXPR]: true,
|
|
217
|
+
content: { fragment, name }
|
|
218
|
+
});
|
|
180
219
|
const raw = (content) => ({
|
|
181
220
|
[SYM_RAW]: true,
|
|
182
221
|
content
|
|
@@ -187,6 +226,7 @@ exports.all = all;
|
|
|
187
226
|
exports.as = as;
|
|
188
227
|
exports.concat = concat;
|
|
189
228
|
exports.empty = empty;
|
|
229
|
+
exports.expr = expr;
|
|
190
230
|
exports.g = select;
|
|
191
231
|
exports.groupBy = select;
|
|
192
232
|
exports.h = select;
|
|
@@ -208,6 +248,7 @@ exports.sql = sql;
|
|
|
208
248
|
exports.toMysql = toMysql;
|
|
209
249
|
exports.toPostgres = toPostgres;
|
|
210
250
|
exports.update = update;
|
|
251
|
+
exports.updateAs = updateAs;
|
|
211
252
|
exports.w = select;
|
|
212
253
|
exports.where = select;
|
|
213
254
|
//# sourceMappingURL=index.js.map
|