@@ -995,12 +995,22 @@ export class SqlDriver implements IDataDriver {
995995 // ── Database helpers ────────────────────────────────────────────────────────
996996
997997 protected async ensureDatabaseExists ( ) {
998- if ( ! this . isPostgres ) return ;
998+ // SQLite auto-creates database files — no need to check
999+ if ( this . isSqlite ) return ;
1000+
1001+ // Only PostgreSQL and MySQL support programmatic database creation
1002+ if ( ! this . isPostgres && ! this . isMysql ) return ;
9991003
10001004 try {
10011005 await this . knex . raw ( 'SELECT 1' ) ;
10021006 } catch ( e : any ) {
1003- if ( e . code === '3D000' ) {
1007+ // PostgreSQL: '3D000' = database does not exist
1008+ // MySQL: 'ER_BAD_DB_ERROR' (errno 1049) = unknown database
1009+ if (
1010+ e . code === '3D000' ||
1011+ e . code === 'ER_BAD_DB_ERROR' ||
1012+ e . errno === 1049
1013+ ) {
10041014 await this . createDatabase ( ) ;
10051015 } else {
10061016 throw e ;
@@ -1014,19 +1024,40 @@ export class SqlDriver implements IDataDriver {
10141024 let dbName = '' ;
10151025 const adminConfig = { ...config } ;
10161026
1017- if ( typeof connection === 'string' ) {
1018- const url = new URL ( connection ) ;
1019- dbName = url . pathname . slice ( 1 ) ;
1020- url . pathname = '/postgres' ;
1021- adminConfig . connection = url . toString ( ) ;
1027+ if ( this . isPostgres ) {
1028+ // PostgreSQL: connect to the 'postgres' maintenance database
1029+ if ( typeof connection === 'string' ) {
1030+ const url = new URL ( connection ) ;
1031+ dbName = url . pathname . slice ( 1 ) ;
1032+ url . pathname = '/postgres' ;
1033+ adminConfig . connection = url . toString ( ) ;
1034+ } else {
1035+ dbName = connection . database ;
1036+ adminConfig . connection = { ...connection , database : 'postgres' } ;
1037+ }
1038+ } else if ( this . isMysql ) {
1039+ // MySQL: connect without specifying a database
1040+ if ( typeof connection === 'string' ) {
1041+ const url = new URL ( connection ) ;
1042+ dbName = url . pathname . slice ( 1 ) ;
1043+ url . pathname = '/' ;
1044+ adminConfig . connection = url . toString ( ) ;
1045+ } else {
1046+ dbName = connection . database ;
1047+ const { database : _db , ...rest } = connection ;
1048+ adminConfig . connection = rest ;
1049+ }
10221050 } else {
1023- dbName = connection . database ;
1024- adminConfig . connection = { ...connection , database : 'postgres' } ;
1051+ return ; // Unsupported dialect for auto-creation
10251052 }
10261053
10271054 const adminKnex = knex ( adminConfig ) ;
10281055 try {
1029- await adminKnex . raw ( `CREATE DATABASE "${ dbName } "` ) ;
1056+ if ( this . isPostgres ) {
1057+ await adminKnex . raw ( `CREATE DATABASE "${ dbName } "` ) ;
1058+ } else if ( this . isMysql ) {
1059+ await adminKnex . raw ( `CREATE DATABASE IF NOT EXISTS \`${ dbName } \`` ) ;
1060+ }
10301061 } finally {
10311062 await adminKnex . destroy ( ) ;
10321063 }
0 commit comments