88 "github.com/TeaWeb/code/teadb/shared"
99 _ "github.com/go-sql-driver/mysql"
1010 "github.com/iwind/TeaGo/logs"
11+ "strings"
1112)
1213
1314type MySQLDriver struct {
@@ -108,7 +109,7 @@ func (this *MySQLDriver) CreateTable(table string, definitionSQL string) error {
108109}
109110
110111// 测试DSN
111- func (this * MySQLDriver ) TestDSN (dsn string ) (message string , ok bool ) {
112+ func (this * MySQLDriver ) TestDSN (dsn string , autoCreateDB bool ) (message string , ok bool ) {
112113 dbInstance , err := sql .Open ("mysql" , dsn )
113114 if err != nil {
114115 message = "DSN解析错误:" + err .Error ()
@@ -118,8 +119,39 @@ func (this *MySQLDriver) TestDSN(dsn string) (message string, ok bool) {
118119 _ = dbInstance .Close ()
119120 }()
120121
122+ // 检查数据库
123+ if autoCreateDB {
124+ index := strings .Index (dsn , "/" )
125+ if index == - 1 {
126+ message = "invalid dsn"
127+ return
128+ }
129+ database := dsn [index + 1 :]
130+ index = strings .Index (database , "?" )
131+ if index > - 1 {
132+ database = database [:index ]
133+ }
134+ if len (database ) == 0 {
135+ message = "no database defined"
136+ return
137+ }
138+ newDSN := strings .Replace (dsn , "/" + database , "/" , - 1 )
139+ newDBInstance , err := sql .Open ("mysql" , newDSN )
140+ if err != nil {
141+ message = err .Error ()
142+ return
143+ }
144+ _ , err = newDBInstance .ExecContext (context .Background (), "CREATE DATABASE IF NOT EXISTS `" + database + "`" )
145+ if err != nil {
146+ message = err .Error ()
147+ _ = newDBInstance .Close ()
148+ return
149+ }
150+ _ = newDBInstance .Close ()
151+ }
152+
121153 // 测试创建数据表
122- _ , err = dbInstance .ExecContext (context .Background (), "CREATE TABLE `teaweb.test ` ( " +
154+ _ , err = dbInstance .ExecContext (context .Background (), "CREATE TABLE `teaweb_test ` ( " +
123155 "`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT," +
124156 "`_id` varchar(24) DEFAULT NULL," +
125157 "PRIMARY KEY (`id`)," +
@@ -131,14 +163,14 @@ func (this *MySQLDriver) TestDSN(dsn string) (message string, ok bool) {
131163 }
132164
133165 // 测试写入数据表
134- _ , err = dbInstance .ExecContext (context .Background (), "INSERT INTO `teaweb.test ` (`_id`) VALUES (\" " + shared .NewObjectId ().Hex ()+ "\" )" )
166+ _ , err = dbInstance .ExecContext (context .Background (), "INSERT INTO `teaweb_test ` (`_id`) VALUES (\" " + shared .NewObjectId ().Hex ()+ "\" )" )
135167 if err != nil {
136168 message = "尝试写入数据表失败:" + err .Error ()
137169 return
138170 }
139171
140172 // 测试删除数据表
141- _ , err = dbInstance .ExecContext (context .Background (), "DROP TABLE `teaweb.test `" )
173+ _ , err = dbInstance .ExecContext (context .Background (), "DROP TABLE `teaweb_test `" )
142174 if err != nil {
143175 message = "尝试删除数据表失败:" + err .Error ()
144176 return
0 commit comments