feat: Upgrade to Astro with full PDPA compliance
PDPA Features: ✅ Cookie consent banner ✅ Consent logging API ✅ Admin dashboard ✅ Privacy Policy ✅ Terms & Conditions Technical: ✅ Astro 5.x + Tailwind v4 ✅ Docker on port 80 ✅ SQLite database ✅ 15 pages built Ready for Easypanel deployment.
This commit is contained in:
1 parent
668f69048f
commit
77ac4d2d05
13719 files changed
+307487
-25765
No files matched your search
+93
@@ -0,0 +1,93 @@
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var driver_exports = {};
|
||||
__export(driver_exports, {
|
||||
TiDBServerlessDatabase: () => TiDBServerlessDatabase,
|
||||
drizzle: () => drizzle
|
||||
});
|
||||
module.exports = __toCommonJS(driver_exports);
|
||||
var import_serverless = require("@tidbcloud/serverless");
|
||||
var import_entity = require("../entity.cjs");
|
||||
var import_logger = require("../logger.cjs");
|
||||
var import_db = require("../mysql-core/db.cjs");
|
||||
var import_dialect = require("../mysql-core/dialect.cjs");
|
||||
var import_relations = require("../relations.cjs");
|
||||
var import_utils = require("../utils.cjs");
|
||||
var import_session = require("./session.cjs");
|
||||
class TiDBServerlessDatabase extends import_db.MySqlDatabase {
|
||||
static [import_entity.entityKind] = "TiDBServerlessDatabase";
|
||||
}
|
||||
function construct(client, config = {}) {
|
||||
const dialect = new import_dialect.MySqlDialect({ casing: config.casing });
|
||||
let logger;
|
||||
if (config.logger === true) {
|
||||
logger = new import_logger.DefaultLogger();
|
||||
} else if (config.logger !== false) {
|
||||
logger = config.logger;
|
||||
}
|
||||
let schema;
|
||||
if (config.schema) {
|
||||
const tablesConfig = (0, import_relations.extractTablesRelationalConfig)(
|
||||
config.schema,
|
||||
import_relations.createTableRelationsHelpers
|
||||
);
|
||||
schema = {
|
||||
fullSchema: config.schema,
|
||||
schema: tablesConfig.tables,
|
||||
tableNamesMap: tablesConfig.tableNamesMap
|
||||
};
|
||||
}
|
||||
const session = new import_session.TiDBServerlessSession(client, dialect, void 0, schema, { logger, cache: config.cache });
|
||||
const db = new TiDBServerlessDatabase(dialect, session, schema, "default");
|
||||
db.$client = client;
|
||||
db.$cache = config.cache;
|
||||
if (db.$cache) {
|
||||
db.$cache["invalidate"] = config.cache?.onMutate;
|
||||
}
|
||||
return db;
|
||||
}
|
||||
function drizzle(...params) {
|
||||
if (typeof params[0] === "string") {
|
||||
const instance = (0, import_serverless.connect)({
|
||||
url: params[0]
|
||||
});
|
||||
return construct(instance, params[1]);
|
||||
}
|
||||
if ((0, import_utils.isConfig)(params[0])) {
|
||||
const { connection, client, ...drizzleConfig } = params[0];
|
||||
if (client) return construct(client, drizzleConfig);
|
||||
const instance = typeof connection === "string" ? (0, import_serverless.connect)({
|
||||
url: connection
|
||||
}) : (0, import_serverless.connect)(connection);
|
||||
return construct(instance, drizzleConfig);
|
||||
}
|
||||
return construct(params[0], params[1]);
|
||||
}
|
||||
((drizzle2) => {
|
||||
function mock(config) {
|
||||
return construct({}, config);
|
||||
}
|
||||
drizzle2.mock = mock;
|
||||
})(drizzle || (drizzle = {}));
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
TiDBServerlessDatabase,
|
||||
drizzle
|
||||
});
|
||||
//# sourceMappingURL=driver.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/tidb-serverless/driver.ts"],"sourcesContent":["import { type Config, connect, type Connection } from '@tidbcloud/serverless';\nimport { entityKind } from '~/entity.ts';\nimport type { Logger } from '~/logger.ts';\nimport { DefaultLogger } from '~/logger.ts';\nimport { MySqlDatabase } from '~/mysql-core/db.ts';\nimport { MySqlDialect } from '~/mysql-core/dialect.ts';\nimport {\n\tcreateTableRelationsHelpers,\n\textractTablesRelationalConfig,\n\ttype RelationalSchemaConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport { type DrizzleConfig, isConfig } from '~/utils.ts';\nimport type { TiDBServerlessPreparedQueryHKT, TiDBServerlessQueryResultHKT } from './session.ts';\nimport { TiDBServerlessSession } from './session.ts';\n\nexport interface TiDBServerlessSDriverOptions {\n\tlogger?: Logger;\n\tcache?: Cache;\n}\n\nexport class TiDBServerlessDatabase<\n\tTSchema extends Record<string, unknown> = Record<string, never>,\n> extends MySqlDatabase<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TSchema> {\n\tstatic override readonly [entityKind]: string = 'TiDBServerlessDatabase';\n}\n\nfunction construct<TSchema extends Record<string, unknown> = Record<string, never>>(\n\tclient: Connection,\n\tconfig: DrizzleConfig<TSchema> = {},\n): TiDBServerlessDatabase<TSchema> & {\n\t$client: Connection;\n} {\n\tconst dialect = new MySqlDialect({ casing: config.casing });\n\tlet logger;\n\tif (config.logger === true) {\n\t\tlogger = new DefaultLogger();\n\t} else if (config.logger !== false) {\n\t\tlogger = config.logger;\n\t}\n\n\tlet schema: RelationalSchemaConfig<TablesRelationalConfig> | undefined;\n\tif (config.schema) {\n\t\tconst tablesConfig = extractTablesRelationalConfig(\n\t\t\tconfig.schema,\n\t\t\tcreateTableRelationsHelpers,\n\t\t);\n\t\tschema = {\n\t\t\tfullSchema: config.schema,\n\t\t\tschema: tablesConfig.tables,\n\t\t\ttableNamesMap: tablesConfig.tableNamesMap,\n\t\t};\n\t}\n\n\tconst session = new TiDBServerlessSession(client, dialect, undefined, schema, { logger, cache: config.cache });\n\tconst db = new TiDBServerlessDatabase(dialect, session, schema as any, 'default') as TiDBServerlessDatabase<TSchema>;\n\t(<any> db).$client = client;\n\t(<any> db).$cache = config.cache;\n\tif ((<any> db).$cache) {\n\t\t(<any> db).$cache['invalidate'] = config.cache?.onMutate;\n\t}\n\n\treturn db as any;\n}\n\nexport function drizzle<\n\tTSchema extends Record<string, unknown> = Record<string, never>,\n\tTClient extends Connection = Connection,\n>(\n\t...params: [\n\t\tTClient | string,\n\t] | [\n\t\tTClient | string,\n\t\tDrizzleConfig<TSchema>,\n\t] | [\n\t\t& ({\n\t\t\tconnection: string | Config;\n\t\t} | {\n\t\t\tclient: TClient;\n\t\t})\n\t\t& DrizzleConfig<TSchema>,\n\t]\n): TiDBServerlessDatabase<TSchema> & {\n\t$client: TClient;\n} {\n\tif (typeof params[0] === 'string') {\n\t\tconst instance = connect({\n\t\t\turl: params[0],\n\t\t});\n\n\t\treturn construct(instance, params[1]) as any;\n\t}\n\n\tif (isConfig(params[0])) {\n\t\tconst { connection, client, ...drizzleConfig } = params[0] as\n\t\t\t& { connection?: Config | string; client?: TClient }\n\t\t\t& DrizzleConfig<TSchema>;\n\n\t\tif (client) return construct(client, drizzleConfig) as any;\n\n\t\tconst instance = typeof connection === 'string'\n\t\t\t? connect({\n\t\t\t\turl: connection,\n\t\t\t})\n\t\t\t: connect(connection!);\n\n\t\treturn construct(instance, drizzleConfig) as any;\n\t}\n\n\treturn construct(params[0] as TClient, params[1] as DrizzleConfig<TSchema> | undefined) as any;\n}\n\nexport namespace drizzle {\n\texport function mock<TSchema extends Record<string, unknown> = Record<string, never>>(\n\t\tconfig?: DrizzleConfig<TSchema>,\n\t): TiDBServerlessDatabase<TSchema> & {\n\t\t$client: '$client is not available on drizzle.mock()';\n\t} {\n\t\treturn construct({} as any, config) as any;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAsD;AACtD,oBAA2B;AAE3B,oBAA8B;AAC9B,gBAA8B;AAC9B,qBAA6B;AAC7B,uBAKO;AACP,mBAA6C;AAE7C,qBAAsC;AAO/B,MAAM,+BAEH,wBAAqF;AAAA,EAC9F,QAA0B,wBAAU,IAAY;AACjD;AAEA,SAAS,UACR,QACA,SAAiC,CAAC,GAGjC;AACD,QAAM,UAAU,IAAI,4BAAa,EAAE,QAAQ,OAAO,OAAO,CAAC;AAC1D,MAAI;AACJ,MAAI,OAAO,WAAW,MAAM;AAC3B,aAAS,IAAI,4BAAc;AAAA,EAC5B,WAAW,OAAO,WAAW,OAAO;AACnC,aAAS,OAAO;AAAA,EACjB;AAEA,MAAI;AACJ,MAAI,OAAO,QAAQ;AAClB,UAAM,mBAAe;AAAA,MACpB,OAAO;AAAA,MACP;AAAA,IACD;AACA,aAAS;AAAA,MACR,YAAY,OAAO;AAAA,MACnB,QAAQ,aAAa;AAAA,MACrB,eAAe,aAAa;AAAA,IAC7B;AAAA,EACD;AAEA,QAAM,UAAU,IAAI,qCAAsB,QAAQ,SAAS,QAAW,QAAQ,EAAE,QAAQ,OAAO,OAAO,MAAM,CAAC;AAC7G,QAAM,KAAK,IAAI,uBAAuB,SAAS,SAAS,QAAe,SAAS;AAChF,EAAO,GAAI,UAAU;AACrB,EAAO,GAAI,SAAS,OAAO;AAC3B,MAAW,GAAI,QAAQ;AACtB,IAAO,GAAI,OAAO,YAAY,IAAI,OAAO,OAAO;AAAA,EACjD;AAEA,SAAO;AACR;AAEO,SAAS,WAIZ,QAeF;AACD,MAAI,OAAO,OAAO,CAAC,MAAM,UAAU;AAClC,UAAM,eAAW,2BAAQ;AAAA,MACxB,KAAK,OAAO,CAAC;AAAA,IACd,CAAC;AAED,WAAO,UAAU,UAAU,OAAO,CAAC,CAAC;AAAA,EACrC;AAEA,UAAI,uBAAS,OAAO,CAAC,CAAC,GAAG;AACxB,UAAM,EAAE,YAAY,QAAQ,GAAG,cAALine truncated
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { type Config, type Connection } from '@tidbcloud/serverless';
|
||||
import { entityKind } from "../entity.cjs";
|
||||
import type { Logger } from "../logger.cjs";
|
||||
import { MySqlDatabase } from "../mysql-core/db.cjs";
|
||||
import { type DrizzleConfig } from "../utils.cjs";
|
||||
import type { TiDBServerlessPreparedQueryHKT, TiDBServerlessQueryResultHKT } from "./session.cjs";
|
||||
export interface TiDBServerlessSDriverOptions {
|
||||
logger?: Logger;
|
||||
cache?: Cache;
|
||||
}
|
||||
export declare class TiDBServerlessDatabase<TSchema extends Record<string, unknown> = Record<string, never>> extends MySqlDatabase<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TSchema> {
|
||||
static readonly [entityKind]: string;
|
||||
}
|
||||
export declare function drizzle<TSchema extends Record<string, unknown> = Record<string, never>, TClient extends Connection = Connection>(...params: [
|
||||
TClient | string
|
||||
] | [
|
||||
TClient | string,
|
||||
DrizzleConfig<TSchema>
|
||||
] | [
|
||||
({
|
||||
connection: string | Config;
|
||||
} | {
|
||||
client: TClient;
|
||||
}) & DrizzleConfig<TSchema>
|
||||
]): TiDBServerlessDatabase<TSchema> & {
|
||||
$client: TClient;
|
||||
};
|
||||
export declare namespace drizzle {
|
||||
function mock<TSchema extends Record<string, unknown> = Record<string, never>>(config?: DrizzleConfig<TSchema>): TiDBServerlessDatabase<TSchema> & {
|
||||
$client: '$client is not available on drizzle.mock()';
|
||||
};
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { type Config, type Connection } from '@tidbcloud/serverless';
|
||||
import { entityKind } from "../entity.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { MySqlDatabase } from "../mysql-core/db.js";
|
||||
import { type DrizzleConfig } from "../utils.js";
|
||||
import type { TiDBServerlessPreparedQueryHKT, TiDBServerlessQueryResultHKT } from "./session.js";
|
||||
export interface TiDBServerlessSDriverOptions {
|
||||
logger?: Logger;
|
||||
cache?: Cache;
|
||||
}
|
||||
export declare class TiDBServerlessDatabase<TSchema extends Record<string, unknown> = Record<string, never>> extends MySqlDatabase<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TSchema> {
|
||||
static readonly [entityKind]: string;
|
||||
}
|
||||
export declare function drizzle<TSchema extends Record<string, unknown> = Record<string, never>, TClient extends Connection = Connection>(...params: [
|
||||
TClient | string
|
||||
] | [
|
||||
TClient | string,
|
||||
DrizzleConfig<TSchema>
|
||||
] | [
|
||||
({
|
||||
connection: string | Config;
|
||||
} | {
|
||||
client: TClient;
|
||||
}) & DrizzleConfig<TSchema>
|
||||
]): TiDBServerlessDatabase<TSchema> & {
|
||||
$client: TClient;
|
||||
};
|
||||
export declare namespace drizzle {
|
||||
function mock<TSchema extends Record<string, unknown> = Record<string, never>>(config?: DrizzleConfig<TSchema>): TiDBServerlessDatabase<TSchema> & {
|
||||
$client: '$client is not available on drizzle.mock()';
|
||||
};
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { connect } from "@tidbcloud/serverless";
|
||||
import { entityKind } from "../entity.js";
|
||||
import { DefaultLogger } from "../logger.js";
|
||||
import { MySqlDatabase } from "../mysql-core/db.js";
|
||||
import { MySqlDialect } from "../mysql-core/dialect.js";
|
||||
import {
|
||||
createTableRelationsHelpers,
|
||||
extractTablesRelationalConfig
|
||||
} from "../relations.js";
|
||||
import { isConfig } from "../utils.js";
|
||||
import { TiDBServerlessSession } from "./session.js";
|
||||
class TiDBServerlessDatabase extends MySqlDatabase {
|
||||
static [entityKind] = "TiDBServerlessDatabase";
|
||||
}
|
||||
function construct(client, config = {}) {
|
||||
const dialect = new MySqlDialect({ casing: config.casing });
|
||||
let logger;
|
||||
if (config.logger === true) {
|
||||
logger = new DefaultLogger();
|
||||
} else if (config.logger !== false) {
|
||||
logger = config.logger;
|
||||
}
|
||||
let schema;
|
||||
if (config.schema) {
|
||||
const tablesConfig = extractTablesRelationalConfig(
|
||||
config.schema,
|
||||
createTableRelationsHelpers
|
||||
);
|
||||
schema = {
|
||||
fullSchema: config.schema,
|
||||
schema: tablesConfig.tables,
|
||||
tableNamesMap: tablesConfig.tableNamesMap
|
||||
};
|
||||
}
|
||||
const session = new TiDBServerlessSession(client, dialect, void 0, schema, { logger, cache: config.cache });
|
||||
const db = new TiDBServerlessDatabase(dialect, session, schema, "default");
|
||||
db.$client = client;
|
||||
db.$cache = config.cache;
|
||||
if (db.$cache) {
|
||||
db.$cache["invalidate"] = config.cache?.onMutate;
|
||||
}
|
||||
return db;
|
||||
}
|
||||
function drizzle(...params) {
|
||||
if (typeof params[0] === "string") {
|
||||
const instance = connect({
|
||||
url: params[0]
|
||||
});
|
||||
return construct(instance, params[1]);
|
||||
}
|
||||
if (isConfig(params[0])) {
|
||||
const { connection, client, ...drizzleConfig } = params[0];
|
||||
if (client) return construct(client, drizzleConfig);
|
||||
const instance = typeof connection === "string" ? connect({
|
||||
url: connection
|
||||
}) : connect(connection);
|
||||
return construct(instance, drizzleConfig);
|
||||
}
|
||||
return construct(params[0], params[1]);
|
||||
}
|
||||
((drizzle2) => {
|
||||
function mock(config) {
|
||||
return construct({}, config);
|
||||
}
|
||||
drizzle2.mock = mock;
|
||||
})(drizzle || (drizzle = {}));
|
||||
export {
|
||||
TiDBServerlessDatabase,
|
||||
drizzle
|
||||
};
|
||||
//# sourceMappingURL=driver.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/tidb-serverless/driver.ts"],"sourcesContent":["import { type Config, connect, type Connection } from '@tidbcloud/serverless';\nimport { entityKind } from '~/entity.ts';\nimport type { Logger } from '~/logger.ts';\nimport { DefaultLogger } from '~/logger.ts';\nimport { MySqlDatabase } from '~/mysql-core/db.ts';\nimport { MySqlDialect } from '~/mysql-core/dialect.ts';\nimport {\n\tcreateTableRelationsHelpers,\n\textractTablesRelationalConfig,\n\ttype RelationalSchemaConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport { type DrizzleConfig, isConfig } from '~/utils.ts';\nimport type { TiDBServerlessPreparedQueryHKT, TiDBServerlessQueryResultHKT } from './session.ts';\nimport { TiDBServerlessSession } from './session.ts';\n\nexport interface TiDBServerlessSDriverOptions {\n\tlogger?: Logger;\n\tcache?: Cache;\n}\n\nexport class TiDBServerlessDatabase<\n\tTSchema extends Record<string, unknown> = Record<string, never>,\n> extends MySqlDatabase<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TSchema> {\n\tstatic override readonly [entityKind]: string = 'TiDBServerlessDatabase';\n}\n\nfunction construct<TSchema extends Record<string, unknown> = Record<string, never>>(\n\tclient: Connection,\n\tconfig: DrizzleConfig<TSchema> = {},\n): TiDBServerlessDatabase<TSchema> & {\n\t$client: Connection;\n} {\n\tconst dialect = new MySqlDialect({ casing: config.casing });\n\tlet logger;\n\tif (config.logger === true) {\n\t\tlogger = new DefaultLogger();\n\t} else if (config.logger !== false) {\n\t\tlogger = config.logger;\n\t}\n\n\tlet schema: RelationalSchemaConfig<TablesRelationalConfig> | undefined;\n\tif (config.schema) {\n\t\tconst tablesConfig = extractTablesRelationalConfig(\n\t\t\tconfig.schema,\n\t\t\tcreateTableRelationsHelpers,\n\t\t);\n\t\tschema = {\n\t\t\tfullSchema: config.schema,\n\t\t\tschema: tablesConfig.tables,\n\t\t\ttableNamesMap: tablesConfig.tableNamesMap,\n\t\t};\n\t}\n\n\tconst session = new TiDBServerlessSession(client, dialect, undefined, schema, { logger, cache: config.cache });\n\tconst db = new TiDBServerlessDatabase(dialect, session, schema as any, 'default') as TiDBServerlessDatabase<TSchema>;\n\t(<any> db).$client = client;\n\t(<any> db).$cache = config.cache;\n\tif ((<any> db).$cache) {\n\t\t(<any> db).$cache['invalidate'] = config.cache?.onMutate;\n\t}\n\n\treturn db as any;\n}\n\nexport function drizzle<\n\tTSchema extends Record<string, unknown> = Record<string, never>,\n\tTClient extends Connection = Connection,\n>(\n\t...params: [\n\t\tTClient | string,\n\t] | [\n\t\tTClient | string,\n\t\tDrizzleConfig<TSchema>,\n\t] | [\n\t\t& ({\n\t\t\tconnection: string | Config;\n\t\t} | {\n\t\t\tclient: TClient;\n\t\t})\n\t\t& DrizzleConfig<TSchema>,\n\t]\n): TiDBServerlessDatabase<TSchema> & {\n\t$client: TClient;\n} {\n\tif (typeof params[0] === 'string') {\n\t\tconst instance = connect({\n\t\t\turl: params[0],\n\t\t});\n\n\t\treturn construct(instance, params[1]) as any;\n\t}\n\n\tif (isConfig(params[0])) {\n\t\tconst { connection, client, ...drizzleConfig } = params[0] as\n\t\t\t& { connection?: Config | string; client?: TClient }\n\t\t\t& DrizzleConfig<TSchema>;\n\n\t\tif (client) return construct(client, drizzleConfig) as any;\n\n\t\tconst instance = typeof connection === 'string'\n\t\t\t? connect({\n\t\t\t\turl: connection,\n\t\t\t})\n\t\t\t: connect(connection!);\n\n\t\treturn construct(instance, drizzleConfig) as any;\n\t}\n\n\treturn construct(params[0] as TClient, params[1] as DrizzleConfig<TSchema> | undefined) as any;\n}\n\nexport namespace drizzle {\n\texport function mock<TSchema extends Record<string, unknown> = Record<string, never>>(\n\t\tconfig?: DrizzleConfig<TSchema>,\n\t): TiDBServerlessDatabase<TSchema> & {\n\t\t$client: '$client is not available on drizzle.mock()';\n\t} {\n\t\treturn construct({} as any, config) as any;\n\t}\n}\n"],"mappings":"AAAA,SAAsB,eAAgC;AACtD,SAAS,kBAAkB;AAE3B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B;AAAA,EACC;AAAA,EACA;AAAA,OAGM;AACP,SAA6B,gBAAgB;AAE7C,SAAS,6BAA6B;AAO/B,MAAM,+BAEH,cAAqF;AAAA,EAC9F,QAA0B,UAAU,IAAY;AACjD;AAEA,SAAS,UACR,QACA,SAAiC,CAAC,GAGjC;AACD,QAAM,UAAU,IAAI,aAAa,EAAE,QAAQ,OAAO,OAAO,CAAC;AAC1D,MAAI;AACJ,MAAI,OAAO,WAAW,MAAM;AAC3B,aAAS,IAAI,cAAc;AAAA,EAC5B,WAAW,OAAO,WAAW,OAAO;AACnC,aAAS,OAAO;AAAA,EACjB;AAEA,MAAI;AACJ,MAAI,OAAO,QAAQ;AAClB,UAAM,eAAe;AAAA,MACpB,OAAO;AAAA,MACP;AAAA,IACD;AACA,aAAS;AAAA,MACR,YAAY,OAAO;AAAA,MACnB,QAAQ,aAAa;AAAA,MACrB,eAAe,aAAa;AAAA,IAC7B;AAAA,EACD;AAEA,QAAM,UAAU,IAAI,sBAAsB,QAAQ,SAAS,QAAW,QAAQ,EAAE,QAAQ,OAAO,OAAO,MAAM,CAAC;AAC7G,QAAM,KAAK,IAAI,uBAAuB,SAAS,SAAS,QAAe,SAAS;AAChF,EAAO,GAAI,UAAU;AACrB,EAAO,GAAI,SAAS,OAAO;AAC3B,MAAW,GAAI,QAAQ;AACtB,IAAO,GAAI,OAAO,YAAY,IAAI,OAAO,OAAO;AAAA,EACjD;AAEA,SAAO;AACR;AAEO,SAAS,WAIZ,QAeF;AACD,MAAI,OAAO,OAAO,CAAC,MAAM,UAAU;AAClC,UAAM,WAAW,QAAQ;AAAA,MACxB,KAAK,OAAO,CAAC;AAAA,IACd,CAAC;AAED,WAAO,UAAU,UAAU,OAAO,CAAC,CAAC;AAAA,EACrC;AAEA,MAAI,SAAS,OAAO,CAAC,CAAC,GAAG;AACxB,UAAM,EAAE,YAAY,QAAQ,GAALine truncated
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var tidb_serverless_exports = {};
|
||||
module.exports = __toCommonJS(tidb_serverless_exports);
|
||||
__reExport(tidb_serverless_exports, require("./driver.cjs"), module.exports);
|
||||
__reExport(tidb_serverless_exports, require("./session.cjs"), module.exports);
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
...require("./driver.cjs"),
|
||||
...require("./session.cjs")
|
||||
});
|
||||
//# sourceMappingURL=index.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/tidb-serverless/index.ts"],"sourcesContent":["export * from './driver.ts';\nexport * from './session.ts';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAAA,oCAAc,wBAAd;AACA,oCAAc,yBADd;","names":[]}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export * from "./driver.cjs";
|
||||
export * from "./session.cjs";
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export * from "./driver.js";
|
||||
export * from "./session.js";
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export * from "./driver.js";
|
||||
export * from "./session.js";
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/tidb-serverless/index.ts"],"sourcesContent":["export * from './driver.ts';\nexport * from './session.ts';\n"],"mappings":"AAAA,cAAc;AACd,cAAc;","names":[]}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var migrator_exports = {};
|
||||
__export(migrator_exports, {
|
||||
migrate: () => migrate
|
||||
});
|
||||
module.exports = __toCommonJS(migrator_exports);
|
||||
var import_migrator = require("../migrator.cjs");
|
||||
async function migrate(db, config) {
|
||||
const migrations = (0, import_migrator.readMigrationFiles)(config);
|
||||
await db.dialect.migrate(migrations, db.session, config);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
migrate
|
||||
});
|
||||
//# sourceMappingURL=migrator.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/tidb-serverless/migrator.ts"],"sourcesContent":["import type { MigrationConfig } from '~/migrator.ts';\nimport { readMigrationFiles } from '~/migrator.ts';\nimport type { TiDBServerlessDatabase } from './driver.ts';\n\nexport async function migrate<TSchema extends Record<string, unknown>>(\n\tdb: TiDBServerlessDatabase<TSchema>,\n\tconfig: MigrationConfig,\n) {\n\tconst migrations = readMigrationFiles(config);\n\tawait db.dialect.migrate(migrations, db.session, config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,sBAAmC;AAGnC,eAAsB,QACrB,IACA,QACC;AACD,QAAM,iBAAa,oCAAmB,MAAM;AAC5C,QAAM,GAAG,QAAQ,QAAQ,YAAY,GAAG,SAAS,MAAM;AACxD;","names":[]}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { MigrationConfig } from "../migrator.cjs";
|
||||
import type { TiDBServerlessDatabase } from "./driver.cjs";
|
||||
export declare function migrate<TSchema extends Record<string, unknown>>(db: TiDBServerlessDatabase<TSchema>, config: MigrationConfig): Promise<void>;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { MigrationConfig } from "../migrator.js";
|
||||
import type { TiDBServerlessDatabase } from "./driver.js";
|
||||
export declare function migrate<TSchema extends Record<string, unknown>>(db: TiDBServerlessDatabase<TSchema>, config: MigrationConfig): Promise<void>;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { readMigrationFiles } from "../migrator.js";
|
||||
async function migrate(db, config) {
|
||||
const migrations = readMigrationFiles(config);
|
||||
await db.dialect.migrate(migrations, db.session, config);
|
||||
}
|
||||
export {
|
||||
migrate
|
||||
};
|
||||
//# sourceMappingURL=migrator.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/tidb-serverless/migrator.ts"],"sourcesContent":["import type { MigrationConfig } from '~/migrator.ts';\nimport { readMigrationFiles } from '~/migrator.ts';\nimport type { TiDBServerlessDatabase } from './driver.ts';\n\nexport async function migrate<TSchema extends Record<string, unknown>>(\n\tdb: TiDBServerlessDatabase<TSchema>,\n\tconfig: MigrationConfig,\n) {\n\tconst migrations = readMigrationFiles(config);\n\tawait db.dialect.migrate(migrations, db.session, config);\n}\n"],"mappings":"AACA,SAAS,0BAA0B;AAGnC,eAAsB,QACrB,IACA,QACC;AACD,QAAM,aAAa,mBAAmB,MAAM;AAC5C,QAAM,GAAG,QAAQ,QAAQ,YAAY,GAAG,SAAS,MAAM;AACxD;","names":[]}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var session_exports = {};
|
||||
__export(session_exports, {
|
||||
TiDBServerlessPreparedQuery: () => TiDBServerlessPreparedQuery,
|
||||
TiDBServerlessSession: () => TiDBServerlessSession,
|
||||
TiDBServerlessTransaction: () => TiDBServerlessTransaction
|
||||
});
|
||||
module.exports = __toCommonJS(session_exports);
|
||||
var import_core = require("../cache/core/index.cjs");
|
||||
var import_column = require("../column.cjs");
|
||||
var import_entity = require("../entity.cjs");
|
||||
var import_logger = require("../logger.cjs");
|
||||
var import_session = require("../mysql-core/session.cjs");
|
||||
var import_sql = require("../sql/sql.cjs");
|
||||
var import_utils = require("../utils.cjs");
|
||||
const executeRawConfig = { fullResult: true };
|
||||
const queryConfig = { arrayMode: true };
|
||||
class TiDBServerlessPreparedQuery extends import_session.MySqlPreparedQuery {
|
||||
constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, customResultMapper, generatedIds, returningIds) {
|
||||
super(cache, queryMetadata, cacheConfig);
|
||||
this.client = client;
|
||||
this.queryString = queryString;
|
||||
this.params = params;
|
||||
this.logger = logger;
|
||||
this.fields = fields;
|
||||
this.customResultMapper = customResultMapper;
|
||||
this.generatedIds = generatedIds;
|
||||
this.returningIds = returningIds;
|
||||
}
|
||||
static [import_entity.entityKind] = "TiDBPreparedQuery";
|
||||
async execute(placeholderValues = {}) {
|
||||
const params = (0, import_sql.fillPlaceholders)(this.params, placeholderValues);
|
||||
this.logger.logQuery(this.queryString, params);
|
||||
const { fields, client, queryString, joinsNotNullableMap, customResultMapper, returningIds, generatedIds } = this;
|
||||
if (!fields && !customResultMapper) {
|
||||
const res = await this.queryWithCache(queryString, params, async () => {
|
||||
return await client.execute(queryString, params, executeRawConfig);
|
||||
});
|
||||
const insertId = res.lastInsertId ?? 0;
|
||||
const affectedRows = res.rowsAffected ?? 0;
|
||||
if (returningIds) {
|
||||
const returningResponse = [];
|
||||
let j = 0;
|
||||
for (let i = insertId; i < insertId + affectedRows; i++) {
|
||||
for (const column of returningIds) {
|
||||
const key = returningIds[0].path[0];
|
||||
if ((0, import_entity.is)(column.field, import_column.Column)) {
|
||||
if (column.field.primary && column.field.autoIncrement) {
|
||||
returningResponse.push({ [key]: i });
|
||||
}
|
||||
if (column.field.defaultFn && generatedIds) {
|
||||
returningResponse.push({ [key]: generatedIds[j][key] });
|
||||
}
|
||||
}
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return returningResponse;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
const rows = await this.queryWithCache(queryString, params, async () => {
|
||||
return await client.execute(queryString, params, queryConfig);
|
||||
});
|
||||
if (customResultMapper) {
|
||||
return customResultMapper(rows);
|
||||
}
|
||||
return rows.map((row) => (0, import_utils.mapResultRow)(fields, row, joinsNotNullableMap));
|
||||
}
|
||||
iterator(_placeholderValues) {
|
||||
throw new Error("Streaming is not supported by the TiDB Cloud Serverless driver");
|
||||
}
|
||||
}
|
||||
class TiDBServerlessSession extends import_session.MySqlSession {
|
||||
constructor(baseClient, dialect, tx, schema, options = {}) {
|
||||
super(dialect);
|
||||
this.baseClient = baseClient;
|
||||
this.schema = schema;
|
||||
this.options = options;
|
||||
this.client = tx ?? baseClient;
|
||||
this.logger = options.logger ?? new import_logger.NoopLogger();
|
||||
this.cache = options.cache ?? new import_core.NoopCache();
|
||||
}
|
||||
static [import_entity.entityKind] = "TiDBServerlessSession";
|
||||
logger;
|
||||
client;
|
||||
cache;
|
||||
prepareQuery(query, fields, customResultMapper, generatedIds, returningIds, queryMetadata, cacheConfig) {
|
||||
return new TiDBServerlessPreparedQuery(
|
||||
this.client,
|
||||
query.sql,
|
||||
query.params,
|
||||
this.logger,
|
||||
this.cache,
|
||||
queryMetadata,
|
||||
cacheConfig,
|
||||
fields,
|
||||
customResultMapper,
|
||||
generatedIds,
|
||||
returningIds
|
||||
);
|
||||
}
|
||||
all(query) {
|
||||
const querySql = this.dialect.sqlToQuery(query);
|
||||
this.logger.logQuery(querySql.sql, querySql.params);
|
||||
return this.client.execute(querySql.sql, querySql.params);
|
||||
}
|
||||
async count(sql2) {
|
||||
const res = await this.execute(sql2);
|
||||
return Number(
|
||||
res["rows"][0]["count"]
|
||||
);
|
||||
}
|
||||
async transaction(transaction) {
|
||||
const nativeTx = await this.baseClient.begin();
|
||||
try {
|
||||
const session = new TiDBServerlessSession(this.baseClient, this.dialect, nativeTx, this.schema, this.options);
|
||||
const tx = new TiDBServerlessTransaction(
|
||||
this.dialect,
|
||||
session,
|
||||
this.schema
|
||||
);
|
||||
const result = await transaction(tx);
|
||||
await nativeTx.commit();
|
||||
return result;
|
||||
} catch (err) {
|
||||
await nativeTx.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
class TiDBServerlessTransaction extends import_session.MySqlTransaction {
|
||||
static [import_entity.entityKind] = "TiDBServerlessTransaction";
|
||||
constructor(dialect, session, schema, nestedIndex = 0) {
|
||||
super(dialect, session, schema, nestedIndex, "default");
|
||||
}
|
||||
async transaction(transaction) {
|
||||
const savepointName = `sp${this.nestedIndex + 1}`;
|
||||
const tx = new TiDBServerlessTransaction(
|
||||
this.dialect,
|
||||
this.session,
|
||||
this.schema,
|
||||
this.nestedIndex + 1
|
||||
);
|
||||
await tx.execute(import_sql.sql.raw(`savepoint ${savepointName}`));
|
||||
try {
|
||||
const result = await transaction(tx);
|
||||
await tx.execute(import_sql.sql.raw(`release savepoint ${savepointName}`));
|
||||
return result;
|
||||
} catch (err) {
|
||||
await tx.execute(import_sql.sql.raw(`rollback to savepoint ${savepointName}`));
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
TiDBServerlessPreparedQuery,
|
||||
TiDBServerlessSession,
|
||||
TiDBServerlessTransaction
|
||||
});
|
||||
//# sourceMappingURL=session.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/tidb-serverless/session.ts"],"sourcesContent":["import type { Connection, ExecuteOptions, FullResult, Tx } from '@tidbcloud/serverless';\nimport { type Cache, NoopCache } from '~/cache/core/index.ts';\nimport type { WithCacheConfig } from '~/cache/core/types.ts';\nimport { Column } from '~/column.ts';\n\nimport { entityKind, is } from '~/entity.ts';\nimport type { Logger } from '~/logger.ts';\nimport { NoopLogger } from '~/logger.ts';\nimport type { MySqlDialect } from '~/mysql-core/dialect.ts';\nimport type { SelectedFieldsOrdered } from '~/mysql-core/query-builders/select.types.ts';\nimport {\n\tMySqlPreparedQuery,\n\ttype MySqlPreparedQueryConfig,\n\ttype MySqlPreparedQueryHKT,\n\ttype MySqlQueryResultHKT,\n\tMySqlSession,\n\tMySqlTransaction,\n} from '~/mysql-core/session.ts';\nimport type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';\nimport { fillPlaceholders, type Query, type SQL, sql } from '~/sql/sql.ts';\nimport { type Assume, mapResultRow } from '~/utils.ts';\n\nconst executeRawConfig = { fullResult: true } satisfies ExecuteOptions;\nconst queryConfig = { arrayMode: true } satisfies ExecuteOptions;\n\nexport class TiDBServerlessPreparedQuery<T extends MySqlPreparedQueryConfig> extends MySqlPreparedQuery<T> {\n\tstatic override readonly [entityKind]: string = 'TiDBPreparedQuery';\n\n\tconstructor(\n\t\tprivate client: Tx | Connection,\n\t\tprivate queryString: string,\n\t\tprivate params: unknown[],\n\t\tprivate logger: Logger,\n\t\tcache: Cache,\n\t\tqueryMetadata: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t} | undefined,\n\t\tcacheConfig: WithCacheConfig | undefined,\n\t\tprivate fields: SelectedFieldsOrdered | undefined,\n\t\tprivate customResultMapper?: (rows: unknown[][]) => T['execute'],\n\t\t// Keys that were used in $default and the value that was generated for them\n\t\tprivate generatedIds?: Record<string, unknown>[],\n\t\t// Keys that should be returned, it has the column with all properries + key from object\n\t\tprivate returningIds?: SelectedFieldsOrdered,\n\t) {\n\t\tsuper(cache, queryMetadata, cacheConfig);\n\t}\n\n\tasync execute(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['execute']> {\n\t\tconst params = fillPlaceholders(this.params, placeholderValues);\n\n\t\tthis.logger.logQuery(this.queryString, params);\n\n\t\tconst { fields, client, queryString, joinsNotNullableMap, customResultMapper, returningIds, generatedIds } = this;\n\t\tif (!fields && !customResultMapper) {\n\t\t\tconst res = await this.queryWithCache(queryString, params, async () => {\n\t\t\t\treturn await client.execute(queryString, params, executeRawConfig) as FullResult;\n\t\t\t});\n\t\t\tconst insertId = res.lastInsertId ?? 0;\n\t\t\tconst affectedRows = res.rowsAffected ?? 0;\n\t\t\t// for each row, I need to check keys from\n\t\t\tif (returningIds) {\n\t\t\t\tconst returningResponse = [];\n\t\t\t\tlet j = 0;\n\t\t\t\tfor (let i = insertId; i < insertId + affectedRows; i++) {\n\t\t\t\t\tfor (const column of returningIds) {\n\t\t\t\t\t\tconst key = returningIds[0]!.path[0]!;\n\t\t\t\t\t\tif (is(column.field, Column)) {\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tif (column.field.primary && column.field.autoIncrement) {\n\t\t\t\t\t\t\t\treturningResponse.push({ [key]: i });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (column.field.defaultFn && generatedIds) {\n\t\t\t\t\t\t\t\t// generatedIds[rowIdx][key]\n\t\t\t\t\t\t\t\treturningResponse.push({ [key]: generatedIds[j]![key] });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj++;\n\t\t\t\t}\n\n\t\t\t\treturn returningResponse;\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\n\t\tconst rows = await this.queryWithCache(queryString, params, async () => {\n\t\t\treturn await client.execute(queryString, params, queryConfig) as unknown[][];\n\t\t});\n\n\t\tif (customResultMapper) {\n\t\t\treturn customResultMapper(rows);\n\t\t}\n\n\t\treturn rows.map((row) => mapResultRow<T['execute']>(fields!, row, joinsNotNullableMap));\n\t}\n\n\toverride iterator(_placeholderValues?: Record<string, unknown>): AsyncGenerator<T['iterator']> {\n\t\tthrow new Error('Streaming is not supported by the TiDB Cloud Serverless driver');\n\t}\n}\n\nexport interface TiDBServerlessSessionOptions {\n\tlogger?: Logger;\n\tcache?: Cache;\n}\n\nexport class TiDBServerlessSession<\n\tTFullSchema extends Record<string, unknown>,\n\tTSchema extends TablesRelationalConfig,\n> extends MySqlSession<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TFullSchema, TSchema> {\n\tstatic override readonly [entityKind]: string = 'TiDBServerlessSession';\n\n\tprivate logger: Logger;\n\tprivate client: Tx | Connection;\n\tprivate cache: Cache;\n\n\tconstructor(\n\t\tprivate baseClient: Connection,\n\t\tdialect: MySqlDialect,\n\t\ttx: Tx | undefined,\n\t\tprivate schema: RelationalSchemaConfig<TSchema> | undefined,\n\t\tprivate options: TiDBServerlessSessionOptions = {},\n\t) {\n\tLine truncated
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
import type { Connection, FullResult, Tx } from '@tidbcloud/serverless';
|
||||
import { type Cache } from "../cache/core/index.cjs";
|
||||
import type { WithCacheConfig } from "../cache/core/types.cjs";
|
||||
import { entityKind } from "../entity.cjs";
|
||||
import type { Logger } from "../logger.cjs";
|
||||
import type { MySqlDialect } from "../mysql-core/dialect.cjs";
|
||||
import type { SelectedFieldsOrdered } from "../mysql-core/query-builders/select.types.cjs";
|
||||
import { MySqlPreparedQuery, type MySqlPreparedQueryConfig, type MySqlPreparedQueryHKT, type MySqlQueryResultHKT, MySqlSession, MySqlTransaction } from "../mysql-core/session.cjs";
|
||||
import type { RelationalSchemaConfig, TablesRelationalConfig } from "../relations.cjs";
|
||||
import { type Query, type SQL } from "../sql/sql.cjs";
|
||||
import { type Assume } from "../utils.cjs";
|
||||
export declare class TiDBServerlessPreparedQuery<T extends MySqlPreparedQueryConfig> extends MySqlPreparedQuery<T> {
|
||||
private client;
|
||||
private queryString;
|
||||
private params;
|
||||
private logger;
|
||||
private fields;
|
||||
private customResultMapper?;
|
||||
private generatedIds?;
|
||||
private returningIds?;
|
||||
static readonly [entityKind]: string;
|
||||
constructor(client: Tx | Connection, queryString: string, params: unknown[], logger: Logger, cache: Cache, queryMetadata: {
|
||||
type: 'select' | 'update' | 'delete' | 'insert';
|
||||
tables: string[];
|
||||
} | undefined, cacheConfig: WithCacheConfig | undefined, fields: SelectedFieldsOrdered | undefined, customResultMapper?: ((rows: unknown[][]) => T["execute"]) | undefined, generatedIds?: Record<string, unknown>[] | undefined, returningIds?: SelectedFieldsOrdered | undefined);
|
||||
execute(placeholderValues?: Record<string, unknown> | undefined): Promise<T['execute']>;
|
||||
iterator(_placeholderValues?: Record<string, unknown>): AsyncGenerator<T['iterator']>;
|
||||
}
|
||||
export interface TiDBServerlessSessionOptions {
|
||||
logger?: Logger;
|
||||
cache?: Cache;
|
||||
}
|
||||
export declare class TiDBServerlessSession<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig> extends MySqlSession<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TFullSchema, TSchema> {
|
||||
private baseClient;
|
||||
private schema;
|
||||
private options;
|
||||
static readonly [entityKind]: string;
|
||||
private logger;
|
||||
private client;
|
||||
private cache;
|
||||
constructor(baseClient: Connection, dialect: MySqlDialect, tx: Tx | undefined, schema: RelationalSchemaConfig<TSchema> | undefined, options?: TiDBServerlessSessionOptions);
|
||||
prepareQuery<T extends MySqlPreparedQueryConfig = MySqlPreparedQueryConfig>(query: Query, fields: SelectedFieldsOrdered | undefined, customResultMapper?: (rows: unknown[][]) => T['execute'], generatedIds?: Record<string, unknown>[], returningIds?: SelectedFieldsOrdered, queryMetadata?: {
|
||||
type: 'select' | 'update' | 'delete' | 'insert';
|
||||
tables: string[];
|
||||
}, cacheConfig?: WithCacheConfig): MySqlPreparedQuery<T>;
|
||||
all<T = unknown>(query: SQL): Promise<T[]>;
|
||||
count(sql: SQL): Promise<number>;
|
||||
transaction<T>(transaction: (tx: TiDBServerlessTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T>;
|
||||
}
|
||||
export declare class TiDBServerlessTransaction<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig> extends MySqlTransaction<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TFullSchema, TSchema> {
|
||||
static readonly [entityKind]: string;
|
||||
constructor(dialect: MySqlDialect, session: MySqlSession, schema: RelationalSchemaConfig<TSchema> | undefined, nestedIndex?: number);
|
||||
transaction<T>(transaction: (tx: TiDBServerlessTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T>;
|
||||
}
|
||||
export interface TiDBServerlessQueryResultHKT extends MySqlQueryResultHKT {
|
||||
type: FullResult;
|
||||
}
|
||||
export interface TiDBServerlessPreparedQueryHKT extends MySqlPreparedQueryHKT {
|
||||
type: TiDBServerlessPreparedQuery<Assume<this['config'], MySqlPreparedQueryConfig>>;
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
import type { Connection, FullResult, Tx } from '@tidbcloud/serverless';
|
||||
import { type Cache } from "../cache/core/index.js";
|
||||
import type { WithCacheConfig } from "../cache/core/types.js";
|
||||
import { entityKind } from "../entity.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { MySqlDialect } from "../mysql-core/dialect.js";
|
||||
import type { SelectedFieldsOrdered } from "../mysql-core/query-builders/select.types.js";
|
||||
import { MySqlPreparedQuery, type MySqlPreparedQueryConfig, type MySqlPreparedQueryHKT, type MySqlQueryResultHKT, MySqlSession, MySqlTransaction } from "../mysql-core/session.js";
|
||||
import type { RelationalSchemaConfig, TablesRelationalConfig } from "../relations.js";
|
||||
import { type Query, type SQL } from "../sql/sql.js";
|
||||
import { type Assume } from "../utils.js";
|
||||
export declare class TiDBServerlessPreparedQuery<T extends MySqlPreparedQueryConfig> extends MySqlPreparedQuery<T> {
|
||||
private client;
|
||||
private queryString;
|
||||
private params;
|
||||
private logger;
|
||||
private fields;
|
||||
private customResultMapper?;
|
||||
private generatedIds?;
|
||||
private returningIds?;
|
||||
static readonly [entityKind]: string;
|
||||
constructor(client: Tx | Connection, queryString: string, params: unknown[], logger: Logger, cache: Cache, queryMetadata: {
|
||||
type: 'select' | 'update' | 'delete' | 'insert';
|
||||
tables: string[];
|
||||
} | undefined, cacheConfig: WithCacheConfig | undefined, fields: SelectedFieldsOrdered | undefined, customResultMapper?: ((rows: unknown[][]) => T["execute"]) | undefined, generatedIds?: Record<string, unknown>[] | undefined, returningIds?: SelectedFieldsOrdered | undefined);
|
||||
execute(placeholderValues?: Record<string, unknown> | undefined): Promise<T['execute']>;
|
||||
iterator(_placeholderValues?: Record<string, unknown>): AsyncGenerator<T['iterator']>;
|
||||
}
|
||||
export interface TiDBServerlessSessionOptions {
|
||||
logger?: Logger;
|
||||
cache?: Cache;
|
||||
}
|
||||
export declare class TiDBServerlessSession<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig> extends MySqlSession<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TFullSchema, TSchema> {
|
||||
private baseClient;
|
||||
private schema;
|
||||
private options;
|
||||
static readonly [entityKind]: string;
|
||||
private logger;
|
||||
private client;
|
||||
private cache;
|
||||
constructor(baseClient: Connection, dialect: MySqlDialect, tx: Tx | undefined, schema: RelationalSchemaConfig<TSchema> | undefined, options?: TiDBServerlessSessionOptions);
|
||||
prepareQuery<T extends MySqlPreparedQueryConfig = MySqlPreparedQueryConfig>(query: Query, fields: SelectedFieldsOrdered | undefined, customResultMapper?: (rows: unknown[][]) => T['execute'], generatedIds?: Record<string, unknown>[], returningIds?: SelectedFieldsOrdered, queryMetadata?: {
|
||||
type: 'select' | 'update' | 'delete' | 'insert';
|
||||
tables: string[];
|
||||
}, cacheConfig?: WithCacheConfig): MySqlPreparedQuery<T>;
|
||||
all<T = unknown>(query: SQL): Promise<T[]>;
|
||||
count(sql: SQL): Promise<number>;
|
||||
transaction<T>(transaction: (tx: TiDBServerlessTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T>;
|
||||
}
|
||||
export declare class TiDBServerlessTransaction<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig> extends MySqlTransaction<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TFullSchema, TSchema> {
|
||||
static readonly [entityKind]: string;
|
||||
constructor(dialect: MySqlDialect, session: MySqlSession, schema: RelationalSchemaConfig<TSchema> | undefined, nestedIndex?: number);
|
||||
transaction<T>(transaction: (tx: TiDBServerlessTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T>;
|
||||
}
|
||||
export interface TiDBServerlessQueryResultHKT extends MySqlQueryResultHKT {
|
||||
type: FullResult;
|
||||
}
|
||||
export interface TiDBServerlessPreparedQueryHKT extends MySqlPreparedQueryHKT {
|
||||
type: TiDBServerlessPreparedQuery<Assume<this['config'], MySqlPreparedQueryConfig>>;
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
import { NoopCache } from "../cache/core/index.js";
|
||||
import { Column } from "../column.js";
|
||||
import { entityKind, is } from "../entity.js";
|
||||
import { NoopLogger } from "../logger.js";
|
||||
import {
|
||||
MySqlPreparedQuery,
|
||||
MySqlSession,
|
||||
MySqlTransaction
|
||||
} from "../mysql-core/session.js";
|
||||
import { fillPlaceholders, sql } from "../sql/sql.js";
|
||||
import { mapResultRow } from "../utils.js";
|
||||
const executeRawConfig = { fullResult: true };
|
||||
const queryConfig = { arrayMode: true };
|
||||
class TiDBServerlessPreparedQuery extends MySqlPreparedQuery {
|
||||
constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, customResultMapper, generatedIds, returningIds) {
|
||||
super(cache, queryMetadata, cacheConfig);
|
||||
this.client = client;
|
||||
this.queryString = queryString;
|
||||
this.params = params;
|
||||
this.logger = logger;
|
||||
this.fields = fields;
|
||||
this.customResultMapper = customResultMapper;
|
||||
this.generatedIds = generatedIds;
|
||||
this.returningIds = returningIds;
|
||||
}
|
||||
static [entityKind] = "TiDBPreparedQuery";
|
||||
async execute(placeholderValues = {}) {
|
||||
const params = fillPlaceholders(this.params, placeholderValues);
|
||||
this.logger.logQuery(this.queryString, params);
|
||||
const { fields, client, queryString, joinsNotNullableMap, customResultMapper, returningIds, generatedIds } = this;
|
||||
if (!fields && !customResultMapper) {
|
||||
const res = await this.queryWithCache(queryString, params, async () => {
|
||||
return await client.execute(queryString, params, executeRawConfig);
|
||||
});
|
||||
const insertId = res.lastInsertId ?? 0;
|
||||
const affectedRows = res.rowsAffected ?? 0;
|
||||
if (returningIds) {
|
||||
const returningResponse = [];
|
||||
let j = 0;
|
||||
for (let i = insertId; i < insertId + affectedRows; i++) {
|
||||
for (const column of returningIds) {
|
||||
const key = returningIds[0].path[0];
|
||||
if (is(column.field, Column)) {
|
||||
if (column.field.primary && column.field.autoIncrement) {
|
||||
returningResponse.push({ [key]: i });
|
||||
}
|
||||
if (column.field.defaultFn && generatedIds) {
|
||||
returningResponse.push({ [key]: generatedIds[j][key] });
|
||||
}
|
||||
}
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return returningResponse;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
const rows = await this.queryWithCache(queryString, params, async () => {
|
||||
return await client.execute(queryString, params, queryConfig);
|
||||
});
|
||||
if (customResultMapper) {
|
||||
return customResultMapper(rows);
|
||||
}
|
||||
return rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
|
||||
}
|
||||
iterator(_placeholderValues) {
|
||||
throw new Error("Streaming is not supported by the TiDB Cloud Serverless driver");
|
||||
}
|
||||
}
|
||||
class TiDBServerlessSession extends MySqlSession {
|
||||
constructor(baseClient, dialect, tx, schema, options = {}) {
|
||||
super(dialect);
|
||||
this.baseClient = baseClient;
|
||||
this.schema = schema;
|
||||
this.options = options;
|
||||
this.client = tx ?? baseClient;
|
||||
this.logger = options.logger ?? new NoopLogger();
|
||||
this.cache = options.cache ?? new NoopCache();
|
||||
}
|
||||
static [entityKind] = "TiDBServerlessSession";
|
||||
logger;
|
||||
client;
|
||||
cache;
|
||||
prepareQuery(query, fields, customResultMapper, generatedIds, returningIds, queryMetadata, cacheConfig) {
|
||||
return new TiDBServerlessPreparedQuery(
|
||||
this.client,
|
||||
query.sql,
|
||||
query.params,
|
||||
this.logger,
|
||||
this.cache,
|
||||
queryMetadata,
|
||||
cacheConfig,
|
||||
fields,
|
||||
customResultMapper,
|
||||
generatedIds,
|
||||
returningIds
|
||||
);
|
||||
}
|
||||
all(query) {
|
||||
const querySql = this.dialect.sqlToQuery(query);
|
||||
this.logger.logQuery(querySql.sql, querySql.params);
|
||||
return this.client.execute(querySql.sql, querySql.params);
|
||||
}
|
||||
async count(sql2) {
|
||||
const res = await this.execute(sql2);
|
||||
return Number(
|
||||
res["rows"][0]["count"]
|
||||
);
|
||||
}
|
||||
async transaction(transaction) {
|
||||
const nativeTx = await this.baseClient.begin();
|
||||
try {
|
||||
const session = new TiDBServerlessSession(this.baseClient, this.dialect, nativeTx, this.schema, this.options);
|
||||
const tx = new TiDBServerlessTransaction(
|
||||
this.dialect,
|
||||
session,
|
||||
this.schema
|
||||
);
|
||||
const result = await transaction(tx);
|
||||
await nativeTx.commit();
|
||||
return result;
|
||||
} catch (err) {
|
||||
await nativeTx.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
class TiDBServerlessTransaction extends MySqlTransaction {
|
||||
static [entityKind] = "TiDBServerlessTransaction";
|
||||
constructor(dialect, session, schema, nestedIndex = 0) {
|
||||
super(dialect, session, schema, nestedIndex, "default");
|
||||
}
|
||||
async transaction(transaction) {
|
||||
const savepointName = `sp${this.nestedIndex + 1}`;
|
||||
const tx = new TiDBServerlessTransaction(
|
||||
this.dialect,
|
||||
this.session,
|
||||
this.schema,
|
||||
this.nestedIndex + 1
|
||||
);
|
||||
await tx.execute(sql.raw(`savepoint ${savepointName}`));
|
||||
try {
|
||||
const result = await transaction(tx);
|
||||
await tx.execute(sql.raw(`release savepoint ${savepointName}`));
|
||||
return result;
|
||||
} catch (err) {
|
||||
await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`));
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
export {
|
||||
TiDBServerlessPreparedQuery,
|
||||
TiDBServerlessSession,
|
||||
TiDBServerlessTransaction
|
||||
};
|
||||
//# sourceMappingURL=session.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/tidb-serverless/session.ts"],"sourcesContent":["import type { Connection, ExecuteOptions, FullResult, Tx } from '@tidbcloud/serverless';\nimport { type Cache, NoopCache } from '~/cache/core/index.ts';\nimport type { WithCacheConfig } from '~/cache/core/types.ts';\nimport { Column } from '~/column.ts';\n\nimport { entityKind, is } from '~/entity.ts';\nimport type { Logger } from '~/logger.ts';\nimport { NoopLogger } from '~/logger.ts';\nimport type { MySqlDialect } from '~/mysql-core/dialect.ts';\nimport type { SelectedFieldsOrdered } from '~/mysql-core/query-builders/select.types.ts';\nimport {\n\tMySqlPreparedQuery,\n\ttype MySqlPreparedQueryConfig,\n\ttype MySqlPreparedQueryHKT,\n\ttype MySqlQueryResultHKT,\n\tMySqlSession,\n\tMySqlTransaction,\n} from '~/mysql-core/session.ts';\nimport type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';\nimport { fillPlaceholders, type Query, type SQL, sql } from '~/sql/sql.ts';\nimport { type Assume, mapResultRow } from '~/utils.ts';\n\nconst executeRawConfig = { fullResult: true } satisfies ExecuteOptions;\nconst queryConfig = { arrayMode: true } satisfies ExecuteOptions;\n\nexport class TiDBServerlessPreparedQuery<T extends MySqlPreparedQueryConfig> extends MySqlPreparedQuery<T> {\n\tstatic override readonly [entityKind]: string = 'TiDBPreparedQuery';\n\n\tconstructor(\n\t\tprivate client: Tx | Connection,\n\t\tprivate queryString: string,\n\t\tprivate params: unknown[],\n\t\tprivate logger: Logger,\n\t\tcache: Cache,\n\t\tqueryMetadata: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t} | undefined,\n\t\tcacheConfig: WithCacheConfig | undefined,\n\t\tprivate fields: SelectedFieldsOrdered | undefined,\n\t\tprivate customResultMapper?: (rows: unknown[][]) => T['execute'],\n\t\t// Keys that were used in $default and the value that was generated for them\n\t\tprivate generatedIds?: Record<string, unknown>[],\n\t\t// Keys that should be returned, it has the column with all properries + key from object\n\t\tprivate returningIds?: SelectedFieldsOrdered,\n\t) {\n\t\tsuper(cache, queryMetadata, cacheConfig);\n\t}\n\n\tasync execute(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['execute']> {\n\t\tconst params = fillPlaceholders(this.params, placeholderValues);\n\n\t\tthis.logger.logQuery(this.queryString, params);\n\n\t\tconst { fields, client, queryString, joinsNotNullableMap, customResultMapper, returningIds, generatedIds } = this;\n\t\tif (!fields && !customResultMapper) {\n\t\t\tconst res = await this.queryWithCache(queryString, params, async () => {\n\t\t\t\treturn await client.execute(queryString, params, executeRawConfig) as FullResult;\n\t\t\t});\n\t\t\tconst insertId = res.lastInsertId ?? 0;\n\t\t\tconst affectedRows = res.rowsAffected ?? 0;\n\t\t\t// for each row, I need to check keys from\n\t\t\tif (returningIds) {\n\t\t\t\tconst returningResponse = [];\n\t\t\t\tlet j = 0;\n\t\t\t\tfor (let i = insertId; i < insertId + affectedRows; i++) {\n\t\t\t\t\tfor (const column of returningIds) {\n\t\t\t\t\t\tconst key = returningIds[0]!.path[0]!;\n\t\t\t\t\t\tif (is(column.field, Column)) {\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tif (column.field.primary && column.field.autoIncrement) {\n\t\t\t\t\t\t\t\treturningResponse.push({ [key]: i });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (column.field.defaultFn && generatedIds) {\n\t\t\t\t\t\t\t\t// generatedIds[rowIdx][key]\n\t\t\t\t\t\t\t\treturningResponse.push({ [key]: generatedIds[j]![key] });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj++;\n\t\t\t\t}\n\n\t\t\t\treturn returningResponse;\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\n\t\tconst rows = await this.queryWithCache(queryString, params, async () => {\n\t\t\treturn await client.execute(queryString, params, queryConfig) as unknown[][];\n\t\t});\n\n\t\tif (customResultMapper) {\n\t\t\treturn customResultMapper(rows);\n\t\t}\n\n\t\treturn rows.map((row) => mapResultRow<T['execute']>(fields!, row, joinsNotNullableMap));\n\t}\n\n\toverride iterator(_placeholderValues?: Record<string, unknown>): AsyncGenerator<T['iterator']> {\n\t\tthrow new Error('Streaming is not supported by the TiDB Cloud Serverless driver');\n\t}\n}\n\nexport interface TiDBServerlessSessionOptions {\n\tlogger?: Logger;\n\tcache?: Cache;\n}\n\nexport class TiDBServerlessSession<\n\tTFullSchema extends Record<string, unknown>,\n\tTSchema extends TablesRelationalConfig,\n> extends MySqlSession<TiDBServerlessQueryResultHKT, TiDBServerlessPreparedQueryHKT, TFullSchema, TSchema> {\n\tstatic override readonly [entityKind]: string = 'TiDBServerlessSession';\n\n\tprivate logger: Logger;\n\tprivate client: Tx | Connection;\n\tprivate cache: Cache;\n\n\tconstructor(\n\t\tprivate baseClient: Connection,\n\t\tdialect: MySqlDialect,\n\t\ttx: Tx | undefined,\n\t\tprivate schema: RelationalSchemaConfig<TSchema> | undefined,\n\t\tprivate options: TiDBServerlessSessionOptions = {},\n\t) {\n\tLine truncated
|
||||
Reference in new issue
Block a user