Skip to content

Commit

Permalink
feat(minato): enhance generic typings
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Feb 8, 2024
1 parent fb984b3 commit cdf8309
Show file tree
Hide file tree
Showing 9 changed files with 26 additions and 27 deletions.
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"postgres"
],
"dependencies": {
"cordis": "^3.9.0",
"cordis": "^3.9.1",
"cosmokit": "^1.5.2"
}
}
12 changes: 6 additions & 6 deletions packages/core/src/database.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Dict, Intersect, makeArray, MaybeArray, valueMap } from 'cosmokit'
import { Context, Plugin, Service, Spread } from 'cordis'
import { Context, Service, Spread } from 'cordis'
import { Flatten, Indexable, Keys, Row } from './utils.ts'
import { Selection } from './selection.ts'
import { Field, Model } from './model.ts'
Expand Down Expand Up @@ -37,7 +37,7 @@ type JoinCallback2<S, U extends Dict<TableLike<S>>> = (args: {

const kTransaction = Symbol('transaction')

export class Database<S = any> extends Service {
export class Database<S = any, C extends Context = Context> extends Service<C> {
public tables: { [K in Keys<S>]: Model<S[K]> } = Object.create(null)
public drivers: Record<keyof any, Driver> = Object.create(null)
public migrating = false
Expand All @@ -46,12 +46,12 @@ export class Database<S = any> extends Service {

private stashed = new Set<string>()

constructor(ctx?: Context) {
constructor(ctx?: C) {
super(ctx, 'model', true)
}

async connect<T = undefined>(driver: Plugin.Constructor<Context, T>, ...args: Spread<T>) {
this.ctx.plugin(driver, args[0])
async connect<T = undefined>(driver: Driver.Constructor<T>, ...args: Spread<T>) {
this.ctx.plugin(driver, args[0] as any)
await this.ctx.start()
}

Expand Down Expand Up @@ -92,7 +92,7 @@ export class Database<S = any> extends Service {
}
model.extend(fields, config)
this.prepareTasks[name] = this.prepare(name)
this.ctx.emit('minato/model', name)
;(this.ctx as Context).emit('model', name)
}

migrate<K extends Keys<S>>(name: K, fields: Field.Extension<S[K]>, callback: Model.Migration) {
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ export namespace Driver {
}

export namespace Driver {
export type Constructor<T = any> = new (database: Database, config?: T) => Driver
export type Constructor<T> = new (ctx: Context, config: T) => Driver<T>
}

export abstract class Driver<C = any> {
export abstract class Driver<T = any> {
static inject = ['model']

abstract start(): Promise<void>
Expand All @@ -52,12 +52,12 @@ export abstract class Driver<C = any> {
abstract remove(sel: Selection.Mutable): Promise<Driver.WriteResult>
abstract create(sel: Selection.Mutable, data: any): Promise<any>
abstract upsert(sel: Selection.Mutable, data: any[], keys: string[]): Promise<Driver.WriteResult>
abstract withTransaction(callback: (driver: Driver) => Promise<void>): Promise<void>
abstract withTransaction(callback: (driver: this) => Promise<void>): Promise<void>

public database: Database
public logger: Logger

constructor(public ctx: Context, public config: C) {
constructor(public ctx: Context, public config: T) {
this.database = ctx.model
this.logger = ctx.logger(this.constructor.name)

Expand Down
8 changes: 3 additions & 5 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,15 @@ export * from './utils.ts'

declare module 'cordis' {
interface Events {
'minato/model'(name: string): void
'model'(name: string): void
}

interface Context {
database: Database<Tables>
model: Database<Tables>
database: Database
model: Database
}
}

export interface Tables {}

export { Logger, Schema, Schema as z } from 'cordis'

export default Database
14 changes: 8 additions & 6 deletions packages/memory/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { clone, Dict, makeArray, noop, omit, pick, valueMap } from 'cosmokit'
import { Driver, Eval, executeEval, executeQuery, executeSort, executeUpdate, RuntimeError, Selection } from 'minato'

export namespace MemoryDriver {
export interface Config {}
}
import { Driver, Eval, executeEval, executeQuery, executeSort, executeUpdate, RuntimeError, Selection, z } from 'minato'

export class MemoryDriver extends Driver<MemoryDriver.Config> {
static name = 'memory'
Expand Down Expand Up @@ -189,7 +185,7 @@ export class MemoryDriver extends Driver<MemoryDriver.Config> {
return res
}

async withTransaction(callback: (session: Driver) => Promise<void>) {
async withTransaction(callback: (session: this) => Promise<void>) {
const data = clone(this.#store)
await callback(this).then(undefined, (e) => {
this.#store = data
Expand All @@ -198,4 +194,10 @@ export class MemoryDriver extends Driver<MemoryDriver.Config> {
}
}

export namespace MemoryDriver {
export interface Config {}

export const Config: z<Config> = z.object({})
}

export default MemoryDriver
2 changes: 1 addition & 1 deletion packages/mongo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ export class MongoDriver extends Driver<MongoDriver.Config> {
}
}

async withTransaction(callback: (session: Driver) => Promise<void>) {
async withTransaction(callback: (session: this) => Promise<void>) {
await this.client.withSession(async (session) => {
const driver = new Proxy(this, {
get(target, p, receiver) {
Expand Down
2 changes: 1 addition & 1 deletion packages/mysql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,7 @@ INSERT INTO mtt VALUES(json_extract(j, concat('$[', i, ']'))); SET i=i+1; END WH
return { inserted: records - result.changedRows, matched: result.changedRows, modified: result.affectedRows - records }
}

async withTransaction(callback: (session: Driver) => Promise<void>) {
async withTransaction(callback: (session: this) => Promise<void>) {
return new Promise<void>((resolve, reject) => {
this.pool.getConnection((err, conn) => {
if (err) {
Expand Down
2 changes: 1 addition & 1 deletion packages/postgres/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -760,7 +760,7 @@ export class PostgresDriver extends Driver<PostgresDriver.Config> {
return { inserted: result.filter(({ rtime }) => +rtime !== mtime).length, matched: result.filter(({ rtime }) => +rtime === mtime).length }
}

async withTransaction(callback: (session: Driver) => Promise<void>) {
async withTransaction(callback: (session: this) => Promise<void>) {
return await this.postgres.begin(async (conn) => {
const driver = new Proxy(this, {
get(target, p, receiver) {
Expand Down
3 changes: 1 addition & 2 deletions packages/sqlite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,6 @@ export class SQLiteDriver extends Driver<SQLiteDriver.Config> {
: require.resolve('@minatojs/sql.js/dist/' + file),
})
if (!isBrowser || this.config.path === ':memory:') {
console.log(this.config.path)
this.db = new sqlite.Database(this.config.path)
} else {
const buffer = await readFile(this.config.path).catch(() => null)
Expand Down Expand Up @@ -452,7 +451,7 @@ export class SQLiteDriver extends Driver<SQLiteDriver.Config> {
return result
}

async withTransaction(callback: (session: Driver) => Promise<void>) {
async withTransaction(callback: (session: this) => Promise<void>) {
if (this._transactionTask) await this._transactionTask
return this._transactionTask = new Promise<void>((resolve, reject) => {
this.#run('BEGIN TRANSACTION')
Expand Down

0 comments on commit cdf8309

Please sign in to comment.