@20baht/table-query 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +164 -2
- package/dist/elysia.d.ts +84 -0
- package/dist/elysia.js +143 -0
- package/dist/fragment.d.ts +26 -0
- package/dist/fragment.js +25 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/parse.d.ts +53 -0
- package/dist/parse.js +111 -0
- package/dist/query-rows.d.ts +16 -0
- package/dist/query-rows.js +91 -0
- package/dist/table-query.d.ts +82 -0
- package/dist/table-query.js +125 -0
- package/package.json +71 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nattapong Promthong
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,165 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @20baht/table-query
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The server half of `<baht-table>` and `<baht-reference-dialog>`. Those elements send a query (a term, a
|
|
4
|
+
search box, a term per column, a filter, a sort, a page); this package reads it, refuses what it should not
|
|
5
|
+
trust, and writes it as **Postgres** `WHERE` / `ORDER BY` / `LIMIT`. No dependencies. It writes through a
|
|
6
|
+
SQL tag you hand it, so it works with drizzle-orm's `sql` as it is, or with its own `fragment`.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
bun add @20baht/table-query
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## With drizzle
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { and, sql } from 'drizzle-orm';
|
|
16
|
+
import { parseTableQuery, tableQuery } from '@20baht/table-query';
|
|
17
|
+
|
|
18
|
+
// each cell is an expression that yields text: cast what is not
|
|
19
|
+
const servers = tableQuery(sql, {
|
|
20
|
+
key: sql`${server.id}`,
|
|
21
|
+
columns: {
|
|
22
|
+
number: sql`${server.number}`,
|
|
23
|
+
name: sql`${server.name}`,
|
|
24
|
+
size: sql`${server.sizeGb}::text`,
|
|
25
|
+
},
|
|
26
|
+
term: [sql`${server.name}`, sql`${server.number}`], // what a typed term is looked for in
|
|
27
|
+
sortAs: { number: sql`${server.seq}` }, // sort SRV10 after SRV9
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
app.post('/servers/search', async ({ body, status }) => {
|
|
31
|
+
const parsed = parseTableQuery(body); // shape and size: is this a query at all?
|
|
32
|
+
if (!parsed.ok) return status(400, parsed.message);
|
|
33
|
+
const unknown = servers.unknownColumn(parsed.query); // only columns of the shape
|
|
34
|
+
if (unknown) return status(400, `unknown column ${unknown}`);
|
|
35
|
+
|
|
36
|
+
const where = and(tenantIs(caller), servers.where(parsed.query)); // your own conditions beside it
|
|
37
|
+
const { limit, offset } = servers.page(parsed.query);
|
|
38
|
+
const rows = await db.select().from(server).where(where)
|
|
39
|
+
.orderBy(...servers.orderBy(parsed.query)).limit(limit).offset(offset);
|
|
40
|
+
const total = await db.$count(server, where);
|
|
41
|
+
return { rows, total };
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## From a table declared once: `tableQueryOf`
|
|
46
|
+
|
|
47
|
+
`defineTable` (`@20baht/engine`) declares a table from the form its records are filled in with: the
|
|
48
|
+
columns `<baht-table>` shows and filters by. `tableQueryOf` is `tableQuery` for such a table: the
|
|
49
|
+
shape must give SQL for **every** column of the table and for no other, and the compiler says which
|
|
50
|
+
one is missing.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { defineTable } from '@20baht/engine';
|
|
54
|
+
import { tableQueryOf } from '@20baht/table-query';
|
|
55
|
+
|
|
56
|
+
export const ordersTable = defineTable(orderForm, {
|
|
57
|
+
pick: ['number', 'customer', 'qty', 'owner', 'created_at'],
|
|
58
|
+
extra: { number: { label: 'No.' }, created_at: { label: 'Created', type: 'date' } },
|
|
59
|
+
walk: { owner: usersTable }, // a reference column: its record's columns, as `owner.name`
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const orders = tableQueryOf(sql, ordersTable, {
|
|
63
|
+
key: sql`${order.id}`,
|
|
64
|
+
columns: {
|
|
65
|
+
number: sql`${order.number}`,
|
|
66
|
+
customer: sql`${order.customer}`,
|
|
67
|
+
qty: sql`${order.qty}`, // no cast: each cell is cast to text for you
|
|
68
|
+
owner: sql`${order.ownerId}`,
|
|
69
|
+
'owner.name': sql`${user.name}`,
|
|
70
|
+
created_at: sql`to_char(${order.createdAt}, 'YYYY-MM-DD')`,
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The web app hands `ordersTable.columns` to `<baht-table>`, and `TableRow<typeof ordersTable>` is a
|
|
76
|
+
row on both sides. A column added to the table and forgotten here does not compile (and throws when
|
|
77
|
+
`tableQueryOf` is called, for a caller the compiler does not see). Cast a date to the text a date
|
|
78
|
+
filter sends; a timestamp's own text is not a day. `@20baht/engine` is not a dependency: the table
|
|
79
|
+
is read structurally.
|
|
80
|
+
|
|
81
|
+
## The route, typed and documented: `@20baht/table-query/elysia`
|
|
82
|
+
|
|
83
|
+
`tableRoute(table, limits?)` is a search route's options for a table declared with `defineTable`:
|
|
84
|
+
the body is a table query (parsed and sized by `parseTableQuery`, and held to the table's own
|
|
85
|
+
columns), the answer a page of its rows. `elysia` (>=1.4) is an optional peer, imported by this
|
|
86
|
+
entry only.
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { tableRoute } from '@20baht/table-query/elysia';
|
|
90
|
+
|
|
91
|
+
new Elysia().post(
|
|
92
|
+
'/orders/search',
|
|
93
|
+
async ({ body }) => {
|
|
94
|
+
const where = and(tenantIs(caller), orders.where(body));
|
|
95
|
+
const { limit, offset } = orders.page(body);
|
|
96
|
+
const rows = await db.select(/* … */).where(where).orderBy(...orders.orderBy(body)).limit(limit).offset(offset);
|
|
97
|
+
return { rows, total: await db.$count(order, where) };
|
|
98
|
+
},
|
|
99
|
+
tableRoute(ordersTable),
|
|
100
|
+
);
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
- A body that is not a query, or that names a column the table does not have, answers
|
|
104
|
+
`400 { message }` and never reaches the handler: no `parseTableQuery` / `unknownColumn` to call.
|
|
105
|
+
- `body` names only the table's columns (`TableQueryOf`), and the handler must return
|
|
106
|
+
`{ rows, total }` with rows of the table (`TableRow`); an Eden client is typed by both.
|
|
107
|
+
- An OpenAPI document (`@elysiajs/openapi`) describes the query (which columns, which
|
|
108
|
+
comparisons) and the page, so `@20baht/elysia-openapi-mcp` gives an agent a tool that searches,
|
|
109
|
+
filters and sorts the table.
|
|
110
|
+
|
|
111
|
+
`tableBody(table)` and `tablePage(table)` are the two halves, for a route that declares its own
|
|
112
|
+
responses. Spread `tableRoute` beside other options: `{ ...tableRoute(table), detail }`.
|
|
113
|
+
|
|
114
|
+
## No database yet: `queryRows`
|
|
115
|
+
|
|
116
|
+
`queryRows(rows, query)` answers the same query over rows held in memory, `{ rows, total }`, with
|
|
117
|
+
the meaning of the SQL below (`contains` ignores case, `gt` / `lt` read numbers as numbers, an
|
|
118
|
+
empty cell never passes them). For a list too small to need a database, a test, or the first
|
|
119
|
+
version of a screen: swap it for `tableQueryOf` when the rows move to Postgres.
|
|
120
|
+
|
|
121
|
+
## Without a query builder
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { fragment, tableQuery, toQuery } from '@20baht/table-query';
|
|
125
|
+
|
|
126
|
+
const servers = tableQuery(fragment, { key: fragment`id`, columns: { name: fragment`name` } });
|
|
127
|
+
const where = servers.where(query); // undefined when the query narrows nothing
|
|
128
|
+
const { text, params } = toQuery(fragment`select * from server where ${where ?? fragment.raw('true')}`);
|
|
129
|
+
await client.query(text, params); // "select * from server where name ilike $1", ['%core%']
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`toQuery(part, first)` numbers placeholders from `first`, for a piece that follows parameters of your own.
|
|
133
|
+
|
|
134
|
+
## What a query means
|
|
135
|
+
|
|
136
|
+
The same query answered in the browser is `pageOfRows` / `matchesFilter` of `@20baht/ui`; the SQL follows
|
|
137
|
+
them:
|
|
138
|
+
|
|
139
|
+
| Part | SQL |
|
|
140
|
+
| --- | --- |
|
|
141
|
+
| `term` | `ilike '%term%'` in any of `shape.term` (default: every column) |
|
|
142
|
+
| `search`, `columns` | `ilike '%term%'` in that column, all of them; a blank term narrows nothing |
|
|
143
|
+
| `contains` | `ilike '%value%'` |
|
|
144
|
+
| `eq` / `ne` | exact text, an empty cell reading as `''` |
|
|
145
|
+
| `gt` / `lt` | a number compares as a number (a cell that is not a number never passes); anything else as text, an empty cell never passing |
|
|
146
|
+
| `empty` / `not_empty` | null or `''` |
|
|
147
|
+
| `filter.match` | `all` joins with `and`, `any` with `or` |
|
|
148
|
+
| `sort` | the column (or its `sortAs`), `nulls last`, then the key so pages never shuffle |
|
|
149
|
+
| `page`, `pageSize` | `limit` / `offset`; 20 a page when unset |
|
|
150
|
+
|
|
151
|
+
`%` and `_` in a term are literal. One difference from the browser: a `gt` / `lt` against a number, on a
|
|
152
|
+
cell that is not one, is false here; the browser falls back to comparing text.
|
|
153
|
+
|
|
154
|
+
## What it refuses, and how
|
|
155
|
+
|
|
156
|
+
- **Nothing a client sends becomes SQL text.** Terms and values are parameters. A column key only selects
|
|
157
|
+
one of the shape's own expressions; a direction is `asc` or `desc`.
|
|
158
|
+
- **`parseTableQuery(body, limits?)`** answers `{ ok: true, query }` or `{ ok: false, message }`: wrong
|
|
159
|
+
shapes, an unknown comparison, a `pageSize` over `maxPageSize` (100), more than `maxConditions` (20)
|
|
160
|
+
conditions, a term longer than `maxTermLength` (200). Keys it does not know are dropped.
|
|
161
|
+
- **`unknownColumn(query)`** names the first column the shape does not have. Refuse the request: a column
|
|
162
|
+
that is not in the shape writes no SQL either way, but the caller should hear it.
|
|
163
|
+
- **Authorization is yours.** Which rows a caller may see is a condition you `and` beside `where()`.
|
|
164
|
+
|
|
165
|
+
Not here: keyset (cursor) pagination, other databases, and running the SQL query.
|
package/dist/elysia.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { type FilterOp, type ParseLimits } from './parse.js';
|
|
2
|
+
import { type TableLike } from './table-query.js';
|
|
3
|
+
/** A JSON Schema, as plain data. */
|
|
4
|
+
type JsonSchema = Record<string, unknown>;
|
|
5
|
+
/** A Standard Schema (v1) that also describes itself as JSON Schema: what Elysia takes as a schema. */
|
|
6
|
+
export interface TableSchema<Data> {
|
|
7
|
+
readonly '~standard': {
|
|
8
|
+
readonly version: 1;
|
|
9
|
+
readonly vendor: '20baht';
|
|
10
|
+
readonly validate: (value: unknown) => {
|
|
11
|
+
value: Data;
|
|
12
|
+
};
|
|
13
|
+
readonly types?: {
|
|
14
|
+
readonly input: Data;
|
|
15
|
+
readonly output: Data;
|
|
16
|
+
};
|
|
17
|
+
readonly jsonSchema: {
|
|
18
|
+
readonly input: (options?: {
|
|
19
|
+
readonly target?: string;
|
|
20
|
+
}) => JsonSchema;
|
|
21
|
+
readonly output: (options?: {
|
|
22
|
+
readonly target?: string;
|
|
23
|
+
}) => JsonSchema;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** A `TableQuery` that names only columns `Key`: what a handler behind `tableBody` gets. */
|
|
28
|
+
export interface TableQueryOf<Key extends string> {
|
|
29
|
+
term?: string;
|
|
30
|
+
search?: {
|
|
31
|
+
field: Key;
|
|
32
|
+
term: string;
|
|
33
|
+
};
|
|
34
|
+
columns?: Partial<Record<Key, string>>;
|
|
35
|
+
filter?: {
|
|
36
|
+
match: 'all' | 'any';
|
|
37
|
+
conditions: {
|
|
38
|
+
field: Key;
|
|
39
|
+
op: FilterOp;
|
|
40
|
+
value: string;
|
|
41
|
+
}[];
|
|
42
|
+
};
|
|
43
|
+
sort?: {
|
|
44
|
+
key: Key;
|
|
45
|
+
dir: 'asc' | 'desc';
|
|
46
|
+
};
|
|
47
|
+
page?: number;
|
|
48
|
+
pageSize?: number;
|
|
49
|
+
}
|
|
50
|
+
/** One page of a table: its rows, and how many matched on every page. */
|
|
51
|
+
export interface TablePage<Row> {
|
|
52
|
+
rows: Row[];
|
|
53
|
+
total: number;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A table query as the route's `body`: parsed and sized by `parseTableQuery` (its `limits`), and
|
|
57
|
+
* held to the table's own columns. A body it refuses answers `400 { message }` before the
|
|
58
|
+
* handler; the handler's `body` names only columns of the table (`TableQueryOf`).
|
|
59
|
+
*/
|
|
60
|
+
export declare function tableBody<Key extends string>(table: TableLike<Key>, limits?: ParseLimits): TableSchema<TableQueryOf<Key>>;
|
|
61
|
+
/**
|
|
62
|
+
* The page a table's search answers, `{ rows, total }`, as a response schema: it types what the
|
|
63
|
+
* handler must return (rows of the table) and describes it in an OpenAPI document. It checks
|
|
64
|
+
* nothing: the rows are the server's own.
|
|
65
|
+
*/
|
|
66
|
+
export declare function tablePage<Key extends string, Row>(table: TableLike<Key, Row>): TableSchema<TablePage<Row>>;
|
|
67
|
+
/**
|
|
68
|
+
* A table's search route, as the route's options: `tableBody` for the query, `tablePage` for the
|
|
69
|
+
* answer, and the `400 { message }` of a refused query.
|
|
70
|
+
*
|
|
71
|
+
* .post('/orders/search', ({ body }) => search(body), tableRoute(ordersTable))
|
|
72
|
+
*
|
|
73
|
+
* Spread it beside other options (`{ ...tableRoute(table), detail: { summary } }`).
|
|
74
|
+
*/
|
|
75
|
+
export declare function tableRoute<Key extends string, Row>(table: TableLike<Key, Row>, limits?: ParseLimits): {
|
|
76
|
+
body: TableSchema<TableQueryOf<Key>>;
|
|
77
|
+
response: {
|
|
78
|
+
200: TableSchema<TablePage<Row>>;
|
|
79
|
+
400: TableSchema<{
|
|
80
|
+
message: string;
|
|
81
|
+
}>;
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
export {};
|
package/dist/elysia.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { status } from 'elysia';
|
|
2
|
+
import { parseTableQuery } from './parse.js';
|
|
3
|
+
import { keysOf } from './table-query.js';
|
|
4
|
+
const OPS = ['contains', 'eq', 'ne', 'gt', 'lt', 'empty', 'not_empty'];
|
|
5
|
+
const PATH_SEP = ' › ';
|
|
6
|
+
const schemaOf = (validate, describe) => ({
|
|
7
|
+
'~standard': {
|
|
8
|
+
version: 1,
|
|
9
|
+
vendor: '20baht',
|
|
10
|
+
validate,
|
|
11
|
+
jsonSchema: { input: describe, output: describe },
|
|
12
|
+
},
|
|
13
|
+
});
|
|
14
|
+
function querySchema(keys, limits) {
|
|
15
|
+
const column = { type: 'string', enum: keys };
|
|
16
|
+
return {
|
|
17
|
+
type: 'object',
|
|
18
|
+
title: 'A query of the table',
|
|
19
|
+
properties: {
|
|
20
|
+
term: { type: 'string', description: 'Text to look for in any column' },
|
|
21
|
+
search: {
|
|
22
|
+
type: 'object',
|
|
23
|
+
description: 'Text to look for in one column',
|
|
24
|
+
properties: { field: column, term: { type: 'string' } },
|
|
25
|
+
required: ['field', 'term'],
|
|
26
|
+
},
|
|
27
|
+
columns: {
|
|
28
|
+
type: 'object',
|
|
29
|
+
description: 'Text to look for per column: every one must be found',
|
|
30
|
+
properties: Object.fromEntries(keys.map((key) => [key, { type: 'string' }])),
|
|
31
|
+
},
|
|
32
|
+
filter: {
|
|
33
|
+
type: 'object',
|
|
34
|
+
description: 'Conditions on columns: all of them, or any of them',
|
|
35
|
+
properties: {
|
|
36
|
+
match: { type: 'string', enum: ['all', 'any'] },
|
|
37
|
+
conditions: {
|
|
38
|
+
type: 'array',
|
|
39
|
+
maxItems: limits.maxConditions ?? 20,
|
|
40
|
+
items: {
|
|
41
|
+
type: 'object',
|
|
42
|
+
properties: {
|
|
43
|
+
field: column,
|
|
44
|
+
op: {
|
|
45
|
+
type: 'string',
|
|
46
|
+
enum: OPS,
|
|
47
|
+
description: 'contains ignores case; eq and ne are exact; gt and lt compare numbers as numbers; empty and not_empty take no value',
|
|
48
|
+
},
|
|
49
|
+
value: { type: 'string' },
|
|
50
|
+
},
|
|
51
|
+
required: ['field', 'op'],
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
required: ['match', 'conditions'],
|
|
56
|
+
},
|
|
57
|
+
sort: {
|
|
58
|
+
type: 'object',
|
|
59
|
+
properties: { key: column, dir: { type: 'string', enum: ['asc', 'desc'] } },
|
|
60
|
+
required: ['key', 'dir'],
|
|
61
|
+
},
|
|
62
|
+
page: { type: 'integer', minimum: 1, description: 'The page, from 1' },
|
|
63
|
+
pageSize: {
|
|
64
|
+
type: 'integer',
|
|
65
|
+
minimum: 1,
|
|
66
|
+
maximum: limits.maxPageSize ?? 100,
|
|
67
|
+
description: 'Rows a page: 20 when left out',
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function cellSchema(column) {
|
|
73
|
+
if (column.type === 'number')
|
|
74
|
+
return { type: ['number', 'null'] };
|
|
75
|
+
const keys = column.options?.map((option) => option.key);
|
|
76
|
+
if (column.type !== 'choice' || keys === undefined)
|
|
77
|
+
return { type: ['string', 'null'] };
|
|
78
|
+
return keys.length === 2 && keys.includes('true') && keys.includes('false')
|
|
79
|
+
? { type: 'boolean' }
|
|
80
|
+
: { type: ['string', 'null'], enum: [...keys, null] };
|
|
81
|
+
}
|
|
82
|
+
function rowProperties(columns, prefix = '', labels = '') {
|
|
83
|
+
const properties = {};
|
|
84
|
+
for (const [key, column] of Object.entries(columns)) {
|
|
85
|
+
const path = `${prefix}${key}`;
|
|
86
|
+
const title = `${labels}${column.label ?? key}`;
|
|
87
|
+
if (!column.group)
|
|
88
|
+
properties[path] = { ...cellSchema(column), title };
|
|
89
|
+
if (column.fields) {
|
|
90
|
+
Object.assign(properties, rowProperties(column.fields, `${path}.`, `${title}${PATH_SEP}`));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return properties;
|
|
94
|
+
}
|
|
95
|
+
export function tableBody(table, limits = {}) {
|
|
96
|
+
const keys = keysOf(table.columns);
|
|
97
|
+
const known = new Set(keys);
|
|
98
|
+
const named = (query) => [
|
|
99
|
+
...(query.search ? [query.search.field] : []),
|
|
100
|
+
...Object.keys(query.columns ?? {}),
|
|
101
|
+
...(query.filter?.conditions ?? []).map((condition) => condition.field),
|
|
102
|
+
...(query.sort ? [query.sort.key] : []),
|
|
103
|
+
];
|
|
104
|
+
return schemaOf((value) => {
|
|
105
|
+
const parsed = parseTableQuery(value, limits);
|
|
106
|
+
if (!parsed.ok)
|
|
107
|
+
throw status(400, { message: parsed.message });
|
|
108
|
+
const unknown = named(parsed.query).find((key) => !known.has(key));
|
|
109
|
+
if (unknown !== undefined) {
|
|
110
|
+
throw status(400, { message: `unknown column ${JSON.stringify(unknown)}` });
|
|
111
|
+
}
|
|
112
|
+
return { value: parsed.query };
|
|
113
|
+
}, () => querySchema(keys, limits));
|
|
114
|
+
}
|
|
115
|
+
export function tablePage(table) {
|
|
116
|
+
return schemaOf((value) => ({ value: value }), () => ({
|
|
117
|
+
type: 'object',
|
|
118
|
+
title: 'A page of the table',
|
|
119
|
+
properties: {
|
|
120
|
+
rows: {
|
|
121
|
+
type: 'array',
|
|
122
|
+
items: { type: 'object', properties: rowProperties(table.columns) },
|
|
123
|
+
},
|
|
124
|
+
total: { type: 'integer', description: 'Rows matching the query, on every page' },
|
|
125
|
+
},
|
|
126
|
+
required: ['rows', 'total'],
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
129
|
+
const REFUSED = {
|
|
130
|
+
type: 'object',
|
|
131
|
+
title: 'The query was refused',
|
|
132
|
+
properties: { message: { type: 'string' } },
|
|
133
|
+
required: ['message'],
|
|
134
|
+
};
|
|
135
|
+
export function tableRoute(table, limits = {}) {
|
|
136
|
+
return {
|
|
137
|
+
body: tableBody(table, limits),
|
|
138
|
+
response: {
|
|
139
|
+
200: tablePage(table),
|
|
140
|
+
400: schemaOf((value) => ({ value: value }), () => REFUSED),
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SQL tag a query is written with: a template tag whose interpolated values are parameters,
|
|
3
|
+
* except values that are themselves fragments, which are spliced in; and `raw` for trusted text.
|
|
4
|
+
* drizzle-orm's `sql` is one. `fragment` below is another, for a host with no query builder.
|
|
5
|
+
*/
|
|
6
|
+
export interface SqlTag<S> {
|
|
7
|
+
(strings: TemplateStringsArray, ...values: unknown[]): S;
|
|
8
|
+
raw(text: string): S;
|
|
9
|
+
}
|
|
10
|
+
/** A piece of SQL with its parameters still apart from the text. */
|
|
11
|
+
export declare class Fragment {
|
|
12
|
+
readonly strings: readonly string[];
|
|
13
|
+
readonly values: readonly unknown[];
|
|
14
|
+
constructor(strings: readonly string[], values: readonly unknown[]);
|
|
15
|
+
}
|
|
16
|
+
/** The package's own SQL tag: `fragment\`name ilike ${term}\``, then `toQuery`. */
|
|
17
|
+
export declare const fragment: SqlTag<Fragment>;
|
|
18
|
+
/**
|
|
19
|
+
* A fragment as text with `$1`, `$2`… and the parameters in that order, for a driver that takes
|
|
20
|
+
* them apart (`pg`, `postgres`, Bun's `sql.unsafe`). `first` is the number of the first
|
|
21
|
+
* placeholder, for a fragment that follows parameters of your own.
|
|
22
|
+
*/
|
|
23
|
+
export declare function toQuery(part: Fragment, first?: number): {
|
|
24
|
+
text: string;
|
|
25
|
+
params: unknown[];
|
|
26
|
+
};
|
package/dist/fragment.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export class Fragment {
|
|
2
|
+
constructor(strings, values) {
|
|
3
|
+
this.strings = strings;
|
|
4
|
+
this.values = values;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
const tag = (strings, ...values) => new Fragment([...strings], values);
|
|
8
|
+
export const fragment = Object.assign(tag, {
|
|
9
|
+
raw: (text) => new Fragment([text], []),
|
|
10
|
+
});
|
|
11
|
+
export function toQuery(part, first = 1) {
|
|
12
|
+
const params = [];
|
|
13
|
+
const write = (piece) => piece.strings
|
|
14
|
+
.map((text, i) => {
|
|
15
|
+
if (i >= piece.values.length)
|
|
16
|
+
return text;
|
|
17
|
+
const value = piece.values[i];
|
|
18
|
+
if (value instanceof Fragment)
|
|
19
|
+
return text + write(value);
|
|
20
|
+
params.push(value);
|
|
21
|
+
return `${text}$${String(first + params.length - 1)}`;
|
|
22
|
+
})
|
|
23
|
+
.join('');
|
|
24
|
+
return { text: write(part), params };
|
|
25
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { Fragment, fragment, toQuery, type SqlTag } from './fragment.js';
|
|
2
|
+
export { parseTableQuery, type FilterCondition, type FilterOp, type ParseLimits, type Parsed, type TableQuery, } from './parse.js';
|
|
3
|
+
export { tableQuery, tableQueryOf, type TableLike, type TableShape, type TableShapeOf, type TableSql, } from './table-query.js';
|
|
4
|
+
export { queryRows, type QueryRowsOptions } from './query-rows.js';
|
package/dist/index.js
ADDED
package/dist/parse.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** How a filter condition compares: `<baht-filter-builder>`'s seven. */
|
|
2
|
+
export type FilterOp = 'contains' | 'eq' | 'ne' | 'gt' | 'lt' | 'empty' | 'not_empty';
|
|
3
|
+
export interface FilterCondition {
|
|
4
|
+
field: string;
|
|
5
|
+
op: FilterOp;
|
|
6
|
+
value: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* What a table asks its server for. A `ReferenceQuery` of `@20baht/engine` is one; `term` is what
|
|
10
|
+
* was typed into a reference field for its suggestions.
|
|
11
|
+
*/
|
|
12
|
+
export interface TableQuery {
|
|
13
|
+
term?: string;
|
|
14
|
+
/** The box above the table: a term in one column. */
|
|
15
|
+
search?: {
|
|
16
|
+
field: string;
|
|
17
|
+
term: string;
|
|
18
|
+
};
|
|
19
|
+
/** The search row under the headers: column key to term. */
|
|
20
|
+
columns?: Record<string, string>;
|
|
21
|
+
filter?: {
|
|
22
|
+
match: 'all' | 'any';
|
|
23
|
+
conditions: FilterCondition[];
|
|
24
|
+
};
|
|
25
|
+
sort?: {
|
|
26
|
+
key: string;
|
|
27
|
+
dir: 'asc' | 'desc';
|
|
28
|
+
};
|
|
29
|
+
/** 1-based. */
|
|
30
|
+
page?: number;
|
|
31
|
+
pageSize?: number;
|
|
32
|
+
}
|
|
33
|
+
export interface ParseLimits {
|
|
34
|
+
/** Largest `pageSize` a client may ask for. Default 100. */
|
|
35
|
+
maxPageSize?: number;
|
|
36
|
+
/** Most filter conditions. Default 20. */
|
|
37
|
+
maxConditions?: number;
|
|
38
|
+
/** Longest term or filter value, in characters. Default 200. */
|
|
39
|
+
maxTermLength?: number;
|
|
40
|
+
}
|
|
41
|
+
export type Parsed = {
|
|
42
|
+
ok: true;
|
|
43
|
+
query: TableQuery;
|
|
44
|
+
} | {
|
|
45
|
+
ok: false;
|
|
46
|
+
message: string;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* A request body as a `TableQuery`, or why it is not one. It checks shape and size only (a
|
|
50
|
+
* column the table does not have is `unknownColumn`'s to find, against the shape); keys it does
|
|
51
|
+
* not know are dropped.
|
|
52
|
+
*/
|
|
53
|
+
export declare function parseTableQuery(input: unknown, limits?: ParseLimits): Parsed;
|
package/dist/parse.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
const OPS = new Set([
|
|
2
|
+
'contains',
|
|
3
|
+
'eq',
|
|
4
|
+
'ne',
|
|
5
|
+
'gt',
|
|
6
|
+
'lt',
|
|
7
|
+
'empty',
|
|
8
|
+
'not_empty',
|
|
9
|
+
]);
|
|
10
|
+
const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
11
|
+
class Refused extends Error {
|
|
12
|
+
}
|
|
13
|
+
const refuse = (message) => {
|
|
14
|
+
throw new Refused(message);
|
|
15
|
+
};
|
|
16
|
+
function text(value, what, max) {
|
|
17
|
+
if (typeof value !== 'string')
|
|
18
|
+
return refuse(`${what} must be text`);
|
|
19
|
+
return value.length > max ? refuse(`${what} is longer than ${String(max)} characters`) : value;
|
|
20
|
+
}
|
|
21
|
+
function whole(value, what, max) {
|
|
22
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {
|
|
23
|
+
return refuse(`${what} must be a whole number of at least 1`);
|
|
24
|
+
}
|
|
25
|
+
return value > max ? refuse(`${what} must be at most ${String(max)}`) : value;
|
|
26
|
+
}
|
|
27
|
+
function condition(value, max) {
|
|
28
|
+
if (!isRecord(value))
|
|
29
|
+
return refuse('a filter condition must be an object');
|
|
30
|
+
const op = typeof value.op === 'string' && OPS.has(value.op) ? value.op : null;
|
|
31
|
+
if (op === null)
|
|
32
|
+
return refuse(`unknown filter comparison ${JSON.stringify(value.op)}`);
|
|
33
|
+
return {
|
|
34
|
+
field: text(value.field, 'a filter column', max),
|
|
35
|
+
op,
|
|
36
|
+
value: text(value.value ?? '', 'a filter value', max),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function filterOf(value, limits) {
|
|
40
|
+
if (!isRecord(value))
|
|
41
|
+
return refuse('filter must be an object');
|
|
42
|
+
if (value.match !== 'all' && value.match !== 'any')
|
|
43
|
+
return refuse('filter.match must be "all" or "any"');
|
|
44
|
+
const conditions = Array.isArray(value.conditions)
|
|
45
|
+
? value.conditions
|
|
46
|
+
: refuse('filter.conditions must be a list');
|
|
47
|
+
if (conditions.length > limits.maxConditions) {
|
|
48
|
+
return refuse(`a filter has at most ${String(limits.maxConditions)} conditions`);
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
match: value.match,
|
|
52
|
+
conditions: conditions.map((c) => condition(c, limits.maxTermLength)),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function columnsOf(value, max) {
|
|
56
|
+
if (!isRecord(value))
|
|
57
|
+
return refuse('columns must be an object');
|
|
58
|
+
return Object.fromEntries(Object.entries(value).map(([key, term]) => [key, text(term, `the term for ${key}`, max)]));
|
|
59
|
+
}
|
|
60
|
+
function searchOf(value, max) {
|
|
61
|
+
if (!isRecord(value))
|
|
62
|
+
return refuse('search must be an object');
|
|
63
|
+
return {
|
|
64
|
+
field: text(value.field, 'search.field', max),
|
|
65
|
+
term: text(value.term, 'search.term', max),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function sortOf(value, max) {
|
|
69
|
+
if (!isRecord(value))
|
|
70
|
+
return refuse('sort must be an object');
|
|
71
|
+
if (value.dir !== 'asc' && value.dir !== 'desc')
|
|
72
|
+
return refuse('sort.dir must be "asc" or "desc"');
|
|
73
|
+
return { key: text(value.key, 'sort.key', max), dir: value.dir };
|
|
74
|
+
}
|
|
75
|
+
function queryOf(input, limits) {
|
|
76
|
+
if (!isRecord(input))
|
|
77
|
+
return refuse('a query must be an object');
|
|
78
|
+
const max = limits.maxTermLength;
|
|
79
|
+
const query = {};
|
|
80
|
+
if (input.term !== undefined)
|
|
81
|
+
query.term = text(input.term, 'term', max);
|
|
82
|
+
if (input.search !== undefined)
|
|
83
|
+
query.search = searchOf(input.search, max);
|
|
84
|
+
if (input.columns !== undefined)
|
|
85
|
+
query.columns = columnsOf(input.columns, max);
|
|
86
|
+
if (input.filter !== undefined)
|
|
87
|
+
query.filter = filterOf(input.filter, limits);
|
|
88
|
+
if (input.sort !== undefined)
|
|
89
|
+
query.sort = sortOf(input.sort, max);
|
|
90
|
+
if (input.page !== undefined)
|
|
91
|
+
query.page = whole(input.page, 'page', Number.MAX_SAFE_INTEGER);
|
|
92
|
+
if (input.pageSize !== undefined) {
|
|
93
|
+
query.pageSize = whole(input.pageSize, 'pageSize', limits.maxPageSize);
|
|
94
|
+
}
|
|
95
|
+
return query;
|
|
96
|
+
}
|
|
97
|
+
export function parseTableQuery(input, limits = {}) {
|
|
98
|
+
try {
|
|
99
|
+
const query = queryOf(input, {
|
|
100
|
+
maxPageSize: limits.maxPageSize ?? 100,
|
|
101
|
+
maxConditions: limits.maxConditions ?? 20,
|
|
102
|
+
maxTermLength: limits.maxTermLength ?? 200,
|
|
103
|
+
});
|
|
104
|
+
return { ok: true, query };
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
if (error instanceof Refused)
|
|
108
|
+
return { ok: false, message: error.message };
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { TableQuery } from './parse.js';
|
|
2
|
+
export interface QueryRowsOptions {
|
|
3
|
+
/** What `term` is looked for in. Default: every key of the first row. */
|
|
4
|
+
term?: readonly string[];
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* `query` answered over `rows`: the page asked for, and how many rows matched on every page.
|
|
8
|
+
* What `tableQuery` writes as SQL, in memory, with the same meaning (`contains` ignores case,
|
|
9
|
+
* `eq` / `ne` are exact on a cell's text, `gt` / `lt` read numbers as numbers and never pass an
|
|
10
|
+
* empty cell). A column key reads the row's flat key (`'owner.name'`) or walks the path. Unlike
|
|
11
|
+
* the SQL, a sort reads numbers as numbers with no `sortAs`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function queryRows<Row extends Readonly<Record<string, unknown>>>(rows: readonly Row[], query: TableQuery, options?: QueryRowsOptions): {
|
|
14
|
+
rows: Row[];
|
|
15
|
+
total: number;
|
|
16
|
+
};
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
const NUMBER = /^-?\d+(\.\d+)?$/;
|
|
2
|
+
const DEFAULT_PAGE_SIZE = 20;
|
|
3
|
+
function valueAt(row, path) {
|
|
4
|
+
if (Object.hasOwn(row, path))
|
|
5
|
+
return row[path];
|
|
6
|
+
let current = row;
|
|
7
|
+
for (const segment of path.split('.')) {
|
|
8
|
+
if (typeof current !== 'object' || current === null)
|
|
9
|
+
return undefined;
|
|
10
|
+
current = current[segment];
|
|
11
|
+
}
|
|
12
|
+
return current;
|
|
13
|
+
}
|
|
14
|
+
function textOf(value) {
|
|
15
|
+
if (value === null || value === undefined)
|
|
16
|
+
return '';
|
|
17
|
+
if (typeof value === 'string')
|
|
18
|
+
return value;
|
|
19
|
+
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
|
|
20
|
+
return String(value);
|
|
21
|
+
}
|
|
22
|
+
if (value instanceof Date)
|
|
23
|
+
return value.toISOString();
|
|
24
|
+
return JSON.stringify(value);
|
|
25
|
+
}
|
|
26
|
+
const cell = (row, key) => textOf(valueAt(row, key));
|
|
27
|
+
const contains = (text, term) => text.toLowerCase().includes(term.trim().toLowerCase());
|
|
28
|
+
function compared(text, op, value) {
|
|
29
|
+
const wanted = value.trim();
|
|
30
|
+
if (NUMBER.test(wanted)) {
|
|
31
|
+
if (!NUMBER.test(text))
|
|
32
|
+
return false;
|
|
33
|
+
return op === 'gt' ? Number(text) > Number(wanted) : Number(text) < Number(wanted);
|
|
34
|
+
}
|
|
35
|
+
if (text === '')
|
|
36
|
+
return false;
|
|
37
|
+
return op === 'gt' ? text > value : text < value;
|
|
38
|
+
}
|
|
39
|
+
function passes(text, { op, value }) {
|
|
40
|
+
switch (op) {
|
|
41
|
+
case 'contains':
|
|
42
|
+
return contains(text, value);
|
|
43
|
+
case 'eq':
|
|
44
|
+
return text === value;
|
|
45
|
+
case 'ne':
|
|
46
|
+
return text !== value;
|
|
47
|
+
case 'gt':
|
|
48
|
+
case 'lt':
|
|
49
|
+
return compared(text, op, value);
|
|
50
|
+
case 'empty':
|
|
51
|
+
return text === '';
|
|
52
|
+
case 'not_empty':
|
|
53
|
+
return text !== '';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function order(a, b, dir) {
|
|
57
|
+
if (a === '' || b === '')
|
|
58
|
+
return a === b ? 0 : a === '' ? 1 : -1;
|
|
59
|
+
const by = NUMBER.test(a) && NUMBER.test(b) ? Number(a) - Number(b) : a < b ? -1 : a > b ? 1 : 0;
|
|
60
|
+
return dir === 'desc' ? -by : by;
|
|
61
|
+
}
|
|
62
|
+
export function queryRows(rows, query, options = {}) {
|
|
63
|
+
const term = query.term?.trim();
|
|
64
|
+
const places = options.term ?? Object.keys(rows[0] ?? {});
|
|
65
|
+
const asked = [
|
|
66
|
+
...(query.search ? [[query.search.field, query.search.term]] : []),
|
|
67
|
+
...Object.entries(query.columns ?? {}),
|
|
68
|
+
].filter(([, text]) => text.trim() !== '');
|
|
69
|
+
const conditions = query.filter?.conditions ?? [];
|
|
70
|
+
const any = query.filter?.match === 'any';
|
|
71
|
+
const matched = rows.filter((row) => {
|
|
72
|
+
if (term && !places.some((key) => contains(cell(row, key), term)))
|
|
73
|
+
return false;
|
|
74
|
+
if (!asked.every(([key, text]) => contains(cell(row, key), text)))
|
|
75
|
+
return false;
|
|
76
|
+
if (conditions.length === 0)
|
|
77
|
+
return true;
|
|
78
|
+
const each = (c) => passes(cell(row, c.field), c);
|
|
79
|
+
return any ? conditions.some(each) : conditions.every(each);
|
|
80
|
+
});
|
|
81
|
+
const { sort } = query;
|
|
82
|
+
const sorted = sort
|
|
83
|
+
? matched
|
|
84
|
+
.map((row, index) => ({ row, index, text: cell(row, sort.key) }))
|
|
85
|
+
.sort((a, b) => order(a.text, b.text, sort.dir) || a.index - b.index)
|
|
86
|
+
.map(({ row }) => row)
|
|
87
|
+
: matched;
|
|
88
|
+
const size = query.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
89
|
+
const start = ((query.page ?? 1) - 1) * size;
|
|
90
|
+
return { rows: sorted.slice(start, start + size), total: matched.length };
|
|
91
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { SqlTag } from './fragment.js';
|
|
2
|
+
import type { TableQuery } from './parse.js';
|
|
3
|
+
/**
|
|
4
|
+
* The SQL a query is written against. Every cell is an expression that yields **text** (cast
|
|
5
|
+
* what is not: `sql\`${t.size}::text\``), because the client compares text: that is what makes
|
|
6
|
+
* `contains` work on any column and the answers match `pageOfRows` in the browser.
|
|
7
|
+
*/
|
|
8
|
+
export interface TableShape<S> {
|
|
9
|
+
/** The row's id: the last word of every ordering, so pages never shuffle. */
|
|
10
|
+
key: S;
|
|
11
|
+
/** The cells a query may name, by column key. A key that is not here is refused. */
|
|
12
|
+
columns: Record<string, S>;
|
|
13
|
+
/** What `term` (typed into a reference field) is looked for in. Default: every column. */
|
|
14
|
+
term?: readonly S[];
|
|
15
|
+
/** How a column sorts when its text would not: an id by its number. */
|
|
16
|
+
sortAs?: Record<string, S>;
|
|
17
|
+
/** The order with no `sort`. Default: by `key`. */
|
|
18
|
+
defaultOrder?: readonly S[];
|
|
19
|
+
}
|
|
20
|
+
export interface TableSql<S> {
|
|
21
|
+
/** The first column the query names that the shape does not have. Check it before the rest. */
|
|
22
|
+
unknownColumn(query: TableQuery): string | undefined;
|
|
23
|
+
/** The conditions, or undefined when the query narrows nothing. */
|
|
24
|
+
where(query: TableQuery): S | undefined;
|
|
25
|
+
/** The ordering, never empty, always ending on the key. */
|
|
26
|
+
orderBy(query: TableQuery): S[];
|
|
27
|
+
/** `limit` and `offset` of the page asked for. */
|
|
28
|
+
page(query: TableQuery): {
|
|
29
|
+
limit: number;
|
|
30
|
+
offset: number;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A table's queries as Postgres SQL. `sql` is the tag the pieces are written with: drizzle-orm's
|
|
35
|
+
* `sql`, or this package's `fragment`. Nothing a client sends becomes SQL text: terms and values
|
|
36
|
+
* are parameters, and a column key only ever selects one of the shape's own expressions.
|
|
37
|
+
*/
|
|
38
|
+
export declare function tableQuery<S>(sql: SqlTag<S>, shape: TableShape<S>): TableSql<S>;
|
|
39
|
+
/** What `tableQueryOf` reads of a table: `defineTable`'s result (@20baht/engine), structurally. */
|
|
40
|
+
export interface TableLike<Key extends string = string, Row = unknown> {
|
|
41
|
+
readonly columns: Readonly<Record<string, ColumnLike>>;
|
|
42
|
+
/** Never set: carries the keys a query may name and the shape of a row, for the compiler. */
|
|
43
|
+
readonly '~types'?: {
|
|
44
|
+
readonly key: Key;
|
|
45
|
+
readonly row: Row;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** What is read of a column: its fields to walk into, and what describes it. */
|
|
49
|
+
export interface ColumnLike {
|
|
50
|
+
readonly label?: string;
|
|
51
|
+
readonly type?: string;
|
|
52
|
+
readonly options?: readonly {
|
|
53
|
+
readonly key: string;
|
|
54
|
+
}[];
|
|
55
|
+
readonly fields?: Readonly<Record<string, ColumnLike>>;
|
|
56
|
+
/** With `fields`: a heading over them, not a cell: no query names it. */
|
|
57
|
+
readonly group?: boolean;
|
|
58
|
+
}
|
|
59
|
+
/** A `TableShape` whose columns are exactly the table's: SQL for each, and for no other. */
|
|
60
|
+
export interface TableShapeOf<S, Key extends string> extends Omit<TableShape<S>, 'columns' | 'sortAs'> {
|
|
61
|
+
/** One expression per column of the table, walked ones (`owner.name`) included. Any type: each is cast to text. */
|
|
62
|
+
columns: Record<Key, S>;
|
|
63
|
+
sortAs?: Partial<Record<Key, S>>;
|
|
64
|
+
}
|
|
65
|
+
/** Every key of the columns, a reference column's own fields as `owner.name`. */
|
|
66
|
+
export declare function keysOf(columns: Readonly<Record<string, ColumnLike>>, prefix?: string): string[];
|
|
67
|
+
/**
|
|
68
|
+
* `tableQuery` for a table declared with `defineTable`: the table's columns are the ones a query
|
|
69
|
+
* may name, so `shape.columns` must give SQL for every one of them (the compiler says which is
|
|
70
|
+
* missing; so does this function, when it is called, for callers the compiler does not see).
|
|
71
|
+
*
|
|
72
|
+
* const orders = tableQueryOf(sql, ordersTable, {
|
|
73
|
+
* key: sql`${order.id}`,
|
|
74
|
+
* columns: { customer: sql`${order.customer}`, qty: sql`${order.qty}`, … },
|
|
75
|
+
* });
|
|
76
|
+
*
|
|
77
|
+
* Each cell is cast to text (`(expr)::text`), which is what a query compares, so a number or a
|
|
78
|
+
* boolean column is named as it is. Cast a date yourself when its text should be a day
|
|
79
|
+
* (`to_char(…, 'YYYY-MM-DD')`): a timestamp's own text is not what a date filter sends.
|
|
80
|
+
* `key`, `term`, `sortAs` and `defaultOrder` are used as written.
|
|
81
|
+
*/
|
|
82
|
+
export declare function tableQueryOf<S, Key extends string>(sql: SqlTag<S>, table: TableLike<Key>, shape: TableShapeOf<S, Key>): TableSql<S>;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
const NUMBER = /^-?\d+(\.\d+)?$/;
|
|
2
|
+
const DEFAULT_PAGE_SIZE = 20;
|
|
3
|
+
const likeAnywhere = (term) => `%${term.trim().replace(/[%_\\]/g, (c) => `\\${c}`)}%`;
|
|
4
|
+
export function tableQuery(sql, shape) {
|
|
5
|
+
const join = (parts, word) => {
|
|
6
|
+
const glue = sql.raw(` ${word} `);
|
|
7
|
+
const joined = parts.reduce((all, part) => sql `${all}${glue}${part}`);
|
|
8
|
+
return parts.length === 1 ? joined : sql `(${joined})`;
|
|
9
|
+
};
|
|
10
|
+
const cell = (key) => Object.hasOwn(shape.columns, key) ? shape.columns[key] : undefined;
|
|
11
|
+
const contains = (of, term) => sql `${of} ilike ${likeAnywhere(term)}`;
|
|
12
|
+
const blank = (of) => sql `coalesce(${of}, '') = ''`;
|
|
13
|
+
const compared = (of, op, value) => {
|
|
14
|
+
const sign = sql.raw(op);
|
|
15
|
+
const wanted = value.trim();
|
|
16
|
+
return NUMBER.test(wanted)
|
|
17
|
+
? sql `case when ${of} ~ '^-?[0-9]+([.][0-9]+)?$' then (${of})::numeric ${sign} ${wanted}::numeric else false end`
|
|
18
|
+
: sql `(not ${blank(of)} and ${of} ${sign} ${value})`;
|
|
19
|
+
};
|
|
20
|
+
const condition = (of, { op, value }) => {
|
|
21
|
+
switch (op) {
|
|
22
|
+
case 'contains':
|
|
23
|
+
return contains(of, value);
|
|
24
|
+
case 'eq':
|
|
25
|
+
return sql `coalesce(${of}, '') = ${value}`;
|
|
26
|
+
case 'ne':
|
|
27
|
+
return sql `coalesce(${of}, '') <> ${value}`;
|
|
28
|
+
case 'gt':
|
|
29
|
+
return compared(of, '>', value);
|
|
30
|
+
case 'lt':
|
|
31
|
+
return compared(of, '<', value);
|
|
32
|
+
case 'empty':
|
|
33
|
+
return blank(of);
|
|
34
|
+
case 'not_empty':
|
|
35
|
+
return sql `not ${blank(of)}`;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const termParts = (query) => {
|
|
39
|
+
const asked = [
|
|
40
|
+
...(query.search ? [[query.search.field, query.search.term]] : []),
|
|
41
|
+
...Object.entries(query.columns ?? {}),
|
|
42
|
+
];
|
|
43
|
+
const parts = [];
|
|
44
|
+
for (const [key, term] of asked) {
|
|
45
|
+
const of = cell(key);
|
|
46
|
+
if (of !== undefined && term.trim())
|
|
47
|
+
parts.push(contains(of, term));
|
|
48
|
+
}
|
|
49
|
+
return parts;
|
|
50
|
+
};
|
|
51
|
+
const filterPart = (query) => {
|
|
52
|
+
const conditions = [];
|
|
53
|
+
for (const c of query.filter?.conditions ?? []) {
|
|
54
|
+
const of = cell(c.field);
|
|
55
|
+
if (of !== undefined)
|
|
56
|
+
conditions.push(condition(of, c));
|
|
57
|
+
}
|
|
58
|
+
if (conditions.length === 0)
|
|
59
|
+
return [];
|
|
60
|
+
return [join(conditions, query.filter?.match === 'any' ? 'or' : 'and')];
|
|
61
|
+
};
|
|
62
|
+
return {
|
|
63
|
+
unknownColumn: (query) => [
|
|
64
|
+
...(query.search ? [query.search.field] : []),
|
|
65
|
+
...Object.keys(query.columns ?? {}),
|
|
66
|
+
...(query.filter?.conditions ?? []).map((c) => c.field),
|
|
67
|
+
...(query.sort ? [query.sort.key] : []),
|
|
68
|
+
].find((key) => !Object.hasOwn(shape.columns, key)),
|
|
69
|
+
where: (query) => {
|
|
70
|
+
const parts = [];
|
|
71
|
+
const term = query.term?.trim();
|
|
72
|
+
if (term) {
|
|
73
|
+
const places = shape.term ?? Object.values(shape.columns);
|
|
74
|
+
if (places.length > 0)
|
|
75
|
+
parts.push(join(places.map((of) => contains(of, term)), 'or'));
|
|
76
|
+
}
|
|
77
|
+
parts.push(...termParts(query), ...filterPart(query));
|
|
78
|
+
return parts.length === 0 ? undefined : join(parts, 'and');
|
|
79
|
+
},
|
|
80
|
+
orderBy: (query) => {
|
|
81
|
+
const tail = sql `${shape.key} asc`;
|
|
82
|
+
const { sort } = query;
|
|
83
|
+
const by = sort ? (shape.sortAs?.[sort.key] ?? cell(sort.key)) : undefined;
|
|
84
|
+
if (!sort || by === undefined)
|
|
85
|
+
return [...(shape.defaultOrder ?? []), tail];
|
|
86
|
+
return [sql `${by} ${sql.raw(sort.dir === 'desc' ? 'desc' : 'asc')} nulls last`, tail];
|
|
87
|
+
},
|
|
88
|
+
page: (query) => {
|
|
89
|
+
const limit = query.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
90
|
+
return { limit, offset: ((query.page ?? 1) - 1) * limit };
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export function keysOf(columns, prefix = '') {
|
|
95
|
+
return Object.entries(columns).flatMap(([key, column]) => {
|
|
96
|
+
const path = `${prefix}${key}`;
|
|
97
|
+
if (!column.fields)
|
|
98
|
+
return [path];
|
|
99
|
+
const walked = keysOf(column.fields, `${path}.`);
|
|
100
|
+
return column.group ? walked : [path, ...walked];
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
export function tableQueryOf(sql, table, shape) {
|
|
104
|
+
const given = shape.columns;
|
|
105
|
+
const columns = {};
|
|
106
|
+
for (const key of keysOf(table.columns)) {
|
|
107
|
+
const cell = Object.hasOwn(given, key) ? given[key] : undefined;
|
|
108
|
+
if (cell === undefined) {
|
|
109
|
+
throw new Error(`tableQueryOf: no SQL for column ${JSON.stringify(key)}`);
|
|
110
|
+
}
|
|
111
|
+
columns[key] = sql `(${cell})::text`;
|
|
112
|
+
}
|
|
113
|
+
const sortAs = {};
|
|
114
|
+
for (const [key, by] of Object.entries(shape.sortAs ?? {})) {
|
|
115
|
+
if (by !== undefined)
|
|
116
|
+
sortAs[key] = by;
|
|
117
|
+
}
|
|
118
|
+
return tableQuery(sql, {
|
|
119
|
+
key: shape.key,
|
|
120
|
+
columns,
|
|
121
|
+
sortAs,
|
|
122
|
+
...(shape.term ? { term: shape.term } : {}),
|
|
123
|
+
...(shape.defaultOrder ? { defaultOrder: shape.defaultOrder } : {}),
|
|
124
|
+
});
|
|
125
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,73 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@20baht/table-query",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"engines": {
|
|
6
|
+
"node": ">=20.19.0"
|
|
7
|
+
},
|
|
8
|
+
"description": "The server half of <baht-table> and <baht-reference-dialog>: reads the query they send (search, column terms, filter, sort, page), refuses what it should not trust, and writes it as Postgres WHERE / ORDER BY / LIMIT. Works with drizzle's sql tag or its own; no dependencies.",
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"author": "Nattapong Promthong",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/bank20baht/20baht.git",
|
|
14
|
+
"directory": "packages/core/table-query"
|
|
15
|
+
},
|
|
16
|
+
"homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/table-query#readme",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/bank20baht/20baht/issues"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"table",
|
|
22
|
+
"filter",
|
|
23
|
+
"sort",
|
|
24
|
+
"pagination",
|
|
25
|
+
"sql",
|
|
26
|
+
"postgres",
|
|
27
|
+
"drizzle"
|
|
28
|
+
],
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"import": "./dist/index.js",
|
|
39
|
+
"default": "./dist/index.js"
|
|
40
|
+
},
|
|
41
|
+
"./elysia": {
|
|
42
|
+
"types": "./dist/elysia.d.ts",
|
|
43
|
+
"import": "./dist/elysia.js",
|
|
44
|
+
"default": "./dist/elysia.js"
|
|
45
|
+
},
|
|
46
|
+
"./package.json": "./package.json"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "rm -rf dist && tsc -p tsconfig.json --removeComments && tsc -p tsconfig.json --emitDeclarationOnly",
|
|
50
|
+
"test": "vitest run",
|
|
51
|
+
"test:watch": "vitest",
|
|
52
|
+
"test:coverage": "vitest run --coverage"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@20baht/engine": "workspace:*",
|
|
56
|
+
"@elysiajs/openapi": "^1.4.16",
|
|
57
|
+
"drizzle-orm": "^0.44.0",
|
|
58
|
+
"elysia": "^1.4.0",
|
|
59
|
+
"typescript": "^5.9.3",
|
|
60
|
+
"vitest": "^3.2.4"
|
|
61
|
+
},
|
|
62
|
+
"peerDependencies": {
|
|
63
|
+
"elysia": ">=1.4.0 <2.0.0"
|
|
64
|
+
},
|
|
65
|
+
"peerDependenciesMeta": {
|
|
66
|
+
"elysia": {
|
|
67
|
+
"optional": true
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
"main": "./dist/index.js",
|
|
71
|
+
"types": "./dist/index.d.ts",
|
|
72
|
+
"sideEffects": false
|
|
73
|
+
}
|