@gasboost/query 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gasboost
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.
@@ -0,0 +1,9 @@
1
+ import { Operator } from "./FilterOperator";
2
+ export { Operator as Operand };
3
+ export declare class Filter {
4
+ private column;
5
+ private operand;
6
+ private criteria;
7
+ constructor(column: string, operand: Operator, values: (string | number | Date | boolean)[]);
8
+ isFullfiled(record: Record<string, any>): boolean;
9
+ }
package/dist/Filter.js ADDED
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Filter = void 0;
4
+ const FilterOperand_1 = require("./FilterOperand");
5
+ const FilterOperator_1 = require("./FilterOperator");
6
+ class Filter {
7
+ column;
8
+ operand;
9
+ criteria;
10
+ constructor(column, operand, values) {
11
+ this.column = column;
12
+ this.operand = new FilterOperator_1.FilterOperator(operand);
13
+ this.criteria = new FilterOperand_1.FilterOperand(values);
14
+ const isString = this.criteria.isString();
15
+ if (this.criteria.isStringOrBoolean() &&
16
+ this.operand.isMoreThanOrLessThan()) {
17
+ throw new Error(`Operand ${operand} is not supported for type`);
18
+ }
19
+ if (!isString && this.operand.isStringOperator()) {
20
+ throw new Error(`Operand ${operand} is not supported for type`);
21
+ }
22
+ if (this.criteria.isStringOrBoolean() &&
23
+ !isString &&
24
+ !this.operand.isEqualityOperator()) {
25
+ throw new Error(`Operand ${operand} is not supported for type`);
26
+ }
27
+ }
28
+ // レコードがフィルター条件を満たすかどうか
29
+ isFullfiled(record) {
30
+ const value = record[this.column];
31
+ // 日付を比較する
32
+ if (this.criteria.isDate()) {
33
+ const recordTime = value instanceof Date ? value.getTime() : NaN;
34
+ const criteriaTimes = this.criteria.getTimes();
35
+ return this.operand.compareNumber(recordTime, criteriaTimes);
36
+ }
37
+ // 文字列を比較する
38
+ if (this.criteria.isString()) {
39
+ const criteriaValues = this.criteria.getValue();
40
+ if (typeof value !== "string") {
41
+ return false;
42
+ }
43
+ return this.operand.compareString(value, criteriaValues);
44
+ }
45
+ // booleanを比較する
46
+ if (this.criteria.isStringOrBoolean()) {
47
+ const criteriaValues = this.criteria.getValue();
48
+ return this.operand.compare(value, criteriaValues);
49
+ }
50
+ // 数値を比較する
51
+ const criteria = this.criteria.getValue();
52
+ return this.operand.compareNumber(value, criteria);
53
+ }
54
+ }
55
+ exports.Filter = Filter;
@@ -0,0 +1,9 @@
1
+ export declare class FilterOperand {
2
+ private values;
3
+ constructor(values: (string | number | Date | boolean)[]);
4
+ isDate(): boolean;
5
+ getValue(): (string | number | boolean | Date)[];
6
+ getTimes(): number[];
7
+ isStringOrBoolean(): boolean;
8
+ isString(): boolean;
9
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FilterOperand = void 0;
4
+ class FilterOperand {
5
+ values;
6
+ constructor(values) {
7
+ this.values = values;
8
+ if (values.length === 0)
9
+ throw new Error("values must not be empty");
10
+ const firstType = typeof values[0];
11
+ if (firstType === "object")
12
+ return;
13
+ const isSameType = values.every((v) => v !== null && v !== undefined && typeof v === firstType);
14
+ if (!isSameType) {
15
+ throw new Error("values must be all the same type");
16
+ }
17
+ }
18
+ isDate() {
19
+ return Object.prototype.toString.call(this.values[0]) === "[object Date]";
20
+ }
21
+ getValue() {
22
+ return this.values;
23
+ }
24
+ getTimes() {
25
+ if (!this.isDate()) {
26
+ throw new Error("values are not Date type");
27
+ }
28
+ return this.values.map((v) => v.getTime());
29
+ }
30
+ isStringOrBoolean() {
31
+ return (typeof this.values[0] === "string" || typeof this.values[0] === "boolean");
32
+ }
33
+ isString() {
34
+ return typeof this.values[0] === "string";
35
+ }
36
+ }
37
+ exports.FilterOperand = FilterOperand;
@@ -0,0 +1,11 @@
1
+ export type Operator = "=" | "<" | ">" | "<=" | ">=" | "!=" | "*" | "!*" | "^*" | "*$";
2
+ export declare class FilterOperator {
3
+ private operand;
4
+ constructor(operand: Operator);
5
+ isMoreThanOrLessThan(): boolean;
6
+ isStringOperator(): boolean;
7
+ isEqualityOperator(): boolean;
8
+ compareNumber(value: number, criteria: number[]): boolean;
9
+ compare(value: any, criteria: any[]): boolean;
10
+ compareString(value: string, criteria: string[]): boolean;
11
+ }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FilterOperator = void 0;
4
+ class FilterOperator {
5
+ operand;
6
+ constructor(operand) {
7
+ this.operand = operand;
8
+ }
9
+ isMoreThanOrLessThan() {
10
+ return (this.operand === "<" ||
11
+ this.operand === ">" ||
12
+ this.operand === "<=" ||
13
+ this.operand === ">=");
14
+ }
15
+ isStringOperator() {
16
+ return (this.operand === "*" ||
17
+ this.operand === "!*" ||
18
+ this.operand === "^*" ||
19
+ this.operand === "*$");
20
+ }
21
+ isEqualityOperator() {
22
+ return this.operand === "=" || this.operand === "!=";
23
+ }
24
+ compareNumber(value, criteria) {
25
+ switch (this.operand) {
26
+ case "=":
27
+ return criteria.some((time) => time === value);
28
+ case "<":
29
+ return value < Math.min(...criteria);
30
+ case ">":
31
+ return value > Math.max(...criteria);
32
+ case "<=":
33
+ return value <= Math.min(...criteria);
34
+ case ">=":
35
+ return value >= Math.max(...criteria);
36
+ case "!=":
37
+ return !criteria.every((time) => time === value);
38
+ default:
39
+ throw new Error(`Operand ${this.operand} is not supported for number`);
40
+ }
41
+ }
42
+ compare(value, criteria) {
43
+ switch (this.operand) {
44
+ case "=":
45
+ return criteria.includes(value);
46
+ case "!=":
47
+ return !criteria.includes(value);
48
+ default:
49
+ throw new Error(`Operand ${this.operand} is not supported for type`);
50
+ }
51
+ }
52
+ compareString(value, criteria) {
53
+ switch (this.operand) {
54
+ case "=":
55
+ return criteria.includes(value);
56
+ case "!=":
57
+ return !criteria.includes(value);
58
+ case "*":
59
+ return criteria.some((needle) => value.includes(needle));
60
+ case "!*":
61
+ return criteria.every((needle) => !value.includes(needle));
62
+ case "^*":
63
+ return criteria.some((prefix) => value.startsWith(prefix));
64
+ case "*$":
65
+ return criteria.some((suffix) => value.endsWith(suffix));
66
+ default:
67
+ throw new Error(`Operand ${this.operand} is not supported for string`);
68
+ }
69
+ }
70
+ }
71
+ exports.FilterOperator = FilterOperator;
package/dist/Join.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { Query } from "./Query";
2
+ import type { TableDefinition } from "./TableDefinition";
3
+ export declare class Join<T extends readonly TableDefinition[], N extends T[number]["name"] = T[number]["name"]> {
4
+ readonly table: N;
5
+ readonly localKey: string;
6
+ readonly foreignKey: string;
7
+ readonly query: Query<T, N> | null;
8
+ constructor({ table, localKey, foreignKey, query, }: {
9
+ table: N;
10
+ localKey: string;
11
+ foreignKey: string;
12
+ query?: Query<T, N> | null;
13
+ });
14
+ combine(parents: Record<string, unknown>[], children: Record<string, unknown>[]): Record<string, unknown>[];
15
+ }
16
+ export type JoinedRecord = {
17
+ readonly parent: Record<string, unknown>;
18
+ readonly children: Record<string, unknown>[];
19
+ };
package/dist/Join.js ADDED
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Join = void 0;
4
+ class Join {
5
+ table;
6
+ localKey;
7
+ foreignKey;
8
+ query;
9
+ constructor({ table, localKey, foreignKey, query = null, }) {
10
+ this.table = table;
11
+ this.localKey = localKey;
12
+ this.foreignKey = foreignKey;
13
+ this.query = query;
14
+ }
15
+ combine(parents, children) {
16
+ const childrenByKey = new Map();
17
+ for (const child of children) {
18
+ const key = child[this.foreignKey];
19
+ if (key === null || key === undefined) {
20
+ continue;
21
+ }
22
+ const matched = childrenByKey.get(key) ?? [];
23
+ matched.push(child);
24
+ childrenByKey.set(key, matched);
25
+ }
26
+ return parents.map((parent) => {
27
+ const key = parent[this.localKey];
28
+ const matchedChildren = key === null || key === undefined ? [] : (childrenByKey.get(key) ?? []);
29
+ return {
30
+ ...parent,
31
+ [this.table]: matchedChildren,
32
+ };
33
+ });
34
+ }
35
+ }
36
+ exports.Join = Join;
@@ -0,0 +1,6 @@
1
+ export declare class OrderBy {
2
+ private column;
3
+ private direction;
4
+ constructor(column: string, direction: "asc" | "desc");
5
+ sort(a: Record<string, any>, b: Record<string, any>): number;
6
+ }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OrderBy = void 0;
4
+ class OrderBy {
5
+ column;
6
+ direction;
7
+ constructor(column, direction) {
8
+ this.column = column;
9
+ this.direction = direction;
10
+ }
11
+ sort(a, b) {
12
+ const av = a[this.column];
13
+ const bv = b[this.column];
14
+ if (av === bv)
15
+ return 0;
16
+ const result = av > bv ? 1 : -1;
17
+ if (this.direction === "asc")
18
+ return result;
19
+ if (this.direction === "desc")
20
+ return -result;
21
+ throw new Error(`Invalid sort direction: ${this.direction}`);
22
+ }
23
+ }
24
+ exports.OrderBy = OrderBy;
@@ -0,0 +1,39 @@
1
+ import type { z } from "zod";
2
+ import { Filter, Operand } from "./Filter";
3
+ import { Join } from "./Join";
4
+ import { OrderBy } from "./OrderBy";
5
+ import type { TableByName, TableDefinition } from "./TableDefinition";
6
+ export type CriteriaValue<S extends z.ZodObject<any>, K extends keyof z.infer<S>> = z.infer<S>[K];
7
+ export type Loader<T extends readonly TableDefinition[]> = <N extends T[number]["name"]>(table: N) => Promise<Record<string, unknown>[]>;
8
+ export declare class Query<T extends readonly TableDefinition[], N extends T[number]["name"] = T[number]["name"]> {
9
+ private readonly requires;
10
+ private readonly options;
11
+ private orderByValue;
12
+ private limitValue;
13
+ private offsetValue;
14
+ private readonly joins;
15
+ private readonly tableName;
16
+ constructor({ tableName, requires, options, orderBy, limit, offset, joins, }: {
17
+ tableName: N;
18
+ requires?: Filter[];
19
+ options?: Filter[];
20
+ orderBy?: OrderBy | null;
21
+ limit?: number | null;
22
+ offset?: number | null;
23
+ joins?: Join<T>[];
24
+ });
25
+ getTableName(): N;
26
+ and<K extends keyof z.infer<TableByName<T, N>["schema"]>>(column: K, operand: Operand, values: CriteriaValue<TableByName<T, N>["schema"], K>[]): this;
27
+ or<K extends keyof z.infer<TableByName<T, N>["schema"]>>(column: K, operand: Operand, values: CriteriaValue<TableByName<T, N>["schema"], K>[]): this;
28
+ orderBy<K extends keyof z.infer<TableByName<T, N>["schema"]>>(column: K, order?: "asc" | "desc"): this;
29
+ limit(value: number): this;
30
+ offset(value: number): this;
31
+ join<RefName extends T[number]["name"], LocalKey extends keyof z.infer<TableByName<T, N>["schema"]>, RefKey extends keyof z.infer<TableByName<T, RefName>["schema"]>>(localKey: LocalKey, referenceTableName: RefName, referenceKey: RefKey, query?: Query<T, RefName>): this;
32
+ filter(records: Record<string, unknown>[]): Record<string, unknown>[];
33
+ sort(records: Record<string, unknown>[]): Record<string, unknown>[];
34
+ shift(records: Record<string, unknown>[]): Record<string, unknown>[];
35
+ cut(records: Record<string, unknown>[]): Record<string, unknown>[];
36
+ getJoins(): readonly Join<T>[];
37
+ apply(records: Record<string, unknown>[]): Record<string, unknown>[];
38
+ resolve(load: Loader<T>): Promise<Record<string, unknown>[]>;
39
+ }
package/dist/Query.js ADDED
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Query = void 0;
4
+ const Filter_1 = require("./Filter");
5
+ const Join_1 = require("./Join");
6
+ const OrderBy_1 = require("./OrderBy");
7
+ class Query {
8
+ requires;
9
+ options;
10
+ orderByValue;
11
+ limitValue;
12
+ offsetValue;
13
+ joins;
14
+ tableName;
15
+ constructor({ tableName, requires = [], options = [], orderBy = null, limit = null, offset = null, joins = [], }) {
16
+ this.tableName = tableName;
17
+ this.requires = requires;
18
+ this.options = options;
19
+ this.orderByValue = orderBy;
20
+ this.limitValue = limit;
21
+ this.offsetValue = offset;
22
+ this.joins = joins;
23
+ }
24
+ getTableName() {
25
+ return this.tableName;
26
+ }
27
+ and(column, operand, values) {
28
+ this.requires.push(new Filter_1.Filter(column, operand, values));
29
+ return this;
30
+ }
31
+ or(column, operand, values) {
32
+ this.options.push(new Filter_1.Filter(column, operand, values));
33
+ return this;
34
+ }
35
+ orderBy(column, order = "asc") {
36
+ this.orderByValue = new OrderBy_1.OrderBy(column, order);
37
+ return this;
38
+ }
39
+ limit(value) {
40
+ this.limitValue = value;
41
+ return this;
42
+ }
43
+ offset(value) {
44
+ this.offsetValue = value;
45
+ return this;
46
+ }
47
+ join(localKey, referenceTableName, referenceKey, query) {
48
+ this.joins.push(new Join_1.Join({
49
+ table: referenceTableName,
50
+ localKey: localKey,
51
+ foreignKey: referenceKey,
52
+ query: query ?? null,
53
+ }));
54
+ return this;
55
+ }
56
+ filter(records) {
57
+ return records.filter((record) => {
58
+ const requires = this.requires.every((filter) => filter.isFullfiled(record));
59
+ const options = this.options.length === 0 ||
60
+ this.options.some((filter) => filter.isFullfiled(record));
61
+ return requires && options;
62
+ });
63
+ }
64
+ sort(records) {
65
+ if (this.orderByValue !== null) {
66
+ records.sort((a, b) => this.orderByValue.sort(a, b));
67
+ }
68
+ return records;
69
+ }
70
+ shift(records) {
71
+ if (this.offsetValue !== null && this.offsetValue > 0) {
72
+ records.splice(0, this.offsetValue);
73
+ }
74
+ return records;
75
+ }
76
+ cut(records) {
77
+ if (this.limitValue !== null && this.limitValue > 0) {
78
+ records.splice(this.limitValue);
79
+ }
80
+ return records;
81
+ }
82
+ getJoins() {
83
+ return this.joins;
84
+ }
85
+ apply(records) {
86
+ const filtered = this.filter(records);
87
+ const sorted = this.sort(filtered);
88
+ const shifted = this.shift(sorted);
89
+ return this.cut(shifted);
90
+ }
91
+ async resolve(load) {
92
+ let records = this.apply(await load(this.tableName));
93
+ for (const join of this.joins) {
94
+ const children = join.query !== null
95
+ ? await join.query.resolve(load)
96
+ : await load(join.table);
97
+ records = join.combine(records, children);
98
+ }
99
+ return records;
100
+ }
101
+ }
102
+ exports.Query = Query;
@@ -0,0 +1,9 @@
1
+ import type { z } from "zod";
2
+ export type TableDefinition<N extends string = string, S extends z.ZodObject<any> = z.ZodObject<any>> = {
3
+ readonly name: N;
4
+ readonly schema: S;
5
+ };
6
+ export type TableByName<T extends readonly TableDefinition[], N extends T[number]["name"]> = Extract<T[number], {
7
+ name: N;
8
+ }>;
9
+ export type TableRecord<T extends readonly TableDefinition[], N extends T[number]["name"]> = z.infer<TableByName<T, N>["schema"]>;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
File without changes
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@gasboost/query",
3
+ "version": "0.1.0",
4
+ "description": "Type-safe, storage-agnostic query engine powered by Zod",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/gasboost/db.git",
8
+ "directory": "packages/query"
9
+ },
10
+ "license": "MIT",
11
+ "author": "tiger-oshima",
12
+ "keywords": [
13
+ "query",
14
+ "query-builder",
15
+ "database",
16
+ "zod",
17
+ "typescript",
18
+ "type-safe",
19
+ "join"
20
+ ],
21
+ "type": "commonjs",
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "require": "./dist/index.js",
28
+ "default": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md"
34
+ ],
35
+ "dependencies": {
36
+ "zod": "^4.5.4"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "scripts": {
42
+ "typecheck": "tsc --noEmit",
43
+ "test": "vitest run",
44
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
45
+ "pack:check": "pnpm pack"
46
+ }
47
+ }