@hebo-ai/gateway 0.9.2 → 0.9.4
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/dist/config.d.ts +2 -0
- package/dist/config.js +125 -0
- package/dist/endpoints/chat-completions/converters.d.ts +26 -0
- package/dist/endpoints/chat-completions/converters.js +525 -0
- package/dist/endpoints/chat-completions/handler.d.ts +2 -0
- package/dist/endpoints/chat-completions/handler.js +152 -0
- package/dist/endpoints/chat-completions/index.d.ts +4 -0
- package/dist/endpoints/chat-completions/index.js +4 -0
- package/dist/endpoints/chat-completions/otel.d.ts +5 -0
- package/dist/endpoints/chat-completions/otel.js +177 -0
- package/dist/endpoints/chat-completions/schema.d.ts +1170 -0
- package/dist/endpoints/chat-completions/schema.js +252 -0
- package/dist/endpoints/conversations/converters.d.ts +8 -0
- package/dist/endpoints/conversations/converters.js +29 -0
- package/dist/endpoints/conversations/handler.d.ts +2 -0
- package/dist/endpoints/conversations/handler.js +259 -0
- package/dist/endpoints/conversations/index.d.ts +3 -0
- package/dist/endpoints/conversations/index.js +3 -0
- package/dist/endpoints/conversations/schema.d.ts +1511 -0
- package/dist/endpoints/conversations/schema.js +74 -0
- package/dist/endpoints/conversations/storage/dialects/greptime.d.ts +10 -0
- package/dist/endpoints/conversations/storage/dialects/greptime.js +87 -0
- package/dist/endpoints/conversations/storage/dialects/mysql.d.ts +12 -0
- package/dist/endpoints/conversations/storage/dialects/mysql.js +118 -0
- package/dist/endpoints/conversations/storage/dialects/postgres.d.ts +16 -0
- package/dist/endpoints/conversations/storage/dialects/postgres.js +185 -0
- package/dist/endpoints/conversations/storage/dialects/sqlite.d.ts +11 -0
- package/dist/endpoints/conversations/storage/dialects/sqlite.js +176 -0
- package/dist/endpoints/conversations/storage/dialects/types.d.ts +42 -0
- package/dist/endpoints/conversations/storage/dialects/types.js +0 -0
- package/dist/endpoints/conversations/storage/dialects/utils.d.ts +25 -0
- package/dist/endpoints/conversations/storage/dialects/utils.js +80 -0
- package/dist/endpoints/conversations/storage/memory.d.ts +25 -0
- package/dist/endpoints/conversations/storage/memory.js +200 -0
- package/dist/endpoints/conversations/storage/sql.d.ts +33 -0
- package/dist/endpoints/conversations/storage/sql.js +276 -0
- package/dist/endpoints/conversations/storage/types.d.ts +39 -0
- package/dist/endpoints/conversations/storage/types.js +0 -0
- package/dist/endpoints/embeddings/converters.d.ts +10 -0
- package/dist/endpoints/embeddings/converters.js +31 -0
- package/dist/endpoints/embeddings/handler.d.ts +2 -0
- package/dist/endpoints/embeddings/handler.js +99 -0
- package/dist/endpoints/embeddings/index.d.ts +4 -0
- package/dist/endpoints/embeddings/index.js +4 -0
- package/dist/endpoints/embeddings/otel.d.ts +5 -0
- package/dist/endpoints/embeddings/otel.js +29 -0
- package/dist/endpoints/embeddings/schema.d.ts +44 -0
- package/dist/endpoints/embeddings/schema.js +29 -0
- package/dist/endpoints/models/converters.d.ts +6 -0
- package/dist/endpoints/models/converters.js +42 -0
- package/dist/endpoints/models/handler.d.ts +2 -0
- package/dist/endpoints/models/handler.js +29 -0
- package/dist/endpoints/models/index.d.ts +3 -0
- package/dist/endpoints/models/index.js +3 -0
- package/dist/endpoints/models/schema.d.ts +42 -0
- package/dist/endpoints/models/schema.js +31 -0
- package/dist/endpoints/responses/converters.d.ts +17 -0
- package/dist/endpoints/responses/converters.js +1037 -0
- package/dist/endpoints/responses/handler.d.ts +2 -0
- package/dist/endpoints/responses/handler.js +141 -0
- package/dist/endpoints/responses/index.d.ts +4 -0
- package/dist/endpoints/responses/index.js +4 -0
- package/dist/endpoints/responses/otel.d.ts +6 -0
- package/dist/endpoints/responses/otel.js +225 -0
- package/dist/endpoints/responses/schema.d.ts +2109 -0
- package/dist/endpoints/responses/schema.js +314 -0
- package/dist/endpoints/shared/converters.d.ts +56 -0
- package/dist/endpoints/shared/converters.js +180 -0
- package/dist/endpoints/shared/schema.d.ts +70 -0
- package/dist/endpoints/shared/schema.js +46 -0
- package/dist/errors/ai-sdk.d.ts +2 -0
- package/dist/errors/ai-sdk.js +52 -0
- package/dist/errors/gateway.d.ts +5 -0
- package/dist/errors/gateway.js +13 -0
- package/dist/errors/openai.d.ts +15 -0
- package/dist/errors/openai.js +40 -0
- package/dist/errors/utils.d.ts +24 -0
- package/dist/errors/utils.js +46 -0
- package/dist/gateway.d.ts +11 -0
- package/dist/gateway.js +44 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/lifecycle.d.ts +3 -0
- package/dist/lifecycle.js +114 -0
- package/dist/logger/default.d.ts +4 -0
- package/dist/logger/default.js +81 -0
- package/dist/logger/index.d.ts +11 -0
- package/dist/logger/index.js +25 -0
- package/dist/middleware/common.d.ts +12 -0
- package/dist/middleware/common.js +146 -0
- package/dist/middleware/debug.d.ts +3 -0
- package/dist/middleware/debug.js +27 -0
- package/dist/middleware/matcher.d.ts +28 -0
- package/dist/middleware/matcher.js +118 -0
- package/dist/middleware/utils.d.ts +2 -0
- package/dist/middleware/utils.js +24 -0
- package/dist/models/amazon/index.d.ts +2 -0
- package/dist/models/amazon/index.js +2 -0
- package/dist/models/amazon/middleware.d.ts +3 -0
- package/dist/models/amazon/middleware.js +69 -0
- package/dist/models/amazon/presets.d.ts +345 -0
- package/dist/models/amazon/presets.js +80 -0
- package/dist/models/anthropic/index.d.ts +2 -0
- package/dist/models/anthropic/index.js +2 -0
- package/dist/models/anthropic/middleware.d.ts +5 -0
- package/dist/models/anthropic/middleware.js +128 -0
- package/dist/models/anthropic/presets.d.ts +711 -0
- package/dist/models/anthropic/presets.js +140 -0
- package/dist/models/catalog.d.ts +4 -0
- package/dist/models/catalog.js +8 -0
- package/dist/models/cohere/index.d.ts +2 -0
- package/dist/models/cohere/index.js +2 -0
- package/dist/models/cohere/middleware.d.ts +3 -0
- package/dist/models/cohere/middleware.js +62 -0
- package/dist/models/cohere/presets.d.ts +411 -0
- package/dist/models/cohere/presets.js +134 -0
- package/dist/models/google/index.d.ts +2 -0
- package/dist/models/google/index.js +2 -0
- package/dist/models/google/middleware.d.ts +8 -0
- package/dist/models/google/middleware.js +118 -0
- package/dist/models/google/presets.d.ts +815 -0
- package/dist/models/google/presets.js +184 -0
- package/dist/models/meta/index.d.ts +1 -0
- package/dist/models/meta/index.js +1 -0
- package/dist/models/meta/presets.d.ts +483 -0
- package/dist/models/meta/presets.js +105 -0
- package/dist/models/openai/index.d.ts +2 -0
- package/dist/models/openai/index.js +2 -0
- package/dist/models/openai/middleware.d.ts +4 -0
- package/dist/models/openai/middleware.js +89 -0
- package/dist/models/openai/presets.d.ts +1319 -0
- package/dist/models/openai/presets.js +277 -0
- package/dist/models/types.d.ts +20 -0
- package/dist/models/types.js +100 -0
- package/dist/models/voyage/index.d.ts +2 -0
- package/dist/models/voyage/index.js +2 -0
- package/dist/models/voyage/middleware.d.ts +2 -0
- package/dist/models/voyage/middleware.js +19 -0
- package/dist/models/voyage/presets.d.ts +436 -0
- package/dist/models/voyage/presets.js +85 -0
- package/dist/providers/anthropic/canonical.d.ts +3 -0
- package/dist/providers/anthropic/canonical.js +9 -0
- package/dist/providers/anthropic/index.d.ts +1 -0
- package/dist/providers/anthropic/index.js +1 -0
- package/dist/providers/bedrock/canonical.d.ts +17 -0
- package/dist/providers/bedrock/canonical.js +64 -0
- package/dist/providers/bedrock/index.d.ts +2 -0
- package/dist/providers/bedrock/index.js +2 -0
- package/dist/providers/bedrock/middleware.d.ts +5 -0
- package/dist/providers/bedrock/middleware.js +133 -0
- package/dist/providers/cohere/canonical.d.ts +3 -0
- package/dist/providers/cohere/canonical.js +17 -0
- package/dist/providers/cohere/index.d.ts +1 -0
- package/dist/providers/cohere/index.js +1 -0
- package/dist/providers/groq/canonical.d.ts +3 -0
- package/dist/providers/groq/canonical.js +12 -0
- package/dist/providers/groq/index.d.ts +2 -0
- package/dist/providers/groq/index.js +2 -0
- package/dist/providers/groq/middleware.d.ts +2 -0
- package/dist/providers/groq/middleware.js +30 -0
- package/dist/providers/openai/canonical.d.ts +3 -0
- package/dist/providers/openai/canonical.js +8 -0
- package/dist/providers/openai/index.d.ts +1 -0
- package/dist/providers/openai/index.js +1 -0
- package/dist/providers/registry.d.ts +24 -0
- package/dist/providers/registry.js +103 -0
- package/dist/providers/types.d.ts +7 -0
- package/dist/providers/types.js +11 -0
- package/dist/providers/vertex/canonical.d.ts +3 -0
- package/dist/providers/vertex/canonical.js +8 -0
- package/dist/providers/vertex/index.d.ts +2 -0
- package/dist/providers/vertex/index.js +2 -0
- package/dist/providers/vertex/middleware.d.ts +2 -0
- package/dist/providers/vertex/middleware.js +47 -0
- package/dist/providers/voyage/canonical.d.ts +3 -0
- package/dist/providers/voyage/canonical.js +7 -0
- package/dist/providers/voyage/index.d.ts +1 -0
- package/dist/providers/voyage/index.js +1 -0
- package/dist/telemetry/ai-sdk.d.ts +2 -0
- package/dist/telemetry/ai-sdk.js +31 -0
- package/dist/telemetry/baggage.d.ts +1 -0
- package/dist/telemetry/baggage.js +24 -0
- package/dist/telemetry/fetch.d.ts +2 -0
- package/dist/telemetry/fetch.js +49 -0
- package/dist/telemetry/gen-ai.d.ts +7 -0
- package/dist/telemetry/gen-ai.js +112 -0
- package/dist/telemetry/http.d.ts +3 -0
- package/dist/telemetry/http.js +54 -0
- package/dist/telemetry/index.d.ts +1 -0
- package/dist/telemetry/index.js +1 -0
- package/dist/telemetry/memory.d.ts +2 -0
- package/dist/telemetry/memory.js +43 -0
- package/dist/telemetry/span.d.ts +13 -0
- package/dist/telemetry/span.js +60 -0
- package/dist/types.d.ts +231 -0
- package/dist/types.js +2 -0
- package/dist/utils/body.d.ts +19 -0
- package/dist/utils/body.js +99 -0
- package/dist/utils/env.d.ts +2 -0
- package/dist/utils/env.js +7 -0
- package/dist/utils/headers.d.ts +4 -0
- package/dist/utils/headers.js +22 -0
- package/dist/utils/preset.d.ts +10 -0
- package/dist/utils/preset.js +41 -0
- package/dist/utils/request.d.ts +2 -0
- package/dist/utils/request.js +43 -0
- package/dist/utils/response.d.ts +6 -0
- package/dist/utils/response.js +55 -0
- package/dist/utils/stream.d.ts +9 -0
- package/dist/utils/stream.js +100 -0
- package/dist/utils/url.d.ts +4 -0
- package/dist/utils/url.js +21 -0
- package/package.json +1 -1
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { ResponsesMetadataSchema, ResponsesInputItemSchema } from "../responses/schema";
|
|
3
|
+
/**
|
|
4
|
+
* --- Entities ---
|
|
5
|
+
*/
|
|
6
|
+
export const ConversationItemSchema = z
|
|
7
|
+
.object({
|
|
8
|
+
id: z.string(),
|
|
9
|
+
object: z.literal("conversation.item"),
|
|
10
|
+
created_at: z.number().int(),
|
|
11
|
+
})
|
|
12
|
+
.loose()
|
|
13
|
+
.and(ResponsesInputItemSchema);
|
|
14
|
+
export const ConversationSchema = z.object({
|
|
15
|
+
id: z.string(),
|
|
16
|
+
object: z.literal("conversation"),
|
|
17
|
+
created_at: z.number().int(),
|
|
18
|
+
metadata: ResponsesMetadataSchema,
|
|
19
|
+
});
|
|
20
|
+
export const ConversationDeletedSchema = z.object({
|
|
21
|
+
id: z.string(),
|
|
22
|
+
deleted: z.boolean(),
|
|
23
|
+
object: z.literal("conversation.deleted"),
|
|
24
|
+
});
|
|
25
|
+
/**
|
|
26
|
+
* --- API ---
|
|
27
|
+
*/
|
|
28
|
+
export const ConversationCreateParamsSchema = z.object({
|
|
29
|
+
items: z.array(ResponsesInputItemSchema).max(1000).optional(),
|
|
30
|
+
metadata: ResponsesMetadataSchema.optional(),
|
|
31
|
+
});
|
|
32
|
+
export const ConversationUpdateBodySchema = z.object({
|
|
33
|
+
metadata: ResponsesMetadataSchema,
|
|
34
|
+
});
|
|
35
|
+
export const ConversationItemsAddBodySchema = z.object({
|
|
36
|
+
items: z.array(ResponsesInputItemSchema).max(1000),
|
|
37
|
+
});
|
|
38
|
+
export const ConversationItemListSchema = z.object({
|
|
39
|
+
object: z.literal("list"),
|
|
40
|
+
data: z.array(ConversationItemSchema),
|
|
41
|
+
has_more: z.boolean(),
|
|
42
|
+
first_id: z.string().optional(),
|
|
43
|
+
last_id: z.string().optional(),
|
|
44
|
+
});
|
|
45
|
+
export const ConversationListSchema = z.object({
|
|
46
|
+
object: z.literal("list"),
|
|
47
|
+
data: z.array(ConversationSchema),
|
|
48
|
+
has_more: z.boolean(),
|
|
49
|
+
first_id: z.string().optional(),
|
|
50
|
+
last_id: z.string().optional(),
|
|
51
|
+
});
|
|
52
|
+
export const ConversationItemListParamsSchema = z.object({
|
|
53
|
+
after: z.string().optional(),
|
|
54
|
+
limit: z.coerce.number().int().min(0).max(1000).default(20),
|
|
55
|
+
order: z.enum(["asc", "desc"]).default("desc"),
|
|
56
|
+
});
|
|
57
|
+
export const ConversationListParamsSchema = z.preprocess((input) => {
|
|
58
|
+
if (typeof input !== "object" || input === null)
|
|
59
|
+
return input;
|
|
60
|
+
const metadata = {};
|
|
61
|
+
const rest = { ...input };
|
|
62
|
+
for (const [key, value] of Object.entries(input)) {
|
|
63
|
+
if (key.startsWith("metadata.")) {
|
|
64
|
+
metadata[key.slice(9)] = String(value);
|
|
65
|
+
delete rest[key];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (Object.keys(metadata).length > 0) {
|
|
69
|
+
rest["metadata"] = metadata;
|
|
70
|
+
}
|
|
71
|
+
return rest;
|
|
72
|
+
}, ConversationItemListParamsSchema.extend({
|
|
73
|
+
metadata: ResponsesMetadataSchema.optional(),
|
|
74
|
+
}));
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type PgPool, type PostgresJsSql } from "./postgres";
|
|
2
|
+
import { type BunSql, type DialectConfig, type QueryExecutor, type SqlDialect } from "./types";
|
|
3
|
+
export declare const GrepTimeDialectConfig: DialectConfig;
|
|
4
|
+
export declare class GrepTimeDialect implements SqlDialect {
|
|
5
|
+
readonly executor: QueryExecutor;
|
|
6
|
+
readonly config: DialectConfig;
|
|
7
|
+
constructor(options: {
|
|
8
|
+
client: PgPool | PostgresJsSql | BunSql;
|
|
9
|
+
});
|
|
10
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { PostgresDialect, PostgresDialectConfig, isBunSql, isPgPool, } from "./postgres";
|
|
2
|
+
import {} from "./types";
|
|
3
|
+
import { createParamsMapper, dateToBigInt, escapeSqlString, jsonStringify } from "./utils";
|
|
4
|
+
const GrepTimeBase = {
|
|
5
|
+
types: {
|
|
6
|
+
varchar: "VARCHAR",
|
|
7
|
+
json: "JSON",
|
|
8
|
+
timestamp: "TIMESTAMP",
|
|
9
|
+
index: "TIME",
|
|
10
|
+
},
|
|
11
|
+
};
|
|
12
|
+
export const GrepTimeDialectConfig = Object.assign({}, PostgresDialectConfig, GrepTimeBase, {
|
|
13
|
+
/**
|
|
14
|
+
* GreptimeDB has a bug where it can return invalid JSON strings
|
|
15
|
+
* containing Rust-style Unicode escapes like \u{xxxx} instead of standard JSON escapes \uxxxx.
|
|
16
|
+
* https://github.com/GreptimeTeam/greptimedb/issues/7808
|
|
17
|
+
*
|
|
18
|
+
* To prevent the Postgres drivers (postgresjs, pg, bun:sql) from crashing when they attempt
|
|
19
|
+
* to auto-parse this invalid JSON, we cast the JSON column to a raw STRING on the wire.
|
|
20
|
+
*
|
|
21
|
+
* Our storage layer then manually normalizes these Rust escapes before calling JSON.parse().
|
|
22
|
+
* See: src/endpoints/conversations/storage/dialects/utils.ts -> normalizeJsonUnicodeEscapes
|
|
23
|
+
*/
|
|
24
|
+
selectJson: (c) => `${c}::STRING`,
|
|
25
|
+
jsonExtract: (c, k) => `json_get_string(${c}, '${escapeSqlString(k)}')`,
|
|
26
|
+
upsertSuffix: undefined,
|
|
27
|
+
supportCreateIndexIfNotExists: true,
|
|
28
|
+
limitAsLiteral: true,
|
|
29
|
+
partitionClause: (cols) => {
|
|
30
|
+
const col = cols[0];
|
|
31
|
+
return (`PARTITION ON COLUMNS (${col}) (` +
|
|
32
|
+
`${col} < '1', ` +
|
|
33
|
+
`${col} >= 'f', ` +
|
|
34
|
+
`${col} >= '1' AND ${col} < '2', ` +
|
|
35
|
+
`${col} >= '2' AND ${col} < '3', ` +
|
|
36
|
+
`${col} >= '3' AND ${col} < '4', ` +
|
|
37
|
+
`${col} >= '4' AND ${col} < '5', ` +
|
|
38
|
+
`${col} >= '5' AND ${col} < '6', ` +
|
|
39
|
+
`${col} >= '6' AND ${col} < '7', ` +
|
|
40
|
+
`${col} >= '7' AND ${col} < '8', ` +
|
|
41
|
+
`${col} >= '8' AND ${col} < '9', ` +
|
|
42
|
+
`${col} >= '9' AND ${col} < 'a', ` +
|
|
43
|
+
`${col} >= 'a' AND ${col} < 'b', ` +
|
|
44
|
+
`${col} >= 'b' AND ${col} < 'c', ` +
|
|
45
|
+
`${col} >= 'c' AND ${col} < 'd', ` +
|
|
46
|
+
`${col} >= 'd' AND ${col} < 'e', ` +
|
|
47
|
+
`${col} >= 'e' AND ${col} < 'f')`);
|
|
48
|
+
},
|
|
49
|
+
types: GrepTimeBase.types,
|
|
50
|
+
});
|
|
51
|
+
const pad = (n, l = 2) => n.toString().padStart(l, "0");
|
|
52
|
+
function dateToGreptimeString(v) {
|
|
53
|
+
if (v instanceof Date) {
|
|
54
|
+
return `${v.getUTCFullYear()}-${pad(v.getUTCMonth() + 1)}-${pad(v.getUTCDate())} ${pad(v.getUTCHours())}:${pad(v.getUTCMinutes())}:${pad(v.getUTCSeconds())}.${pad(v.getUTCMilliseconds(), 3)}`;
|
|
55
|
+
}
|
|
56
|
+
return v;
|
|
57
|
+
}
|
|
58
|
+
// GreptimeDB is strictly typed over the Postgres wire protocol, and each driver
|
|
59
|
+
// coerces JavaScript types differently. There is no unified parameter format:
|
|
60
|
+
//
|
|
61
|
+
// 1. Timestamps:
|
|
62
|
+
// - `pg` requires a strictly formatted string (YYYY-MM-DD HH:mm:ss.SSS).
|
|
63
|
+
// It fails on BigInt.
|
|
64
|
+
// - `postgresjs` requires a BigInt (milliseconds). It parses strings into ISO
|
|
65
|
+
// formats which GreptimeDB rejects.
|
|
66
|
+
// - `Bun.SQL` is flexible, but we use BigInt for consistency with postgresjs.
|
|
67
|
+
//
|
|
68
|
+
// 2. JSON:
|
|
69
|
+
// - GreptimeDB rejects plain strings for JSON, expecting a bytea-compatible format.
|
|
70
|
+
// - `pg` and `Bun.SQL` require the JSON string to be wrapped in a Uint8Array (binary).
|
|
71
|
+
// - `postgresjs` works with plain JSON strings.
|
|
72
|
+
const mapParams = createParamsMapper([dateToBigInt, (v) => jsonStringify(v)]);
|
|
73
|
+
const mapParamsBun = createParamsMapper([dateToBigInt, (v) => jsonStringify(v, true)]);
|
|
74
|
+
const mapParamsPg = createParamsMapper([dateToGreptimeString, (v) => jsonStringify(v, true)]);
|
|
75
|
+
export class GrepTimeDialect {
|
|
76
|
+
executor;
|
|
77
|
+
config = GrepTimeDialectConfig;
|
|
78
|
+
constructor(options) {
|
|
79
|
+
const { client } = options;
|
|
80
|
+
const dialect = new PostgresDialect({
|
|
81
|
+
client,
|
|
82
|
+
config: this.config,
|
|
83
|
+
mapParams: isPgPool(client) ? mapParamsPg : isBunSql(client) ? mapParamsBun : mapParams,
|
|
84
|
+
});
|
|
85
|
+
this.executor = dialect.executor;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Pool as Mysql2Pool } from "mysql2/promise";
|
|
2
|
+
import type { BunSql, DialectConfig, QueryExecutor, SqlDialect } from "./types";
|
|
3
|
+
export type { Mysql2Pool };
|
|
4
|
+
export declare const MySQLDialectConfig: DialectConfig;
|
|
5
|
+
export declare class MysqlDialect implements SqlDialect {
|
|
6
|
+
readonly executor: QueryExecutor;
|
|
7
|
+
readonly config: DialectConfig;
|
|
8
|
+
constructor(options: {
|
|
9
|
+
client: Mysql2Pool | BunSql;
|
|
10
|
+
config?: DialectConfig;
|
|
11
|
+
});
|
|
12
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { createParamsMapper, dateToNumber, escapeSqlString, jsonStringify } from "./utils";
|
|
2
|
+
const mapParams = createParamsMapper([dateToNumber, jsonStringify]);
|
|
3
|
+
export const MySQLDialectConfig = {
|
|
4
|
+
placeholder: (_i) => "?",
|
|
5
|
+
quote: (i) => `\`${i}\``,
|
|
6
|
+
selectJson: (c) => c,
|
|
7
|
+
jsonExtract: (c, k) => `JSON_EXTRACT(${c}, '$.${escapeSqlString(k)}')`,
|
|
8
|
+
upsertSuffix: (q, _pk, cols) => `ON DUPLICATE KEY UPDATE ${cols.map((c) => `${q(c)} = VALUES(${q(c)})`).join(", ")}`,
|
|
9
|
+
limitAsLiteral: true,
|
|
10
|
+
supportCreateIndexIfNotExists: false,
|
|
11
|
+
types: {
|
|
12
|
+
varchar: "VARCHAR",
|
|
13
|
+
json: "JSON",
|
|
14
|
+
timestamp: "BIGINT",
|
|
15
|
+
index: "B-TREE",
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
function isMysql2(client) {
|
|
19
|
+
const c = client;
|
|
20
|
+
return !!client && typeof c["execute"] === "function" && typeof c["getConnection"] === "function";
|
|
21
|
+
}
|
|
22
|
+
function isBunSql(client) {
|
|
23
|
+
const c = client;
|
|
24
|
+
return !!client && typeof c["unsafe"] === "function" && typeof c["transaction"] === "function";
|
|
25
|
+
}
|
|
26
|
+
function createMysql2Executor(pool) {
|
|
27
|
+
const executor = {
|
|
28
|
+
async all(sql, params) {
|
|
29
|
+
const [rows] = await pool.execute(sql, mapParams(params));
|
|
30
|
+
return rows;
|
|
31
|
+
},
|
|
32
|
+
async get(sql, params) {
|
|
33
|
+
const [rows] = await pool.execute(sql, mapParams(params));
|
|
34
|
+
return rows?.[0];
|
|
35
|
+
},
|
|
36
|
+
async run(sql, params) {
|
|
37
|
+
const [res] = await pool.execute(sql, mapParams(params));
|
|
38
|
+
const header = res;
|
|
39
|
+
return { changes: header.affectedRows ?? 0 };
|
|
40
|
+
},
|
|
41
|
+
async transaction(fn) {
|
|
42
|
+
const conn = await pool.getConnection();
|
|
43
|
+
await conn.beginTransaction();
|
|
44
|
+
const txExecutor = {
|
|
45
|
+
async all(sql, params) {
|
|
46
|
+
const [rows] = await conn.execute(sql, mapParams(params));
|
|
47
|
+
return rows;
|
|
48
|
+
},
|
|
49
|
+
async get(sql, params) {
|
|
50
|
+
const [rows] = await conn.execute(sql, mapParams(params));
|
|
51
|
+
return rows?.[0];
|
|
52
|
+
},
|
|
53
|
+
async run(sql, params) {
|
|
54
|
+
const [res] = await conn.execute(sql, mapParams(params));
|
|
55
|
+
const header = res;
|
|
56
|
+
return { changes: header.affectedRows ?? 0 };
|
|
57
|
+
},
|
|
58
|
+
transaction(txCallback) {
|
|
59
|
+
return txCallback(txExecutor);
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
try {
|
|
63
|
+
const result = await fn(txExecutor);
|
|
64
|
+
await conn.commit();
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
await conn.rollback();
|
|
69
|
+
throw err;
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
conn.release();
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
return executor;
|
|
77
|
+
}
|
|
78
|
+
function createBunMysqlExecutor(sql) {
|
|
79
|
+
const executor = {
|
|
80
|
+
all(query, params) {
|
|
81
|
+
return sql.unsafe(query, mapParams(params));
|
|
82
|
+
},
|
|
83
|
+
async get(query, params) {
|
|
84
|
+
const rows = await sql.unsafe(query, mapParams(params));
|
|
85
|
+
return rows?.[0];
|
|
86
|
+
},
|
|
87
|
+
async run(query, params) {
|
|
88
|
+
const res = (await sql.unsafe(query, mapParams(params)));
|
|
89
|
+
const result = res;
|
|
90
|
+
return { changes: result.affectedRows ?? result.count ?? 0 };
|
|
91
|
+
},
|
|
92
|
+
transaction(fn) {
|
|
93
|
+
return sql.transaction((tx) => {
|
|
94
|
+
const txExecutor = createBunMysqlExecutor(tx);
|
|
95
|
+
txExecutor.transaction = (f) => f(txExecutor);
|
|
96
|
+
return fn(txExecutor);
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
return executor;
|
|
101
|
+
}
|
|
102
|
+
export class MysqlDialect {
|
|
103
|
+
executor;
|
|
104
|
+
config;
|
|
105
|
+
constructor(options) {
|
|
106
|
+
const { client, config = MySQLDialectConfig } = options;
|
|
107
|
+
this.config = config;
|
|
108
|
+
if (isMysql2(client)) {
|
|
109
|
+
this.executor = createMysql2Executor(client);
|
|
110
|
+
}
|
|
111
|
+
else if (isBunSql(client)) {
|
|
112
|
+
this.executor = createBunMysqlExecutor(client);
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
throw new Error("Unsupported MySQL client");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Pool as PgPool } from "pg";
|
|
2
|
+
import type { Sql as PostgresJsSql } from "postgres";
|
|
3
|
+
import { type BunSql, type DialectConfig, type QueryExecutor, type SqlDialect } from "./types";
|
|
4
|
+
export type { PostgresJsSql, PgPool };
|
|
5
|
+
export declare const PostgresDialectConfig: DialectConfig;
|
|
6
|
+
export declare function isPgPool(client: unknown): client is PgPool;
|
|
7
|
+
export declare function isBunSql(client: unknown): client is BunSql;
|
|
8
|
+
export declare class PostgresDialect implements SqlDialect {
|
|
9
|
+
readonly executor: QueryExecutor;
|
|
10
|
+
readonly config: DialectConfig;
|
|
11
|
+
constructor(options: {
|
|
12
|
+
client: PgPool | PostgresJsSql | BunSql;
|
|
13
|
+
config?: DialectConfig;
|
|
14
|
+
mapParams?: (params?: unknown[]) => (string | number | bigint | boolean | null)[];
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { LRUCache } from "lru-cache";
|
|
2
|
+
import {} from "./types";
|
|
3
|
+
import { createParamsMapper, dateToNumber, escapeSqlString } from "./utils";
|
|
4
|
+
const defaultMapParams = createParamsMapper([dateToNumber]);
|
|
5
|
+
export const PostgresDialectConfig = {
|
|
6
|
+
placeholder: (i) => `$${i + 1}`,
|
|
7
|
+
quote: (i) => `"${i}"`,
|
|
8
|
+
selectJson: (c) => c,
|
|
9
|
+
jsonExtract: (c, k) => `${c}->>'${escapeSqlString(k)}'`,
|
|
10
|
+
upsertSuffix: (q, pk, cols) => `ON CONFLICT (${pk.map((c) => q(c)).join(", ")}) DO UPDATE SET ${cols
|
|
11
|
+
.map((c) => `${q(c)} = EXCLUDED.${q(c)}`)
|
|
12
|
+
.join(", ")}`,
|
|
13
|
+
supportCreateIndexIfNotExists: true,
|
|
14
|
+
types: {
|
|
15
|
+
varchar: "VARCHAR",
|
|
16
|
+
json: "JSONB",
|
|
17
|
+
timestamp: "BIGINT",
|
|
18
|
+
index: "BRIN",
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
const MAX_CACHE_SIZE = 100;
|
|
22
|
+
export function isPgPool(client) {
|
|
23
|
+
const c = client;
|
|
24
|
+
return !!client && typeof c["query"] === "function" && typeof c["connect"] === "function";
|
|
25
|
+
}
|
|
26
|
+
function isPostgresJs(client) {
|
|
27
|
+
const c = client;
|
|
28
|
+
return (!!client &&
|
|
29
|
+
typeof c["unsafe"] === "function" &&
|
|
30
|
+
typeof c["begin"] === "function" &&
|
|
31
|
+
!("transaction" in c));
|
|
32
|
+
}
|
|
33
|
+
export function isBunSql(client) {
|
|
34
|
+
const c = client;
|
|
35
|
+
return !!client && typeof c["unsafe"] === "function" && typeof c["transaction"] === "function";
|
|
36
|
+
}
|
|
37
|
+
function createPgExecutor(pool, mapParams) {
|
|
38
|
+
const cache = new LRUCache({ max: MAX_CACHE_SIZE });
|
|
39
|
+
let count = 0;
|
|
40
|
+
const getQuery = (sql, values) => {
|
|
41
|
+
let name = cache.get(sql);
|
|
42
|
+
if (!name) {
|
|
43
|
+
name = `q_${count++}`;
|
|
44
|
+
cache.set(sql, name);
|
|
45
|
+
}
|
|
46
|
+
return { name, text: sql, values };
|
|
47
|
+
};
|
|
48
|
+
const executor = {
|
|
49
|
+
async all(sql, params) {
|
|
50
|
+
const p = mapParams(params);
|
|
51
|
+
const res = await pool.query(getQuery(sql, p?.length > 0 ? p : undefined));
|
|
52
|
+
return res.rows;
|
|
53
|
+
},
|
|
54
|
+
async get(sql, params) {
|
|
55
|
+
const p = mapParams(params);
|
|
56
|
+
const res = await pool.query(getQuery(sql, p?.length > 0 ? p : undefined));
|
|
57
|
+
return res.rows?.[0];
|
|
58
|
+
},
|
|
59
|
+
async run(sql, params) {
|
|
60
|
+
const p = mapParams(params);
|
|
61
|
+
const res = await pool.query(getQuery(sql, p?.length > 0 ? p : undefined));
|
|
62
|
+
return { changes: res.rowCount ?? 0 };
|
|
63
|
+
},
|
|
64
|
+
async transaction(fn) {
|
|
65
|
+
const client = await pool.connect();
|
|
66
|
+
await client.query("BEGIN");
|
|
67
|
+
const txExecutor = {
|
|
68
|
+
async all(sql, params) {
|
|
69
|
+
const p = mapParams(params);
|
|
70
|
+
const res = await client.query(getQuery(sql, p?.length > 0 ? p : undefined));
|
|
71
|
+
return res.rows;
|
|
72
|
+
},
|
|
73
|
+
async get(sql, params) {
|
|
74
|
+
const p = mapParams(params);
|
|
75
|
+
const res = await client.query(getQuery(sql, p?.length > 0 ? p : undefined));
|
|
76
|
+
return res.rows?.[0];
|
|
77
|
+
},
|
|
78
|
+
async run(sql, params) {
|
|
79
|
+
const p = mapParams(params);
|
|
80
|
+
const res = await client.query(getQuery(sql, p?.length > 0 ? p : undefined));
|
|
81
|
+
return { changes: res.rowCount ?? 0 };
|
|
82
|
+
},
|
|
83
|
+
transaction(txCallback) {
|
|
84
|
+
return txCallback(txExecutor);
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
try {
|
|
88
|
+
const result = await fn(txExecutor);
|
|
89
|
+
await client.query("COMMIT");
|
|
90
|
+
return result;
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
await client.query("ROLLBACK");
|
|
94
|
+
throw err;
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
client.release();
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
return executor;
|
|
102
|
+
}
|
|
103
|
+
function createPostgresJsExecutor(sql, mapParams) {
|
|
104
|
+
const executor = {
|
|
105
|
+
async all(query, params) {
|
|
106
|
+
const p = mapParams(params);
|
|
107
|
+
return (await sql.unsafe(query, (p?.length > 0 ? p : undefined), { prepare: true }));
|
|
108
|
+
},
|
|
109
|
+
async get(query, params) {
|
|
110
|
+
const p = mapParams(params);
|
|
111
|
+
const rows = await sql.unsafe(query, (p?.length > 0 ? p : undefined), { prepare: true });
|
|
112
|
+
return rows?.[0];
|
|
113
|
+
},
|
|
114
|
+
async run(query, params) {
|
|
115
|
+
const p = mapParams(params);
|
|
116
|
+
const res = await sql.unsafe(query, (p?.length > 0 ? p : undefined), { prepare: true });
|
|
117
|
+
const result = res;
|
|
118
|
+
return { changes: result.count ?? 0 };
|
|
119
|
+
},
|
|
120
|
+
async transaction(fn) {
|
|
121
|
+
return (await sql.begin((tx) => {
|
|
122
|
+
const txExecutor = createPostgresJsExecutor(tx, mapParams);
|
|
123
|
+
txExecutor.transaction = (f) => f(txExecutor);
|
|
124
|
+
return fn(txExecutor);
|
|
125
|
+
}));
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
return executor;
|
|
129
|
+
}
|
|
130
|
+
function createBunPostgresExecutor(sql, mapParams) {
|
|
131
|
+
const executor = {
|
|
132
|
+
all(query, params) {
|
|
133
|
+
const p = mapParams(params);
|
|
134
|
+
return sql.unsafe(query, p?.length > 0 ? p : undefined);
|
|
135
|
+
},
|
|
136
|
+
async get(query, params) {
|
|
137
|
+
const p = mapParams(params);
|
|
138
|
+
const rows = await sql.unsafe(query, p?.length > 0 ? p : undefined);
|
|
139
|
+
return rows?.[0];
|
|
140
|
+
},
|
|
141
|
+
async run(query, params) {
|
|
142
|
+
const p = mapParams(params);
|
|
143
|
+
const res = (await sql.unsafe(query, p?.length > 0 ? p : undefined));
|
|
144
|
+
const result = res;
|
|
145
|
+
let changes = result.affectedRows ?? result.count ?? 0;
|
|
146
|
+
// When Bun.SQL is used with GreptimeDB, mutation responses over the Postgres wire
|
|
147
|
+
// protocol don't populate `count` or `affectedRows`, but they do provide a command
|
|
148
|
+
// string like "OK 1"
|
|
149
|
+
if (changes === 0 && result.command?.startsWith("OK ")) {
|
|
150
|
+
const parsed = parseInt(result.command.slice(3), 10);
|
|
151
|
+
if (!isNaN(parsed))
|
|
152
|
+
changes = parsed;
|
|
153
|
+
}
|
|
154
|
+
return { changes };
|
|
155
|
+
},
|
|
156
|
+
transaction(fn) {
|
|
157
|
+
return sql.transaction((tx) => {
|
|
158
|
+
const txExecutor = createBunPostgresExecutor(tx, mapParams);
|
|
159
|
+
txExecutor.transaction = (f) => f(txExecutor);
|
|
160
|
+
return fn(txExecutor);
|
|
161
|
+
});
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
return executor;
|
|
165
|
+
}
|
|
166
|
+
export class PostgresDialect {
|
|
167
|
+
executor;
|
|
168
|
+
config;
|
|
169
|
+
constructor(options) {
|
|
170
|
+
const { client, config = PostgresDialectConfig, mapParams = defaultMapParams } = options;
|
|
171
|
+
this.config = config;
|
|
172
|
+
if (isPgPool(client)) {
|
|
173
|
+
this.executor = createPgExecutor(client, mapParams);
|
|
174
|
+
}
|
|
175
|
+
else if (isBunSql(client)) {
|
|
176
|
+
this.executor = createBunPostgresExecutor(client, mapParams);
|
|
177
|
+
}
|
|
178
|
+
else if (isPostgresJs(client)) {
|
|
179
|
+
this.executor = createPostgresJsExecutor(client, mapParams);
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
throw new Error("Unsupported Postgres client");
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Client as LibsqlClient } from "@libsql/client";
|
|
2
|
+
import type { Database as BetterSqlite3Database } from "better-sqlite3";
|
|
3
|
+
import type { BunSql, DialectConfig, QueryExecutor, SqlDialect } from "./types";
|
|
4
|
+
export declare const SQLiteDialectConfig: DialectConfig;
|
|
5
|
+
export declare class SqliteDialect implements SqlDialect {
|
|
6
|
+
readonly executor: QueryExecutor;
|
|
7
|
+
readonly config: DialectConfig;
|
|
8
|
+
constructor(options: {
|
|
9
|
+
client: BetterSqlite3Database | LibsqlClient | BunSql;
|
|
10
|
+
});
|
|
11
|
+
}
|