Skip to content

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

refactor: migrate schema sync to native proto metadata generation (#4126)

Danny Xub4452087241e
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index 3d7302877e..579857767b 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -50,99 +50,6 @@ type User struct {
Grant string
}
-// View is the database view.
-type View struct {
- Name string
- // ShortName is the short table name.
- ShortName string
- // Schema is the schema name for a table. It should be supported only for Postgres and Snowflake.
- Schema string
- // CreatedTs isn't supported for ClickHouse, MongoDB.
- CreatedTs int64
- // UpdatedTs isn't supported for MongoDB.
- UpdatedTs int64
- // Definition isn't supported for MongoDB.
- Definition string
- // Comment isn't supported for MongoDB.
- Comment string
-}
-
-// Extension is the database extension.
-type Extension struct {
- Name string
- Version string
- Schema string
- Description string
-}
-
-// Index is the database index.
-type Index struct {
- Name string
- // This could refer to a column or an expression.
- Expression string
- // Position isn't supported for MongoDB.
- Position int
- // Type isn't supported for SQLite, MongoDB.
- Type string
- Unique bool
- // Primary isn't supported for MongoDB.
- Primary bool
- // Visible isn't supported for Postgres, SQLite, MongoDB.
- Visible bool
- // Comment isn't supported for SQLite, MongoDB.
- Comment string
-}
-
-// Column the database table column.
-type Column struct {
- Name string
- Position int
- Default *string
- // Nullable isn't supported for ClickHouse.
- Nullable bool
- Type string
- // CharacterSet isn't supported for Postgres, ClickHouse, SQLite.
- CharacterSet string
- // Collation isn't supported for ClickHouse, SQLite.
- Collation string
- // Comment isn't supported for SQLite.
- Comment string
-}
-
-// Table is the database table.
-type Table struct {
- // Name is a combination of schema and short name for legacy purpose.
- Name string
- // ShortName is the short table name.
- ShortName string
- // Schema is the schema name for a table. It should be supported only for Postgres and Snowflake.
- Schema string
- // CreatedTs isn't supported for ClickHouse, SQLite, MongoDB.
- CreatedTs int64
- // UpdatedTs isn't supported for SQLite, MongoDB.
- UpdatedTs int64
- Type string
- // Engine isn't supported for Postgres, Snowflake, SQLite, MongoDB.
- Engine string
- // Collation isn't supported for Postgres, ClickHouse, Snowflake, SQLite, MongoDB.
- Collation string
- RowCount int64
- // DataSize isn't supported for SQLite.
- DataSize int64
- // IndexSize isn't supported for ClickHouse, Snowflake, SQLite.
- IndexSize int64
- // DataFree isn't supported for Postgres, ClickHouse, Snowflake, SQLite, MongoDB.
- DataFree int64
- // CreateOptions isn't supported for Postgres, ClickHouse, Snowflake, SQLite, MongoDB.
- CreateOptions string
- // Comment isn't supported for SQLite, MongoDB.
- Comment string
- // ColumnList isn't supported for MongoDB.
- ColumnList []Column
- // IndexList isn't supported for ClickHouse, Snowflake.
- IndexList []Index
-}
-
// InstanceMeta is the metadata for an instance.
type InstanceMeta struct {
Version string
@@ -159,18 +66,6 @@ type DatabaseMeta struct {
Collation string
}
-// Schema is the database schema.
-type Schema struct {
- Name string
- // CharacterSet isn't supported for ClickHouse, Snowflake, MongoDB.
- CharacterSet string
- // Collation isn't supported for ClickHouse, Snowflake, MongoDB.
- Collation string
- TableList []Table
- ViewList []View
- ExtensionList []Extension
-}
-
// TableKey is the map key for table metadata.
type TableKey struct {
Schema string
diff --git a/plugin/db/mysql/sync.go b/plugin/db/mysql/sync.go
index 16e9d35e13..d210921b7a 100644
--- a/plugin/db/mysql/sync.go
+++ b/plugin/db/mysql/sync.go
@@ -4,8 +4,11 @@ import (
"context"
"database/sql"
"fmt"
+ "sort"
"strings"
+ "google.golang.org/protobuf/types/known/wrapperspb"
+
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/util"
@@ -85,6 +88,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) (*storepb.DatabaseMetadata, error) {
+ schemaMetadata := &storepb.SchemaMetadata{
+ Name: "",
+ }
+
// Query MySQL version
version, err := driver.getVersion(ctx)
if err != nil {
@@ -92,7 +99,8 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
}
isMySQL8 := strings.HasPrefix(version, "8.0")
- // Query index info
+ // Query index info.
+ indexMap := make(map[db.TableKey]map[string]*storepb.IndexMetadata)
indexQuery := `
SELECT
TABLE_NAME,
@@ -105,7 +113,8 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
1,
INDEX_COMMENT
FROM information_schema.STATISTICS
- WHERE TABLE_SCHEMA = ?`
+ WHERE TABLE_SCHEMA = ?
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`
if isMySQL8 {
indexQuery = `
SELECT
@@ -119,52 +128,61 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
CASE IS_VISIBLE WHEN 'YES' THEN 1 ELSE 0 END,
INDEX_COMMENT
FROM information_schema.STATISTICS
- WHERE TABLE_SCHEMA = ?`
+ WHERE TABLE_SCHEMA = ?
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`
}
indexRows, err := driver.db.QueryContext(ctx, indexQuery, databaseName)
if err != nil {
return nil, util.FormatErrorWithQuery(err, indexQuery)
}
defer indexRows.Close()
-
- // tableName -> indexList map
- indexMap := make(map[string][]db.Index)
for indexRows.Next() {
- var tableName string
+ var tableName, indexName, indexType, comment, expression string
var columnName sql.NullString
- var expression sql.NullString
- var index db.Index
+ var expressionName sql.NullString
+ var position int
+ var unique, visible bool
if err := indexRows.Scan(
&tableName,
- &index.Name,
+ &indexName,
&columnName,
- &expression,
- &index.Position,
- &index.Type,
- &index.Unique,
- &index.Visible,
- &index.Comment,
+ &expressionName,
+ &position,
+ &indexType,
+ &unique,
+ &visible,
+ &comment,
); err != nil {
return nil, err
}
-
if columnName.Valid {
- index.Expression = columnName.String
- } else if expression.Valid {
- index.Expression = expression.String
+ expression = columnName.String
+ } else if expressionName.Valid {
+ expression = expressionName.String
}
- if index.Name == "PRIMARY" {
- index.Primary = true
+ key := db.TableKey{Schema: "", Table: tableName}
+ if _, ok := indexMap[key]; !ok {
+ indexMap[key] = make(map[string]*storepb.IndexMetadata)
}
-
- indexMap[tableName] = append(indexMap[tableName], index)
+ if _, ok := indexMap[key][indexName]; !ok {
+ indexMap[key][indexName] = &storepb.IndexMetadata{
+ Name: indexName,
+ Type: indexType,
+ Unique: unique,
+ Primary: indexName == "PRIMARY",
+ Visible: visible,
+ Comment: comment,
+ }
+ }
+ indexMap[key][indexName].Expressions = append(indexMap[key][indexName].Expressions, expression)
}
if err := indexRows.Err(); err != nil {
return nil, util.FormatErrorWithQuery(err, indexQuery)
}
- // Query column info
+ // Query column info.
+ columnMap := make(map[db.TableKey][]*storepb.ColumnMetadata)
columnQuery := `
SELECT
TABLE_NAME,
@@ -177,20 +195,17 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
IFNULL(COLLATION_NAME, ''),
COLUMN_COMMENT
FROM information_schema.COLUMNS
- WHERE TABLE_SCHEMA = ?`
+ WHERE TABLE_SCHEMA = ?
+ ORDER BY TABLE_NAME, ORDINAL_POSITION`
columnRows, err := driver.db.QueryContext(ctx, columnQuery, databaseName)
if err != nil {
return nil, util.FormatErrorWithQuery(err, columnQuery)
}
defer columnRows.Close()
-
- // tableName -> columnList map
- columnMap := make(map[string][]db.Column)
for columnRows.Next() {
- var tableName string
- var nullable string
+ column := &storepb.ColumnMetadata{}
+ var tableName, nullable string
var defaultStr sql.NullString
- var column db.Column
if err := columnRows.Scan(
&tableName,
&column.Name,
@@ -204,27 +219,60 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
); err != nil {
return nil, err
}
-
if defaultStr.Valid {
- column.Default = &defaultStr.String
+ column.Default = &wrapperspb.StringValue{Value: defaultStr.String}
}
- // TODO(d): use convertBoolFromYesNo() if possible.
- if nullable == "YES" {
- column.Nullable = true
+ isNullBool, err := util.ConvertYesNo(nullable)
+ if err != nil {
+ return nil, err
}
+ column.Nullable = isNullBool
- columnMap[tableName] = append(columnMap[tableName], column)
+ key := db.TableKey{Schema: "", Table: tableName}
+ columnMap[key] = append(columnMap[key], column)
}
if err := columnRows.Err(); err != nil {
return nil, util.FormatErrorWithQuery(err, columnQuery)
}
- // Query table info
+ // Query view info.
+ viewMap := make(map[db.TableKey]*storepb.ViewMetadata)
+ 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, util.FormatErrorWithQuery(err, viewQuery)
+ }
+ defer viewRows.Close()
+ for viewRows.Next() {
+ view := &storepb.ViewMetadata{}
+ if err := viewRows.Scan(
+ &view.Name,
+ &view.Definition,
+ ); err != nil {
+ return nil, err
+ }
+ key := db.TableKey{Schema: "", Table: view.Name}
+ viewMap[key] = view
+ }
+ if err := viewRows.Err(); err != nil {
+ return nil, util.FormatErrorWithQuery(err, viewQuery)
+ }
+
+ // Query foreign key info.
+ foreignKeysMap, err := driver.getForeignKeyList(ctx, databaseName)
+ if err != nil {
+ return nil, err
+ }
+
+ // Query table info.
tableQuery := `
SELECT
TABLE_NAME,
- IFNULL(UNIX_TIMESTAMP(CREATE_TIME), 0),
- IFNULL(UNIX_TIMESTAMP(UPDATE_TIME), 0),
TABLE_TYPE,
IFNULL(ENGINE, ''),
IFNULL(TABLE_COLLATION, ''),
@@ -235,56 +283,68 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
IFNULL(CREATE_OPTIONS, ''),
IFNULL(TABLE_COMMENT, '')
FROM information_schema.TABLES
- WHERE TABLE_SCHEMA = ?`
+ WHERE TABLE_SCHEMA = ?
+ ORDER BY TABLE_NAME`
tableRows, err := driver.db.QueryContext(ctx, tableQuery, databaseName)
if err != nil {
return nil, util.FormatErrorWithQuery(err, tableQuery)
}
defer tableRows.Close()
-
- var tableList []db.Table
- type ViewInfo struct {
- createdTs int64
- updatedTs int64
- comment string
- }
- // viewName -> ViewInfo
- viewInfoMap := make(map[string]ViewInfo)
for tableRows.Next() {
+ var tableName, tableType, engine, collation, createOptions, comment string
+ var rowCount, dataSize, indexSize, dataFree int64
// Workaround TiDB bug https://github.com/pingcap/tidb/issues/27970
var tableCollation sql.NullString
- var table db.Table
if err := tableRows.Scan(
- &table.Name,
- &table.CreatedTs,
- &table.UpdatedTs,
- &table.Type,
- &table.Engine,
- &tableCollation,
- &table.RowCount,
- &table.DataSize,
- &table.IndexSize,
- &table.DataFree,
- &table.CreateOptions,
- &table.Comment,
+ &tableName,
+ &tableType,
+ &engine,
+ &collation,
+ &rowCount,
+ &dataSize,
+ &indexSize,
+ &dataFree,
+ &createOptions,
+ &comment,
); err != nil {
return nil, err
}
- table.ShortName = table.Name
- switch table.Type {
+ key := db.TableKey{Schema: "", Table: tableName}
+ switch tableType {
case baseTableType:
+ tableMetadata := &storepb.TableMetadata{
+ Name: tableName,
+ Columns: columnMap[key],
+ ForeignKeys: foreignKeysMap[key],
+ Engine: engine,
+ Collation: collation,
+ RowCount: rowCount,
+ DataSize: dataSize,
+ IndexSize: indexSize,
+ DataFree: dataFree,
+ CreateOptions: createOptions,
+ Comment: comment,
+ }
if tableCollation.Valid {
- table.Collation = tableCollation.String
+ tableMetadata.Collation = tableCollation.String
}
- table.ColumnList = columnMap[table.Name]
- table.IndexList = indexMap[table.Name]
- tableList = append(tableList, table)
+ var indexNames []string
+ if indexes, ok := indexMap[key]; ok {
+ for indexName := range indexes {
+ indexNames = append(indexNames, indexName)
+ }
+ sort.Strings(indexNames)
+ for _, indexName := range indexNames {
+ tableMetadata.Indexes = append(tableMetadata.Indexes, indexes[indexName])
+ }
+ }
+
+ schemaMetadata.Tables = append(schemaMetadata.Tables, tableMetadata)
case viewTableType:
- viewInfoMap[table.Name] = ViewInfo{
- createdTs: table.CreatedTs,
- updatedTs: table.UpdatedTs,
- comment: table.Comment,
+ if view, ok := viewMap[key]; ok {
+ view.Comment = comment
+ schemaMetadata.Views = append(schemaMetadata.Views, view)
}
}
}
@@ -292,71 +352,27 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
return nil, util.FormatErrorWithQuery(err, tableQuery)
}
- 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, util.FormatErrorWithQuery(err, viewQuery)
- }
- defer viewRows.Close()
-
- var viewList []db.View
- for viewRows.Next() {
- var view db.View
- if err := viewRows.Scan(
- &view.Name,
- &view.Definition,
- ); err != nil {
- return nil, err
- }
- view.ShortName = view.Name
-
- info := viewInfoMap[view.Name]
- view.CreatedTs = info.createdTs
- view.UpdatedTs = info.updatedTs
- view.Comment = info.comment
- viewList = append(viewList, view)
- }
- if err := viewRows.Err(); err != nil {
- return nil, util.FormatErrorWithQuery(err, viewQuery)
+ databaseMetadata := &storepb.DatabaseMetadata{
+ Name: databaseName,
+ Schemas: []*storepb.SchemaMetadata{schemaMetadata},
}
-
- // Query db info
+ // Query db info.
databaseQuery := `
SELECT
- SCHEMA_NAME,
DEFAULT_CHARACTER_SET_NAME,
DEFAULT_COLLATION_NAME
FROM information_schema.SCHEMATA
WHERE SCHEMA_NAME = ?`
- var schema db.Schema
if err := driver.db.QueryRowContext(ctx, databaseQuery, databaseName).Scan(
- &schema.Name,
- &schema.CharacterSet,
- &schema.Collation); err != nil {
+ &databaseMetadata.CharacterSet,
+ &databaseMetadata.Collation,
+ ); err != nil {
if err == sql.ErrNoRows {
return nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
}
return nil, err
}
- schema.TableList = tableList
- schema.ViewList = viewList
-
- foreignKeysMap, err := driver.getForeignKeyList(ctx, databaseName)
- if err != nil {
- return nil, err
- }
- databaseMetadata := util.ConvertDBSchema(&schema)
- for _, schemaMetadata := range databaseMetadata.Schemas {
- for _, tableMetadata := range schemaMetadata.Tables {
- tableMetadata.ForeignKeys = foreignKeysMap[db.TableKey{Schema: schemaMetadata.Name, Table: tableMetadata.Name}]
- }
- }
return databaseMetadata, err
}
diff --git a/plugin/db/pg/sync.go b/plugin/db/pg/sync.go
index 7cdc5119c4..eeb3a86bae 100644
--- a/plugin/db/pg/sync.go
+++ b/plugin/db/pg/sync.go
@@ -5,10 +5,11 @@ import (
"database/sql"
"fmt"
"regexp"
+ "sort"
"strings"
- "time"
"github.com/pkg/errors"
+ "google.golang.org/protobuf/types/known/wrapperspb"
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/plugin/db"
@@ -23,62 +24,6 @@ type pgDatabaseSchema struct {
collate string
}
-// tableSchema describes the schema of a pg table.
-type tableSchema struct {
- schemaName string
- name string
- tableowner string
- comment string
- rowCount int64
- tableSizeByte int64
- indexSizeByte int64
-
- columns []*columnSchema
- constraints []*tableConstraint
-}
-
-// columnSchema describes the schema of a pg table column.
-type columnSchema struct {
- columnName string
- dataType string
- ordinalPosition int
- characterMaximumLength string
- columnDefault string
- isNullable bool
- collationName string
- comment string
-}
-
-// tableConstraint describes constraint schema of a pg table.
-type tableConstraint struct {
- name string
- schemaName string
- tableName string
- constraint string
-}
-
-// viewSchema describes the schema of a pg view.
-type viewSchema struct {
- schemaName string
- name string
- definition string
- comment string
-}
-
-// indexSchema describes the schema of a pg index.
-type indexSchema struct {
- schemaName string
- name string
- tableName string
- statement string
- unique bool
- primary bool
- // methodType such as btree.
- methodType string
- columnExpressions []string
- comment string
-}
-
// SyncInstance syncs the instance.
func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error) {
version, err := driver.getVersion(ctx)
@@ -130,15 +75,15 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
return nil, errors.Wrap(err, "failed to get databases")
}
- schema := db.Schema{
+ databaseMetadata := &storepb.DatabaseMetadata{
Name: databaseName,
}
found := false
for _, database := range databases {
if database.name == databaseName {
found = true
- schema.CharacterSet = database.encoding
- schema.Collation = database.collate
+ databaseMetadata.CharacterSet = database.encoding
+ databaseMetadata.Collation = database.collate
break
}
}
@@ -156,100 +101,44 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
}
defer txn.Rollback()
- // Index statements.
- indicesMap := make(map[string][]*indexSchema)
- indices, err := getIndices(txn)
- if err != nil {
- 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)
- indicesMap[key] = append(indicesMap[key], idx)
- }
-
- // Table statements.
- tables, err := getPgTables(txn)
+ tableMap, err := getTables(txn)
if err != nil {
return nil, errors.Wrapf(err, "failed to get tables from database %q", databaseName)
}
- for _, tbl := range tables {
- var dbTable db.Table
- dbTable.Name = fmt.Sprintf("%s.%s", tbl.schemaName, tbl.name)
- dbTable.Schema = tbl.schemaName
- dbTable.ShortName = tbl.name
- dbTable.Type = "BASE TABLE"
- dbTable.Comment = tbl.comment
- dbTable.RowCount = tbl.rowCount
- dbTable.DataSize = tbl.tableSizeByte
- dbTable.IndexSize = tbl.indexSizeByte
- for _, col := range tbl.columns {
- var dbColumn db.Column
- dbColumn.Name = col.columnName
- dbColumn.Position = col.ordinalPosition
- dbColumn.Default = &col.columnDefault
- dbColumn.Type = col.dataType
- dbColumn.Nullable = col.isNullable
- dbColumn.Collation = col.collationName
- dbColumn.Comment = col.comment
- dbTable.ColumnList = append(dbTable.ColumnList, dbColumn)
- }
- indices := indicesMap[dbTable.Name]
- for _, idx := range indices {
- for i, colExp := range idx.columnExpressions {
- var dbIndex db.Index
- dbIndex.Name = idx.name
- dbIndex.Expression = colExp
- dbIndex.Position = i + 1
- dbIndex.Type = idx.methodType
- dbIndex.Unique = idx.unique
- dbIndex.Primary = idx.primary
- dbIndex.Comment = idx.comment
- dbTable.IndexList = append(dbTable.IndexList, dbIndex)
- }
- }
-
- schema.TableList = append(schema.TableList, dbTable)
- }
- // View statements.
- views, err := getViews(txn)
+ viewMap, err := getViews(txn)
if err != nil {
return nil, errors.Wrapf(err, "failed to get views from database %q", databaseName)
}
- for _, view := range views {
- var dbView db.View
- dbView.Name = fmt.Sprintf("%s.%s", view.schemaName, view.name)
- dbView.Schema = view.schemaName
- dbView.ShortName = view.name
- // Postgres does not store
- dbView.CreatedTs = time.Now().Unix()
- dbView.Definition = view.definition
- dbView.Comment = view.comment
-
- schema.ViewList = append(schema.ViewList, dbView)
- }
- // Extensions.
extensions, err := getExtensions(txn)
if err != nil {
return nil, errors.Wrapf(err, "failed to get extensions from database %q", databaseName)
}
- // Foreign keys.
- foreignKeysMap, err := getForeignKeys(txn)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to get foreign keys from database %q", databaseName)
- }
-
if err := txn.Commit(); err != nil {
return nil, err
}
- databaseMetadata := util.ConvertDBSchema(&schema)
- for _, schemaMetadata := range databaseMetadata.Schemas {
- for _, tableMetadata := range schemaMetadata.Tables {
- tableMetadata.ForeignKeys = foreignKeysMap[db.TableKey{Schema: schemaMetadata.Name, Table: tableMetadata.Name}]
- }
+ schemaNameMap := make(map[string]bool)
+ for schemaName := range tableMap {
+ schemaNameMap[schemaName] = true
+ }
+ for schemaName := range viewMap {
+ schemaNameMap[schemaName] = true
+ }
+ var schemaNames []string
+ for schemaName := range schemaNameMap {
+ schemaNames = append(schemaNames, schemaName)
+ }
+ sort.Strings(schemaNames)
+ for _, schemaName := range schemaNames {
+ databaseMetadata.Schemas = append(databaseMetadata.Schemas, &storepb.SchemaMetadata{
+ Name: schemaName,
+ Tables: tableMap[schemaName],
+ Views: viewMap[schemaName],
+ })
}
databaseMetadata.Extensions = extensions
+
return databaseMetadata, err
}
@@ -339,7 +228,8 @@ func getForeignKeys(txn *sql.Tx) (map[db.TableKey][]*storepb.ForeignKeyMetadata,
JOIN pg_namespace n ON n.oid = c.connamespace
WHERE
n.nspname NOT IN('pg_catalog', 'information_schema')
- AND c.contype = 'f';
+ AND c.contype = 'f'
+ ORDER BY fk_schema, fk_table, fk_name;
`
foreignKeysMap := make(map[db.TableKey][]*storepb.ForeignKeyMetadata)
rows, err := txn.Query(query)
@@ -453,26 +343,31 @@ func formatTableNameFromRegclass(name string) string {
}
// getTables gets all tables of a database.
-func getPgTables(txn *sql.Tx) ([]*tableSchema, error) {
- constraints, err := getTableConstraints(txn)
+func getTables(txn *sql.Tx) (map[string][]*storepb.TableMetadata, error) {
+ columnMap, err := getTableColumns(txn)
if err != nil {
- return nil, errors.Wrap(err, "failed to get table constraints")
+ return nil, errors.Wrap(err, "failed to get table columns")
}
- columns, err := getTableColumns(txn)
+ indexMap, err := getIndexes(txn)
if err != nil {
- return nil, errors.Wrap(err, "failed to get table columns")
+ return nil, errors.Wrapf(err, "failed to get indices")
+ }
+ foreignKeysMap, err := getForeignKeys(txn)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get foreign keys")
}
- var tables []*tableSchema
+ tableMap := make(map[string][]*storepb.TableMetadata)
query := `
- SELECT tbl.schemaname, tbl.tablename, tbl.tableowner,
- pg_table_size(format('%s.%s', quote_ident(tbl.schemaname), quote_ident(tbl.tablename))::regclass),
- pg_indexes_size(format('%s.%s', quote_ident(tbl.schemaname), quote_ident(tbl.tablename))::regclass),
- GREATEST(pc.reltuples::bigint, 0::BIGINT) AS estimate,
- obj_description(format('%s.%s', quote_ident(tbl.schemaname), quote_ident(tbl.tablename))::regclass) AS comment
- FROM pg_catalog.pg_tables tbl
- LEFT JOIN pg_class as pc ON pc.oid = format('%s.%s', quote_ident(tbl.schemaname), quote_ident(tbl.tablename))::regclass
- WHERE tbl.schemaname NOT IN ('pg_catalog', 'information_schema');`
+ SELECT tbl.schemaname, tbl.tablename,
+ pg_table_size(format('%s.%s', quote_ident(tbl.schemaname), quote_ident(tbl.tablename))::regclass),
+ pg_indexes_size(format('%s.%s', quote_ident(tbl.schemaname), quote_ident(tbl.tablename))::regclass),
+ GREATEST(pc.reltuples::bigint, 0::BIGINT) AS estimate,
+ obj_description(format('%s.%s', quote_ident(tbl.schemaname), quote_ident(tbl.tablename))::regclass) AS comment
+ FROM pg_catalog.pg_tables tbl
+ LEFT JOIN pg_class as pc ON pc.oid = format('%s.%s', quote_ident(tbl.schemaname), quote_ident(tbl.tablename))::regclass
+ WHERE tbl.schemaname NOT IN ('pg_catalog', 'information_schema')
+ ORDER BY tbl.schemaname, tbl.tablename;`
rows, err := txn.Query(query)
if err != nil {
return nil, err
@@ -480,162 +375,125 @@ func getPgTables(txn *sql.Tx) ([]*tableSchema, error) {
defer rows.Close()
for rows.Next() {
- var tbl tableSchema
- var schemaname, tablename, tableowner string
- var tableSizeByte, indexSizeByte, rowCountEstimate int64
+ table := &storepb.TableMetadata{}
+ // var tbl tableSchema
+ var schemaName string
var comment sql.NullString
- if err := rows.Scan(&schemaname, &tablename, &tableowner, &tableSizeByte, &indexSizeByte, &rowCountEstimate, &comment); err != nil {
+ if err := rows.Scan(&schemaName, &table.Name, &table.DataSize, &table.IndexSize, &table.RowCount, &comment); err != nil {
return nil, err
}
- tbl.schemaName = schemaname
- tbl.name = tablename
- tbl.tableowner = tableowner
- tbl.tableSizeByte = tableSizeByte
- tbl.indexSizeByte = indexSizeByte
- tbl.rowCount = rowCountEstimate
if comment.Valid {
- tbl.comment = comment.String
+ table.Comment = comment.String
}
+ key := db.TableKey{Schema: schemaName, Table: table.Name}
+ table.Columns = columnMap[key]
+ table.Indexes = indexMap[key]
+ table.ForeignKeys = foreignKeysMap[key]
- tables = append(tables, &tbl)
+ tableMap[schemaName] = append(tableMap[schemaName], table)
}
if err := rows.Err(); err != nil {
return nil, err
}
- for _, tbl := range tables {
- key := fmt.Sprintf("%s.%s", tbl.schemaName, tbl.name)
- tbl.constraints = constraints[key]
- tbl.columns = columns[key]
- }
- return tables, nil
+ return tableMap, nil
}
// getTableColumns gets the columns of a table.
-func getTableColumns(txn *sql.Tx) (map[string][]*columnSchema, error) {
+func getTableColumns(txn *sql.Tx) (map[db.TableKey][]*storepb.ColumnMetadata, error) {
+ columnsMap := make(map[db.TableKey][]*storepb.ColumnMetadata)
+
query := `
- SELECT
- cols.table_schema,
- cols.table_name,
- cols.column_name,
- cols.data_type,
- cols.ordinal_position,
- cols.character_maximum_length,
- cols.column_default,
- cols.is_nullable,
- cols.collation_name,
- cols.udt_schema,
- cols.udt_name,
- pg_catalog.col_description(format('%s.%s', quote_ident(table_schema), quote_ident(table_name))::regclass, cols.ordinal_position::int) as column_comment
- FROM INFORMATION_SCHEMA.COLUMNS AS cols
- WHERE cols.table_schema NOT IN ('pg_catalog', 'information_schema');`
+ SELECT
+ cols.table_schema,
+ cols.table_name,
+ cols.column_name,
+ cols.data_type,
+ cols.ordinal_position,
+ cols.column_default,
+ cols.is_nullable,
+ cols.collation_name,
+ cols.udt_schema,
+ cols.udt_name,
+ pg_catalog.col_description(format('%s.%s', quote_ident(table_schema), quote_ident(table_name))::regclass, cols.ordinal_position::int) as column_comment
+ FROM INFORMATION_SCHEMA.COLUMNS AS cols
+ WHERE cols.table_schema NOT IN ('pg_catalog', 'information_schema')
+ ORDER BY cols.table_schema, cols.table_name, cols.ordinal_position;`
rows, err := txn.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
-
- columnsMap := make(map[string][]*columnSchema)
for rows.Next() {
- var tableSchema, tableName, columnName, dataType, isNullable string
- var characterMaximumLength, columnDefault, collationName, udtSchema, udtName, comment sql.NullString
- var ordinalPosition int
- if err := rows.Scan(&tableSchema, &tableName, &columnName, &dataType, &ordinalPosition, &characterMaximumLength, &columnDefault, &isNullable, &collationName, &udtSchema, &udtName, &comment); err != nil {
+ column := &storepb.ColumnMetadata{}
+ var schemaName, tableName, nullable string
+ var defaultStr, collation, udtSchema, udtName, comment sql.NullString
+ if err := rows.Scan(&schemaName, &tableName, &column.Name, &column.Type, &column.Position, &defaultStr, &nullable, &collation, &udtSchema, &udtName, &comment); err != nil {
return nil, err
}
- isNullBool, err := convertBoolFromYesNo(isNullable)
+ if defaultStr.Valid {
+ column.Default = &wrapperspb.StringValue{Value: defaultStr.String}
+ }
+ isNullBool, err := util.ConvertYesNo(nullable)
if err != nil {
return nil, err
}
- c := columnSchema{
- columnName: columnName,
- dataType: dataType,
- ordinalPosition: ordinalPosition,
- characterMaximumLength: characterMaximumLength.String,
- columnDefault: columnDefault.String,
- isNullable: isNullBool,
- collationName: collationName.String,
- comment: comment.String,
- }
- switch dataType {
+ column.Nullable = isNullBool
+ switch column.Type {
case "USER-DEFINED":
- c.dataType = fmt.Sprintf("%s.%s", udtSchema.String, udtName.String)
+ column.Type = fmt.Sprintf("%s.%s", udtSchema.String, udtName.String)
case "ARRAY":
- c.dataType = udtName.String
+ column.Type = udtName.String
}
- key := fmt.Sprintf("%s.%s", tableSchema, tableName)
- columnsMap[key] = append(columnsMap[key], &c)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return columnsMap, nil
-}
-
-// getTableConstraints gets all table constraints of a database.
-func getTableConstraints(txn *sql.Tx) (map[string][]*tableConstraint, error) {
- query := "" +
- "SELECT n.nspname, conrelid::regclass, conname, pg_get_constraintdef(c.oid) " +
- "FROM pg_constraint c " +
- "JOIN pg_namespace n ON n.oid = c.connamespace " +
- "WHERE n.nspname NOT IN ('pg_catalog', 'information_schema');"
- ret := make(map[string][]*tableConstraint)
- rows, err := txn.Query(query)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
+ column.Collation = collation.String
+ column.Comment = comment.String
- for rows.Next() {
- var constraint tableConstraint
- if err := rows.Scan(&constraint.schemaName, &constraint.tableName, &constraint.name, &constraint.constraint); err != nil {
- return nil, err
- }
- if strings.Contains(constraint.tableName, ".") {
- constraint.tableName = constraint.tableName[1+strings.Index(constraint.tableName, "."):]
- }
- key := fmt.Sprintf("%s.%s", constraint.schemaName, constraint.tableName)
- ret[key] = append(ret[key], &constraint)
+ key := db.TableKey{Schema: schemaName, Table: tableName}
+ columnsMap[key] = append(columnsMap[key], column)
}
if err := rows.Err(); err != nil {
return nil, err
}
- return ret, nil
+
+ return columnsMap, nil
}
// getViews gets all views of a database.
-func getViews(txn *sql.Tx) ([]*viewSchema, error) {
+func getViews(txn *sql.Tx) (map[string][]*storepb.ViewMetadata, error) {
+ viewMap := make(map[string][]*storepb.ViewMetadata)
+
query := `
- SELECT schemaname, viewname, definition, obj_description(format('%s.%s', quote_ident(schemaname), quote_ident(viewname))::regclass) FROM pg_catalog.pg_views
- WHERE schemaname NOT IN ('pg_catalog', 'information_schema');`
- var views []*viewSchema
+ SELECT schemaname, viewname, definition, obj_description(format('%s.%s', quote_ident(schemaname), quote_ident(viewname))::regclass) FROM pg_catalog.pg_views
+ WHERE schemaname NOT IN ('pg_catalog', 'information_schema');`
rows, err := txn.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
-
for rows.Next() {
- var view viewSchema
+ view := &storepb.ViewMetadata{}
+ var schemaName string
var def, comment sql.NullString
- if err := rows.Scan(&view.schemaName, &view.name, &def, &comment); err != nil {
+ if err := rows.Scan(&schemaName, &view.Name, &def, &comment); err != nil {
return nil, err
}
// Return error on NULL view definition.
// https://github.com/bytebase/bytebase/issues/343
if !def.Valid {
- return nil, errors.Errorf("schema %q view %q has empty definition; please check whether proper privileges have been granted to Bytebase", view.schemaName, view.name)
+ return nil, errors.Errorf("schema %q view %q has empty definition; please check whether proper privileges have been granted to Bytebase", schemaName, view.Name)
}
- view.definition = def.String
+ view.Definition = def.String
if comment.Valid {
- view.comment = comment.String
+ view.Comment = comment.String
}
- views = append(views, &view)
+
+ viewMap[schemaName] = append(viewMap[schemaName], view)
}
if err := rows.Err(); err != nil {
return nil, err
}
- return views, nil
+
+ return viewMap, nil
}
// getExtensions gets all extensions of a database.
@@ -654,13 +512,12 @@ func getExtensions(txn *sql.Tx) ([]*storepb.ExtensionMetadata, error) {
return nil, err
}
defer rows.Close()
-
for rows.Next() {
- var e storepb.ExtensionMetadata
+ e := &storepb.ExtensionMetadata{}
if err := rows.Scan(&e.Name, &e.Version, &e.Schema, &e.Description); err != nil {
return nil, err
}
- extensions = append(extensions, &e)
+ extensions = append(extensions, e)
}
if err := rows.Err(); err != nil {
return nil, err
@@ -669,63 +526,55 @@ func getExtensions(txn *sql.Tx) ([]*storepb.ExtensionMetadata, error) {
return extensions, nil
}
-// getIndices gets all indices of a database.
-func getIndices(txn *sql.Tx) ([]*indexSchema, error) {
+// getIndexes gets all indices of a database.
+func getIndexes(txn *sql.Tx) (map[db.TableKey][]*storepb.IndexMetadata, error) {
+ indexMap := make(map[db.TableKey][]*storepb.IndexMetadata)
+
query := `
- SELECT idx.schemaname, idx.tablename, idx.indexname, idx.indexdef, (SELECT 1
- FROM information_schema.table_constraints
- WHERE constraint_schema = idx.schemaname
- AND constraint_name = idx.indexname
- AND table_schema = idx.schemaname
- AND table_name = idx.tablename
- AND constraint_type = 'PRIMARY KEY') AS primary,
- obj_description(format('%s.%s', quote_ident(idx.schemaname), quote_ident(idx.indexname))::regclass) AS comment
- FROM pg_indexes AS idx WHERE idx.schemaname NOT IN ('pg_catalog', 'information_schema');`
-
- var indices []*indexSchema
+ SELECT idx.schemaname, idx.tablename, idx.indexname, idx.indexdef, (SELECT 1
+ FROM information_schema.table_constraints
+ WHERE constraint_schema = idx.schemaname
+ AND constraint_name = idx.indexname
+ AND table_schema = idx.schemaname
+ AND table_name = idx.tablename
+ AND constraint_type = 'PRIMARY KEY') AS primary,
+ obj_description(format('%s.%s', quote_ident(idx.schemaname), quote_ident(idx.indexname))::regclass) AS comment
+ FROM pg_indexes AS idx WHERE idx.schemaname NOT IN ('pg_catalog', 'information_schema')
+ ORDER BY idx.schemaname, idx.tablename, idx.indexname;`
rows, err := txn.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
-
for rows.Next() {
- var idx indexSchema
+ index := &storepb.IndexMetadata{}
+ var schemaName, tableName, statement string
var primary sql.NullInt32
var comment sql.NullString
- if err := rows.Scan(&idx.schemaName, &idx.tableName, &idx.name, &idx.statement, &primary, &comment); err != nil {
+ if err := rows.Scan(&schemaName, &tableName, &index.Name, &statement, &primary, &comment); err != nil {
return nil, err
}
- idx.unique = strings.Contains(idx.statement, " UNIQUE INDEX ")
- idx.methodType = getIndexMethodType(idx.statement)
- idx.columnExpressions, err = getIndexColumnExpressions(idx.statement)
+ index.Type = getIndexMethodType(statement)
+ index.Unique = strings.Contains(statement, " UNIQUE INDEX ")
+ index.Expressions, err = getIndexColumnExpressions(statement)
if err != nil {
return nil, err
}
if primary.Valid && primary.Int32 == 1 {
- idx.primary = true
+ index.Primary = true
}
if comment.Valid {
- idx.comment = comment.String
+ index.Comment = comment.String
}
- indices = append(indices, &idx)
+
+ key := db.TableKey{Schema: schemaName, Table: tableName}
+ indexMap[key] = append(indexMap[key], index)
}
if err := rows.Err(); err != nil {
return nil, err
}
- return indices, nil
-}
-
-func convertBoolFromYesNo(s string) (bool, error) {
- switch s {
- case "YES":
- return true, nil
- case "NO":
- return false, nil
- default:
- return false, errors.Errorf("unrecognized isNullable type %q", s)
- }
+ return indexMap, nil
}
func getIndexMethodType(stmt string) string {
diff --git a/plugin/db/snowflake/sync.go b/plugin/db/snowflake/sync.go
index f542f8bce0..c86d605642 100644
--- a/plugin/db/snowflake/sync.go
+++ b/plugin/db/snowflake/sync.go
@@ -4,8 +4,11 @@ import (
"context"
"database/sql"
"fmt"
+ "sort"
"strings"
+ "google.golang.org/protobuf/types/known/wrapperspb"
+
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/util"
@@ -75,7 +78,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
return nil, err
}
- schema := db.Schema{
+ databaseMetadata := &storepb.DatabaseMetadata{
Name: databaseName,
}
found := false
@@ -89,13 +92,31 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
return nil, common.Errorf(common.NotFound, "database %q not found", databaseName)
}
- tableList, viewList, err := driver.syncTableSchema(ctx, databaseName)
+ tableMap, viewMap, err := driver.getTableSchema(ctx, databaseName)
if err != nil {
return nil, err
}
- schema.TableList, schema.ViewList = tableList, viewList
+ schemaNameMap := make(map[string]bool)
+ for schemaName := range tableMap {
+ schemaNameMap[schemaName] = true
+ }
+ for schemaName := range viewMap {
+ schemaNameMap[schemaName] = true
+ }
+ var schemaNames []string
+ for schemaName := range schemaNameMap {
+ schemaNames = append(schemaNames, schemaName)
+ }
+ sort.Strings(schemaNames)
+ for _, schemaName := range schemaNames {
+ databaseMetadata.Schemas = append(databaseMetadata.Schemas, &storepb.SchemaMetadata{
+ Name: schemaName,
+ Tables: tableMap[schemaName],
+ Views: viewMap[schemaName],
+ })
+ }
- return util.ConvertDBSchema(&schema), nil
+ return databaseMetadata, nil
}
func (driver *Driver) getUserList(ctx context.Context) ([]db.User, error) {
@@ -160,17 +181,19 @@ func (driver *Driver) getUserList(ctx context.Context) ([]db.User, error) {
return userList, nil
}
-func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]db.Table, []db.View, error) {
+func (driver *Driver) getTableSchema(ctx context.Context, database string) (map[string][]*storepb.TableMetadata, map[string][]*storepb.ViewMetadata, error) {
+ tableMap, viewMap := make(map[string][]*storepb.TableMetadata), make(map[string][]*storepb.ViewMetadata)
+
// Query table info
var excludedSchemaList []string
-
// Skip all system schemas.
for k := range systemSchemas {
excludedSchemaList = append(excludedSchemaList, fmt.Sprintf("'%s'", k))
}
excludeWhere := fmt.Sprintf("LOWER(TABLE_SCHEMA) NOT IN (%s)", strings.Join(excludedSchemaList, ", "))
- // Query column info
+ // Query column info.
+ columnMap := make(map[db.TableKey][]*storepb.ColumnMetadata)
columnQuery := fmt.Sprintf(`
SELECT
TABLE_SCHEMA,
@@ -184,21 +207,17 @@ func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]d
IFNULL(COLLATION_NAME, ''),
IFNULL(COMMENT, '')
FROM %s.INFORMATION_SCHEMA.COLUMNS
- WHERE %s`, database, excludeWhere)
+ WHERE %s
+ ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION`, database, excludeWhere)
columnRows, err := driver.db.QueryContext(ctx, columnQuery)
if err != nil {
return nil, nil, util.FormatErrorWithQuery(err, columnQuery)
}
defer columnRows.Close()
-
- // schemaName.tableName -> columnList map
- columnMap := make(map[string][]db.Column)
for columnRows.Next() {
- var schemaName string
- var tableName string
- var nullable string
+ var schemaName, tableName, nullable string
var defaultStr sql.NullString
- var column db.Column
+ column := &storepb.ColumnMetadata{}
if err := columnRows.Scan(
&schemaName,
&tableName,
@@ -213,12 +232,16 @@ func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]d
); err != nil {
return nil, nil, err
}
-
if defaultStr.Valid {
- column.Default = &defaultStr.String
+ column.Default = &wrapperspb.StringValue{Value: defaultStr.String}
+ }
+ isNullBool, err := util.ConvertYesNo(nullable)
+ if err != nil {
+ return nil, nil, err
}
+ column.Nullable = isNullBool
- key := fmt.Sprintf("%s.%s", schemaName, tableName)
+ key := db.TableKey{Schema: schemaName, Table: tableName}
columnMap[key] = append(columnMap[key], column)
}
if err := columnRows.Err(); err != nil {
@@ -229,30 +252,23 @@ func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]d
SELECT
TABLE_SCHEMA,
TABLE_NAME,
- DATE_PART(EPOCH_SECOND, CREATED),
- DATE_PART(EPOCH_SECOND, LAST_ALTERED),
- TABLE_TYPE,
ROW_COUNT,
BYTES,
IFNULL(COMMENT, '')
FROM %s.INFORMATION_SCHEMA.TABLES
- WHERE TABLE_TYPE = 'BASE TABLE' AND %s`, database, excludeWhere)
+ WHERE TABLE_TYPE = 'BASE TABLE' AND %s
+ ORDER BY TABLE_SCHEMA, TABLE_NAME`, database, excludeWhere)
tableRows, err := driver.db.QueryContext(ctx, tableQuery)
if err != nil {
return nil, nil, util.FormatErrorWithQuery(err, tableQuery)
}
defer tableRows.Close()
-
- var tables []db.Table
for tableRows.Next() {
- var schemaName, tableName string
- var table db.Table
+ var schemaName string
+ table := &storepb.TableMetadata{}
if err := tableRows.Scan(
&schemaName,
- &tableName,
- &table.CreatedTs,
- &table.UpdatedTs,
- &table.Type,
+ &table.Name,
&table.RowCount,
&table.DataSize,
&table.Comment,
@@ -260,61 +276,43 @@ func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]d
return nil, nil, err
}
- table.Name = fmt.Sprintf("%s.%s", schemaName, tableName)
- table.Schema = schemaName
- table.ShortName = tableName
- table.ColumnList = columnMap[table.Name]
- tables = append(tables, table)
+ tableMap[schemaName] = append(tableMap[schemaName], table)
}
if err := tableRows.Err(); err != nil {
return nil, nil, util.FormatErrorWithQuery(err, tableQuery)
}
viewQuery := fmt.Sprintf(`
- SELECT
- TABLE_SCHEMA,
- TABLE_NAME,
- DATE_PART(EPOCH_SECOND, CREATED),
- DATE_PART(EPOCH_SECOND, LAST_ALTERED),
- IFNULL(VIEW_DEFINITION, ''),
- IFNULL(COMMENT, '')
- FROM %s.INFORMATION_SCHEMA.VIEWS
- WHERE %s`, database, excludeWhere)
+ SELECT
+ TABLE_SCHEMA,
+ TABLE_NAME,
+ IFNULL(VIEW_DEFINITION, ''),
+ IFNULL(COMMENT, '')
+ FROM %s.INFORMATION_SCHEMA.VIEWS
+ WHERE %s
+ ORDER BY TABLE_SCHEMA, TABLE_NAME`, database, excludeWhere)
viewRows, err := driver.db.QueryContext(ctx, viewQuery)
if err != nil {
return nil, nil, util.FormatErrorWithQuery(err, viewQuery)
}
defer viewRows.Close()
-
- var views []db.View
for viewRows.Next() {
- var schemaName, viewName string
- var createdTs, updatedTs sql.NullInt64
- var view db.View
+ view := &storepb.ViewMetadata{}
+ var schemaName string
if err := viewRows.Scan(
&schemaName,
- &viewName,
- &createdTs,
- &updatedTs,
+ &view.Name,
&view.Definition,
&view.Comment,
); err != nil {
return nil, nil, err
}
- view.Name = fmt.Sprintf("%s.%s", schemaName, viewName)
- view.Schema = schemaName
- view.ShortName = viewName
- if createdTs.Valid {
- view.CreatedTs = createdTs.Int64
- }
- if updatedTs.Valid {
- view.UpdatedTs = updatedTs.Int64
- }
- views = append(views, view)
+
+ viewMap[schemaName] = append(viewMap[schemaName], view)
}
if err := viewRows.Err(); err != nil {
return nil, nil, util.FormatErrorWithQuery(err, viewQuery)
}
- return tables, views, nil
+ return tableMap, viewMap, nil
}
diff --git a/plugin/db/sqlite/sync.go b/plugin/db/sqlite/sync.go
index 5ab7956a15..8c1164d432 100644
--- a/plugin/db/sqlite/sync.go
+++ b/plugin/db/sqlite/sync.go
@@ -7,6 +7,7 @@ import (
"strings"
"github.com/pkg/errors"
+ "google.golang.org/protobuf/types/known/wrapperspb"
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/plugin/db"
@@ -21,14 +22,6 @@ var (
}
)
-// indexSchema describes the schema of an index.
-type indexSchema struct {
- name string
- tableName string
- statement string
- unique bool
-}
-
// SyncInstance syncs the instance.
func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error) {
version, err := driver.getVersion(ctx)
@@ -69,8 +62,12 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
return nil, err
}
- schema := db.Schema{
- Name: databaseName,
+ schemaMetadata := &storepb.SchemaMetadata{
+ Name: "",
+ }
+ databaseMetadata := &storepb.DatabaseMetadata{
+ Name: databaseName,
+ Schemas: []*storepb.SchemaMetadata{schemaMetadata},
}
found := false
for _, database := range databases {
@@ -92,46 +89,45 @@ func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*s
return nil, err
}
defer txn.Rollback()
- // Index statements.
- indicesMap := make(map[string][]indexSchema)
- indices, err := getIndices(txn)
- if err != nil {
- 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)
- }
- tbls, err := getTables(txn, indicesMap)
+ tables, err := getTables(txn)
if err != nil {
return nil, err
}
- schema.TableList = tbls
+ schemaMetadata.Tables = tables
views, err := getViews(txn)
if err != nil {
return nil, err
}
- schema.ViewList = views
+ schemaMetadata.Views = views
if err := txn.Commit(); err != nil {
return nil, err
}
- return util.ConvertDBSchema(&schema), nil
+ return databaseMetadata, nil
}
// getTables gets all tables of a database.
-func getTables(txn *sql.Tx, indicesMap map[string][]indexSchema) ([]db.Table, error) {
- var tables []db.Table
- query := "SELECT name FROM sqlite_schema WHERE type ='table' AND name NOT LIKE 'sqlite_%';"
+func getTables(txn *sql.Tx) ([]*storepb.TableMetadata, error) {
+ indexMap, err := getIndices(txn)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get indices")
+ }
+
+ var tableNames []string
+ query := `
+ SELECT
+ name
+ FROM sqlite_schema
+ WHERE type ='table' AND name NOT LIKE 'sqlite_%'
+ ORDER BY name;`
rows, err := txn.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
-
- var tableNames []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
@@ -142,12 +138,12 @@ func getTables(txn *sql.Tx, indicesMap map[string][]indexSchema) ([]db.Table, er
if err := rows.Err(); err != nil {
return nil, util.FormatErrorWithQuery(err, query)
}
- for _, name := range tableNames {
- var tbl db.Table
- tbl.Name = name
- tbl.ShortName = name
- tbl.Type = "BASE TABLE"
+ var tables []*storepb.TableMetadata
+ for _, name := range tableNames {
+ table := &storepb.TableMetadata{
+ Name: name,
+ }
if err := func() error {
// Get columns: cid, name, type, notnull, dflt_value, pk.
query := fmt.Sprintf("pragma table_info(%s);", name)
@@ -156,49 +152,75 @@ func getTables(txn *sql.Tx, indicesMap map[string][]indexSchema) ([]db.Table, er
return err
}
defer rows.Close()
-
for rows.Next() {
- var col db.Column
-
- var cid int
- var notnull, pk bool
- var name, ctype string
- var dfltValue sql.NullString
- if err := rows.Scan(&cid, &name, &ctype, &notnull, &dfltValue, &pk); err != nil {
+ column := &storepb.ColumnMetadata{}
+ var notNull, unusedPk bool
+ var defaultStr sql.NullString
+ if err := rows.Scan(&column.Position, &column.Name, &column.Type, &notNull, &defaultStr, &unusedPk); err != nil {
return err
}
- col.Position = cid
- col.Name = name
- col.Nullable = !notnull
- col.Type = ctype
- if dfltValue.Valid {
- col.Default = &dfltValue.String
+ column.Nullable = !notNull
+ if defaultStr.Valid {
+ column.Default = &wrapperspb.StringValue{Value: defaultStr.String}
}
- tbl.ColumnList = append(tbl.ColumnList, col)
+ table.Columns = append(table.Columns, column)
+ table.Indexes = indexMap[table.Name]
}
return rows.Err()
}(); err != nil {
return nil, err
}
- for _, idx := range indicesMap[tbl.Name] {
+ tables = append(tables, table)
+ }
+ return tables, nil
+}
+
+// getIndices gets all indices of a database.
+func getIndices(txn *sql.Tx) (map[string][]*storepb.IndexMetadata, error) {
+ indexMap := make(map[string][]*storepb.IndexMetadata)
+ query := `
+ SELECT
+ tbl_name, name, sql
+ FROM sqlite_schema
+ WHERE type ='index' AND name NOT LIKE 'sqlite_%'
+ ORDER BY tbl_name, name;`
+ rows, err := txn.Query(query)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var tableName, statement string
+ index := &storepb.IndexMetadata{}
+ if err := rows.Scan(tableName, &index.Name, &statement); err != nil {
+ return nil, err
+ }
+ index.Unique = strings.Contains(statement, " UNIQUE INDEX ")
+ indexMap[tableName] = append(indexMap[tableName], index)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, util.FormatErrorWithQuery(err, query)
+ }
+
+ for _, indexes := range indexMap {
+ for _, index := range indexes {
if err := func() error {
- query := fmt.Sprintf("pragma index_info(%s);", idx.name)
+ query := fmt.Sprintf("pragma index_info(%s);", index.Name)
rows, err := txn.Query(query)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
- var dbIdx db.Index
- dbIdx.Name = idx.name
- dbIdx.Unique = idx.unique
- var cid string
- if err := rows.Scan(&dbIdx.Position, &cid, &dbIdx.Expression); err != nil {
+ var unusedPosition int
+ var unusedCid, expression string
+ if err := rows.Scan(&unusedPosition, &unusedCid, &expression); err != nil {
return err
}
- tbl.IndexList = append(tbl.IndexList, dbIdx)
+ index.Expressions = append(index.Expressions, expression)
}
if err := rows.Err(); err != nil {
return util.FormatErrorWithQuery(err, query)
@@ -208,55 +230,35 @@ func getTables(txn *sql.Tx, indicesMap map[string][]indexSchema) ([]db.Table, er
return nil, err
}
}
-
- tables = append(tables, tbl)
- }
- return tables, nil
-}
-
-// getIndices gets all indices of a database.
-func getIndices(txn *sql.Tx) ([]indexSchema, error) {
- var indices []indexSchema
- query := "SELECT name, tbl_name, sql FROM sqlite_schema WHERE type ='index' AND name NOT LIKE 'sqlite_%';"
- rows, err := txn.Query(query)
- if err != nil {
- return nil, err
}
- defer rows.Close()
- for rows.Next() {
- var idx indexSchema
- if err := rows.Scan(&idx.name, &idx.tableName, &idx.statement); err != nil {
- return nil, err
- }
- idx.unique = strings.Contains(idx.statement, " UNIQUE INDEX ")
- indices = append(indices, idx)
- }
- if err := rows.Err(); err != nil {
- return nil, util.FormatErrorWithQuery(err, query)
- }
- return indices, nil
+ return indexMap, nil
}
-func getViews(txn *sql.Tx) ([]db.View, error) {
- var views []db.View
- query := "SELECT name, sql FROM sqlite_schema WHERE type ='view' AND name NOT LIKE 'sqlite_%';"
+func getViews(txn *sql.Tx) ([]*storepb.ViewMetadata, error) {
+ var views []*storepb.ViewMetadata
+
+ query := `
+ SELECT
+ name, sql
+ FROM sqlite_schema
+ WHERE type ='view' AND name NOT LIKE 'sqlite_%'
+ ORDER BY name;`
rows, err := txn.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
-
for rows.Next() {
- var view db.View
+ view := &storepb.ViewMetadata{}
if err := rows.Scan(&view.Name, &view.Definition); err != nil {
return nil, err
}
- view.ShortName = view.Name
views = append(views, view)
}
if err := rows.Err(); err != nil {
return nil, util.FormatErrorWithQuery(err, query)
}
+
return views, nil
}
diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.go
index 8ab8cd7c63..89a424fdc5 100644
--- a/plugin/db/util/driverutil.go
+++ b/plugin/db/util/driverutil.go
@@ -9,7 +9,6 @@ import (
"fmt"
"io"
"regexp"
- "sort"
"strconv"
"strings"
"time"
@@ -17,12 +16,10 @@ 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.
@@ -734,112 +731,14 @@ func IsAffectedRowsStatement(stmt string) bool {
return false
}
-// ConvertDBSchema converts db schema to database metadata.
-func ConvertDBSchema(schema *db.Schema) *storepb.DatabaseMetadata {
- 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,
- }
-
- 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)
+// ConvertYesNo converts YES/NO to bool.
+func ConvertYesNo(s string) (bool, error) {
+ switch s {
+ case "YES":
+ return true, nil
+ case "NO":
+ return false, nil
+ default:
+ return false, errors.Errorf("unrecognized isNullable type %q", s)
}
- return databaseMetadata
}
diff --git a/plugin/db/util/driverutil_test.go b/plugin/db/util/driverutil_test.go
index da5a4d1bae..1e6bdec8ce 100644
--- a/plugin/db/util/driverutil_test.go
+++ b/plugin/db/util/driverutil_test.go
@@ -7,12 +7,9 @@ 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"
@@ -716,258 +713,3 @@ 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",
- },
- },
- }
- 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",
- },
- },
- },
- },
- }
- got := ConvertDBSchema(dbSchema)
- assert.Equal(t, want, got)
-}
diff --git a/tests/schema_update_test.go b/tests/schema_update_test.go
index 30bdba6446..7c830a9a68 100644
--- a/tests/schema_update_test.go
+++ b/tests/schema_update_test.go
@@ -20,7 +20,6 @@ import (
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/testing/protocmp"
- "google.golang.org/protobuf/types/known/wrapperspb"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/plugin/advisor"
@@ -1885,8 +1884,8 @@ CREATE TABLE public.book (
Name: "book",
DataSize: 8192,
Columns: []*storepb.ColumnMetadata{
- {Name: "id", Position: 1, Default: &wrapperspb.StringValue{Value: ""}, Nullable: true, Type: "integer"},
- {Name: "name", Position: 2, Default: &wrapperspb.StringValue{Value: ""}, Nullable: true, Type: "text"},
+ {Name: "id", Position: 1, Nullable: true, Type: "integer"},
+ {Name: "name", Position: 2, Nullable: true, Type: "text"},
},
},
},
diff --git a/tests/syncer_test.go b/tests/syncer_test.go
index b4186b8961..ee313f27b1 100644
--- a/tests/syncer_test.go
+++ b/tests/syncer_test.go
@@ -8,8 +8,10 @@ import (
"strconv"
"testing"
+ "github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/testing/protocmp"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/plugin/db"
@@ -37,111 +39,92 @@ func TestSyncerForPostgreSQL(t *testing.T) {
CONSTRAINT tfk_ibfk_1 FOREIGN KEY (a, b, c) REFERENCES schema1.trd ("A", "B", c)
);
`
- expectedSchema = `
- {
- "name":"test_sync_postgresql_schema_db",
- "schemas":[
- {
- "name":"public",
- "tables":[
- {
- "name":"TFK",
- "columns":[
- {
- "name":"a",
- "position":1,
- "default":"",
- "nullable":true,
- "type":"integer"
- },
- {
- "name":"b",
- "position":2,
- "default":"",
- "nullable":true,
- "type":"integer"
- },
- {
- "name":"c",
- "position":3,
- "default":"",
- "nullable":true,
- "type":"integer"
- }
- ],
- "foreignKeys":[
- {
- "name":"tfk_ibfk_1",
- "columns":[
- "a",
- "b",
- "c"
- ],
- "referencedSchema":"schema1",
- "referencedTable":"trd",
- "referencedColumns":[
- "A",
- "B",
- "c"
- ],
- "onDelete":"NO ACTION",
- "onUpdate":"NO ACTION",
- "matchType":"SIMPLE"
- }
- ]
- }
- ]
- },
- {
- "name":"schema1",
- "tables":[
- {
- "name":"trd",
- "columns":[
- {
- "name":"A",
- "position":1,
- "default":"",
- "nullable":true,
- "type":"integer"
- },
- {
- "name":"B",
- "position":2,
- "default":"",
- "nullable":true,
- "type":"integer"
- },
- {
- "name":"c",
- "position":3,
- "default":"",
- "nullable":true,
- "type":"integer"
- }
- ],
- "indexes":[
- {
- "name":"trd_A_B_c_key",
- "expressions":[
- "\"A\"",
- "\"B\"",
- "c"
- ],
- "type":"btree",
- "unique":true
- }
- ],
- "indexSize":"8192"
- }
- ]
- }
- ],
- "characterSet":"UTF8",
- "collation":"en_US.UTF-8"
- }
- `
)
+ wantDatabaseMetadata := &storepb.DatabaseMetadata{
+ Name: "test_sync_postgresql_schema_db",
+ CharacterSet: "UTF8",
+ Collation: "en_US.UTF-8",
+ Schemas: []*storepb.SchemaMetadata{
+ {
+ Name: "public",
+ Tables: []*storepb.TableMetadata{
+ {
+ Name: "TFK",
+ Columns: []*storepb.ColumnMetadata{
+ {
+ Name: "a",
+ Position: 1,
+ Nullable: true,
+ Type: "integer",
+ },
+ {
+ Name: "b",
+ Position: 2,
+ Nullable: true,
+ Type: "integer",
+ },
+ {
+ Name: "c",
+ Position: 3,
+ Nullable: true,
+ Type: "integer",
+ },
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{
+ {
+ Name: "tfk_ibfk_1",
+ Columns: []string{"a", "b", "c"},
+ ReferencedSchema: "schema1",
+ ReferencedTable: "trd",
+ ReferencedColumns: []string{"A", "B", "c"},
+ OnDelete: "NO ACTION",
+ OnUpdate: "NO ACTION",
+ MatchType: "SIMPLE",
+ },
+ },
+ },
+ },
+ },
+ {
+ Name: "schema1",
+ Tables: []*storepb.TableMetadata{
+ {
+ Name: "trd",
+ Columns: []*storepb.ColumnMetadata{
+ {
+ Name: "A",
+ Position: 1,
+ Nullable: true,
+ Type: "integer",
+ },
+ {
+ Name: "B",
+ Position: 2,
+ Nullable: true,
+ Type: "integer",
+ },
+ {
+ Name: "c",
+ Position: 3,
+ Nullable: true,
+ Type: "integer",
+ },
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "trd_A_B_c_key",
+ // TODO(rebelice): the expressions should not double double quotes.
+ Expressions: []string{`"A"`, `"B"`, "c"},
+ Type: "btree",
+ Unique: true,
+ },
+ },
+ IndexSize: 8192,
+ },
+ },
+ },
+ },
+ }
t.Parallel()
a := require.New(t)
@@ -248,10 +231,8 @@ func TestSyncerForPostgreSQL(t *testing.T) {
err = protojson.Unmarshal([]byte(metadata), &latestSchemaMetadata)
a.NoError(err)
- var expectedSchemaMetadata storepb.DatabaseMetadata
- err = protojson.Unmarshal([]byte(expectedSchema), &expectedSchemaMetadata)
- a.NoError(err)
- a.Equal(&expectedSchemaMetadata, &latestSchemaMetadata)
+ diff := cmp.Diff(wantDatabaseMetadata, &latestSchemaMetadata, protocmp.Transform())
+ a.Equal("", diff)
}
func TestSyncerForMySQL(t *testing.T) {