forked from pingcap/tidb-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ddl_syncer.go
67 lines (60 loc) · 1.85 KB
/
ddl_syncer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2018 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package checker
import (
"context"
"database/sql"
"github.com/pingcap/errors"
"github.com/pingcap/tidb-tools/pkg/dbutil"
)
// DDLSyncer can sync the table structure from upstream(usually MySQL) to ExecutableChecker
type DDLSyncer struct {
db *sql.DB
ec *ExecutableChecker
}
// NewDDLSyncer create a new DDLSyncer
func NewDDLSyncer(cfg *dbutil.DBConfig, executableChecker *ExecutableChecker) (*DDLSyncer, error) {
db, err := dbutil.OpenDB(*cfg)
if err != nil {
return nil, errors.Trace(err)
}
return &DDLSyncer{db, executableChecker}, nil
}
// SyncTable can sync table structure from upstream by table name
func (ds *DDLSyncer) SyncTable(tidbContext context.Context, schemaName string, tableName string) error {
createTableSQL, err := dbutil.GetCreateTableSQL(context.Background(), ds.db, schemaName, tableName)
if err != nil {
return errors.Trace(err)
}
err = ds.ec.DropTable(tidbContext, tableName)
if err != nil {
return errors.Trace(err)
}
err = ds.ec.Execute(tidbContext, createTableSQL)
if err != nil {
return errors.Trace(err)
}
return nil
}
// Close the DDLSyncer, if the ExecutableChecker in DDLSyncer is open, it will be closed, too
func (ds *DDLSyncer) Close() error {
err1 := ds.ec.Close()
err2 := dbutil.CloseDB(ds.db)
if err1 != nil {
return errors.Trace(err1)
}
if err2 != nil {
return errors.Trace(err2)
}
return nil
}