| 128 | >(schema: Schema, options?: CreateOptions): Promise<ClientContract<Schema, Options>>; |
| 129 | export async function createTestClient(schema: string, options?: CreateTestClientOptions<SchemaDef>): Promise<any>; |
| 130 | export async function createTestClient( |
| 131 | schema: SchemaDef | string, |
| 132 | options?: CreateTestClientOptions<SchemaDef>, |
| 133 | ): Promise<any> { |
| 134 | let workDir = options?.workDir; |
| 135 | let _schema: SchemaDef; |
| 136 | const provider = options?.provider ?? getTestDbProvider() ?? 'sqlite'; |
| 137 | const dbName = options?.dbName ?? getTestDbName(provider); |
| 138 | const dbUrl = match(provider) |
| 139 | .with('sqlite', () => `file:${dbName}`) |
| 140 | .with('mysql', () => `${TEST_MYSQL_URL}/${dbName}`) |
| 141 | .with('postgresql', () => `${TEST_PG_URL}/${dbName}`) |
| 142 | .exhaustive(); |
| 143 | let model: Model | undefined; |
| 144 | |
| 145 | if (typeof schema === 'string') { |
| 146 | const generated = await generateTsSchema( |
| 147 | schema, |
| 148 | provider, |
| 149 | dbUrl, |
| 150 | options?.extraSourceFiles, |
| 151 | undefined, |
| 152 | options?.extraZModelFiles, |
| 153 | options?.extraPluginModelFiles, |
| 154 | ); |
| 155 | workDir = generated.workDir; |
| 156 | model = generated.model; |
| 157 | // replace schema's provider |
| 158 | _schema = { |
| 159 | ...generated.schema, |
| 160 | provider: { |
| 161 | ...generated.schema.provider, |
| 162 | type: provider, |
| 163 | }, |
| 164 | } as SchemaDef; |
| 165 | } else { |
| 166 | // replace schema's provider |
| 167 | _schema = { |
| 168 | ...schema, |
| 169 | provider: { |
| 170 | type: provider, |
| 171 | }, |
| 172 | }; |
| 173 | workDir ??= createTestProject(); |
| 174 | if (options?.schemaFile) { |
| 175 | let schemaContent = fs.readFileSync(options.schemaFile, 'utf-8'); |
| 176 | if (dbUrl) { |
| 177 | // replace `datasource db { }` section |
| 178 | schemaContent = schemaContent.replace( |
| 179 | /datasource\s+db\s*{[^}]*}/m, |
| 180 | `datasource db { |
| 181 | provider = '${provider}' |
| 182 | url = '${dbUrl}' |
| 183 | ${options.dataSourceExtensions ? `extensions = [${options.dataSourceExtensions.join(', ')}]` : ''} |
| 184 | }`, |
| 185 | ); |
| 186 | } |
| 187 | fs.writeFileSync(path.join(workDir!, 'schema.zmodel'), schemaContent); |