@20baht/table-query 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +88 -2
- package/dist/fragment.d.ts +26 -0
- package/dist/fragment.js +25 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/parse.d.ts +53 -0
- package/dist/parse.js +111 -0
- package/dist/table-query.d.ts +38 -0
- package/dist/table-query.js +93 -0
- package/package.json +56 -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,89 @@
|
|
|
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
|
+
## Without a query builder
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { fragment, tableQuery, toQuery } from '@20baht/table-query';
|
|
49
|
+
|
|
50
|
+
const servers = tableQuery(fragment, { key: fragment`id`, columns: { name: fragment`name` } });
|
|
51
|
+
const where = servers.where(query); // undefined when the query narrows nothing
|
|
52
|
+
const { text, params } = toQuery(fragment`select * from server where ${where ?? fragment.raw('true')}`);
|
|
53
|
+
await client.query(text, params); // "select * from server where name ilike $1", ['%core%']
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`toQuery(part, first)` numbers placeholders from `first`, for a piece that follows parameters of your own.
|
|
57
|
+
|
|
58
|
+
## What a query means
|
|
59
|
+
|
|
60
|
+
The same query answered in the browser is `pageOfRows` / `matchesFilter` of `@20baht/ui`; the SQL follows
|
|
61
|
+
them:
|
|
62
|
+
|
|
63
|
+
| Part | SQL |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `term` | `ilike '%term%'` in any of `shape.term` (default: every column) |
|
|
66
|
+
| `search`, `columns` | `ilike '%term%'` in that column, all of them; a blank term narrows nothing |
|
|
67
|
+
| `contains` | `ilike '%value%'` |
|
|
68
|
+
| `eq` / `ne` | exact text, an empty cell reading as `''` |
|
|
69
|
+
| `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 |
|
|
70
|
+
| `empty` / `not_empty` | null or `''` |
|
|
71
|
+
| `filter.match` | `all` joins with `and`, `any` with `or` |
|
|
72
|
+
| `sort` | the column (or its `sortAs`), `nulls last`, then the key so pages never shuffle |
|
|
73
|
+
| `page`, `pageSize` | `limit` / `offset`; 20 a page when unset |
|
|
74
|
+
|
|
75
|
+
`%` and `_` in a term are literal. One difference from the browser: a `gt` / `lt` against a number, on a
|
|
76
|
+
cell that is not one, is false here; the browser falls back to comparing text.
|
|
77
|
+
|
|
78
|
+
## What it refuses, and how
|
|
79
|
+
|
|
80
|
+
- **Nothing a client sends becomes SQL text.** Terms and values are parameters. A column key only selects
|
|
81
|
+
one of the shape's own expressions; a direction is `asc` or `desc`.
|
|
82
|
+
- **`parseTableQuery(body, limits?)`** answers `{ ok: true, query }` or `{ ok: false, message }`: wrong
|
|
83
|
+
shapes, an unknown comparison, a `pageSize` over `maxPageSize` (100), more than `maxConditions` (20)
|
|
84
|
+
conditions, a term longer than `maxTermLength` (200). Keys it does not know are dropped.
|
|
85
|
+
- **`unknownColumn(query)`** names the first column the shape does not have. Refuse the request: a column
|
|
86
|
+
that is not in the shape writes no SQL either way, but the caller should hear it.
|
|
87
|
+
- **Authorization is yours.** Which rows a caller may see is a condition you `and` beside `where()`.
|
|
88
|
+
|
|
89
|
+
Not here: keyset (cursor) pagination, other databases, and running the query.
|
|
@@ -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,3 @@
|
|
|
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, type TableShape, type TableSql } from './table-query.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,38 @@
|
|
|
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>;
|
|
@@ -0,0 +1,93 @@
|
|
|
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@20baht/table-query",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"./package.json": "./package.json"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "rm -rf dist && tsc -p tsconfig.json --removeComments && tsc -p tsconfig.json --emitDeclarationOnly",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"test:watch": "vitest",
|
|
47
|
+
"test:coverage": "vitest run --coverage"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@20baht/engine": "workspace:*",
|
|
51
|
+
"drizzle-orm": "^0.44.0",
|
|
52
|
+
"typescript": "^5.8.3",
|
|
53
|
+
"vitest": "^3.2.4"
|
|
54
|
+
},
|
|
55
|
+
"main": "./dist/index.js",
|
|
56
|
+
"types": "./dist/index.d.ts",
|
|
57
|
+
"sideEffects": false
|
|
58
|
+
}
|