2022-02-15 00:20:25 +08:00
|
|
|
import { merge, uid } from '@nocobase/utils';
|
|
|
|
import { resolve } from 'path';
|
|
|
|
import { Database, IDatabaseOptions } from './database';
|
|
|
|
|
|
|
|
export class MockDatabase extends Database {
|
|
|
|
constructor(options: IDatabaseOptions) {
|
|
|
|
super({
|
|
|
|
storage: ':memory:',
|
|
|
|
tablePrefix: `mock_${uid(6)}_`,
|
2022-03-28 22:01:10 +08:00
|
|
|
dialect: 'sqlite',
|
2022-02-15 00:20:25 +08:00
|
|
|
...options,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getConfigByEnv() {
|
|
|
|
return {
|
|
|
|
username: process.env.DB_USER,
|
|
|
|
password: process.env.DB_PASSWORD,
|
|
|
|
database: process.env.DB_DATABASE,
|
|
|
|
host: process.env.DB_HOST,
|
|
|
|
port: process.env.DB_PORT,
|
2022-10-06 10:29:53 +08:00
|
|
|
dialect: process.env.DB_DIALECT || 'sqlite',
|
2022-05-19 00:40:55 +08:00
|
|
|
logging: process.env.DB_LOGGING === 'on' ? console.log : false,
|
2022-03-28 22:01:10 +08:00
|
|
|
storage:
|
|
|
|
process.env.DB_STORAGE && process.env.DB_STORAGE !== ':memory:'
|
|
|
|
? resolve(process.cwd(), process.env.DB_STORAGE)
|
|
|
|
: ':memory:',
|
2022-02-15 22:32:02 +08:00
|
|
|
define: {
|
2022-02-15 00:20:25 +08:00
|
|
|
charset: 'utf8mb4',
|
|
|
|
collate: 'utf8mb4_unicode_ci',
|
|
|
|
},
|
2022-06-01 11:41:46 +08:00
|
|
|
timezone: process.env.DB_TIMEZONE,
|
2023-02-13 21:38:47 +08:00
|
|
|
underscored: process.env.DB_UNDERSCORED === 'true',
|
2023-02-16 10:53:04 +08:00
|
|
|
schema: process.env.DB_SCHEMA !== 'public' ? process.env.DB_SCHEMA : undefined,
|
2022-02-15 00:20:25 +08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export function mockDatabase(options: IDatabaseOptions = {}): MockDatabase {
|
2023-02-13 21:38:47 +08:00
|
|
|
const dbOptions = merge(getConfigByEnv(), options) as any;
|
2022-03-28 22:01:10 +08:00
|
|
|
return new MockDatabase(dbOptions);
|
2022-02-15 00:20:25 +08:00
|
|
|
}
|