@vanit-co/sql-ts 1.0.3 → 1.1.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 ADDED
@@ -0,0 +1,67 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [1.1.0] - 2026-11-28
8
+
9
+ ### Added
10
+ - Native ES module build (`dist/index.mjs`) alongside the CommonJS build, with an
11
+ `exports` map and separate type declarations for `import` and `require`.
12
+ - `sideEffects: false` for better tree-shaking.
13
+ - Opt-in typed result rows: `schema<{ ... }>()({ ... })` builds a typed table, and the
14
+ new `SelectAsRow<...>` / `Row<...>` types derive row shapes from it. `as()` returns
15
+ the literal key (`'u_id'`) for typed columns. Plain `schema({ ... })` keeps exactly
16
+ the types it had.
17
+ - Public type exports: `Fragment`, `Result`, `SchemaTable`, `TypedTable`, `SelectAsRow`, `Row`.
18
+
19
+ ### Changed
20
+ - **Zero runtime dependencies**: `ramda` is no longer a dependency. Output is
21
+ unchanged.
22
+
23
+ ## [1.0.4] - 2026-10-28
24
+
25
+ ### Added
26
+ - SQLite support documented and tested through `.sql` (`better-sqlite3`, `node:sqlite`).
27
+
28
+ ## [1.0.0] - 2026-07-31
29
+
30
+ ### Added
31
+ - `insert` and `update` accept `raw(...)` SQL expressions as values.
32
+ - `insert` and `update` accept column references as values, rendered as quoted identifiers.
33
+
34
+ ## [0.9.0] - 2026-06-10
35
+
36
+ ### Changed
37
+ - `undefined` interpolations are discarded instead of becoming bind parameters,
38
+ which makes optional values easy to drop.
39
+
40
+ ## [0.7.0] - 2026-05-03
41
+
42
+ ### Security
43
+ - Identifiers are escaped (embedded quotes are doubled), fixing SQL injection
44
+ through crafted table or column names.
45
+
46
+ ## [0.5.0] - 2026-04-28
47
+
48
+ ### Added
49
+ - `null` accepted as a bind parameter.
50
+
51
+ ## [0.3.0] - 2026-04-06
52
+
53
+ ### Added
54
+ - `groupBy`, `having` and `orderBy` tags (semantic aliases of `select`).
55
+
56
+ ## [0.2.0] - 2026-04-02
57
+
58
+ ### Added
59
+ - Column helpers, including `as(column)`.
60
+
61
+ ## [0.0.1] - 2026-03-28
62
+
63
+ ### Added
64
+ - First release: `schema`, the `sql` / `select` / `selectAs` / `join` / `where`
65
+ tags, `all`, `pick`, `raw`, `insert`, `update`, `concat`, `empty`,
66
+ `toMysql`, `toPostgres` and `preparedStatementName`.
67
+
package/README.md CHANGED
@@ -1,8 +1,67 @@
1
1
  # @vanit-co/sql-ts
2
2
 
3
- A TypeScript SQL query builder using tagged template literals. Write plain SQL with safe, automatic parameter binding and properly quoted identifiers. No DSL to learn, no magic, no ORM.
3
+ [![npm](https://img.shields.io/npm/v/@vanit-co/sql-ts)](https://www.npmjs.com/package/@vanit-co/sql-ts)
4
+ [![CI](https://github.com/vanit-co/sql-ts/actions/workflows/ci.yml/badge.svg)](https://github.com/vanit-co/sql-ts/actions/workflows/ci.yml)
5
+ [![minzipped size](https://img.shields.io/bundlephobia/minzip/@vanit-co/sql-ts)](https://bundlephobia.com/package/@vanit-co/sql-ts)
6
+ ![types included](https://img.shields.io/npm/types/@vanit-co/sql-ts)
7
+ [![license](https://img.shields.io/npm/l/@vanit-co/sql-ts)](./LICENSE)
4
8
 
5
- Supports **MySQL** (`?` placeholders, `` ` `` backtick identifiers) and **PostgreSQL** (`$n` placeholders, `"` double-quote identifiers) out of the box.
9
+ **Write plain SQL. Get quoted identifiers, qualified columns and bound parameters for free. Compose queries like data.**
10
+
11
+ A TypeScript SQL builder using tagged template literals. No DSL to learn, no magic, no ORM. **Zero dependencies, ~2 KB gzipped, ESM and CommonJS.**
12
+
13
+ Supports **PostgreSQL** (`$n` placeholders, `"` identifiers), **MySQL** (`?` placeholders, `` ` `` identifiers) and **SQLite** (through the MySQL format, see [Result object](#result-object)), all from the same query.
14
+
15
+ ```sh
16
+ npm install @vanit-co/sql-ts
17
+ ```
18
+
19
+ ### In 30 seconds
20
+
21
+ Without it, you hand-qualify every column, alias every result key to avoid collisions, and track placeholder numbers yourself:
22
+
23
+ ```ts
24
+ let text = `SELECT "u"."id" AS "u_id", "u"."email" AS "u_email", "p"."id" AS "p_id", "p"."title" AS "p_title"
25
+ FROM "posts" "p" JOIN "users" "u" ON "p"."user_id" = "u"."id"`
26
+ const values = []
27
+ if (userId) { values.push(userId); text += ` WHERE "u"."id" = $${values.length}` }
28
+ ```
29
+
30
+ With it, you declare the tables once and the rest follows:
31
+
32
+ ```ts
33
+ import { schema, selectAs, join, where, all, empty } from '@vanit-co/sql-ts'
34
+
35
+ const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
36
+ const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
37
+
38
+ const postsQuery = (userId?: number) =>
39
+ selectAs`SELECT ${all(users, posts)} FROM ${posts}`
40
+ .append(join` JOIN ${users} ON ${posts.user_id} = ${users.id}`)
41
+ .append(userId ? where` WHERE ${users.id} = ${userId}` : empty)
42
+
43
+ const q = postsQuery(7)
44
+ q.text // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email" ,"p"."id" as "p_id" ... WHERE "u"."id" = $1
45
+ q.sql // same query for MySQL / SQLite: `u`.`id` ... WHERE `u`.`id` = ?
46
+ q.values // [7]
47
+
48
+ await pg.query(q) // node-postgres reads { text, values }
49
+ ```
50
+
51
+ A typo like `users.emial` is a compile error, and every query is an immutable value you can pass around, `reduce` over or `pipe` through.
52
+
53
+ ### How it compares
54
+
55
+ | | sql-ts | [sql-template-tag](https://github.com/blakeembrey/sql-template-tag) | [slonik](https://github.com/gajus/slonik) | [kysely](https://kysely.dev) |
56
+ |-----------------------------------------|:------:|:----------------:|:------:|:------:|
57
+ | Plain SQL is the primary API | ✅ | ✅ | ✅ | ❌ (method-chain DSL) |
58
+ | Identifiers quoted from a typed schema | ✅ | ❌ | manual `sql.identifier` | ✅ |
59
+ | Automatic `alias.column` / `AS alias_column` | ✅ | ❌ | ❌ | ❌ |
60
+ | One query → PostgreSQL *and* MySQL/SQLite | ✅ | ✅ | ❌ (PostgreSQL only) | per-dialect instance |
61
+ | Composable as a monoid (`concat` / `empty`) | ✅ | partial (`join`, `empty`) | ❌ | ❌ |
62
+ | Executes queries itself (wraps the driver) | ❌ (use your driver) | ❌ | ✅ | ✅ |
63
+
64
+ Pick **sql-ts** if you like SQL, use your driver directly, and want query building that fits functional code. Pick **kysely** or an ORM if you'd rather not write SQL at all.
6
65
 
7
66
  ## Why this library?
8
67
 
@@ -18,12 +77,6 @@ Writing raw SQL in TypeScript runs into a set of recurring friction points that
18
77
 
19
78
  - **`all` and `pick` helpers** - expand an entire table's columns or a chosen subset into a comma-separated list inside any tag, so `SELECT ${all(users, posts)}` replaces repetitive column lists without losing type safety.
20
79
 
21
- ## Installation
22
-
23
- ```sh
24
- npm install @vanit-co/sql-ts
25
- ```
26
-
27
80
  ## Quick example
28
81
 
29
82
  **sql** tag takes care of quoting the identifiers (tables and columns) with the proper quotes `` ` `` for MySQL and `"` for PostgreSQL.
@@ -136,7 +189,7 @@ Every template tag and statement builder returns a `Result` object with three pr
136
189
 
137
190
  | property | description |
138
191
  |----------|-------------|
139
- | `.sql` | Query string in MySQL format (`?` placeholders, backtick-quoted identifiers) |
192
+ | `.sql` | Query string in MySQL format (`?` placeholders, backtick-quoted identifiers), also used for SQLite |
140
193
  | `.text` | Query string in PostgreSQL format (`$n` placeholders, double-quote identifiers) |
141
194
  | `.values` | Array of bind values in order, ready to pass to your database driver |
142
195
 
@@ -148,8 +201,13 @@ await client.query(query)
148
201
 
149
202
  // mysql2
150
203
  await connection.query(query)
204
+
205
+ // better-sqlite3 / node:sqlite
206
+ db.prepare(query.sql).all(...query.values)
151
207
  ```
152
208
 
209
+ SQLite accepts backtick-quoted identifiers and `?` placeholders, so use `.sql` with it. Do not use `.text`: SQLite reads `$1` as a named parameter, so positional values won't bind.
210
+
153
211
  ---
154
212
 
155
213
  ## Template tag functions
@@ -321,6 +379,34 @@ rows.map(row => ({
321
379
 
322
380
  ---
323
381
 
382
+ ## Typed result rows
383
+
384
+ Pass a type record to `schema` (note the extra `()`) and the library can derive the row type of your queries. This is opt-in: plain `schema({...})` works exactly as before.
385
+
386
+ ```ts
387
+ import { schema, selectAs, join, all, as, type SelectAsRow, type Row } from '@vanit-co/sql-ts'
388
+
389
+ const users = schema<{ id: number; email: string }>()({ table: 'users', columns: ['id', 'email'], alias: 'u' })
390
+ const posts = schema<{ id: number; user_id: number; title: string | null }>()({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
391
+
392
+ // selectAs keys: alias_column
393
+ type PostWithAuthor = SelectAsRow<typeof users | typeof posts>
394
+ // { u_id: number; u_email: string; p_id: number; p_user_id: number; p_title: string | null }
395
+
396
+ const q = selectAs`SELECT ${all(users, posts)} FROM ${posts}`
397
+ .append(join` JOIN ${users} ON ${posts.user_id} = ${users.id}`)
398
+
399
+ const { rows } = await pg.query<PostWithAuthor>(q)
400
+ rows[0][as(posts.title)] // string | null, and as(posts.title) is typed as 'p_title'
401
+ ```
402
+
403
+ - `SelectAsRow<...>` takes tables or single columns (`typeof users.email | typeof posts.title`), matching `all(...)` and `pick(...)`.
404
+ - `Row<typeof users>` gives bare column names (`{ id: number; email: string }`), matching `sql` / `select`.
405
+ - `columns` must be keys of the type record, so `columns: ['id', 'emial']` is a compile error.
406
+ - `alias(users, 'author')` keeps the types and re-prefixes the keys (`author_id`, ...).
407
+
408
+ ---
409
+
324
410
  ## Statement builders: `insert` and `update`
325
411
 
326
412
  ### `insert(table, ...rows)`
@@ -351,7 +437,7 @@ q3.text // insert into "users" ("id" ,"email") values (nextval('users_id_seq'
351
437
  q3.values // ['alice@example.com']
352
438
  ```
353
439
 
354
- Column objects used as values are resolved to quoted identifiers rather than bound. They render unprefixed, since the statement has no alias in scope.
440
+ Column objects used as values are resolved to quoted identifiers rather than bound. They render unprefixed, since the statement has no alias in scope. Referencing a column inside `values (...)` is only accepted by MySQL; PostgreSQL and SQLite reject it.
355
441
 
356
442
  ### `update(table, colsVals)`
357
443
 
@@ -384,7 +470,9 @@ q4.values // []
384
470
 
385
471
  ---
386
472
 
387
- ## Fragment utilities: `concat` and `empty`
473
+ ## Composing queries (functional by design): `concat` and `empty`
474
+
475
+ Every tag and statement builder returns an immutable value, and fragments form a monoid: `concat` is associative and `empty` is its identity. Query building becomes ordinary data transformation, so it works with `reduce`, `pipe` (ramda, Effect, fp-ts) or plain `.append` chains.
388
476
 
389
477
  ### `concat`
390
478
 
@@ -414,7 +502,7 @@ const full = base.append(where`WHERE ${users.id} = ${5}`)
414
502
 
415
503
  Because `concat` is curried, it fits naturally into a `pipe`. Each `concat(fragment)` call becomes one step in the pipeline, appending a fragment to the result of the previous step.
416
504
 
417
- Using **ramda** (already a dependency of this package):
505
+ Using **ramda** (`npm install ramda`, not needed by this package itself):
418
506
 
419
507
  ```ts
420
508
  import { pipe } from 'ramda'
@@ -493,6 +581,29 @@ q.values // [7, '%TypeScript%']
493
581
 
494
582
  ---
495
583
 
584
+ ## Arrays and `IN` lists
585
+
586
+ An array is bound as a single parameter, which is what the drivers expect:
587
+
588
+ ```ts
589
+ const ids = [1, 2, 3]
590
+
591
+ // PostgreSQL (node-postgres): use = ANY(...)
592
+ where`WHERE ${users.id} = ANY(${ids})`.text // WHERE "u"."id" = ANY($1) values: [[1, 2, 3]]
593
+
594
+ // MySQL (mysql2, with .query): IN (?) expands the array
595
+ where`WHERE ${users.id} IN (${ids})`.sql // WHERE `u`.`id` IN (?) values: [[1, 2, 3]]
596
+ ```
597
+
598
+ SQLite drivers don't expand arrays. Bind the list as JSON instead:
599
+
600
+ ```ts
601
+ sql`WHERE ${users.id} IN (SELECT value FROM json_each(${JSON.stringify(ids)}))`.sql
602
+ // WHERE `id` IN (SELECT value FROM json_each(?)) values: ['[1,2,3]']
603
+ ```
604
+
605
+ ---
606
+
496
607
  ## Dialect functions: `toMysql` and `toPostgres`
497
608
 
498
609
  Convert any `Fragment` directly to a dialect-specific result. The template tags already expose `.sql` and `.text` on their return value, but you can call these directly when working with raw fragments.
@@ -0,0 +1,114 @@
1
+ type Fragment = {
2
+ readonly strings: ReadonlyArray<string>;
3
+ readonly binds: ReadonlyArray<unknown>;
4
+ };
5
+
6
+ type MysqlResult = {
7
+ readonly sql: string;
8
+ readonly values: ReadonlyArray<unknown>;
9
+ };
10
+ type PostgresResult = {
11
+ readonly text: string;
12
+ readonly values: ReadonlyArray<unknown>;
13
+ };
14
+ declare const toMysql: (s: Fragment) => MysqlResult;
15
+ declare const toPostgres: (s: Fragment) => PostgresResult;
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
+ type Table = {
28
+ readonly name: string;
29
+ readonly alias: string;
30
+ };
31
+ type Column = {
32
+ readonly name: string;
33
+ readonly prefix: string;
34
+ };
35
+ type SchemaColumn<T extends string> = {
36
+ [K in T]: {
37
+ [KC in symbol]: Column;
38
+ };
39
+ };
40
+ type SchemaTable<T extends string> = {
41
+ readonly [KT in symbol]: Table;
42
+ } & SchemaColumn<T>;
43
+ type Params<T extends string> = {
44
+ readonly table: string;
45
+ readonly columns: ReadonlyArray<T>;
46
+ readonly alias?: string;
47
+ };
48
+ declare const COL: unique symbol;
49
+ declare const ROW: unique symbol;
50
+ type ColumnMeta<P extends string = string, N extends string = string, V = unknown> = {
51
+ readonly prefix: P;
52
+ readonly name: N;
53
+ readonly type: V;
54
+ };
55
+ type TypedColumn<P extends string, N extends string, V> = {
56
+ [KC in symbol]: Column & {
57
+ readonly [COL]: ColumnMeta<P, N, V>;
58
+ };
59
+ };
60
+ type TypedTable<T extends string, A extends string, R> = {
61
+ readonly [KT in symbol]: Table & {
62
+ readonly [ROW]: R;
63
+ };
64
+ } & {
65
+ [K in T]: TypedColumn<A, K, K extends keyof R ? R[K] : unknown>;
66
+ };
67
+ type TypedParams<T extends string, N extends string, A extends string> = {
68
+ readonly table: N;
69
+ readonly columns: ReadonlyArray<T>;
70
+ readonly alias?: A;
71
+ };
72
+ type TypedSchema<R> = <T extends keyof R & string, N extends string, A extends string = N>(params: TypedParams<T, N, A>) => TypedTable<T, A, R>;
73
+ type ColumnMetaOf<C> = C extends {
74
+ readonly [k: symbol]: {
75
+ readonly [COL]: infer M;
76
+ };
77
+ } ? M extends ColumnMeta ? M : never : never;
78
+ type Metas<X> = X extends unknown ? ColumnMetaOf<X> | ColumnMetaOf<X[Exclude<keyof X, symbol>]> : never;
79
+ type SelectAsRow<X> = {
80
+ [M in Metas<X> as `${M['prefix']}_${M['name']}`]: M['type'];
81
+ };
82
+ type Row<X> = {
83
+ [M in Metas<X> as M['name']]: M['type'];
84
+ };
85
+ declare function schema<R extends object>(): TypedSchema<R>;
86
+ declare function schema<T extends string>(params: Params<T>): SchemaTable<T>;
87
+ declare function as<P extends string, N extends string>(col: TypedColumn<P, N, unknown>): `${P}_${N}`;
88
+ declare function as(col: {
89
+ [K in symbol]: Column;
90
+ }): string;
91
+ declare function alias<T extends string, R, NA extends string>(t: TypedTable<T, string, R>, newAlias: NA): TypedTable<T, NA, R>;
92
+ declare function alias<T extends string>(t: SchemaTable<T>, newAlias: string): SchemaTable<T>;
93
+
94
+ declare const sql: (strings: TemplateStringsArray, ...binds: Array<any>) => Result;
95
+ declare const select: (strings: TemplateStringsArray, ...binds: Array<any>) => Result;
96
+ declare const selectAs: (strings: TemplateStringsArray, ...binds: Array<any>) => Result;
97
+ declare const empty: Result;
98
+ declare const insert: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, ...colsVals: Array<{ [K in T]?: any; }>) => Result;
99
+ declare const update: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, colsVals: { [K in T]?: any; }) => Result;
100
+
101
+ type Value = {
102
+ readonly [K in symbol]: boolean;
103
+ } & {
104
+ content: any;
105
+ };
106
+
107
+ declare const all: (...tables: Array<SchemaTable<string>>) => Value;
108
+ declare const pick: (...columns: Array<{
109
+ [key: symbol]: Column;
110
+ }>) => Value;
111
+ declare const raw: (content: string) => Value;
112
+
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 };
package/dist/index.d.ts CHANGED
@@ -45,16 +45,58 @@ type Params<T extends string> = {
45
45
  readonly columns: ReadonlyArray<T>;
46
46
  readonly alias?: string;
47
47
  };
48
- declare const schema: <T extends string>({ table, columns, alias }: Params<T>) => SchemaTable<T>;
49
- declare const as: (col: { [K in symbol]: Column; }) => string;
50
- declare const alias: <T extends string>(t: SchemaTable<T>, newAlias: string) => SchemaTable<T>;
48
+ declare const COL: unique symbol;
49
+ declare const ROW: unique symbol;
50
+ type ColumnMeta<P extends string = string, N extends string = string, V = unknown> = {
51
+ readonly prefix: P;
52
+ readonly name: N;
53
+ readonly type: V;
54
+ };
55
+ type TypedColumn<P extends string, N extends string, V> = {
56
+ [KC in symbol]: Column & {
57
+ readonly [COL]: ColumnMeta<P, N, V>;
58
+ };
59
+ };
60
+ type TypedTable<T extends string, A extends string, R> = {
61
+ readonly [KT in symbol]: Table & {
62
+ readonly [ROW]: R;
63
+ };
64
+ } & {
65
+ [K in T]: TypedColumn<A, K, K extends keyof R ? R[K] : unknown>;
66
+ };
67
+ type TypedParams<T extends string, N extends string, A extends string> = {
68
+ readonly table: N;
69
+ readonly columns: ReadonlyArray<T>;
70
+ readonly alias?: A;
71
+ };
72
+ type TypedSchema<R> = <T extends keyof R & string, N extends string, A extends string = N>(params: TypedParams<T, N, A>) => TypedTable<T, A, R>;
73
+ type ColumnMetaOf<C> = C extends {
74
+ readonly [k: symbol]: {
75
+ readonly [COL]: infer M;
76
+ };
77
+ } ? M extends ColumnMeta ? M : never : never;
78
+ type Metas<X> = X extends unknown ? ColumnMetaOf<X> | ColumnMetaOf<X[Exclude<keyof X, symbol>]> : never;
79
+ type SelectAsRow<X> = {
80
+ [M in Metas<X> as `${M['prefix']}_${M['name']}`]: M['type'];
81
+ };
82
+ type Row<X> = {
83
+ [M in Metas<X> as M['name']]: M['type'];
84
+ };
85
+ declare function schema<R extends object>(): TypedSchema<R>;
86
+ declare function schema<T extends string>(params: Params<T>): SchemaTable<T>;
87
+ declare function as<P extends string, N extends string>(col: TypedColumn<P, N, unknown>): `${P}_${N}`;
88
+ declare function as(col: {
89
+ [K in symbol]: Column;
90
+ }): string;
91
+ declare function alias<T extends string, R, NA extends string>(t: TypedTable<T, string, R>, newAlias: NA): TypedTable<T, NA, R>;
92
+ declare function alias<T extends string>(t: SchemaTable<T>, newAlias: string): SchemaTable<T>;
51
93
 
52
94
  declare const sql: (strings: TemplateStringsArray, ...binds: Array<any>) => Result;
53
95
  declare const select: (strings: TemplateStringsArray, ...binds: Array<any>) => Result;
54
96
  declare const selectAs: (strings: TemplateStringsArray, ...binds: Array<any>) => Result;
55
97
  declare const empty: Result;
56
- declare const insert: <T extends string>(table: SchemaTable<T>, ...colsVals: Array<{ [K in T]?: any; }>) => Result;
57
- declare const update: <T extends string>(table: SchemaTable<T>, colsVals: { [K in T]?: any; }) => Result;
98
+ declare const insert: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, ...colsVals: Array<{ [K in T]?: any; }>) => Result;
99
+ declare const update: <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown>, colsVals: { [K in T]?: any; }) => Result;
58
100
 
59
101
  type Value = {
60
102
  readonly [K in symbol]: boolean;
@@ -69,3 +111,4 @@ declare const pick: (...columns: Array<{
69
111
  declare const raw: (content: string) => Value;
70
112
 
71
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 };
package/dist/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- var ramda = require('ramda');
4
-
5
3
  // for schema
6
4
  const SYM_COLUMN = Symbol('sql-ts/column');
7
5
  const SYM_MULTIPLE_COLUMNS = Symbol('sql-ts/multipleColumns');
@@ -46,7 +44,7 @@ const toMysql = (s) => {
46
44
  const toPostgres = (s) => {
47
45
  const ss = stringfyIdentifierAndRaw('"')(s);
48
46
  return {
49
- text: ss.strings[0] + ramda.zipWith((i, str) => `$${i}${str}`, ramda.range(1, ss.binds.length + 1), ss.strings.slice(1)).join(''),
47
+ text: ss.strings[0] + ss.strings.slice(1).map((str, i) => `$${i + 1}${str}`).join(''),
50
48
  values: ss.binds
51
49
  };
52
50
  };
@@ -72,22 +70,27 @@ const result = (s) => ({
72
70
  });
73
71
 
74
72
  const makeColumns = (prefix, cols) => cols.reduce((a, key) => ({ ...a, [key]: { [SYM_COLUMN]: { name: key, prefix } } }), {});
75
- const schema = ({ table, columns, alias }) => {
73
+ function schema(params) {
74
+ if (params === undefined)
75
+ return schema;
76
+ const { table, columns, alias } = params;
76
77
  const resolvedAlias = alias ?? table;
77
78
  return {
78
79
  [SYM_TABLE]: { name: table, alias: resolvedAlias },
79
80
  ...makeColumns(resolvedAlias, columns)
80
81
  };
81
- };
82
- const as = (col) => {
82
+ }
83
+ function as(col) {
83
84
  const c = col[SYM_COLUMN];
84
85
  return c.prefix + '_' + c.name;
85
- };
86
- const alias$1 = (t, newAlias) => schema({
87
- table: t[SYM_TABLE].name,
88
- columns: Object.keys(t),
89
- alias: newAlias
90
- });
86
+ }
87
+ function alias$1(t, newAlias) {
88
+ return schema({
89
+ table: t[SYM_TABLE].name,
90
+ columns: Object.keys(t),
91
+ alias: newAlias
92
+ });
93
+ }
91
94
 
92
95
  const identifier = (content) => ({ [SYM_IDENTIFIER]: true, content });
93
96
 
@@ -138,8 +141,10 @@ const dropUndefined = (strings, binds) => {
138
141
  };
139
142
  const buildTag = (fn) => (strings, ...binds) => {
140
143
  const [ss, bs] = dropUndefined(strings, binds);
141
- const [s, v] = ramda.transpose(zipLongest(ss, bs).flatMap(fn));
142
- return result(fragment(s, v ?? []));
144
+ const pairs = zipLongest(ss, bs).flatMap(fn);
145
+ const strs = pairs.map(([s]) => s);
146
+ const vals = pairs.slice(0, -1).map(([, v]) => v);
147
+ return result(fragment(strs, vals));
143
148
  };
144
149
  const sql = buildTag(pure);
145
150
  const select = buildTag(prefix);
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/symbol.ts","../src/list.ts","../src/fragment.ts","../src/dialect.ts","../src/result.ts","../src/schema.ts","../src/identifier.ts","../src/statement.ts","../src/wildcard.ts"],"sourcesContent":["// for schema\nconst SYM_COLUMN = Symbol('sql-ts/column')\nconst SYM_MULTIPLE_COLUMNS = Symbol('sql-ts/multipleColumns')\nconst SYM_TABLE = Symbol('sql-ts/table')\n\n// for fragment\nconst SYM_RAW = Symbol('sql-ts/raw')\nconst SYM_IDENTIFIER = Symbol('sql-ts/identifier')\n\nexport {\n SYM_COLUMN\n ,SYM_IDENTIFIER\n ,SYM_MULTIPLE_COLUMNS\n ,SYM_RAW\n ,SYM_TABLE\n}\n","const zipLongest = (l1: Array<string>, l2: Array<any>): Array<[string ,any]> => {\n const maxLength = Math.max(l1.length, l2.length)\n return Array.from({ length: maxLength }, (_, i) => [l1[i], l2[i]])\n}\n\nexport { zipLongest }\n","import * as sym from './symbol'\nimport { zipLongest } from './list'\nimport { Result, result } from './result'\n\ntype Fragment = {\n readonly strings: ReadonlyArray<string>\n readonly binds: ReadonlyArray<unknown>\n}\n\nconst fragment = (strings: ReadonlyArray<string> ,binds: ReadonlyArray<unknown> = []): Fragment => {\n\n if(strings.length !== binds.length + 1) \n throw new Error(`Malformed fragment: ${strings.length} strings for ${binds.length} values`)\n\n return Object.freeze({ strings, binds })\n}\n\nconst stringfyIdentifierAndRaw = (quote: string = '') => (s: Fragment): Fragment => {\n\n const fn = ([strings ,binds ,merge]: [Array<string> ,Array<any> ,Array<string>], [ss, bs]: [string, any]): [Array<string> ,Array<any> ,Array<string>] => {\n\n if(bs && bs[sym.SYM_RAW]) {\n return [strings ,binds ,[...merge, ss, bs.content]]\n }\n else if(bs && bs[sym.SYM_IDENTIFIER]) {\n return [strings ,binds ,[...merge, ss, (quote + bs.content.replaceAll(quote, quote + quote) + quote)]]\n }\n else if(bs !== undefined) {\n return [[...strings ,merge.join('') + ss] ,[...binds ,bs] ,[]]\n }\n else {\n return [[...strings ,merge.join('') + ss] ,binds ,[]]\n }\n\n }\n\n const [ns, nb] = zipLongest(s.strings as Array<string> ,s.binds as Array<string>).reduce(fn, [[] ,[] ,[]])\n\n return fragment(ns, nb)\n\n}\n\nexport type { Fragment }\nexport {\n fragment\n ,stringfyIdentifierAndRaw\n}\n","import { Fragment, stringfyIdentifierAndRaw } from './fragment'\n\ntype MysqlResult = { readonly sql: string; readonly values: ReadonlyArray<unknown> }\ntype PostgresResult = { readonly text: string; readonly values: ReadonlyArray<unknown> }\n\nconst toMysql = (s: Fragment): MysqlResult => {\n const ss = stringfyIdentifierAndRaw('`')(s)\n return { sql: [...ss.strings].join('?'), values: ss.binds }\n}\n\nconst toPostgres = (s: Fragment): PostgresResult => {\n const ss = stringfyIdentifierAndRaw('\"')(s)\n return {\n text: ss.strings[0] + ss.strings.slice(1).map((str, i) => `$${i + 1}${str}`).join(''),\n values: ss.binds\n }\n}\n\nexport { toMysql, toPostgres }\nexport type { MysqlResult, PostgresResult }\n","import { toMysql, toPostgres } from './dialect'\nimport { Fragment, fragment } from './fragment'\nimport { SYM_IDENTIFIER, SYM_RAW } from './symbol'\n\ntype Result = {\n append: (s: Fragment) => Result\n name?: string\n sql: string\n text: string\n values: Array<any>\n} & Fragment\n\nconst preparedStatementName = (r: Result ,n: string): Result => ({ ...r ,name: n })\n\nconst concat = (right: Fragment) => (left: Fragment): Result => {\n const lastLeft = left.strings[left.strings.length - 1] ?? ''\n const firstRight = right.strings[0] ?? ''\n return result(fragment(\n [...left.strings.slice(0, -1), lastLeft + firstRight, ...right.strings.slice(1)]\n ,[...left.binds, ...right.binds]\n ))\n}\n\nconst result = (s: Fragment): Result => ({\n ...s,\n append: (x: Fragment) => concat(x)(s)\n ,get sql() {\n return toMysql(s).sql\n }\n ,get text() {\n return toPostgres(s).text\n }\n ,get values() {\n return s.binds.filter((x: any) => !(x && (x[SYM_RAW] || x[SYM_IDENTIFIER])))\n }\n})\n\nexport type { Result }\nexport {\n concat\n ,preparedStatementName\n ,result\n}\n","import * as sym from './symbol'\n\ntype Table = {\n readonly name: string\n readonly alias: string\n}\n\ntype Column = {\n readonly name: string\n readonly prefix: string\n}\n\ntype SchemaColumn<T extends string> = { [K in T]: { [KC in symbol]: Column } }\n\ntype SchemaTable<T extends string> = {\n readonly [KT in symbol]: Table\n} & SchemaColumn<T>\n\ntype Params<T extends string> = {\n readonly table: string\n readonly columns: ReadonlyArray<T>\n readonly alias?: string\n}\n\n// Type-only brands: they never exist at runtime. COL carries the prefix, name and\n// value type of a typed column, ROW the row record of a typed table.\ndeclare const COL: unique symbol\ndeclare const ROW: unique symbol\n\ntype ColumnMeta<P extends string = string, N extends string = string, V = unknown> = {\n readonly prefix: P\n readonly name: N\n readonly type: V\n}\n\ntype TypedColumn<P extends string, N extends string, V> = {\n [KC in symbol]: Column & { readonly [COL]: ColumnMeta<P, N, V> }\n}\n\n// Table built with schema<R>()({...}). Assignable to SchemaTable<T>, so it works\n// everywhere a plain table does.\ntype TypedTable<T extends string, A extends string, R> = {\n readonly [KT in symbol]: Table & { readonly [ROW]: R }\n} & {\n [K in T]: TypedColumn<A, K, K extends keyof R ? R[K] : unknown>\n}\n\ntype TypedParams<T extends string, N extends string, A extends string> = {\n readonly table: N\n readonly columns: ReadonlyArray<T>\n readonly alias?: A\n}\n\ntype TypedSchema<R> = <T extends keyof R & string, N extends string, A extends string = N>(\n params: TypedParams<T, N, A>\n) => TypedTable<T, A, R>\n\n// Metadata of a typed column, or of every column of a typed table; never for untyped input\ntype ColumnMetaOf<C> = C extends { readonly [k: symbol]: { readonly [COL]: infer M } }\n ? M extends ColumnMeta ? M : never\n : never\n\ntype Metas<X> = X extends unknown ? ColumnMetaOf<X> | ColumnMetaOf<X[Exclude<keyof X, symbol>]> : never\n\n// Row shape returned by selectAs: keys are `prefix_column`\ntype SelectAsRow<X> = { [M in Metas<X> as `${M['prefix']}_${M['name']}`]: M['type'] }\n\n// Row shape returned by sql / select: keys are the bare column names\ntype Row<X> = { [M in Metas<X> as M['name']]: M['type'] }\n\nconst makeColumns = <T extends string>(prefix: string ,cols: ReadonlyArray<T>): SchemaColumn<T> =>\n cols.reduce(\n (a, key) => ({ ...a ,[key]: { [sym.SYM_COLUMN]: { name: key ,prefix } } })\n ,{} as SchemaColumn<T>\n )\n\nfunction schema<R extends object>(): TypedSchema<R>\nfunction schema<T extends string>(params: Params<T>): SchemaTable<T>\nfunction schema<T extends string>(params?: Params<T>): SchemaTable<T> | TypedSchema<object> {\n if(params === undefined) return schema as unknown as TypedSchema<object>\n const { table ,columns ,alias } = params\n const resolvedAlias = alias ?? table\n return {\n [sym.SYM_TABLE]: { name: table, alias: resolvedAlias }\n , ...makeColumns(resolvedAlias, columns)\n } as SchemaTable<T>\n}\n\nfunction as<P extends string, N extends string>(col: TypedColumn<P, N, unknown>): `${P}_${N}`\nfunction as(col: { [K in symbol]: Column }): string\nfunction as(col: { [K in symbol]: Column }): string {\n const c = col[sym.SYM_COLUMN] as Column\n return c.prefix + '_' + c.name\n}\n\nfunction alias<T extends string, R, NA extends string>(t: TypedTable<T, string, R>, newAlias: NA): TypedTable<T, NA, R>\nfunction alias<T extends string>(t: SchemaTable<T> ,newAlias: string): SchemaTable<T>\nfunction alias<T extends string>(t: SchemaTable<T> ,newAlias: string): SchemaTable<T> {\n return schema({\n table: t[sym.SYM_TABLE].name\n ,columns: Object.keys(t) as Array<T>\n ,alias: newAlias\n })\n}\n\nexport type { SchemaTable ,SchemaColumn ,Table ,Column ,TypedTable ,TypedColumn ,SelectAsRow ,Row }\nexport { schema ,as ,alias }\n","import { SYM_IDENTIFIER} from './symbol'\n\nconst identifier = (content: string) => ({ [SYM_IDENTIFIER]: true ,content })\n\nexport { identifier }\n","import * as sym from './symbol'\nimport { fragment } from './fragment'\nimport { Column ,SchemaTable ,Table ,TypedTable } from './schema'\nimport { zipLongest } from './list'\nimport { Result ,result } from './result'\nimport { identifier } from './identifier'\n\ntype Pair = [string, any?]\ntype PairTransformer = (pair: Pair) => Array<Pair>\n\nconst transformer = (table: (s: string ,t: Table) => Array<Pair> ,column: (s: string ,c: Column) => Array<Pair>) => ([ss ,bs]: Pair): Array<Pair> => {\n\n if(bs === undefined) return [[ss]]\n\n if(bs === null) return [[ss ,bs]]\n\n if(bs[sym.SYM_TABLE]) return table(ss ,bs[sym.SYM_TABLE] as Table)\n\n if(bs[sym.SYM_COLUMN]) return column(ss ,bs[sym.SYM_COLUMN] as Column)\n\n if(bs[sym.SYM_MULTIPLE_COLUMNS]) return (bs.content as Array<Column>)\n .flatMap((c ,i) => i === 0 ? column(ss ,c) : column(' ,' ,c))\n\n return [[ss ,bs]]\n\n}\n\nconst tableWithAlias = (s: string ,t: Table): Array<Pair> => [\n [s ,identifier(t.name)]\n ,[' ' ,identifier(t.alias)]\n]\n\nconst prefixedColumn = (s: string ,c: Column): Array<Pair> => [\n [s ,identifier(c.prefix)]\n ,['.' ,identifier(c.name)]\n]\n\nconst pure = transformer(\n (s ,t) => [[s ,identifier(t.name)]]\n ,(s ,c) => [[s ,identifier(c.name)]]\n)\n\nconst prefix = transformer(tableWithAlias ,prefixedColumn)\n\nconst alias = transformer(\n tableWithAlias\n ,(s ,c) => [\n ...prefixedColumn(s ,c)\n ,[' as ' ,identifier(`${c.prefix}_${c.name}`)]\n ]\n)\n\nconst dropUndefined = (strings: Array<string> ,binds: Array<any>): [Array<string> ,Array<any>] => {\n const outStrings: Array<string> = []\n const outBinds: Array<any> = []\n let carry = ''\n\n strings.forEach((s ,i) => {\n if(i === strings.length - 1) outStrings.push(carry + s)\n else if(binds[i] === undefined) carry = carry + s\n else { outStrings.push(carry + s) ;outBinds.push(binds[i]) ;carry = '' }\n })\n\n return [outStrings ,outBinds]\n}\n\nconst buildTag = (fn: PairTransformer) => (strings: TemplateStringsArray ,...binds: Array<any>): Result => {\n const [ss ,bs] = dropUndefined(strings as unknown as Array<string> ,binds)\n const pairs = zipLongest(ss ,bs).flatMap(fn)\n const strs = pairs.map(([s]) => s)\n const vals = pairs.slice(0, -1).map(([, v]) => v)\n return result(fragment(strs ,vals))\n}\n\nconst sql = buildTag(pure)\nconst select = buildTag(prefix)\nconst selectAs = buildTag(alias)\n\nconst empty: Result = sql``\n\nconst value = (v: any): any =>\n v && v[sym.SYM_COLUMN] ? identifier((v[sym.SYM_COLUMN] as Column).name) : v\n\nconst insert = <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown> ,...colsVals: Array<{ [K in T]?: any }>): Result => {\n const tableName = table[sym.SYM_TABLE].name\n const columns = Object.keys(colsVals[0]).filter(c => colsVals[0][c as T] !== undefined)\n\n const colStrings = columns.map((_, i) => i === 0 ? ' (' : ' ,')\n const colBinds = columns.map(c => identifier(c))\n\n const [valStrings, valBinds] = colsVals.reduce<[Array<string>, Array<any>]>(\n ([ss ,bs] ,row ,rowIdx) => {\n const rowStrings = columns.map((_, colIdx) =>\n colIdx === 0 ? (rowIdx === 0 ? ') values (' : ') ,(') : ' ,'\n )\n return [[...ss, ...rowStrings], [...bs, ...columns.map(c => value(row[c as T]))]]\n }\n ,[[] ,[]]\n )\n\n return result(fragment(['insert into ', ...colStrings, ...valStrings, ')'], [identifier(tableName), ...colBinds, ...valBinds]))\n}\n\nconst update = <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown> ,colsVals: { [K in T]?: any }): Result => {\n const tableName = table[sym.SYM_TABLE].name\n const entries = Object.entries(colsVals).filter(([, v]) => v !== undefined)\n\n const [strings ,binds] = entries.reduce<[Array<string> ,Array<any>]>(\n ([ss ,bs], [colName, v], i) => [[...ss ,i === 0 ? ' set ' : ' ,' ,' = '] ,[...bs ,identifier(colName) ,value(v)]]\n ,[['update '] ,[identifier(tableName)]]\n )\n\n return result(fragment([...strings, ''], binds))\n}\n\nexport {\n empty\n ,sql\n ,select\n ,select as s\n ,selectAs\n ,selectAs as sa\n ,select as groupBy\n ,select as g\n ,select as having\n ,select as h\n ,select as join\n ,select as j\n ,select as orderBy\n ,select as o\n ,select as where\n ,select as w\n ,insert\n ,update\n}\n","import * as sym from './symbol'\nimport { Value } from './value'\nimport { SchemaTable, Column } from './schema'\n\nconst all = (...tables: Array<SchemaTable<string>>): Value => ({\n [sym.SYM_MULTIPLE_COLUMNS]: true\n ,content: tables.flatMap(t => Object.values(t).map(x => x[sym.SYM_COLUMN]))\n})\n\nconst pick = (...columns: Array<{ [key: symbol]: Column }>): Value => ({\n [sym.SYM_MULTIPLE_COLUMNS]: true\n ,content: columns.map(x => x[sym.SYM_COLUMN])\n})\n\nconst raw = (content: string): Value => ({\n [sym.SYM_RAW]: true\n ,content\n})\n\nexport {\n all\n ,pick\n ,raw\n}\n"],"names":["sym.SYM_RAW","sym.SYM_IDENTIFIER","sym.SYM_COLUMN","sym.SYM_TABLE","alias","sym.SYM_MULTIPLE_COLUMNS"],"mappings":";;AAAA;AACA,MAAM,UAAU,GAAG,MAAM,CAAC,eAAe,CAAC;AAC1C,MAAM,oBAAoB,GAAG,MAAM,CAAC,wBAAwB,CAAC;AAC7D,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC;AAExC;AACA,MAAM,OAAO,GAAG,MAAM,CAAC,YAAY,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,mBAAmB,CAAC;;ACPlD,MAAM,UAAU,G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Symbol('sql-ts/multipleColumns');
4
+ const SYM_TABLE = Symbol('sql-ts/table');
5
+ // for fragment
6
+ const SYM_RAW = Symbol('sql-ts/raw');
7
+ const SYM_IDENTIFIER = Symbol('sql-ts/identifier');
8
+
9
+ const zipLongest = (l1, l2) => {
10
+ const maxLength = Math.max(l1.length, l2.length);
11
+ return Array.from({ length: maxLength }, (_, i) => [l1[i], l2[i]]);
12
+ };
13
+
14
+ const fragment = (strings, binds = []) => {
15
+ if (strings.length !== binds.length + 1)
16
+ throw new Error(`Malformed fragment: ${strings.length} strings for ${binds.length} values`);
17
+ return Object.freeze({ strings, binds });
18
+ };
19
+ const stringfyIdentifierAndRaw = (quote = '') => (s) => {
20
+ const fn = ([strings, binds, merge], [ss, bs]) => {
21
+ if (bs && bs[SYM_RAW]) {
22
+ return [strings, binds, [...merge, ss, bs.content]];
23
+ }
24
+ else if (bs && bs[SYM_IDENTIFIER]) {
25
+ return [strings, binds, [...merge, ss, (quote + bs.content.replaceAll(quote, quote + quote) + quote)]];
26
+ }
27
+ else if (bs !== undefined) {
28
+ return [[...strings, merge.join('') + ss], [...binds, bs], []];
29
+ }
30
+ else {
31
+ return [[...strings, merge.join('') + ss], binds, []];
32
+ }
33
+ };
34
+ const [ns, nb] = zipLongest(s.strings, s.binds).reduce(fn, [[], [], []]);
35
+ return fragment(ns, nb);
36
+ };
37
+
38
+ const toMysql = (s) => {
39
+ const ss = stringfyIdentifierAndRaw('`')(s);
40
+ return { sql: [...ss.strings].join('?'), values: ss.binds };
41
+ };
42
+ const toPostgres = (s) => {
43
+ const ss = stringfyIdentifierAndRaw('"')(s);
44
+ return {
45
+ text: ss.strings[0] + ss.strings.slice(1).map((str, i) => `$${i + 1}${str}`).join(''),
46
+ values: ss.binds
47
+ };
48
+ };
49
+
50
+ const preparedStatementName = (r, n) => ({ ...r, name: n });
51
+ const concat = (right) => (left) => {
52
+ const lastLeft = left.strings[left.strings.length - 1] ?? '';
53
+ const firstRight = right.strings[0] ?? '';
54
+ return result(fragment([...left.strings.slice(0, -1), lastLeft + firstRight, ...right.strings.slice(1)], [...left.binds, ...right.binds]));
55
+ };
56
+ const result = (s) => ({
57
+ ...s,
58
+ append: (x) => concat(x)(s),
59
+ get sql() {
60
+ return toMysql(s).sql;
61
+ },
62
+ get text() {
63
+ return toPostgres(s).text;
64
+ },
65
+ get values() {
66
+ return s.binds.filter((x) => !(x && (x[SYM_RAW] || x[SYM_IDENTIFIER])));
67
+ }
68
+ });
69
+
70
+ const makeColumns = (prefix, cols) => cols.reduce((a, key) => ({ ...a, [key]: { [SYM_COLUMN]: { name: key, prefix } } }), {});
71
+ function schema(params) {
72
+ if (params === undefined)
73
+ return schema;
74
+ const { table, columns, alias } = params;
75
+ const resolvedAlias = alias ?? table;
76
+ return {
77
+ [SYM_TABLE]: { name: table, alias: resolvedAlias },
78
+ ...makeColumns(resolvedAlias, columns)
79
+ };
80
+ }
81
+ function as(col) {
82
+ const c = col[SYM_COLUMN];
83
+ return c.prefix + '_' + c.name;
84
+ }
85
+ function alias$1(t, newAlias) {
86
+ return schema({
87
+ table: t[SYM_TABLE].name,
88
+ columns: Object.keys(t),
89
+ alias: newAlias
90
+ });
91
+ }
92
+
93
+ const identifier = (content) => ({ [SYM_IDENTIFIER]: true, content });
94
+
95
+ const transformer = (table, column) => ([ss, bs]) => {
96
+ if (bs === undefined)
97
+ return [[ss]];
98
+ if (bs === null)
99
+ return [[ss, bs]];
100
+ if (bs[SYM_TABLE])
101
+ return table(ss, bs[SYM_TABLE]);
102
+ if (bs[SYM_COLUMN])
103
+ return column(ss, bs[SYM_COLUMN]);
104
+ if (bs[SYM_MULTIPLE_COLUMNS])
105
+ return bs.content
106
+ .flatMap((c, i) => i === 0 ? column(ss, c) : column(' ,', c));
107
+ return [[ss, bs]];
108
+ };
109
+ const tableWithAlias = (s, t) => [
110
+ [s, identifier(t.name)],
111
+ [' ', identifier(t.alias)]
112
+ ];
113
+ const prefixedColumn = (s, c) => [
114
+ [s, identifier(c.prefix)],
115
+ ['.', identifier(c.name)]
116
+ ];
117
+ const pure = transformer((s, t) => [[s, identifier(t.name)]], (s, c) => [[s, identifier(c.name)]]);
118
+ const prefix = transformer(tableWithAlias, prefixedColumn);
119
+ const alias = transformer(tableWithAlias, (s, c) => [
120
+ ...prefixedColumn(s, c),
121
+ [' as ', identifier(`${c.prefix}_${c.name}`)]
122
+ ]);
123
+ const dropUndefined = (strings, binds) => {
124
+ const outStrings = [];
125
+ const outBinds = [];
126
+ let carry = '';
127
+ strings.forEach((s, i) => {
128
+ if (i === strings.length - 1)
129
+ outStrings.push(carry + s);
130
+ else if (binds[i] === undefined)
131
+ carry = carry + s;
132
+ else {
133
+ outStrings.push(carry + s);
134
+ outBinds.push(binds[i]);
135
+ carry = '';
136
+ }
137
+ });
138
+ return [outStrings, outBinds];
139
+ };
140
+ const buildTag = (fn) => (strings, ...binds) => {
141
+ const [ss, bs] = dropUndefined(strings, binds);
142
+ const pairs = zipLongest(ss, bs).flatMap(fn);
143
+ const strs = pairs.map(([s]) => s);
144
+ const vals = pairs.slice(0, -1).map(([, v]) => v);
145
+ return result(fragment(strs, vals));
146
+ };
147
+ const sql = buildTag(pure);
148
+ const select = buildTag(prefix);
149
+ const selectAs = buildTag(alias);
150
+ const empty = sql ``;
151
+ const value = (v) => v && v[SYM_COLUMN] ? identifier(v[SYM_COLUMN].name) : v;
152
+ const insert = (table, ...colsVals) => {
153
+ const tableName = table[SYM_TABLE].name;
154
+ const columns = Object.keys(colsVals[0]).filter(c => colsVals[0][c] !== undefined);
155
+ const colStrings = columns.map((_, i) => i === 0 ? ' (' : ' ,');
156
+ const colBinds = columns.map(c => identifier(c));
157
+ const [valStrings, valBinds] = colsVals.reduce(([ss, bs], row, rowIdx) => {
158
+ const rowStrings = columns.map((_, colIdx) => colIdx === 0 ? (rowIdx === 0 ? ') values (' : ') ,(') : ' ,');
159
+ return [[...ss, ...rowStrings], [...bs, ...columns.map(c => value(row[c]))]];
160
+ }, [[], []]);
161
+ return result(fragment(['insert into ', ...colStrings, ...valStrings, ')'], [identifier(tableName), ...colBinds, ...valBinds]));
162
+ };
163
+ const update = (table, colsVals) => {
164
+ const tableName = table[SYM_TABLE].name;
165
+ const entries = Object.entries(colsVals).filter(([, v]) => v !== undefined);
166
+ const [strings, binds] = entries.reduce(([ss, bs], [colName, v], i) => [[...ss, i === 0 ? ' set ' : ' ,', ' = '], [...bs, identifier(colName), value(v)]], [['update '], [identifier(tableName)]]);
167
+ return result(fragment([...strings, ''], binds));
168
+ };
169
+
170
+ const all = (...tables) => ({
171
+ [SYM_MULTIPLE_COLUMNS]: true,
172
+ content: tables.flatMap(t => Object.values(t).map(x => x[SYM_COLUMN]))
173
+ });
174
+ const pick = (...columns) => ({
175
+ [SYM_MULTIPLE_COLUMNS]: true,
176
+ content: columns.map(x => x[SYM_COLUMN])
177
+ });
178
+ const raw = (content) => ({
179
+ [SYM_RAW]: true,
180
+ content
181
+ });
182
+
183
+ export { alias$1 as 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 };
184
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../src/symbol.ts","../src/list.ts","../src/fragment.ts","../src/dialect.ts","../src/result.ts","../src/schema.ts","../src/identifier.ts","../src/statement.ts","../src/wildcard.ts"],"sourcesContent":["// for schema\nconst SYM_COLUMN = Symbol('sql-ts/column')\nconst SYM_MULTIPLE_COLUMNS = Symbol('sql-ts/multipleColumns')\nconst SYM_TABLE = Symbol('sql-ts/table')\n\n// for fragment\nconst SYM_RAW = Symbol('sql-ts/raw')\nconst SYM_IDENTIFIER = Symbol('sql-ts/identifier')\n\nexport {\n SYM_COLUMN\n ,SYM_IDENTIFIER\n ,SYM_MULTIPLE_COLUMNS\n ,SYM_RAW\n ,SYM_TABLE\n}\n","const zipLongest = (l1: Array<string>, l2: Array<any>): Array<[string ,any]> => {\n const maxLength = Math.max(l1.length, l2.length)\n return Array.from({ length: maxLength }, (_, i) => [l1[i], l2[i]])\n}\n\nexport { zipLongest }\n","import * as sym from './symbol'\nimport { zipLongest } from './list'\nimport { Result, result } from './result'\n\ntype Fragment = {\n readonly strings: ReadonlyArray<string>\n readonly binds: ReadonlyArray<unknown>\n}\n\nconst fragment = (strings: ReadonlyArray<string> ,binds: ReadonlyArray<unknown> = []): Fragment => {\n\n if(strings.length !== binds.length + 1) \n throw new Error(`Malformed fragment: ${strings.length} strings for ${binds.length} values`)\n\n return Object.freeze({ strings, binds })\n}\n\nconst stringfyIdentifierAndRaw = (quote: string = '') => (s: Fragment): Fragment => {\n\n const fn = ([strings ,binds ,merge]: [Array<string> ,Array<any> ,Array<string>], [ss, bs]: [string, any]): [Array<string> ,Array<any> ,Array<string>] => {\n\n if(bs && bs[sym.SYM_RAW]) {\n return [strings ,binds ,[...merge, ss, bs.content]]\n }\n else if(bs && bs[sym.SYM_IDENTIFIER]) {\n return [strings ,binds ,[...merge, ss, (quote + bs.content.replaceAll(quote, quote + quote) + quote)]]\n }\n else if(bs !== undefined) {\n return [[...strings ,merge.join('') + ss] ,[...binds ,bs] ,[]]\n }\n else {\n return [[...strings ,merge.join('') + ss] ,binds ,[]]\n }\n\n }\n\n const [ns, nb] = zipLongest(s.strings as Array<string> ,s.binds as Array<string>).reduce(fn, [[] ,[] ,[]])\n\n return fragment(ns, nb)\n\n}\n\nexport type { Fragment }\nexport {\n fragment\n ,stringfyIdentifierAndRaw\n}\n","import { Fragment, stringfyIdentifierAndRaw } from './fragment'\n\ntype MysqlResult = { readonly sql: string; readonly values: ReadonlyArray<unknown> }\ntype PostgresResult = { readonly text: string; readonly values: ReadonlyArray<unknown> }\n\nconst toMysql = (s: Fragment): MysqlResult => {\n const ss = stringfyIdentifierAndRaw('`')(s)\n return { sql: [...ss.strings].join('?'), values: ss.binds }\n}\n\nconst toPostgres = (s: Fragment): PostgresResult => {\n const ss = stringfyIdentifierAndRaw('\"')(s)\n return {\n text: ss.strings[0] + ss.strings.slice(1).map((str, i) => `$${i + 1}${str}`).join(''),\n values: ss.binds\n }\n}\n\nexport { toMysql, toPostgres }\nexport type { MysqlResult, PostgresResult }\n","import { toMysql, toPostgres } from './dialect'\nimport { Fragment, fragment } from './fragment'\nimport { SYM_IDENTIFIER, SYM_RAW } from './symbol'\n\ntype Result = {\n append: (s: Fragment) => Result\n name?: string\n sql: string\n text: string\n values: Array<any>\n} & Fragment\n\nconst preparedStatementName = (r: Result ,n: string): Result => ({ ...r ,name: n })\n\nconst concat = (right: Fragment) => (left: Fragment): Result => {\n const lastLeft = left.strings[left.strings.length - 1] ?? ''\n const firstRight = right.strings[0] ?? ''\n return result(fragment(\n [...left.strings.slice(0, -1), lastLeft + firstRight, ...right.strings.slice(1)]\n ,[...left.binds, ...right.binds]\n ))\n}\n\nconst result = (s: Fragment): Result => ({\n ...s,\n append: (x: Fragment) => concat(x)(s)\n ,get sql() {\n return toMysql(s).sql\n }\n ,get text() {\n return toPostgres(s).text\n }\n ,get values() {\n return s.binds.filter((x: any) => !(x && (x[SYM_RAW] || x[SYM_IDENTIFIER])))\n }\n})\n\nexport type { Result }\nexport {\n concat\n ,preparedStatementName\n ,result\n}\n","import * as sym from './symbol'\n\ntype Table = {\n readonly name: string\n readonly alias: string\n}\n\ntype Column = {\n readonly name: string\n readonly prefix: string\n}\n\ntype SchemaColumn<T extends string> = { [K in T]: { [KC in symbol]: Column } }\n\ntype SchemaTable<T extends string> = {\n readonly [KT in symbol]: Table\n} & SchemaColumn<T>\n\ntype Params<T extends string> = {\n readonly table: string\n readonly columns: ReadonlyArray<T>\n readonly alias?: string\n}\n\n// Type-only brands: they never exist at runtime. COL carries the prefix, name and\n// value type of a typed column, ROW the row record of a typed table.\ndeclare const COL: unique symbol\ndeclare const ROW: unique symbol\n\ntype ColumnMeta<P extends string = string, N extends string = string, V = unknown> = {\n readonly prefix: P\n readonly name: N\n readonly type: V\n}\n\ntype TypedColumn<P extends string, N extends string, V> = {\n [KC in symbol]: Column & { readonly [COL]: ColumnMeta<P, N, V> }\n}\n\n// Table built with schema<R>()({...}). Assignable to SchemaTable<T>, so it works\n// everywhere a plain table does.\ntype TypedTable<T extends string, A extends string, R> = {\n readonly [KT in symbol]: Table & { readonly [ROW]: R }\n} & {\n [K in T]: TypedColumn<A, K, K extends keyof R ? R[K] : unknown>\n}\n\ntype TypedParams<T extends string, N extends string, A extends string> = {\n readonly table: N\n readonly columns: ReadonlyArray<T>\n readonly alias?: A\n}\n\ntype TypedSchema<R> = <T extends keyof R & string, N extends string, A extends string = N>(\n params: TypedParams<T, N, A>\n) => TypedTable<T, A, R>\n\n// Metadata of a typed column, or of every column of a typed table; never for untyped input\ntype ColumnMetaOf<C> = C extends { readonly [k: symbol]: { readonly [COL]: infer M } }\n ? M extends ColumnMeta ? M : never\n : never\n\ntype Metas<X> = X extends unknown ? ColumnMetaOf<X> | ColumnMetaOf<X[Exclude<keyof X, symbol>]> : never\n\n// Row shape returned by selectAs: keys are `prefix_column`\ntype SelectAsRow<X> = { [M in Metas<X> as `${M['prefix']}_${M['name']}`]: M['type'] }\n\n// Row shape returned by sql / select: keys are the bare column names\ntype Row<X> = { [M in Metas<X> as M['name']]: M['type'] }\n\nconst makeColumns = <T extends string>(prefix: string ,cols: ReadonlyArray<T>): SchemaColumn<T> =>\n cols.reduce(\n (a, key) => ({ ...a ,[key]: { [sym.SYM_COLUMN]: { name: key ,prefix } } })\n ,{} as SchemaColumn<T>\n )\n\nfunction schema<R extends object>(): TypedSchema<R>\nfunction schema<T extends string>(params: Params<T>): SchemaTable<T>\nfunction schema<T extends string>(params?: Params<T>): SchemaTable<T> | TypedSchema<object> {\n if(params === undefined) return schema as unknown as TypedSchema<object>\n const { table ,columns ,alias } = params\n const resolvedAlias = alias ?? table\n return {\n [sym.SYM_TABLE]: { name: table, alias: resolvedAlias }\n , ...makeColumns(resolvedAlias, columns)\n } as SchemaTable<T>\n}\n\nfunction as<P extends string, N extends string>(col: TypedColumn<P, N, unknown>): `${P}_${N}`\nfunction as(col: { [K in symbol]: Column }): string\nfunction as(col: { [K in symbol]: Column }): string {\n const c = col[sym.SYM_COLUMN] as Column\n return c.prefix + '_' + c.name\n}\n\nfunction alias<T extends string, R, NA extends string>(t: TypedTable<T, string, R>, newAlias: NA): TypedTable<T, NA, R>\nfunction alias<T extends string>(t: SchemaTable<T> ,newAlias: string): SchemaTable<T>\nfunction alias<T extends string>(t: SchemaTable<T> ,newAlias: string): SchemaTable<T> {\n return schema({\n table: t[sym.SYM_TABLE].name\n ,columns: Object.keys(t) as Array<T>\n ,alias: newAlias\n })\n}\n\nexport type { SchemaTable ,SchemaColumn ,Table ,Column ,TypedTable ,TypedColumn ,SelectAsRow ,Row }\nexport { schema ,as ,alias }\n","import { SYM_IDENTIFIER} from './symbol'\n\nconst identifier = (content: string) => ({ [SYM_IDENTIFIER]: true ,content })\n\nexport { identifier }\n","import * as sym from './symbol'\nimport { fragment } from './fragment'\nimport { Column ,SchemaTable ,Table ,TypedTable } from './schema'\nimport { zipLongest } from './list'\nimport { Result ,result } from './result'\nimport { identifier } from './identifier'\n\ntype Pair = [string, any?]\ntype PairTransformer = (pair: Pair) => Array<Pair>\n\nconst transformer = (table: (s: string ,t: Table) => Array<Pair> ,column: (s: string ,c: Column) => Array<Pair>) => ([ss ,bs]: Pair): Array<Pair> => {\n\n if(bs === undefined) return [[ss]]\n\n if(bs === null) return [[ss ,bs]]\n\n if(bs[sym.SYM_TABLE]) return table(ss ,bs[sym.SYM_TABLE] as Table)\n\n if(bs[sym.SYM_COLUMN]) return column(ss ,bs[sym.SYM_COLUMN] as Column)\n\n if(bs[sym.SYM_MULTIPLE_COLUMNS]) return (bs.content as Array<Column>)\n .flatMap((c ,i) => i === 0 ? column(ss ,c) : column(' ,' ,c))\n\n return [[ss ,bs]]\n\n}\n\nconst tableWithAlias = (s: string ,t: Table): Array<Pair> => [\n [s ,identifier(t.name)]\n ,[' ' ,identifier(t.alias)]\n]\n\nconst prefixedColumn = (s: string ,c: Column): Array<Pair> => [\n [s ,identifier(c.prefix)]\n ,['.' ,identifier(c.name)]\n]\n\nconst pure = transformer(\n (s ,t) => [[s ,identifier(t.name)]]\n ,(s ,c) => [[s ,identifier(c.name)]]\n)\n\nconst prefix = transformer(tableWithAlias ,prefixedColumn)\n\nconst alias = transformer(\n tableWithAlias\n ,(s ,c) => [\n ...prefixedColumn(s ,c)\n ,[' as ' ,identifier(`${c.prefix}_${c.name}`)]\n ]\n)\n\nconst dropUndefined = (strings: Array<string> ,binds: Array<any>): [Array<string> ,Array<any>] => {\n const outStrings: Array<string> = []\n const outBinds: Array<any> = []\n let carry = ''\n\n strings.forEach((s ,i) => {\n if(i === strings.length - 1) outStrings.push(carry + s)\n else if(binds[i] === undefined) carry = carry + s\n else { outStrings.push(carry + s) ;outBinds.push(binds[i]) ;carry = '' }\n })\n\n return [outStrings ,outBinds]\n}\n\nconst buildTag = (fn: PairTransformer) => (strings: TemplateStringsArray ,...binds: Array<any>): Result => {\n const [ss ,bs] = dropUndefined(strings as unknown as Array<string> ,binds)\n const pairs = zipLongest(ss ,bs).flatMap(fn)\n const strs = pairs.map(([s]) => s)\n const vals = pairs.slice(0, -1).map(([, v]) => v)\n return result(fragment(strs ,vals))\n}\n\nconst sql = buildTag(pure)\nconst select = buildTag(prefix)\nconst selectAs = buildTag(alias)\n\nconst empty: Result = sql``\n\nconst value = (v: any): any =>\n v && v[sym.SYM_COLUMN] ? identifier((v[sym.SYM_COLUMN] as Column).name) : v\n\nconst insert = <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown> ,...colsVals: Array<{ [K in T]?: any }>): Result => {\n const tableName = table[sym.SYM_TABLE].name\n const columns = Object.keys(colsVals[0]).filter(c => colsVals[0][c as T] !== undefined)\n\n const colStrings = columns.map((_, i) => i === 0 ? ' (' : ' ,')\n const colBinds = columns.map(c => identifier(c))\n\n const [valStrings, valBinds] = colsVals.reduce<[Array<string>, Array<any>]>(\n ([ss ,bs] ,row ,rowIdx) => {\n const rowStrings = columns.map((_, colIdx) =>\n colIdx === 0 ? (rowIdx === 0 ? ') values (' : ') ,(') : ' ,'\n )\n return [[...ss, ...rowStrings], [...bs, ...columns.map(c => value(row[c as T]))]]\n }\n ,[[] ,[]]\n )\n\n return result(fragment(['insert into ', ...colStrings, ...valStrings, ')'], [identifier(tableName), ...colBinds, ...valBinds]))\n}\n\nconst update = <T extends string>(table: SchemaTable<T> | TypedTable<T, string, unknown> ,colsVals: { [K in T]?: any }): Result => {\n const tableName = table[sym.SYM_TABLE].name\n const entries = Object.entries(colsVals).filter(([, v]) => v !== undefined)\n\n const [strings ,binds] = entries.reduce<[Array<string> ,Array<any>]>(\n ([ss ,bs], [colName, v], i) => [[...ss ,i === 0 ? ' set ' : ' ,' ,' = '] ,[...bs ,identifier(colName) ,value(v)]]\n ,[['update '] ,[identifier(tableName)]]\n )\n\n return result(fragment([...strings, ''], binds))\n}\n\nexport {\n empty\n ,sql\n ,select\n ,select as s\n ,selectAs\n ,selectAs as sa\n ,select as groupBy\n ,select as g\n ,select as having\n ,select as h\n ,select as join\n ,select as j\n ,select as orderBy\n ,select as o\n ,select as where\n ,select as w\n ,insert\n ,update\n}\n","import * as sym from './symbol'\nimport { Value } from './value'\nimport { SchemaTable, Column } from './schema'\n\nconst all = (...tables: Array<SchemaTable<string>>): Value => ({\n [sym.SYM_MULTIPLE_COLUMNS]: true\n ,content: tables.flatMap(t => Object.values(t).map(x => x[sym.SYM_COLUMN]))\n})\n\nconst pick = (...columns: Array<{ [key: symbol]: Column }>): Value => ({\n [sym.SYM_MULTIPLE_COLUMNS]: true\n ,content: columns.map(x => x[sym.SYM_COLUMN])\n})\n\nconst raw = (content: string): Value => ({\n [sym.SYM_RAW]: true\n ,content\n})\n\nexport {\n all\n ,pick\n ,raw\n}\n"],"names":["sym.SYM_RAW","sym.SYM_IDENTIFIER","sym.SYM_COLUMN","sym.SYM_T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EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAACH,UAAc,CAAC;AAC7C,CAAA;AAED,MAAM,GAAG,GAAG,CAAC,OAAe,MAAa;AACvC,IAAA,CAACF,OAAW,GAAG,IAAI;IAClB;AACF,CAAA;;;;"}
package/package.json CHANGED
@@ -1,32 +1,52 @@
1
1
  {
2
2
  "name": "@vanit-co/sql-ts",
3
- "version": "1.0.3",
3
+ "version": "1.1.0",
4
4
  "description": "A TypeScript SQL query builder using tagged template literals. Write plain SQL with safe, automatic parameter binding and properly quoted identifiers. No DSL to learn, no magic, no ORM.",
5
5
  "type": "commonjs",
6
6
  "main": "./dist/index.js",
7
+ "module": "./dist/index.mjs",
7
8
  "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.mts",
13
+ "default": "./dist/index.mjs"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "./package.json": "./package.json"
21
+ },
22
+ "sideEffects": false,
8
23
  "files": [
9
- "./dist/index.js",
10
- "./dist/index.d.ts",
24
+ "dist/index.js",
25
+ "dist/index.js.map",
26
+ "dist/index.mjs",
27
+ "dist/index.mjs.map",
28
+ "dist/index.d.ts",
29
+ "dist/index.d.mts",
11
30
  "README.md",
12
- "LICENSE"
31
+ "LICENSE",
32
+ "CHANGELOG.md"
13
33
  ],
14
34
  "scripts": {
15
- "test": "vitest run",
16
- "build": "npx rollup --config --bundleConfigAsCjs"
35
+ "test": "vitest run --typecheck --typecheck.tsconfig=tsconfig.test.json",
36
+ "build": "npx rollup --config --bundleConfigAsCjs",
37
+ "lint": "publint && attw --pack .",
38
+ "prepublishOnly": "npm test && npm run build"
17
39
  },
18
40
  "devDependencies": {
41
+ "@arethetypeswrong/cli": "^0.18.5",
19
42
  "@rollup/plugin-typescript": "^12.3.0",
20
- "@types/ramda": "^0.31.1",
43
+ "publint": "^0.3.25",
21
44
  "rollup": "^4.60.0",
22
45
  "rollup-plugin-dts": "^6.4.1",
23
46
  "tslib": "^2.8.1",
24
47
  "typescript": "^5.9.0",
25
48
  "vitest": "^4.1.0"
26
49
  },
27
- "dependencies": {
28
- "ramda": "^0.32.0"
29
- },
30
50
  "repository": {
31
51
  "type": "git",
32
52
  "url": "git+https://github.com/vanit-co/sql-ts.git"
@@ -37,12 +57,31 @@
37
57
  "postgres",
38
58
  "pg",
39
59
  "mysql",
40
- "mysql2"
60
+ "mysql2",
61
+ "sqlite",
62
+ "better-sqlite3",
63
+ "tagged-template",
64
+ "template-literal",
65
+ "sql-template",
66
+ "sql-tag",
67
+ "query-builder",
68
+ "typescript",
69
+ "functional",
70
+ "fp",
71
+ "monoid",
72
+ "composable",
73
+ "node-postgres",
74
+ "no-orm",
75
+ "effect",
76
+ "ramda"
41
77
  ],
42
78
  "author": "Geovanny Silva",
43
79
  "license": "MIT",
44
80
  "bugs": {
45
81
  "url": "https://github.com/vanit-co/sql-ts/issues"
46
82
  },
47
- "homepage": "https://github.com/vanit-co/sql-ts#readme"
83
+ "homepage": "https://github.com/vanit-co/sql-ts#readme",
84
+ "engines": {
85
+ "node": ">=18"
86
+ }
48
87
  }