|
|
@@ -14,6 +14,8 @@ import { Work } from './entities/Work.js';
|
|
|
import { WorkDayStatistics } from './entities/WorkDayStatistics.js';
|
|
|
import { UserDayStatistics } from './entities/UserDayStatistics.js';
|
|
|
|
|
|
+const MYSQL_CHINA_TIMEZONE = '+08:00';
|
|
|
+
|
|
|
export const AppDataSource = new DataSource({
|
|
|
type: 'mysql',
|
|
|
host: config.database.host,
|
|
|
@@ -24,6 +26,7 @@ export const AppDataSource = new DataSource({
|
|
|
// 永远关闭 synchronize:避免自动改表/删列(统一走 migrations)
|
|
|
synchronize: false,
|
|
|
logging: config.env === 'development',
|
|
|
+ timezone: MYSQL_CHINA_TIMEZONE,
|
|
|
entities: [
|
|
|
User,
|
|
|
UserToken,
|
|
|
@@ -42,9 +45,32 @@ export const AppDataSource = new DataSource({
|
|
|
charset: 'utf8mb4',
|
|
|
});
|
|
|
|
|
|
+let timezoneHookInstalled = false;
|
|
|
+
|
|
|
+async function ensureMysqlSessionTimezone(): Promise<void> {
|
|
|
+ try {
|
|
|
+ await AppDataSource.query(`SET time_zone = '${MYSQL_CHINA_TIMEZONE}'`);
|
|
|
+ } catch {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (timezoneHookInstalled) return;
|
|
|
+
|
|
|
+ const driver: any = AppDataSource.driver as any;
|
|
|
+ const pool: any = driver?.pool;
|
|
|
+
|
|
|
+ if (pool && typeof pool.on === 'function') {
|
|
|
+ pool.on('connection', (connection: any) => {
|
|
|
+ connection.query(`SET time_zone = '${MYSQL_CHINA_TIMEZONE}'`);
|
|
|
+ });
|
|
|
+ timezoneHookInstalled = true;
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
export async function initDatabase(): Promise<DataSource> {
|
|
|
if (!AppDataSource.isInitialized) {
|
|
|
await AppDataSource.initialize();
|
|
|
+ await ensureMysqlSessionTimezone();
|
|
|
}
|
|
|
return AppDataSource;
|
|
|
}
|