import { DMMF } from '@prisma/client/runtime/dmmf-types' ; import { DataSource } from '@prisma/generator-helper' ; import * as fs from 'fs' ; import _ from 'lodash' ; import * as os from 'os' ; import * as path from 'path' ; import { promisify } from 'util' ; import { migrateLift , getTmpPrismaSchemaPath } from '../lift' ; import { InternalPool } from '../pool' ; import { Pool , DBInstance } from '../../types' ; const fsUnlink = promisify ( fs . unlink ) ; param dmmf export function getSQLitePool ( dmmf , cwd ) { return class extends SQLitePool { constructor ( options ? ) { super ( dmmf , { databasePath : getTmpSQLiteDB , tmpPrismaSchemaPath : getTmpPrismaSchemaPath , ... options , } , cwd ) ; } } ; } export interface SQLitePoolOptions { databasePath ? : ( id : string ) => string ; tmpPrismaSchemaPath ? : ( id : string ) => string ; pool ? : { max ? : number ; } ; } class SQLitePool extends InternalPool { private dmmf : DMMF . Document ; private projectDir : string ; private getDatabasePath : ( id : string ) => string ; private getTmpPrismaSchemaPath : ( id : string ) => string ; constructor ( dmmf , options , cwd ) { super ( { max : _ . get ( options , [ 'pool' , 'max' ] , Infinity ) } ) ; this . dmmf = dmmf ; this . projectDir = cwd ; this . getDatabasePath = options . databasePath ! ; this . getTmpPrismaSchemaPath = options . tmpPrismaSchemaPath ! ; } /**
     * Creates a new DB instances and lifts a migration.
     */ async createDBInstance ( id ) { try { const dbFile = this . getDatabasePath ( id ) ; const tmpPrismaSchemaPath = this . getTmpPrismaSchemaPath ( id ) ; const datasources = [ { name : 'db' , connectorType : 'sqlite' , url : { value : `file:${ dbFile }` , fromEnvVar : null , } , config : { } , } , ] ; const { datamodel } = await migrateLift ( { id , projectDir : this . projectDir , datasources , tmpPrismaSchemaPath , dmmf : this . dmmf , } ) ; const instance = { url : dbFile , cwd : this . projectDir , datamodel : datamodel , } ; return instance ; } catch ( err ) { throw err ; } } param instance protected async deleteDBInstance ( instance ) { try { await fsUnlink ( instance . url ) ; } catch ( err ) { throw err ; } } } param id export function getTmpSQLiteDB ( id ) { const tmpDir = os . tmpdir ( ) ; const dbFile = path . join ( tmpDir , `./prisma-sqlite-${ id }-db.db` ) ; return dbFile ; }