Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor: prepare to get rid of db structures (#4124)

Danny Xu6ca02c5da9a4
diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.go
index fffe1d9b79..f40cc15d8a 100644
--- a/plugin/advisor/utils_for_tests.go
+++ b/plugin/advisor/utils_for_tests.go
@@ -289,8 +289,8 @@ func (*MockDriver) SyncInstance(_ context.Context) (*database.InstanceMeta, erro
}
// SyncDBSchema implements the Driver interface.
-func (*MockDriver) SyncDBSchema(_ context.Context, _ string) (*database.Schema, map[string][]*storepb.ForeignKeyMetadata, error) {
- return nil, nil, nil
+func (*MockDriver) SyncDBSchema(_ context.Context, _ string) (*storepb.DatabaseMetadata, error) {
+ return nil, nil
}
// NeedsSetupMigration implements the Driver interface.
diff --git a/plugin/db/clickhouse/sync.go b/plugin/db/clickhouse/sync.go
index 13a1b974f9..77e9f5799f 100644
--- a/plugin/db/clickhouse/sync.go
+++ b/plugin/db/clickhouse/sync.go
@@ -69,7 +69,7 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error
}
// SyncDBSchema syncs a single database schema.
-func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*db.Schema, map[string][]*storepb.ForeignKeyMetadata, error) {
+func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*storepb.DatabaseMetadata, error) {
// Query column info
columnWhere := fmt.Sprintf("LOWER(database) = '%s'", strings.ToLower(databaseName))
columnQuery := `
@@ -85,7 +85,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
WHERE ` + columnWhere
columnRows, err := driver.db.QueryContext(ctx, columnQuery)
if err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, columnQuery)
+ return nil, util.FormatErrorWithQuery(err, columnQuery)
}
defer columnRows.Close()
@@ -104,7 +104,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
&column.Type,
&column.Comment,
); err != nil {
- return nil, nil, err
+ return nil, err
}
key := fmt.Sprintf("%s/%s", dbName, tableName)
@@ -115,7 +115,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
}
}
if err := columnRows.Err(); err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, columnQuery)
+ return nil, util.FormatErrorWithQuery(err, columnQuery)
}
// Query table info
@@ -134,7 +134,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
WHERE ` + tableWhere
tableRows, err := driver.db.QueryContext(ctx, tableQuery)
if err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, tableQuery)
+ return nil, util.FormatErrorWithQuery(err, tableQuery)
}
defer tableRows.Close()
@@ -157,7 +157,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
&definition,
&comment,
); err != nil {
- return nil, nil, err
+ return nil, err
}
if engine == "View" {
@@ -183,7 +183,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
}
}
if err := tableRows.Err(); err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, tableQuery)
+ return nil, util.FormatErrorWithQuery(err, tableQuery)
}
// Query db info
@@ -198,14 +198,14 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
&schema.Name,
); err != nil {
if err == sql.ErrNoRows {
- return nil, nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
+ return nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
}
- return nil, nil, err
+ return nil, err
}
schema.TableList = tableMap[schema.Name]
schema.ViewList = viewMap[schema.Name]
- return &schema, nil, nil
+ return util.ConvertDBSchema(&schema, nil), nil
}
func (driver *Driver) getUserList(ctx context.Context) ([]db.User, error) {
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index 9e9e6b2237..83274fbacc 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -505,7 +505,7 @@ type Driver interface {
// SyncInstance syncs the instance metadata.
SyncInstance(ctx context.Context) (*InstanceMeta, error)
// SyncDBSchema syncs a single database schema.
- SyncDBSchema(ctx context.Context, database string) (*Schema, map[string][]*storepb.ForeignKeyMetadata, error)
+ SyncDBSchema(ctx context.Context, database string) (*storepb.DatabaseMetadata, error)
// Role
// CreateRole creates the role.
diff --git a/plugin/db/mongodb/sync.go b/plugin/db/mongodb/sync.go
index 550a2ecf1c..70c8ee58e2 100644
--- a/plugin/db/mongodb/sync.go
+++ b/plugin/db/mongodb/sync.go
@@ -12,6 +12,7 @@ import (
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
+ "github.com/bytebase/bytebase/plugin/db/util"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -78,30 +79,30 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error
}
// SyncDBSchema syncs the database schema.
-func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*db.Schema, map[string][]*storepb.ForeignKeyMetadata, error) {
+func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*storepb.DatabaseMetadata, error) {
exist, err := driver.isDatabaseExist(ctx, databaseName)
if err != nil {
- return nil, nil, err
+ return nil, err
}
if !exist {
- return nil, nil, errors.Errorf("database %s does not exist", databaseName)
+ return nil, errors.Errorf("database %s does not exist", databaseName)
}
schema := db.Schema{}
schema.Name = databaseName
tableList, err := driver.syncAllCollectionSchema(ctx, databaseName)
if err != nil {
- return nil, nil, err
+ return nil, err
}
schema.TableList = tableList
viewList, err := driver.syncAllViewSchema(ctx, databaseName)
if err != nil {
- return nil, nil, err
+ return nil, err
}
schema.ViewList = viewList
- return &schema, nil, nil
+ return util.ConvertDBSchema(&schema, nil), nil
}
// syncAllViewSchema returns all views schema of a database.
diff --git a/plugin/db/mysql/sync.go b/plugin/db/mysql/sync.go
index 9ad72cd7fd..a1ae03ffa5 100644
--- a/plugin/db/mysql/sync.go
+++ b/plugin/db/mysql/sync.go
@@ -84,34 +84,31 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error
}
// SyncDBSchema syncs a single database schema.
-func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*db.Schema, map[string][]*storepb.ForeignKeyMetadata, error) {
+func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*storepb.DatabaseMetadata, error) {
// Query MySQL version
version, err := driver.getVersion(ctx)
if err != nil {
- return nil, nil, err
+ return nil, err
}
isMySQL8 := strings.HasPrefix(version, "8.0")
// Query index info
- indexWhere := fmt.Sprintf("LOWER(TABLE_SCHEMA) = '%s'", strings.ToLower(databaseName))
indexQuery := `
- SELECT
- TABLE_SCHEMA,
- TABLE_NAME,
- INDEX_NAME,
- COLUMN_NAME,
- '',
- SEQ_IN_INDEX,
- INDEX_TYPE,
- CASE NON_UNIQUE WHEN 0 THEN 1 ELSE 0 END AS IS_UNIQUE,
- 1,
- INDEX_COMMENT
- FROM information_schema.STATISTICS
- WHERE ` + indexWhere
+ SELECT
+ TABLE_NAME,
+ INDEX_NAME,
+ COLUMN_NAME,
+ '',
+ SEQ_IN_INDEX,
+ INDEX_TYPE,
+ CASE NON_UNIQUE WHEN 0 THEN 1 ELSE 0 END AS IS_UNIQUE,
+ 1,
+ INDEX_COMMENT
+ FROM information_schema.STATISTICS
+ WHERE TABLE_SCHEMA = ?`
if isMySQL8 {
indexQuery = `
SELECT
- TABLE_SCHEMA,
TABLE_NAME,
INDEX_NAME,
COLUMN_NAME,
@@ -122,24 +119,22 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
CASE IS_VISIBLE WHEN 'YES' THEN 1 ELSE 0 END,
INDEX_COMMENT
FROM information_schema.STATISTICS
- WHERE ` + indexWhere
+ WHERE TABLE_SCHEMA = ?`
}
- indexRows, err := driver.db.QueryContext(ctx, indexQuery)
+ indexRows, err := driver.db.QueryContext(ctx, indexQuery, databaseName)
if err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, indexQuery)
+ return nil, util.FormatErrorWithQuery(err, indexQuery)
}
defer indexRows.Close()
- // dbName/tableName -> indexList map
+ // tableName -> indexList map
indexMap := make(map[string][]db.Index)
for indexRows.Next() {
- var dbName string
var tableName string
var columnName sql.NullString
var expression sql.NullString
var index db.Index
if err := indexRows.Scan(
- &dbName,
&tableName,
&index.Name,
&columnName,
@@ -150,7 +145,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
&index.Visible,
&index.Comment,
); err != nil {
- return nil, nil, err
+ return nil, err
}
if columnName.Valid {
@@ -163,49 +158,40 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
index.Primary = true
}
- key := fmt.Sprintf("%s/%s", dbName, tableName)
- if indexList, ok := indexMap[key]; ok {
- indexMap[key] = append(indexList, index)
- } else {
- indexMap[key] = []db.Index{index}
- }
+ indexMap[tableName] = append(indexMap[tableName], index)
}
if err := indexRows.Err(); err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, indexQuery)
+ return nil, util.FormatErrorWithQuery(err, indexQuery)
}
// Query column info
- columnWhere := fmt.Sprintf("LOWER(TABLE_SCHEMA) = '%s'", strings.ToLower(databaseName))
columnQuery := `
- SELECT
- TABLE_SCHEMA,
- TABLE_NAME,
- IFNULL(COLUMN_NAME, ''),
- ORDINAL_POSITION,
- COLUMN_DEFAULT,
- IS_NULLABLE,
- COLUMN_TYPE,
- IFNULL(CHARACTER_SET_NAME, ''),
- IFNULL(COLLATION_NAME, ''),
- COLUMN_COMMENT
- FROM information_schema.COLUMNS
- WHERE ` + columnWhere
- columnRows, err := driver.db.QueryContext(ctx, columnQuery)
+ SELECT
+ TABLE_NAME,
+ IFNULL(COLUMN_NAME, ''),
+ ORDINAL_POSITION,
+ COLUMN_DEFAULT,
+ IS_NULLABLE,
+ COLUMN_TYPE,
+ IFNULL(CHARACTER_SET_NAME, ''),
+ IFNULL(COLLATION_NAME, ''),
+ COLUMN_COMMENT
+ FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = ?`
+ columnRows, err := driver.db.QueryContext(ctx, columnQuery, databaseName)
if err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, columnQuery)
+ return nil, util.FormatErrorWithQuery(err, columnQuery)
}
defer columnRows.Close()
- // dbName/tableName -> columnList map
+ // tableName -> columnList map
columnMap := make(map[string][]db.Column)
for columnRows.Next() {
- var dbName string
var tableName string
var nullable string
var defaultStr sql.NullString
var column db.Column
if err := columnRows.Scan(
- &dbName,
&tableName,
&column.Name,
&column.Position,
@@ -216,7 +202,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
&column.Collation,
&column.Comment,
); err != nil {
- return nil, nil, err
+ return nil, err
}
if defaultStr.Valid {
@@ -227,58 +213,48 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
column.Nullable = true
}
- key := fmt.Sprintf("%s/%s", dbName, tableName)
- if tableList, ok := columnMap[key]; ok {
- columnMap[key] = append(tableList, column)
- } else {
- columnMap[key] = []db.Column{column}
- }
+ columnMap[tableName] = append(columnMap[tableName], column)
}
if err := columnRows.Err(); err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, columnQuery)
+ return nil, util.FormatErrorWithQuery(err, columnQuery)
}
// Query table info
- tableWhere := fmt.Sprintf("LOWER(TABLE_SCHEMA) = '%s'", strings.ToLower(databaseName))
tableQuery := `
- SELECT
- TABLE_SCHEMA,
- TABLE_NAME,
- IFNULL(UNIX_TIMESTAMP(CREATE_TIME), 0),
- IFNULL(UNIX_TIMESTAMP(UPDATE_TIME), 0),
- TABLE_TYPE,
- IFNULL(ENGINE, ''),
- IFNULL(TABLE_COLLATION, ''),
- IFNULL(TABLE_ROWS, 0),
- IFNULL(DATA_LENGTH, 0),
- IFNULL(INDEX_LENGTH, 0),
- IFNULL(DATA_FREE, 0),
- IFNULL(CREATE_OPTIONS, ''),
- IFNULL(TABLE_COMMENT, '')
- FROM information_schema.TABLES
- WHERE ` + tableWhere
- tableRows, err := driver.db.QueryContext(ctx, tableQuery)
+ SELECT
+ TABLE_NAME,
+ IFNULL(UNIX_TIMESTAMP(CREATE_TIME), 0),
+ IFNULL(UNIX_TIMESTAMP(UPDATE_TIME), 0),
+ TABLE_TYPE,
+ IFNULL(ENGINE, ''),
+ IFNULL(TABLE_COLLATION, ''),
+ IFNULL(TABLE_ROWS, 0),
+ IFNULL(DATA_LENGTH, 0),
+ IFNULL(INDEX_LENGTH, 0),
+ IFNULL(DATA_FREE, 0),
+ IFNULL(CREATE_OPTIONS, ''),
+ IFNULL(TABLE_COMMENT, '')
+ FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = ?`
+ tableRows, err := driver.db.QueryContext(ctx, tableQuery, databaseName)
if err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, tableQuery)
+ return nil, util.FormatErrorWithQuery(err, tableQuery)
}
defer tableRows.Close()
- // dbName -> tableList map
- tableMap := make(map[string][]db.Table)
+ var tableList []db.Table
type ViewInfo struct {
createdTs int64
updatedTs int64
comment string
}
- // dbName/viewName -> ViewInfo
+ // viewName -> ViewInfo
viewInfoMap := make(map[string]ViewInfo)
for tableRows.Next() {
- var dbName string
// Workaround TiDB bug https://github.com/pingcap/tidb/issues/27970
var tableCollation sql.NullString
var table db.Table
if err := tableRows.Scan(
- &dbName,
&table.Name,
&table.CreatedTs,
&table.UpdatedTs,
@@ -292,7 +268,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
&table.CreateOptions,
&table.Comment,
); err != nil {
- return nil, nil, err
+ return nil, err
}
table.ShortName = table.Name
@@ -301,18 +277,11 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
if tableCollation.Valid {
table.Collation = tableCollation.String
}
-
- key := fmt.Sprintf("%s/%s", dbName, table.Name)
- table.ColumnList = columnMap[key]
- table.IndexList = indexMap[key]
-
- if tableList, ok := tableMap[dbName]; ok {
- tableMap[dbName] = append(tableList, table)
- } else {
- tableMap[dbName] = []db.Table{table}
- }
+ table.ColumnList = columnMap[table.Name]
+ table.IndexList = indexMap[table.Name]
+ tableList = append(tableList, table)
case viewTableType:
- viewInfoMap[fmt.Sprintf("%s/%s", dbName, table.Name)] = ViewInfo{
+ viewInfoMap[table.Name] = ViewInfo{
createdTs: table.CreatedTs,
updatedTs: table.UpdatedTs,
comment: table.Comment,
@@ -320,84 +289,72 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
}
}
if err := tableRows.Err(); err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, tableQuery)
+ return nil, util.FormatErrorWithQuery(err, tableQuery)
}
- // Query view info
- viewWhere := fmt.Sprintf("LOWER(TABLE_SCHEMA) = '%s'", strings.ToLower(databaseName))
viewQuery := `
- SELECT
- TABLE_SCHEMA,
- TABLE_NAME,
- VIEW_DEFINITION
- FROM information_schema.VIEWS
- WHERE ` + viewWhere
- viewRows, err := driver.db.QueryContext(ctx, viewQuery)
+ SELECT
+ TABLE_NAME,
+ VIEW_DEFINITION
+ FROM information_schema.VIEWS
+ WHERE TABLE_SCHEMA = ?`
+ viewRows, err := driver.db.QueryContext(ctx, viewQuery, databaseName)
if err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, viewQuery)
+ return nil, util.FormatErrorWithQuery(err, viewQuery)
}
defer viewRows.Close()
- // dbName -> viewList map
- viewMap := make(map[string][]db.View)
+ var viewList []db.View
for viewRows.Next() {
- var dbName string
var view db.View
if err := viewRows.Scan(
- &dbName,
&view.Name,
&view.Definition,
); err != nil {
- return nil, nil, err
+ return nil, err
}
view.ShortName = view.Name
- info := viewInfoMap[fmt.Sprintf("%s/%s", dbName, view.Name)]
+ info := viewInfoMap[view.Name]
view.CreatedTs = info.createdTs
view.UpdatedTs = info.updatedTs
view.Comment = info.comment
-
- if viewList, ok := viewMap[dbName]; ok {
- viewMap[dbName] = append(viewList, view)
- } else {
- viewMap[dbName] = []db.View{view}
- }
+ viewList = append(viewList, view)
}
if err := viewRows.Err(); err != nil {
- return nil, nil, util.FormatErrorWithQuery(err, viewQuery)
+ return nil, util.FormatErrorWithQuery(err, viewQuery)
}
// Query db info
- databaseWhere := fmt.Sprintf("LOWER(SCHEMA_NAME) = '%s'", strings.ToLower(databaseName))
databaseQuery := `
SELECT
SCHEMA_NAME,
DEFAULT_CHARACTER_SET_NAME,
DEFAULT_COLLATION_NAME
FROM information_schema.SCHEMATA
- WHERE ` + databaseWhere
+ WHERE SCHEMA_NAME = ?`
var schema db.Schema
- if err := driver.db.QueryRowContext(ctx, databaseQuery).Scan(
+ if err := driver.db.QueryRowContext(ctx, databaseQuery, databaseName).Scan(
&schema.Name,
&schema.CharacterSet,
&schema.Collation); err != nil {
if err == sql.ErrNoRows {
- return nil, nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
+ return nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
}
- return nil, nil, err
+ return nil, err
}
- schema.TableList = tableMap[schema.Name]
- schema.ViewList = viewMap[schema.Name]
+ schema.TableList = tableList
+ schema.ViewList = viewList
fkMap, err := driver.getForeignKeyList(ctx, databaseName)
if err != nil {
- return nil, nil, err
+ return nil, err
}
- return &schema, fkMap, err
+ return util.ConvertDBSchema(&schema, fkMap), err
}
func (driver *Driver) getForeignKeyList(ctx context.Context, databaseName string) (map[string][]*storepb.ForeignKeyMetadata, error) {
- fkQuery := fmt.Sprintf(`
+ fkQuery := `
SELECT
fks.TABLE_NAME,
fks.CONSTRAINT_NAME,
@@ -413,11 +370,11 @@ func (driver *Driver) getForeignKeyList(ctx context.Context, databaseName string
ON fks.CONSTRAINT_SCHEMA = kcu.TABLE_SCHEMA
AND fks.TABLE_NAME = kcu.TABLE_NAME
AND fks.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
- WHERE LOWER(fks.CONSTRAINT_SCHEMA) = '%s'
+ WHERE LOWER(fks.CONSTRAINT_SCHEMA) = ?
ORDER BY fks.TABLE_NAME, fks.CONSTRAINT_NAME, kcu.ORDINAL_POSITION;
- `, strings.ToLower(databaseName))
+ `
- fkRows, err := driver.db.QueryContext(ctx, fkQuery)
+ fkRows, err := driver.db.QueryContext(ctx, fkQuery, databaseName)
if err != nil {
return nil, util.FormatErrorWithQuery(err, fkQuery)
}
diff --git a/plugin/db/pg/sync.go b/plugin/db/pg/sync.go
index 7640684728..31386eec92 100644
--- a/plugin/db/pg/sync.go
+++ b/plugin/db/pg/sync.go
@@ -123,11 +123,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error
}
// SyncDBSchema syncs a single database schema.
-func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*db.Schema, map[string][]*storepb.ForeignKeyMetadata, error) {
+func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*storepb.DatabaseMetadata, error) {
// Query db info
databases, err := driver.getDatabases(ctx)
if err != nil {
- return nil, nil, errors.Wrap(err, "failed to get databases")
+ return nil, errors.Wrap(err, "failed to get databases")
}
schema := db.Schema{
@@ -143,16 +143,16 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
}
}
if !found {
- return nil, nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
+ return nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
}
sqldb, err := driver.GetDBConnection(ctx, databaseName)
if err != nil {
- return nil, nil, errors.Wrapf(err, "failed to get database connection for %q", databaseName)
+ return nil, errors.Wrapf(err, "failed to get database connection for %q", databaseName)
}
txn, err := sqldb.BeginTx(ctx, nil)
if err != nil {
- return nil, nil, err
+ return nil, err
}
defer txn.Rollback()
@@ -160,7 +160,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
indicesMap := make(map[string][]*indexSchema)
indices, err := getIndices(txn)
if err != nil {
- return nil, nil, errors.Wrapf(err, "failed to get indices from database %q", databaseName)
+ return nil, errors.Wrapf(err, "failed to get indices from database %q", databaseName)
}
for _, idx := range indices {
key := fmt.Sprintf("%s.%s", idx.schemaName, idx.tableName)
@@ -170,7 +170,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
// Table statements.
tables, err := getPgTables(txn)
if err != nil {
- return nil, nil, errors.Wrapf(err, "failed to get tables from database %q", databaseName)
+ return nil, errors.Wrapf(err, "failed to get tables from database %q", databaseName)
}
for _, tbl := range tables {
var dbTable db.Table
@@ -213,7 +213,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
// View statements.
views, err := getViews(txn)
if err != nil {
- return nil, nil, errors.Wrapf(err, "failed to get views from database %q", databaseName)
+ return nil, errors.Wrapf(err, "failed to get views from database %q", databaseName)
}
for _, view := range views {
var dbView db.View
@@ -230,21 +230,21 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
// Extensions.
extensions, err := getExtensions(txn)
if err != nil {
- return nil, nil, errors.Wrapf(err, "failed to get extensions from database %q", databaseName)
+ return nil, errors.Wrapf(err, "failed to get extensions from database %q", databaseName)
}
schema.ExtensionList = extensions
// Foreign keys.
foreignKeys, err := getPgForeignKeys(txn)
if err != nil {
- return nil, nil, errors.Wrapf(err, "failed to get foreign keys from database %q", databaseName)
+ return nil, errors.Wrapf(err, "failed to get foreign keys from database %q", databaseName)
}
if err := txn.Commit(); err != nil {
- return nil, nil, err
+ return nil, err
}
- return &schema, foreignKeys, err
+ return util.ConvertDBSchema(&schema, foreignKeys), err
}
func (driver *Driver) getUserList(ctx context.Context) ([]db.User, error) {
diff --git a/plugin/db/snowflake/sync.go b/plugin/db/snowflake/sync.go
index 99a2c1f508..c951173e44 100644
--- a/plugin/db/snowflake/sync.go
+++ b/plugin/db/snowflake/sync.go
@@ -63,16 +63,16 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error
}
// SyncDBSchema syncs a single database schema.
-func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*db.Schema, map[string][]*storepb.ForeignKeyMetadata, error) {
+func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*storepb.DatabaseMetadata, error) {
// Query user info
if err := driver.useRole(ctx, accountAdminRole); err != nil {
- return nil, nil, err
+ return nil, err
}
// Query db info
databases, err := driver.getDatabases(ctx)
if err != nil {
- return nil, nil, err
+ return nil, err
}
schema := db.Schema{
@@ -86,16 +86,16 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
}
}
if !found {
- return nil, nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
+ return nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
}
tableList, viewList, err := driver.syncTableSchema(ctx, databaseName)
if err != nil {
- return nil, nil, err
+ return nil, err
}
schema.TableList, schema.ViewList = tableList, viewList
- return &schema, nil, nil
+ return util.ConvertDBSchema(&schema, nil), nil
}
func (driver *Driver) getUserList(ctx context.Context) ([]db.User, error) {
diff --git a/plugin/db/spanner/sync.go b/plugin/db/spanner/sync.go
index 6818c11205..cc58be2dae 100644
--- a/plugin/db/spanner/sync.go
+++ b/plugin/db/spanner/sync.go
@@ -46,6 +46,6 @@ func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error) {
}
// SyncDBSchema syncs a single database schema.
-func (*Driver) SyncDBSchema(_ context.Context, _ string) (*db.Schema, map[string][]*storepb.ForeignKeyMetadata, error) {
- return nil, nil, errors.New("not implemented")
+func (*Driver) SyncDBSchema(_ context.Context, _ string) (*storepb.DatabaseMetadata, error) {
+ return nil, errors.New("not implemented")
}
diff --git a/plugin/db/sqlite/sync.go b/plugin/db/sqlite/sync.go
index 5f6f106129..96b3ba2ce8 100644
--- a/plugin/db/sqlite/sync.go
+++ b/plugin/db/sqlite/sync.go
@@ -63,10 +63,10 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error
}
// SyncDBSchema syncs a single database schema.
-func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*db.Schema, map[string][]*storepb.ForeignKeyMetadata, error) {
+func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*storepb.DatabaseMetadata, error) {
databases, err := driver.getDatabases()
if err != nil {
- return nil, nil, err
+ return nil, err
}
schema := db.Schema{
@@ -80,23 +80,23 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
}
}
if !found {
- return nil, nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
+ return nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
}
sqldb, err := driver.GetDBConnection(ctx, databaseName)
if err != nil {
- return nil, nil, errors.Wrapf(err, "failed to get database connection for %q", databaseName)
+ return nil, errors.Wrapf(err, "failed to get database connection for %q", databaseName)
}
txn, err := sqldb.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
- return nil, nil, err
+ return nil, err
}
defer txn.Rollback()
// Index statements.
indicesMap := make(map[string][]indexSchema)
indices, err := getIndices(txn)
if err != nil {
- return nil, nil, errors.Wrapf(err, "failed to get indices from database %q", databaseName)
+ return nil, errors.Wrapf(err, "failed to get indices from database %q", databaseName)
}
for _, idx := range indices {
indicesMap[idx.tableName] = append(indicesMap[idx.tableName], idx)
@@ -104,21 +104,21 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*d
tbls, err := getTables(txn, indicesMap)
if err != nil {
- return nil, nil, err
+ return nil, err
}
schema.TableList = tbls
views, err := getViews(txn)
if err != nil {
- return nil, nil, err
+ return nil, err
}
schema.ViewList = views
if err := txn.Commit(); err != nil {
- return nil, nil, err
+ return nil, err
}
- return &schema, nil, nil
+ return util.ConvertDBSchema(&schema, nil), nil
}
// getTables gets all tables of a database.
diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.go
index 530f4e556f..b66dc707ab 100644
--- a/plugin/db/util/driverutil.go
+++ b/plugin/db/util/driverutil.go
@@ -9,6 +9,7 @@ import (
"fmt"
"io"
"regexp"
+ "sort"
"strconv"
"strings"
"time"
@@ -16,10 +17,12 @@ import (
"github.com/blang/semver/v4"
"github.com/pkg/errors"
"go.uber.org/zap"
+ "google.golang.org/protobuf/types/known/wrapperspb"
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
// FormatErrorWithQuery will format the error with failed query.
@@ -730,3 +733,129 @@ func IsAffectedRowsStatement(stmt string) bool {
}
return false
}
+
+// ConvertDBSchema converts db schema to database metadata.
+func ConvertDBSchema(schema *db.Schema, fkMap map[string][]*storepb.ForeignKeyMetadata) *storepb.DatabaseMetadata {
+ if fkMap == nil {
+ fkMap = make(map[string][]*storepb.ForeignKeyMetadata)
+ }
+ databaseMetadata := &storepb.DatabaseMetadata{
+ Name: schema.Name,
+ CharacterSet: schema.CharacterSet,
+ Collation: schema.Collation,
+ }
+
+ schemaNameMap := make(map[string]bool)
+ schemaTableMap := make(map[string][]db.Table)
+ schemaViewMap := make(map[string][]db.View)
+ for _, table := range schema.TableList {
+ schemaNameMap[table.Schema] = true
+ schemaTableMap[table.Schema] = append(schemaTableMap[table.Schema], table)
+ }
+ for _, view := range schema.ViewList {
+ schemaNameMap[view.Schema] = true
+ schemaViewMap[view.Schema] = append(schemaViewMap[view.Schema], view)
+ }
+ var schemaNames []string
+ for schemaName := range schemaNameMap {
+ schemaNames = append(schemaNames, schemaName)
+ }
+ sort.Strings(schemaNames)
+ for _, schemaName := range schemaNames {
+ schemaMetadata := &storepb.SchemaMetadata{
+ Name: schemaName,
+ }
+ tables := schemaTableMap[schemaName]
+ sort.Slice(tables, func(i, j int) bool {
+ return tables[i].ShortName < tables[j].ShortName
+ })
+ for _, table := range tables {
+ tableMetadata := &storepb.TableMetadata{
+ Name: table.ShortName,
+ Engine: table.Engine,
+ Collation: table.Collation,
+ RowCount: table.RowCount,
+ DataSize: table.DataSize,
+ DataFree: table.DataFree,
+ IndexSize: table.IndexSize,
+ CreateOptions: table.CreateOptions,
+ Comment: table.Comment,
+ ForeignKeys: fkMap[table.Name],
+ }
+
+ sort.Slice(table.ColumnList, func(i, j int) bool {
+ return table.ColumnList[i].Position < table.ColumnList[j].Position
+ })
+ for _, column := range table.ColumnList {
+ columnMetadata := &storepb.ColumnMetadata{
+ Name: column.Name,
+ Position: int32(column.Position),
+ Nullable: column.Nullable,
+ Type: column.Type,
+ CharacterSet: column.CharacterSet,
+ Collation: column.Collation,
+ Comment: column.Comment,
+ }
+ if column.Default != nil {
+ columnMetadata.Default = &wrapperspb.StringValue{Value: *column.Default}
+ }
+ tableMetadata.Columns = append(tableMetadata.Columns, columnMetadata)
+ }
+
+ indexMap := make(map[string][]db.Index)
+ for _, expression := range table.IndexList {
+ indexMap[expression.Name] = append(indexMap[expression.Name], expression)
+ }
+ var indexNames []string
+ for indexName := range indexMap {
+ indexNames = append(indexNames, indexName)
+ }
+ sort.Strings(indexNames)
+ for _, indexName := range indexNames {
+ expressionList := indexMap[indexName]
+ sort.Slice(expressionList, func(i, j int) bool {
+ return expressionList[i].Position < expressionList[j].Position
+ })
+ indexMetadata := &storepb.IndexMetadata{
+ Name: expressionList[0].Name,
+ Type: expressionList[0].Type,
+ Unique: expressionList[0].Unique,
+ Primary: expressionList[0].Primary,
+ Visible: expressionList[0].Visible,
+ Comment: expressionList[0].Comment,
+ }
+ for _, expression := range expressionList {
+ indexMetadata.Expressions = append(indexMetadata.Expressions, expression.Expression)
+ }
+ tableMetadata.Indexes = append(tableMetadata.Indexes, indexMetadata)
+ }
+
+ schemaMetadata.Tables = append(schemaMetadata.Tables, tableMetadata)
+ }
+ views := schemaViewMap[schemaName]
+ sort.Slice(views, func(i, j int) bool {
+ return views[i].ShortName < views[j].ShortName
+ })
+ for _, view := range views {
+ schemaMetadata.Views = append(schemaMetadata.Views, &storepb.ViewMetadata{
+ Name: view.ShortName,
+ Definition: view.Definition,
+ Comment: view.Comment,
+ })
+ }
+ databaseMetadata.Schemas = append(databaseMetadata.Schemas, schemaMetadata)
+ }
+
+ sort.Slice(schema.ExtensionList, func(i, j int) bool {
+ return schema.ExtensionList[i].Name < schema.ExtensionList[j].Name
+ })
+ for _, extension := range schema.ExtensionList {
+ databaseMetadata.Extensions = append(databaseMetadata.Extensions, &storepb.ExtensionMetadata{
+ Name: extension.Name,
+ Schema: extension.Schema,
+ Version: extension.Version,
+ Description: extension.Description,
+ })
+ }
+ return databaseMetadata
+}
diff --git a/plugin/db/util/driverutil_test.go b/plugin/db/util/driverutil_test.go
index cc8dc97c46..35d6850096 100644
--- a/plugin/db/util/driverutil_test.go
+++ b/plugin/db/util/driverutil_test.go
@@ -7,9 +7,13 @@ import (
"testing"
"time"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/wrapperspb"
"github.com/bytebase/bytebase/plugin/db"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+
// Register pingcap parser driver.
_ "github.com/pingcap/tidb/types/parser_driver"
)
@@ -712,3 +716,286 @@ func TestExtractSensitiveField(t *testing.T) {
require.Equal(t, test.fieldList, res, test.statement)
}
}
+
+func TestConvertDBSchema(t *testing.T) {
+ defaultString := "Jay"
+
+ dbSchema := &db.Schema{
+ Name: "db1",
+ CharacterSet: "charset1",
+ Collation: "collation1",
+ TableList: []db.Table{
+ {
+ Name: "public.hello",
+ ShortName: "hello",
+ Schema: "public",
+ CreatedTs: 20210113,
+ UpdatedTs: 20221214,
+ Type: "BASE TABLE",
+ Engine: "btree",
+ Collation: "collation-hello",
+ RowCount: 123,
+ DataSize: 4542,
+ IndexSize: 2113,
+ DataFree: 123,
+ CreateOptions: "create option hello",
+ Comment: "comment hello",
+ ColumnList: []db.Column{
+ {
+ Name: "name",
+ Position: 1,
+ Default: &defaultString,
+ Nullable: false,
+ Type: "varchar(10)",
+ CharacterSet: "charset1",
+ Collation: "collation1",
+ Comment: "col1",
+ },
+ {
+ Name: "id",
+ Position: 0,
+ Default: nil,
+ Nullable: false,
+ Type: "int",
+ CharacterSet: "charset1",
+ Collation: "collation1",
+ Comment: "col1",
+ },
+ {
+ Name: "age",
+ Position: 2,
+ Default: nil,
+ Nullable: false,
+ Type: "int",
+ CharacterSet: "charset1",
+ Collation: "collation1",
+ Comment: "col1",
+ },
+ },
+ IndexList: []db.Index{
+ {
+ Name: "id-primary",
+ // This could refer to a column or an expression.
+ Expression: "id",
+ Position: 0,
+ Type: "index type",
+ Unique: true,
+ Primary: true,
+ Visible: true,
+ Comment: "comment index",
+ },
+ {
+ Name: "name-age-unique",
+ // This could refer to a column or an expression.
+ Expression: "age",
+ Position: 1,
+ Type: "index type2",
+ Unique: true,
+ Primary: false,
+ Visible: true,
+ Comment: "comment index2",
+ },
+ {
+ Name: "name-age-unique",
+ // This could refer to a column or an expression.
+ Expression: "name",
+ Position: 0,
+ Type: "index type2",
+ Unique: true,
+ Primary: false,
+ Visible: true,
+ Comment: "comment index2",
+ },
+ },
+ },
+ {
+ Name: "hello",
+ ShortName: "hello",
+ Schema: "",
+ CreatedTs: 20210113,
+ UpdatedTs: 20221214,
+ Type: "BASE TABLE",
+ Engine: "btree",
+ Collation: "collation-hello",
+ RowCount: 123,
+ DataSize: 4542,
+ IndexSize: 2113,
+ DataFree: 123,
+ CreateOptions: "create option hello",
+ Comment: "comment hello",
+ ColumnList: nil,
+ IndexList: nil,
+ },
+ {
+ Name: "public.world",
+ ShortName: "world",
+ Schema: "public",
+ CreatedTs: 20210114,
+ UpdatedTs: 20221215,
+ Type: "BASE TABLE",
+ Engine: "btree",
+ Collation: "collation-world",
+ RowCount: 123,
+ DataSize: 4542,
+ IndexSize: 2113,
+ DataFree: 123,
+ CreateOptions: "create option world",
+ Comment: "comment world",
+ ColumnList: nil,
+ IndexList: nil,
+ },
+ },
+ ViewList: []db.View{
+ {
+ Name: "public.nice_view",
+ ShortName: "nice_view",
+ Schema: "public",
+ CreatedTs: 2313,
+ UpdatedTs: 21124,
+ Definition: "select 1",
+ Comment: "comment view",
+ },
+ },
+ ExtensionList: []db.Extension{
+ {
+ Name: "hstore",
+ Version: "v2021",
+ Schema: "public",
+ Description: "awesome hstore",
+ },
+ {
+ Name: "atom",
+ Version: "v2022",
+ Schema: "public",
+ Description: "awesome sphere",
+ },
+ },
+ }
+ want := &storepb.DatabaseMetadata{
+ Name: "db1",
+ CharacterSet: "charset1",
+ Collation: "collation1",
+ Schemas: []*storepb.SchemaMetadata{
+ {
+ Name: "",
+ Tables: []*storepb.TableMetadata{
+ {
+ Name: "hello",
+ Engine: "btree",
+ Collation: "collation-hello",
+ RowCount: 123,
+ DataSize: 4542,
+ IndexSize: 2113,
+ DataFree: 123,
+ CreateOptions: "create option hello",
+ Comment: "comment hello",
+ },
+ },
+ },
+ {
+ Name: "public",
+ Tables: []*storepb.TableMetadata{
+ {
+ Name: "hello",
+ Engine: "btree",
+ Collation: "collation-hello",
+ RowCount: 123,
+ DataSize: 4542,
+ IndexSize: 2113,
+ DataFree: 123,
+ CreateOptions: "create option hello",
+ Comment: "comment hello",
+ Columns: []*storepb.ColumnMetadata{
+ {
+ Name: "id",
+ Position: 0,
+ Default: nil,
+ Nullable: false,
+ Type: "int",
+ CharacterSet: "charset1",
+ Collation: "collation1",
+ Comment: "col1",
+ },
+ {
+ Name: "name",
+ Position: 1,
+ Default: &wrapperspb.StringValue{Value: "Jay"},
+ Nullable: false,
+ Type: "varchar(10)",
+ CharacterSet: "charset1",
+ Collation: "collation1",
+ Comment: "col1",
+ },
+ {
+ Name: "age",
+ Position: 2,
+ Default: nil,
+ Nullable: false,
+ Type: "int",
+ CharacterSet: "charset1",
+ Collation: "collation1",
+ Comment: "col1",
+ },
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "id-primary",
+ // This could refer to a column or an expression.
+ Expressions: []string{"id"},
+ Type: "index type",
+ Unique: true,
+ Primary: true,
+ Visible: true,
+ Comment: "comment index",
+ },
+ {
+ Name: "name-age-unique",
+ // This could refer to a column or an expression.
+ Expressions: []string{"name", "age"},
+ Type: "index type2",
+ Unique: true,
+ Primary: false,
+ Visible: true,
+ Comment: "comment index2",
+ },
+ },
+ },
+ {
+ Name: "world",
+ Engine: "btree",
+ Collation: "collation-world",
+ RowCount: 123,
+ DataSize: 4542,
+ IndexSize: 2113,
+ DataFree: 123,
+ CreateOptions: "create option world",
+ Comment: "comment world",
+ },
+ },
+ Views: []*storepb.ViewMetadata{
+ {
+ Name: "nice_view",
+ Definition: "select 1",
+ Comment: "comment view",
+ },
+ },
+ },
+ },
+ Extensions: []*storepb.ExtensionMetadata{
+ {
+ Name: "atom",
+ Version: "v2022",
+ Schema: "public",
+ Description: "awesome sphere",
+ },
+ {
+ Name: "hstore",
+ Version: "v2021",
+ Schema: "public",
+ Description: "awesome hstore",
+ },
+ },
+ }
+ got := ConvertDBSchema(dbSchema, nil)
+ assert.Equal(t, want, got)
+}
diff --git a/server/runner/schemasync/syncer.go b/server/runner/schemasync/syncer.go
index 83a302e0f5..2a12d4466b 100644
--- a/server/runner/schemasync/syncer.go
+++ b/server/runner/schemasync/syncer.go
@@ -6,7 +6,6 @@ import (
"context"
"fmt"
"net/http"
- "sort"
"sync"
"time"
@@ -15,7 +14,6 @@ import (
"github.com/pkg/errors"
"go.uber.org/zap"
"google.golang.org/protobuf/testing/protocmp"
- "google.golang.org/protobuf/types/known/wrapperspb"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
@@ -342,14 +340,14 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, instance *api.Instance,
}
// Sync database schema
- schema, fkMap, err := driver.SyncDBSchema(ctx, databaseName)
+ databaseMetadata, err := driver.SyncDBSchema(ctx, databaseName)
if err != nil {
return err
}
// When there are too many databases, this might have performance issue and will
// cause frontend timeout since we set a 30s limit (INSTANCE_OPERATION_TIMEOUT).
- schemaVersion, err := utils.GetLatestSchemaVersion(ctx, driver, schema.Name)
+ schemaVersion, err := utils.GetLatestSchemaVersion(ctx, driver, databaseMetadata.Name)
if err != nil {
return err
}
@@ -379,9 +377,9 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, instance *api.Instance,
ProjectID: api.DefaultProjectID,
InstanceID: instance.ID,
EnvironmentID: instance.EnvironmentID,
- Name: schema.Name,
- CharacterSet: schema.CharacterSet,
- Collation: schema.Collation,
+ Name: databaseMetadata.Name,
+ CharacterSet: databaseMetadata.CharacterSet,
+ Collation: databaseMetadata.Collation,
SchemaVersion: schemaVersion,
LastSuccessfulSyncTs: time.Now().Unix(),
}
@@ -396,10 +394,10 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, instance *api.Instance,
}
// Sync database schema
- return syncDBSchema(ctx, s.store, database, schema, fkMap, driver, force)
+ return syncDBSchema(ctx, s.store, database, databaseMetadata, driver, force)
}
-func syncDBSchema(ctx context.Context, stores *store.Store, database *api.Database, schema *db.Schema, fkMap map[string][]*storepb.ForeignKeyMetadata, driver db.Driver, force bool) error {
+func syncDBSchema(ctx context.Context, stores *store.Store, database *api.Database, databaseMetadata *storepb.DatabaseMetadata, driver db.Driver, force bool) error {
dbSchema, err := stores.GetDBSchema(ctx, database.ID)
if err != nil {
return err
@@ -409,8 +407,6 @@ func syncDBSchema(ctx context.Context, stores *store.Store, database *api.Databa
oldDatabaseMetadata = dbSchema.Metadata
}
- databaseMetadata := convertDBSchema(schema, fkMap)
-
if !cmp.Equal(oldDatabaseMetadata, databaseMetadata, protocmp.Transform()) {
rawDump := ""
if dbSchema != nil {
@@ -438,131 +434,6 @@ func syncDBSchema(ctx context.Context, stores *store.Store, database *api.Databa
return nil
}
-func convertDBSchema(schema *db.Schema, fkMap map[string][]*storepb.ForeignKeyMetadata) *storepb.DatabaseMetadata {
- if fkMap == nil {
- fkMap = make(map[string][]*storepb.ForeignKeyMetadata)
- }
- databaseMetadata := &storepb.DatabaseMetadata{
- Name: schema.Name,
- CharacterSet: schema.CharacterSet,
- Collation: schema.Collation,
- }
-
- schemaNameMap := make(map[string]bool)
- schemaTableMap := make(map[string][]db.Table)
- schemaViewMap := make(map[string][]db.View)
- for _, table := range schema.TableList {
- schemaNameMap[table.Schema] = true
- schemaTableMap[table.Schema] = append(schemaTableMap[table.Schema], table)
- }
- for _, view := range schema.ViewList {
- schemaNameMap[view.Schema] = true
- schemaViewMap[view.Schema] = append(schemaViewMap[view.Schema], view)
- }
- var schemaNames []string
- for schemaName := range schemaNameMap {
- schemaNames = append(schemaNames, schemaName)
- }
- sort.Strings(schemaNames)
- for _, schemaName := range schemaNames {
- schemaMetadata := &storepb.SchemaMetadata{
- Name: schemaName,
- }
- tables := schemaTableMap[schemaName]
- sort.Slice(tables, func(i, j int) bool {
- return tables[i].ShortName < tables[j].ShortName
- })
- for _, table := range tables {
- tableMetadata := &storepb.TableMetadata{
- Name: table.ShortName,
- Engine: table.Engine,
- Collation: table.Collation,
- RowCount: table.RowCount,
- DataSize: table.DataSize,
- DataFree: table.DataFree,
- IndexSize: table.IndexSize,
- CreateOptions: table.CreateOptions,
- Comment: table.Comment,
- ForeignKeys: fkMap[table.Name],
- }
-
- sort.Slice(table.ColumnList, func(i, j int) bool {
- return table.ColumnList[i].Position < table.ColumnList[j].Position
- })
- for _, column := range table.ColumnList {
- columnMetadata := &storepb.ColumnMetadata{
- Name: column.Name,
- Position: int32(column.Position),
- Nullable: column.Nullable,
- Type: column.Type,
- CharacterSet: column.CharacterSet,
- Collation: column.Collation,
- Comment: column.Comment,
- }
- if column.Default != nil {
- columnMetadata.Default = &wrapperspb.StringValue{Value: *column.Default}
- }
- tableMetadata.Columns = append(tableMetadata.Columns, columnMetadata)
- }
-
- indexMap := make(map[string][]db.Index)
- for _, expression := range table.IndexList {
- indexMap[expression.Name] = append(indexMap[expression.Name], expression)
- }
- var indexNames []string
- for indexName := range indexMap {
- indexNames = append(indexNames, indexName)
- }
- sort.Strings(indexNames)
- for _, indexName := range indexNames {
- expressionList := indexMap[indexName]
- sort.Slice(expressionList, func(i, j int) bool {
- return expressionList[i].Position < expressionList[j].Position
- })
- indexMetadata := &storepb.IndexMetadata{
- Name: expressionList[0].Name,
- Type: expressionList[0].Type,
- Unique: expressionList[0].Unique,
- Primary: expressionList[0].Primary,
- Visible: expressionList[0].Visible,
- Comment: expressionList[0].Comment,
- }
- for _, expression := range expressionList {
- indexMetadata.Expressions = append(indexMetadata.Expressions, expression.Expression)
- }
- tableMetadata.Indexes = append(tableMetadata.Indexes, indexMetadata)
- }
-
- schemaMetadata.Tables = append(schemaMetadata.Tables, tableMetadata)
- }
- views := schemaViewMap[schemaName]
- sort.Slice(views, func(i, j int) bool {
- return views[i].ShortName < views[j].ShortName
- })
- for _, view := range views {
- schemaMetadata.Views = append(schemaMetadata.Views, &storepb.ViewMetadata{
- Name: view.ShortName,
- Definition: view.Definition,
- Comment: view.Comment,
- })
- }
- databaseMetadata.Schemas = append(databaseMetadata.Schemas, schemaMetadata)
- }
-
- sort.Slice(schema.ExtensionList, func(i, j int) bool {
- return schema.ExtensionList[i].Name < schema.ExtensionList[j].Name
- })
- for _, extension := range schema.ExtensionList {
- databaseMetadata.Extensions = append(databaseMetadata.Extensions, &storepb.ExtensionMetadata{
- Name: extension.Name,
- Schema: extension.Schema,
- Version: extension.Version,
- Description: extension.Description,
- })
- }
- return databaseMetadata
-}
-
func equalDatabaseMetadata(x, y *storepb.DatabaseMetadata) bool {
return cmp.Equal(x, y, protocmp.Transform(),
protocmp.IgnoreFields(&storepb.TableMetadata{}, "row_count", "data_size", "index_size", "data_free"),
diff --git a/server/runner/schemasync/syncer_test.go b/server/runner/schemasync/syncer_test.go
index 60c59cd654..0cc471767a 100644
--- a/server/runner/schemasync/syncer_test.go
+++ b/server/runner/schemasync/syncer_test.go
@@ -4,295 +4,10 @@ import (
"testing"
"github.com/stretchr/testify/assert"
- "google.golang.org/protobuf/types/known/wrapperspb"
- "github.com/bytebase/bytebase/plugin/db"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
-func TestConvertDBSchema(t *testing.T) {
- defaultString := "Jay"
-
- dbSchema := &db.Schema{
- Name: "db1",
- CharacterSet: "charset1",
- Collation: "collation1",
- TableList: []db.Table{
- {
- Name: "public.hello",
- ShortName: "hello",
- Schema: "public",
- CreatedTs: 20210113,
- UpdatedTs: 20221214,
- Type: "BASE TABLE",
- Engine: "btree",
- Collation: "collation-hello",
- RowCount: 123,
- DataSize: 4542,
- IndexSize: 2113,
- DataFree: 123,
- CreateOptions: "create option hello",
- Comment: "comment hello",
- ColumnList: []db.Column{
- {
- Name: "name",
- Position: 1,
- Default: &defaultString,
- Nullable: false,
- Type: "varchar(10)",
- CharacterSet: "charset1",
- Collation: "collation1",
- Comment: "col1",
- },
- {
- Name: "id",
- Position: 0,
- Default: nil,
- Nullable: false,
- Type: "int",
- CharacterSet: "charset1",
- Collation: "collation1",
- Comment: "col1",
- },
- {
- Name: "age",
- Position: 2,
- Default: nil,
- Nullable: false,
- Type: "int",
- CharacterSet: "charset1",
- Collation: "collation1",
- Comment: "col1",
- },
- },
- IndexList: []db.Index{
- {
- Name: "id-primary",
- // This could refer to a column or an expression.
- Expression: "id",
- Position: 0,
- Type: "index type",
- Unique: true,
- Primary: true,
- Visible: true,
- Comment: "comment index",
- },
- {
- Name: "name-age-unique",
- // This could refer to a column or an expression.
- Expression: "age",
- Position: 1,
- Type: "index type2",
- Unique: true,
- Primary: false,
- Visible: true,
- Comment: "comment index2",
- },
- {
- Name: "name-age-unique",
- // This could refer to a column or an expression.
- Expression: "name",
- Position: 0,
- Type: "index type2",
- Unique: true,
- Primary: false,
- Visible: true,
- Comment: "comment index2",
- },
- },
- },
- {
- Name: "hello",
- ShortName: "hello",
- Schema: "",
- CreatedTs: 20210113,
- UpdatedTs: 20221214,
- Type: "BASE TABLE",
- Engine: "btree",
- Collation: "collation-hello",
- RowCount: 123,
- DataSize: 4542,
- IndexSize: 2113,
- DataFree: 123,
- CreateOptions: "create option hello",
- Comment: "comment hello",
- ColumnList: nil,
- IndexList: nil,
- },
- {
- Name: "public.world",
- ShortName: "world",
- Schema: "public",
- CreatedTs: 20210114,
- UpdatedTs: 20221215,
- Type: "BASE TABLE",
- Engine: "btree",
- Collation: "collation-world",
- RowCount: 123,
- DataSize: 4542,
- IndexSize: 2113,
- DataFree: 123,
- CreateOptions: "create option world",
- Comment: "comment world",
- ColumnList: nil,
- IndexList: nil,
- },
- },
- ViewList: []db.View{
- {
- Name: "public.nice_view",
- ShortName: "nice_view",
- Schema: "public",
- CreatedTs: 2313,
- UpdatedTs: 21124,
- Definition: "select 1",
- Comment: "comment view",
- },
- },
- ExtensionList: []db.Extension{
- {
- Name: "hstore",
- Version: "v2021",
- Schema: "public",
- Description: "awesome hstore",
- },
- {
- Name: "atom",
- Version: "v2022",
- Schema: "public",
- Description: "awesome sphere",
- },
- },
- }
- want := &storepb.DatabaseMetadata{
- Name: "db1",
- CharacterSet: "charset1",
- Collation: "collation1",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "",
- Tables: []*storepb.TableMetadata{
- {
- Name: "hello",
- Engine: "btree",
- Collation: "collation-hello",
- RowCount: 123,
- DataSize: 4542,
- IndexSize: 2113,
- DataFree: 123,
- CreateOptions: "create option hello",
- Comment: "comment hello",
- },
- },
- },
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "hello",
- Engine: "btree",
- Collation: "collation-hello",
- RowCount: 123,
- DataSize: 4542,
- IndexSize: 2113,
- DataFree: 123,
- CreateOptions: "create option hello",
- Comment: "comment hello",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Position: 0,
- Default: nil,
- Nullable: false,
- Type: "int",
- CharacterSet: "charset1",
- Collation: "collation1",
- Comment: "col1",
- },
- {
- Name: "name",
- Position: 1,
- Default: &wrapperspb.StringValue{Value: "Jay"},
- Nullable: false,
- Type: "varchar(10)",
- CharacterSet: "charset1",
- Collation: "collation1",
- Comment: "col1",
- },
- {
- Name: "age",
- Position: 2,
- Default: nil,
- Nullable: false,
- Type: "int",
- CharacterSet: "charset1",
- Collation: "collation1",
- Comment: "col1",
- },
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "id-primary",
- // This could refer to a column or an expression.
- Expressions: []string{"id"},
- Type: "index type",
- Unique: true,
- Primary: true,
- Visible: true,
- Comment: "comment index",
- },
- {
- Name: "name-age-unique",
- // This could refer to a column or an expression.
- Expressions: []string{"name", "age"},
- Type: "index type2",
- Unique: true,
- Primary: false,
- Visible: true,
- Comment: "comment index2",
- },
- },
- },
- {
- Name: "world",
- Engine: "btree",
- Collation: "collation-world",
- RowCount: 123,
- DataSize: 4542,
- IndexSize: 2113,
- DataFree: 123,
- CreateOptions: "create option world",
- Comment: "comment world",
- },
- },
- Views: []*storepb.ViewMetadata{
- {
- Name: "nice_view",
- Definition: "select 1",
- Comment: "comment view",
- },
- },
- },
- },
- Extensions: []*storepb.ExtensionMetadata{
- {
- Name: "atom",
- Version: "v2022",
- Schema: "public",
- Description: "awesome sphere",
- },
- {
- Name: "hstore",
- Version: "v2021",
- Schema: "public",
- Description: "awesome hstore",
- },
- },
- }
- got := convertDBSchema(dbSchema, nil)
- assert.Equal(t, want, got)
-}
-
func TestEqualDatabaseMetadata(t *testing.T) {
tests := []struct {
x *storepb.DatabaseMetadata