Initial commit

This commit is contained in:
Ammaar Reshi
2025-01-04 14:06:53 +00:00
parent 7082408604
commit d6025af146
23760 changed files with 3299690 additions and 0 deletions

View File

@ -0,0 +1,106 @@
"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, {
PlanetScaleDatabase: () => PlanetScaleDatabase,
drizzle: () => drizzle
});
module.exports = __toCommonJS(driver_exports);
var import_database = require("@planetscale/database");
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 PlanetScaleDatabase extends import_db.MySqlDatabase {
static [import_entity.entityKind] = "PlanetScaleDatabase";
}
function construct(client, config = {}) {
if (!(client instanceof import_database.Client)) {
throw new Error(`Warning: You need to pass an instance of Client:
import { Client } from "@planetscale/database";
const client = new Client({
host: process.env["DATABASE_HOST"],
username: process.env["DATABASE_USERNAME"],
password: process.env["DATABASE_PASSWORD"],
});
const db = drizzle(client);
`);
}
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.PlanetscaleSession(client, dialect, void 0, schema, { logger });
const db = new PlanetScaleDatabase(dialect, session, schema, "planetscale");
db.$client = client;
return db;
}
function drizzle(...params) {
if (typeof params[0] === "string") {
const instance = new import_database.Client({
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" ? new import_database.Client({
url: connection
}) : new import_database.Client(
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 = {
PlanetScaleDatabase,
drizzle
});
//# sourceMappingURL=driver.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,32 @@
import type { Config } from '@planetscale/database';
import { Client } from '@planetscale/database';
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 { PlanetScalePreparedQueryHKT, PlanetscaleQueryResultHKT } from "./session.cjs";
export interface PlanetscaleSDriverOptions {
logger?: Logger;
}
export declare class PlanetScaleDatabase<TSchema extends Record<string, unknown> = Record<string, never>> extends MySqlDatabase<PlanetscaleQueryResultHKT, PlanetScalePreparedQueryHKT, TSchema> {
static readonly [entityKind]: string;
}
export declare function drizzle<TSchema extends Record<string, unknown> = Record<string, never>, TClient extends Client = Client>(...params: [
TClient | string
] | [
TClient | string,
DrizzleConfig<TSchema>
] | [
(DrizzleConfig<TSchema> & ({
connection: string | Config;
} | {
client: TClient;
}))
]): PlanetScaleDatabase<TSchema> & {
$client: TClient;
};
export declare namespace drizzle {
function mock<TSchema extends Record<string, unknown> = Record<string, never>>(config?: DrizzleConfig<TSchema>): PlanetScaleDatabase<TSchema> & {
$client: '$client is not available on drizzle.mock()';
};
}

View File

@ -0,0 +1,32 @@
import type { Config } from '@planetscale/database';
import { Client } from '@planetscale/database';
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 { PlanetScalePreparedQueryHKT, PlanetscaleQueryResultHKT } from "./session.js";
export interface PlanetscaleSDriverOptions {
logger?: Logger;
}
export declare class PlanetScaleDatabase<TSchema extends Record<string, unknown> = Record<string, never>> extends MySqlDatabase<PlanetscaleQueryResultHKT, PlanetScalePreparedQueryHKT, TSchema> {
static readonly [entityKind]: string;
}
export declare function drizzle<TSchema extends Record<string, unknown> = Record<string, never>, TClient extends Client = Client>(...params: [
TClient | string
] | [
TClient | string,
DrizzleConfig<TSchema>
] | [
(DrizzleConfig<TSchema> & ({
connection: string | Config;
} | {
client: TClient;
}))
]): PlanetScaleDatabase<TSchema> & {
$client: TClient;
};
export declare namespace drizzle {
function mock<TSchema extends Record<string, unknown> = Record<string, never>>(config?: DrizzleConfig<TSchema>): PlanetScaleDatabase<TSchema> & {
$client: '$client is not available on drizzle.mock()';
};
}

View File

@ -0,0 +1,84 @@
import { Client } from "@planetscale/database";
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 { PlanetscaleSession } from "./session.js";
class PlanetScaleDatabase extends MySqlDatabase {
static [entityKind] = "PlanetScaleDatabase";
}
function construct(client, config = {}) {
if (!(client instanceof Client)) {
throw new Error(`Warning: You need to pass an instance of Client:
import { Client } from "@planetscale/database";
const client = new Client({
host: process.env["DATABASE_HOST"],
username: process.env["DATABASE_USERNAME"],
password: process.env["DATABASE_PASSWORD"],
});
const db = drizzle(client);
`);
}
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 PlanetscaleSession(client, dialect, void 0, schema, { logger });
const db = new PlanetScaleDatabase(dialect, session, schema, "planetscale");
db.$client = client;
return db;
}
function drizzle(...params) {
if (typeof params[0] === "string") {
const instance = new Client({
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" ? new Client({
url: connection
}) : new Client(
connection
);
return construct(instance, drizzleConfig);
}
return construct(params[0], params[1]);
}
((drizzle2) => {
function mock(config) {
return construct({}, config);
}
drizzle2.mock = mock;
})(drizzle || (drizzle = {}));
export {
PlanetScaleDatabase,
drizzle
};
//# sourceMappingURL=driver.js.map

File diff suppressed because one or more lines are too long

View File

@ -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 planetscale_serverless_exports = {};
module.exports = __toCommonJS(planetscale_serverless_exports);
__reExport(planetscale_serverless_exports, require("./driver.cjs"), module.exports);
__reExport(planetscale_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

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/planetscale-serverless/index.ts"],"sourcesContent":["export * from './driver.ts';\nexport * from './session.ts';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAAA,2CAAc,wBAAd;AACA,2CAAc,yBADd;","names":[]}

View File

@ -0,0 +1,2 @@
export * from "./driver.cjs";
export * from "./session.cjs";

View File

@ -0,0 +1,2 @@
export * from "./driver.js";
export * from "./session.js";

View File

@ -0,0 +1,3 @@
export * from "./driver.js";
export * from "./session.js";
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/planetscale-serverless/index.ts"],"sourcesContent":["export * from './driver.ts';\nexport * from './session.ts';\n"],"mappings":"AAAA,cAAc;AACd,cAAc;","names":[]}

View File

@ -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

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/planetscale-serverless/migrator.ts"],"sourcesContent":["import type { MigrationConfig } from '~/migrator.ts';\nimport { readMigrationFiles } from '~/migrator.ts';\nimport type { PlanetScaleDatabase } from './driver.ts';\n\nexport async function migrate<TSchema extends Record<string, unknown>>(\n\tdb: PlanetScaleDatabase<TSchema>,\n\tconfig: MigrationConfig,\n) {\n\tconst migrations = readMigrationFiles(config);\n\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;AAE5C,QAAM,GAAG,QAAQ,QAAQ,YAAY,GAAG,SAAS,MAAM;AACxD;","names":[]}

View File

@ -0,0 +1,3 @@
import type { MigrationConfig } from "../migrator.cjs";
import type { PlanetScaleDatabase } from "./driver.cjs";
export declare function migrate<TSchema extends Record<string, unknown>>(db: PlanetScaleDatabase<TSchema>, config: MigrationConfig): Promise<void>;

View File

@ -0,0 +1,3 @@
import type { MigrationConfig } from "../migrator.js";
import type { PlanetScaleDatabase } from "./driver.js";
export declare function migrate<TSchema extends Record<string, unknown>>(db: PlanetScaleDatabase<TSchema>, config: MigrationConfig): Promise<void>;

View File

@ -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

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/planetscale-serverless/migrator.ts"],"sourcesContent":["import type { MigrationConfig } from '~/migrator.ts';\nimport { readMigrationFiles } from '~/migrator.ts';\nimport type { PlanetScaleDatabase } from './driver.ts';\n\nexport async function migrate<TSchema extends Record<string, unknown>>(\n\tdb: PlanetScaleDatabase<TSchema>,\n\tconfig: MigrationConfig,\n) {\n\tconst migrations = readMigrationFiles(config);\n\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;AAE5C,QAAM,GAAG,QAAQ,QAAQ,YAAY,GAAG,SAAS,MAAM;AACxD;","names":[]}

View File

@ -0,0 +1,180 @@
"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, {
PlanetScalePreparedQuery: () => PlanetScalePreparedQuery,
PlanetScaleTransaction: () => PlanetScaleTransaction,
PlanetscaleSession: () => PlanetscaleSession
});
module.exports = __toCommonJS(session_exports);
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");
class PlanetScalePreparedQuery extends import_session.MySqlPreparedQuery {
constructor(client, queryString, params, logger, fields, customResultMapper, generatedIds, returningIds) {
super();
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] = "PlanetScalePreparedQuery";
rawQuery = { as: "object" };
query = { as: "array" };
async execute(placeholderValues = {}) {
const params = (0, import_sql.fillPlaceholders)(this.params, placeholderValues);
this.logger.logQuery(this.queryString, params);
const {
fields,
client,
queryString,
rawQuery,
query,
joinsNotNullableMap,
customResultMapper,
returningIds,
generatedIds
} = this;
if (!fields && !customResultMapper) {
const res = await client.execute(queryString, params, rawQuery);
const insertId = Number.parseFloat(res.insertId);
const affectedRows = res.rowsAffected;
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 client.execute(queryString, params, query);
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 PlanetScale Serverless driver");
}
}
class PlanetscaleSession 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();
}
static [import_entity.entityKind] = "PlanetscaleSession";
logger;
client;
prepareQuery(query, fields, customResultMapper, generatedIds, returningIds) {
return new PlanetScalePreparedQuery(
this.client,
query.sql,
query.params,
this.logger,
fields,
customResultMapper,
generatedIds,
returningIds
);
}
async query(query, params) {
this.logger.logQuery(query, params);
return await this.client.execute(query, params, { as: "array" });
}
async queryObjects(query, params) {
return this.client.execute(query, params, { as: "object" });
}
all(query) {
const querySql = this.dialect.sqlToQuery(query);
this.logger.logQuery(querySql.sql, querySql.params);
return this.client.execute(querySql.sql, querySql.params, { as: "object" }).then((eQuery) => eQuery.rows);
}
async count(sql2) {
const res = await this.execute(sql2);
return Number(
res["rows"][0]["count"]
);
}
transaction(transaction) {
return this.baseClient.transaction((pstx) => {
const session = new PlanetscaleSession(this.baseClient, this.dialect, pstx, this.schema, this.options);
const tx = new PlanetScaleTransaction(
this.dialect,
session,
this.schema
);
return transaction(tx);
});
}
}
class PlanetScaleTransaction extends import_session.MySqlTransaction {
static [import_entity.entityKind] = "PlanetScaleTransaction";
constructor(dialect, session, schema, nestedIndex = 0) {
super(dialect, session, schema, nestedIndex, "planetscale");
}
async transaction(transaction) {
const savepointName = `sp${this.nestedIndex + 1}`;
const tx = new PlanetScaleTransaction(
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 = {
PlanetScalePreparedQuery,
PlanetScaleTransaction,
PlanetscaleSession
});
//# sourceMappingURL=session.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,54 @@
import type { Client, Connection, ExecutedQuery, Transaction } from '@planetscale/database';
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 PlanetScalePreparedQuery<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;
private rawQuery;
private query;
constructor(client: Client | Transaction | Connection, queryString: string, params: unknown[], logger: Logger, 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 PlanetscaleSessionOptions {
logger?: Logger;
}
export declare class PlanetscaleSession<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig> extends MySqlSession<MySqlQueryResultHKT, PlanetScalePreparedQueryHKT, TFullSchema, TSchema> {
private baseClient;
private schema;
private options;
static readonly [entityKind]: string;
private logger;
private client;
constructor(baseClient: Client | Connection, dialect: MySqlDialect, tx: Transaction | undefined, schema: RelationalSchemaConfig<TSchema> | undefined, options?: PlanetscaleSessionOptions);
prepareQuery<T extends MySqlPreparedQueryConfig = MySqlPreparedQueryConfig>(query: Query, fields: SelectedFieldsOrdered | undefined, customResultMapper?: (rows: unknown[][]) => T['execute'], generatedIds?: Record<string, unknown>[], returningIds?: SelectedFieldsOrdered): MySqlPreparedQuery<T>;
query(query: string, params: unknown[]): Promise<ExecutedQuery>;
queryObjects(query: string, params: unknown[]): Promise<ExecutedQuery>;
all<T = unknown>(query: SQL): Promise<T[]>;
count(sql: SQL): Promise<number>;
transaction<T>(transaction: (tx: PlanetScaleTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T>;
}
export declare class PlanetScaleTransaction<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig> extends MySqlTransaction<PlanetscaleQueryResultHKT, PlanetScalePreparedQueryHKT, TFullSchema, TSchema> {
static readonly [entityKind]: string;
constructor(dialect: MySqlDialect, session: MySqlSession, schema: RelationalSchemaConfig<TSchema> | undefined, nestedIndex?: number);
transaction<T>(transaction: (tx: PlanetScaleTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T>;
}
export interface PlanetscaleQueryResultHKT extends MySqlQueryResultHKT {
type: ExecutedQuery;
}
export interface PlanetScalePreparedQueryHKT extends MySqlPreparedQueryHKT {
type: PlanetScalePreparedQuery<Assume<this['config'], MySqlPreparedQueryConfig>>;
}

View File

@ -0,0 +1,54 @@
import type { Client, Connection, ExecutedQuery, Transaction } from '@planetscale/database';
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 PlanetScalePreparedQuery<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;
private rawQuery;
private query;
constructor(client: Client | Transaction | Connection, queryString: string, params: unknown[], logger: Logger, 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 PlanetscaleSessionOptions {
logger?: Logger;
}
export declare class PlanetscaleSession<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig> extends MySqlSession<MySqlQueryResultHKT, PlanetScalePreparedQueryHKT, TFullSchema, TSchema> {
private baseClient;
private schema;
private options;
static readonly [entityKind]: string;
private logger;
private client;
constructor(baseClient: Client | Connection, dialect: MySqlDialect, tx: Transaction | undefined, schema: RelationalSchemaConfig<TSchema> | undefined, options?: PlanetscaleSessionOptions);
prepareQuery<T extends MySqlPreparedQueryConfig = MySqlPreparedQueryConfig>(query: Query, fields: SelectedFieldsOrdered | undefined, customResultMapper?: (rows: unknown[][]) => T['execute'], generatedIds?: Record<string, unknown>[], returningIds?: SelectedFieldsOrdered): MySqlPreparedQuery<T>;
query(query: string, params: unknown[]): Promise<ExecutedQuery>;
queryObjects(query: string, params: unknown[]): Promise<ExecutedQuery>;
all<T = unknown>(query: SQL): Promise<T[]>;
count(sql: SQL): Promise<number>;
transaction<T>(transaction: (tx: PlanetScaleTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T>;
}
export declare class PlanetScaleTransaction<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig> extends MySqlTransaction<PlanetscaleQueryResultHKT, PlanetScalePreparedQueryHKT, TFullSchema, TSchema> {
static readonly [entityKind]: string;
constructor(dialect: MySqlDialect, session: MySqlSession, schema: RelationalSchemaConfig<TSchema> | undefined, nestedIndex?: number);
transaction<T>(transaction: (tx: PlanetScaleTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T>;
}
export interface PlanetscaleQueryResultHKT extends MySqlQueryResultHKT {
type: ExecutedQuery;
}
export interface PlanetScalePreparedQueryHKT extends MySqlPreparedQueryHKT {
type: PlanetScalePreparedQuery<Assume<this['config'], MySqlPreparedQueryConfig>>;
}

View File

@ -0,0 +1,158 @@
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";
class PlanetScalePreparedQuery extends MySqlPreparedQuery {
constructor(client, queryString, params, logger, fields, customResultMapper, generatedIds, returningIds) {
super();
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] = "PlanetScalePreparedQuery";
rawQuery = { as: "object" };
query = { as: "array" };
async execute(placeholderValues = {}) {
const params = fillPlaceholders(this.params, placeholderValues);
this.logger.logQuery(this.queryString, params);
const {
fields,
client,
queryString,
rawQuery,
query,
joinsNotNullableMap,
customResultMapper,
returningIds,
generatedIds
} = this;
if (!fields && !customResultMapper) {
const res = await client.execute(queryString, params, rawQuery);
const insertId = Number.parseFloat(res.insertId);
const affectedRows = res.rowsAffected;
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 client.execute(queryString, params, query);
if (customResultMapper) {
return customResultMapper(rows);
}
return rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
}
iterator(_placeholderValues) {
throw new Error("Streaming is not supported by the PlanetScale Serverless driver");
}
}
class PlanetscaleSession 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();
}
static [entityKind] = "PlanetscaleSession";
logger;
client;
prepareQuery(query, fields, customResultMapper, generatedIds, returningIds) {
return new PlanetScalePreparedQuery(
this.client,
query.sql,
query.params,
this.logger,
fields,
customResultMapper,
generatedIds,
returningIds
);
}
async query(query, params) {
this.logger.logQuery(query, params);
return await this.client.execute(query, params, { as: "array" });
}
async queryObjects(query, params) {
return this.client.execute(query, params, { as: "object" });
}
all(query) {
const querySql = this.dialect.sqlToQuery(query);
this.logger.logQuery(querySql.sql, querySql.params);
return this.client.execute(querySql.sql, querySql.params, { as: "object" }).then((eQuery) => eQuery.rows);
}
async count(sql2) {
const res = await this.execute(sql2);
return Number(
res["rows"][0]["count"]
);
}
transaction(transaction) {
return this.baseClient.transaction((pstx) => {
const session = new PlanetscaleSession(this.baseClient, this.dialect, pstx, this.schema, this.options);
const tx = new PlanetScaleTransaction(
this.dialect,
session,
this.schema
);
return transaction(tx);
});
}
}
class PlanetScaleTransaction extends MySqlTransaction {
static [entityKind] = "PlanetScaleTransaction";
constructor(dialect, session, schema, nestedIndex = 0) {
super(dialect, session, schema, nestedIndex, "planetscale");
}
async transaction(transaction) {
const savepointName = `sp${this.nestedIndex + 1}`;
const tx = new PlanetScaleTransaction(
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 {
PlanetScalePreparedQuery,
PlanetScaleTransaction,
PlanetscaleSession
};
//# sourceMappingURL=session.js.map

File diff suppressed because one or more lines are too long